code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
@extends('layouts.loggedout') @section('content') @if(Session::has('error')) <div class="clearfix"> <div class="alert alert-danger"> {{ Session::get('error') }} </div> </div> @endif <h1 class="col-sm-12">{{ trans('reminders.password_reset') }}</h1> {{ Form::open(array('route' => array('password.update'))) }} <p>{{ Form::label('email', 'Email') }} {{ Form::text('email','',array('class' => 'form-control', 'required' => true)) }}</p> <p>{{ Form::label('password', 'Password') }} {{ Form::password('password',array('class' => 'form-control', 'required' => true)) }}</p> <p>{{ Form::label('password_confirmation', 'Password confirm') }} {{ Form::password('password_confirmation',array('class' => 'form-control', 'required' => true)) }}</p> {{ Form::hidden('token', $token) }} <p>{{ Form::submit('Submit',array('class' => 'btn btn-primary')) }}</p> {{ Form::close() }} @stop
ubc/learninglocker
app/views/system/password/reset.blade.php
PHP
gpl-3.0
953
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_redis_instance_info description: - Gather info for GCP Instance short_description: Gather info for GCP Instance version_added: '2.8' author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: region: description: - The name of the Redis region of the instance. required: true type: str project: description: - The Google Cloud Platform project to use. type: str auth_kind: description: - The type of credential used. type: str required: true choices: - application - machineaccount - serviceaccount service_account_contents: description: - The contents of a Service Account JSON file, either in a dictionary or as a JSON string that represents it. type: jsonarg service_account_file: description: - The path of a Service Account JSON file if serviceaccount is selected as type. type: path service_account_email: description: - An optional service account email address if machineaccount is selected and the user does not wish to use the default email. type: str scopes: description: - Array of scopes to be used type: list env_type: description: - Specifies which Ansible environment you're running this module within. - This should not be set unless you know what you're doing. - This only alters the User Agent string for any API requests. type: str notes: - for authentication, you can set service_account_file using the C(gcp_service_account_file) env variable. - for authentication, you can set service_account_contents using the C(GCP_SERVICE_ACCOUNT_CONTENTS) env variable. - For authentication, you can set service_account_email using the C(GCP_SERVICE_ACCOUNT_EMAIL) env variable. - For authentication, you can set auth_kind using the C(GCP_AUTH_KIND) env variable. - For authentication, you can set scopes using the C(GCP_SCOPES) env variable. - Environment variables values will only be used if the playbook values are not set. - The I(service_account_email) and I(service_account_file) options are mutually exclusive. ''' EXAMPLES = ''' - name: get info on an instance gcp_redis_instance_info: region: us-central1 project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" ''' RETURN = ''' resources: description: List of resources returned: always type: complex contains: alternativeLocationId: description: - Only applicable to STANDARD_HA tier which protects the instance against zonal failures by provisioning it across two zones. - If provided, it must be a different zone from the one provided in [locationId]. returned: success type: str authorizedNetwork: description: - The full name of the Google Compute Engine network to which the instance is connected. If left unspecified, the default network will be used. returned: success type: str createTime: description: - The time the instance was created in RFC3339 UTC "Zulu" format, accurate to nanoseconds. returned: success type: str currentLocationId: description: - The current zone where the Redis endpoint is placed. - For Basic Tier instances, this will always be the same as the [locationId] provided by the user at creation time. For Standard Tier instances, this can be either [locationId] or [alternativeLocationId] and can change after a failover event. returned: success type: str displayName: description: - An arbitrary and optional user-provided name for the instance. returned: success type: str host: description: - Hostname or IP address of the exposed Redis endpoint used by clients to connect to the service. returned: success type: str labels: description: - Resource labels to represent user provided metadata. returned: success type: dict redisConfigs: description: - Redis configuration parameters, according to U(http://redis.io/topics/config). - 'Please check Memorystore documentation for the list of supported parameters: U(https://cloud.google.com/memorystore/docs/redis/reference/rest/v1/projects.locations.instances#Instance.FIELDS.redis_configs) .' returned: success type: dict locationId: description: - The zone where the instance will be provisioned. If not provided, the service will choose a zone for the instance. For STANDARD_HA tier, instances will be created across two zones for protection against zonal failures. If [alternativeLocationId] is also provided, it must be different from [locationId]. returned: success type: str name: description: - The ID of the instance or a fully qualified identifier for the instance. returned: success type: str memorySizeGb: description: - Redis memory size in GiB. returned: success type: int port: description: - The port number of the exposed Redis endpoint. returned: success type: int redisVersion: description: - 'The version of Redis software. If not provided, latest supported version will be used. Currently, the supported values are: - REDIS_4_0 for Redis 4.0 compatibility - REDIS_3_2 for Redis 3.2 compatibility .' returned: success type: str reservedIpRange: description: - The CIDR range of internal addresses that are reserved for this instance. If not provided, the service will choose an unused /29 block, for example, 10.0.0.0/29 or 192.168.0.0/29. Ranges must be unique and non-overlapping with existing subnets in an authorized network. returned: success type: str tier: description: - 'The service tier of the instance. Must be one of these values: - BASIC: standalone instance - STANDARD_HA: highly available primary/replica instances .' returned: success type: str region: description: - The name of the Redis region of the instance. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule(argument_spec=dict(region=dict(required=True, type='str'))) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/cloud-platform'] return_value = {'resources': fetch_list(module, collection(module))} module.exit_json(**return_value) def collection(module): return "https://redis.googleapis.com/v1/projects/{project}/locations/{region}/instances".format(**module.params) def fetch_list(module, link): auth = GcpSession(module, 'redis') return auth.list(link, return_if_object, array_name='instances') def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main()
anryko/ansible
lib/ansible/modules/cloud/google/gcp_redis_instance_info.py
Python
gpl-3.0
9,179
#region References using System; using System.Collections.Generic; using Server.Engines.ConPVP; using Server.Items; using Server.Misc; using Server.Mobiles; using Server.Network; using Server.Spells.Bushido; using Server.Spells.Necromancy; using Server.Spells.Ninjitsu; using Server.Spells.Second; using Server.Spells.Spellweaving; using Server.Targeting; #endregion namespace Server.Spells { public abstract class Spell : ISpell { private readonly Mobile m_Caster; private readonly Item m_Scroll; private readonly SpellInfo m_Info; private SpellState m_State; private long m_StartCastTime; public SpellState State { get { return m_State; } set { m_State = value; } } public Mobile Caster { get { return m_Caster; } } public SpellInfo Info { get { return m_Info; } } public string Name { get { return m_Info.Name; } } public string Mantra { get { return m_Info.Mantra; } } public Type[] Reagents { get { return m_Info.Reagents; } } public Item Scroll { get { return m_Scroll; } } public long StartCastTime { get { return m_StartCastTime; } } private static readonly TimeSpan NextSpellDelay = TimeSpan.FromSeconds(0.75); private static TimeSpan AnimateDelay = TimeSpan.FromSeconds(1.5); public virtual SkillName CastSkill { get { return SkillName.Magery; } } public virtual SkillName DamageSkill { get { return SkillName.EvalInt; } } public virtual bool RevealOnCast { get { return true; } } public virtual bool ClearHandsOnCast { get { return true; } } public virtual bool ShowHandMovement { get { return true; } } public virtual bool DelayedDamage { get { return false; } } public virtual bool DelayedDamageStacking { get { return true; } } //In reality, it's ANY delayed Damage spell Post-AoS that can't stack, but, only //Expo & Magic Arrow have enough delay and a short enough cast time to bring up //the possibility of stacking 'em. Note that a MA & an Explosion will stack, but //of course, two MA's won't. private static readonly Dictionary<Type, DelayedDamageContextWrapper> m_ContextTable = new Dictionary<Type, DelayedDamageContextWrapper>(); private class DelayedDamageContextWrapper { private readonly Dictionary<Mobile, Timer> m_Contexts = new Dictionary<Mobile, Timer>(); public void Add(Mobile m, Timer t) { Timer oldTimer; if (m_Contexts.TryGetValue(m, out oldTimer)) { oldTimer.Stop(); m_Contexts.Remove(m); } m_Contexts.Add(m, t); } public void Remove(Mobile m) { m_Contexts.Remove(m); } } public void StartDelayedDamageContext(Mobile m, Timer t) { if (DelayedDamageStacking) { return; //Sanity } DelayedDamageContextWrapper contexts; if (!m_ContextTable.TryGetValue(GetType(), out contexts)) { contexts = new DelayedDamageContextWrapper(); m_ContextTable.Add(GetType(), contexts); } contexts.Add(m, t); } public void RemoveDelayedDamageContext(Mobile m) { DelayedDamageContextWrapper contexts; if (!m_ContextTable.TryGetValue(GetType(), out contexts)) { return; } contexts.Remove(m); } public void HarmfulSpell(Mobile m) { if (m is BaseCreature) { ((BaseCreature)m).OnHarmfulSpell(m_Caster); } } public Spell(Mobile caster, Item scroll, SpellInfo info) { m_Caster = caster; m_Scroll = scroll; m_Info = info; } public virtual int GetNewAosDamage(int bonus, int dice, int sides, Mobile singleTarget) { if (singleTarget != null) { return GetNewAosDamage(bonus, dice, sides, (Caster.Player && singleTarget.Player), GetDamageScalar(singleTarget)); } else { return GetNewAosDamage(bonus, dice, sides, false); } } public virtual int GetNewAosDamage(int bonus, int dice, int sides, bool playerVsPlayer) { return GetNewAosDamage(bonus, dice, sides, playerVsPlayer, 1.0); } public virtual int GetNewAosDamage(int bonus, int dice, int sides, bool playerVsPlayer, double scalar) { int damage = Utility.Dice(dice, sides, bonus) * 100; int damageBonus = 0; int inscribeSkill = GetInscribeFixed(m_Caster); int inscribeBonus = (inscribeSkill + (1000 * (inscribeSkill / 1000))) / 200; damageBonus += inscribeBonus; int intBonus = Caster.Int / 10; damageBonus += intBonus; int sdiBonus = AosAttributes.GetValue(m_Caster, AosAttribute.SpellDamage); #region Mondain's Legacy sdiBonus += ArcaneEmpowermentSpell.GetSpellBonus(m_Caster, playerVsPlayer); #endregion // PvP spell damage increase cap of 15% from an item’s magic property, 30% if spell school focused. if (playerVsPlayer) { if (SpellHelper.HasSpellMastery(m_Caster) && sdiBonus > 30) { sdiBonus = 30; } if (!SpellHelper.HasSpellMastery(m_Caster) && sdiBonus > 15) { sdiBonus = 15; } } damageBonus += sdiBonus; TransformContext context = TransformationSpellHelper.GetContext(Caster); if (context != null && context.Spell is ReaperFormSpell) { damageBonus += ((ReaperFormSpell)context.Spell).SpellDamageBonus; } damage = AOS.Scale(damage, 100 + damageBonus); int evalSkill = GetDamageFixed(m_Caster); int evalScale = 30 + ((9 * evalSkill) / 100); damage = AOS.Scale(damage, evalScale); damage = AOS.Scale(damage, (int)(scalar * 100)); return damage / 100; } public virtual bool IsCasting { get { return m_State == SpellState.Casting; } } public virtual void OnCasterHurt() { //Confirm: Monsters and pets cannot be disturbed. if (!Caster.Player) { return; } if (IsCasting) { object o = ProtectionSpell.Registry[m_Caster]; bool disturb = true; if (o != null && o is double) { if (((double)o) > Utility.RandomDouble() * 100.0) { disturb = false; } } #region Stygian Abyss int focus = SAAbsorptionAttributes.GetValue(Caster, SAAbsorptionAttribute.CastingFocus); if (focus > 0) { if (focus > 30) { focus = 30; } if (focus > Utility.Random(100)) { disturb = false; Caster.SendLocalizedMessage(1113690); // You regain your focus and continue casting the spell. } } #endregion if (disturb) { Disturb(DisturbType.Hurt, false, true); } } } public virtual void OnCasterKilled() { Disturb(DisturbType.Kill); } public virtual void OnConnectionChanged() { FinishSequence(); } public virtual bool OnCasterMoving(Direction d) { if (IsCasting && BlocksMovement) { m_Caster.SendLocalizedMessage(500111); // You are frozen and can not move. return false; } return true; } public virtual bool OnCasterEquiping(Item item) { if (IsCasting) { Disturb(DisturbType.EquipRequest); } return true; } public virtual bool OnCasterUsingObject(object o) { if (m_State == SpellState.Sequencing) { Disturb(DisturbType.UseRequest); } return true; } public virtual bool OnCastInTown(Region r) { return m_Info.AllowTown; } public virtual bool ConsumeReagents() { if (m_Caster.AccessLevel >= AccessLevel.Counselor) return true; if (m_Scroll != null || !m_Caster.Player) { return true; } if (AosAttributes.GetValue(m_Caster, AosAttribute.LowerRegCost) > Utility.Random(100)) { return true; } if (DuelContext.IsFreeConsume(m_Caster)) { return true; } Container pack = m_Caster.Backpack; if (pack == null) { return false; } if (pack.ConsumeTotal(m_Info.Reagents, m_Info.Amounts) == -1) { return true; } return false; } public virtual double GetInscribeSkill(Mobile m) { // There is no chance to gain // m.CheckSkill( SkillName.Inscribe, 0.0, 120.0 ); return m.Skills[SkillName.Inscribe].Value; } public virtual int GetInscribeFixed(Mobile m) { // There is no chance to gain // m.CheckSkill( SkillName.Inscribe, 0.0, 120.0 ); return m.Skills[SkillName.Inscribe].Fixed; } public virtual int GetDamageFixed(Mobile m) { //m.CheckSkill( DamageSkill, 0.0, m.Skills[DamageSkill].Cap ); return m.Skills[DamageSkill].Fixed; } public virtual double GetDamageSkill(Mobile m) { //m.CheckSkill( DamageSkill, 0.0, m.Skills[DamageSkill].Cap ); return m.Skills[DamageSkill].Value; } public virtual double GetResistSkill(Mobile m) { return m.Skills[SkillName.MagicResist].Value; } public virtual double GetDamageScalar(Mobile target) { double scalar = 1.0; if (!Core.AOS) //EvalInt stuff for AoS is handled elsewhere { double casterEI = m_Caster.Skills[DamageSkill].Value; double targetRS = target.Skills[SkillName.MagicResist].Value; /* if( Core.AOS ) targetRS = 0; */ //m_Caster.CheckSkill( DamageSkill, 0.0, 120.0 ); if (casterEI > targetRS) { scalar = (1.0 + ((casterEI - targetRS) / 500.0)); } else { scalar = (1.0 + ((casterEI - targetRS) / 200.0)); } // magery damage bonus, -25% at 0 skill, +0% at 100 skill, +5% at 120 skill scalar += (m_Caster.Skills[CastSkill].Value - 100.0) / 400.0; if (!target.Player && !target.Body.IsHuman /*&& !Core.AOS*/) { scalar *= 2.0; // Double magery damage to monsters/animals if not AOS } } if (target is BaseCreature) { ((BaseCreature)target).AlterDamageScalarFrom(m_Caster, ref scalar); } if (m_Caster is BaseCreature) { ((BaseCreature)m_Caster).AlterDamageScalarTo(target, ref scalar); } if (Core.SE) { scalar *= GetSlayerDamageScalar(target); } target.Region.SpellDamageScalar(m_Caster, target, ref scalar); if (Evasion.CheckSpellEvasion(target)) //Only single target spells an be evaded { scalar = 0; } return scalar; } public virtual double GetSlayerDamageScalar(Mobile defender) { Spellbook atkBook = Spellbook.FindEquippedSpellbook(m_Caster); double scalar = 1.0; if (atkBook != null) { SlayerEntry atkSlayer = SlayerGroup.GetEntryByName(atkBook.Slayer); SlayerEntry atkSlayer2 = SlayerGroup.GetEntryByName(atkBook.Slayer2); if (atkSlayer != null && atkSlayer.Slays(defender) || atkSlayer2 != null && atkSlayer2.Slays(defender)) { defender.FixedEffect(0x37B9, 10, 5); //TODO: Confirm this displays on OSIs scalar = 2.0; } TransformContext context = TransformationSpellHelper.GetContext(defender); if ((atkBook.Slayer == SlayerName.Silver || atkBook.Slayer2 == SlayerName.Silver) && context != null && context.Type != typeof(HorrificBeastSpell)) { scalar += .25; // Every necromancer transformation other than horrific beast take an additional 25% damage } if (scalar != 1.0) { return scalar; } } ISlayer defISlayer = Spellbook.FindEquippedSpellbook(defender); if (defISlayer == null) { defISlayer = defender.Weapon as ISlayer; } if (defISlayer != null) { SlayerEntry defSlayer = SlayerGroup.GetEntryByName(defISlayer.Slayer); SlayerEntry defSlayer2 = SlayerGroup.GetEntryByName(defISlayer.Slayer2); if (defSlayer != null && defSlayer.Group.OppositionSuperSlays(m_Caster) || defSlayer2 != null && defSlayer2.Group.OppositionSuperSlays(m_Caster)) { scalar = 2.0; } } return scalar; } public virtual void DoFizzle() { m_Caster.LocalOverheadMessage(MessageType.Regular, 0x3B2, 502632); // The spell fizzles. if (m_Caster.Player) { if (Core.AOS) { m_Caster.FixedParticles(0x3735, 1, 30, 9503, EffectLayer.Waist); } else { m_Caster.FixedEffect(0x3735, 6, 30); } m_Caster.PlaySound(0x5C); } } private CastTimer m_CastTimer; private AnimTimer m_AnimTimer; public void Disturb(DisturbType type) { Disturb(type, true, false); } public virtual bool CheckDisturb(DisturbType type, bool firstCircle, bool resistable) { if (resistable && m_Scroll is BaseWand) { return false; } return true; } public void Disturb(DisturbType type, bool firstCircle, bool resistable) { if (!CheckDisturb(type, firstCircle, resistable)) { return; } if (m_State == SpellState.Casting) { if (!firstCircle && !Core.AOS && this is MagerySpell && ((MagerySpell)this).Circle == SpellCircle.First) { return; } m_State = SpellState.None; m_Caster.Spell = null; OnDisturb(type, true); if (m_CastTimer != null) { m_CastTimer.Stop(); } if (m_AnimTimer != null) { m_AnimTimer.Stop(); } if (Core.AOS && m_Caster.Player && type == DisturbType.Hurt) { DoHurtFizzle(); } m_Caster.NextSpellTime = Core.TickCount + (int)GetDisturbRecovery().TotalMilliseconds; } else if (m_State == SpellState.Sequencing) { if (!firstCircle && !Core.AOS && this is MagerySpell && ((MagerySpell)this).Circle == SpellCircle.First) { return; } m_State = SpellState.None; m_Caster.Spell = null; OnDisturb(type, false); Target.Cancel(m_Caster); if (Core.AOS && m_Caster.Player && type == DisturbType.Hurt) { DoHurtFizzle(); } } } public virtual void DoHurtFizzle() { m_Caster.FixedEffect(0x3735, 6, 30); m_Caster.PlaySound(0x5C); } public virtual void OnDisturb(DisturbType type, bool message) { if (message) { m_Caster.SendLocalizedMessage(500641); // Your concentration is disturbed, thus ruining thy spell. } } public virtual bool CheckCast() { return true; } public virtual void SayMantra() { if (m_Scroll is BaseWand) { return; } if (m_Info.Mantra != null && m_Info.Mantra.Length > 0 && m_Caster.Player) { m_Caster.PublicOverheadMessage(MessageType.Spell, m_Caster.SpeechHue, true, m_Info.Mantra, false); } } public virtual bool BlockedByHorrificBeast { get { return true; } } public virtual bool BlockedByAnimalForm { get { return true; } } public virtual bool BlocksMovement { get { return true; } } public virtual bool CheckNextSpellTime { get { return !(m_Scroll is BaseWand); } } public bool Cast() { m_StartCastTime = Core.TickCount; if (Core.AOS && m_Caster.Spell is Spell && ((Spell)m_Caster.Spell).State == SpellState.Sequencing) { ((Spell)m_Caster.Spell).Disturb(DisturbType.NewCast); } if (!m_Caster.CheckAlive()) { return false; } else if (m_Caster is PlayerMobile && ((PlayerMobile)m_Caster).Peaced) { m_Caster.SendLocalizedMessage(1072060); // You cannot cast a spell while calmed. } else if (m_Scroll is BaseWand && m_Caster.Spell != null && m_Caster.Spell.IsCasting) { m_Caster.SendLocalizedMessage(502643); // You can not cast a spell while frozen. } else if (m_Caster.Spell != null && m_Caster.Spell.IsCasting) { m_Caster.SendLocalizedMessage(502642); // You are already casting a spell. } else if (BlockedByHorrificBeast && TransformationSpellHelper.UnderTransformation(m_Caster, typeof(HorrificBeastSpell)) || (BlockedByAnimalForm && AnimalForm.UnderTransformation(m_Caster))) { m_Caster.SendLocalizedMessage(1061091); // You cannot cast that spell in this form. } else if (!(m_Scroll is BaseWand) && (m_Caster.Paralyzed || m_Caster.Frozen)) { m_Caster.SendLocalizedMessage(502643); // You can not cast a spell while frozen. } else if (CheckNextSpellTime && Core.TickCount - m_Caster.NextSpellTime < 0) { m_Caster.SendLocalizedMessage(502644); // You have not yet recovered from casting a spell. } else if (m_Caster is PlayerMobile && ((PlayerMobile)m_Caster).PeacedUntil > DateTime.UtcNow) { m_Caster.SendLocalizedMessage(1072060); // You cannot cast a spell while calmed. } #region Dueling else if (m_Caster is PlayerMobile && ((PlayerMobile)m_Caster).DuelContext != null && !((PlayerMobile)m_Caster).DuelContext.AllowSpellCast(m_Caster, this)) { } #endregion else if (m_Caster.Mana >= ScaleMana(GetMana())) { #region Stygian Abyss if (m_Caster.Race == Race.Gargoyle && m_Caster.Flying) { var tiles = Caster.Map.Tiles.GetStaticTiles(Caster.X, Caster.Y, true); ItemData itemData; bool cancast = true; for (int i = 0; i < tiles.Length && cancast; ++i) { itemData = TileData.ItemTable[tiles[i].ID & TileData.MaxItemValue]; cancast = !(itemData.Name == "hover over"); } if (!cancast) { if (m_Caster.IsPlayer()) { m_Caster.SendLocalizedMessage(1113750); // You may not cast spells while flying over such precarious terrain. return false; } else { m_Caster.SendMessage("Your staff level allows you to cast while flying over precarious terrain."); } } } #endregion if (m_Caster.Spell == null && m_Caster.CheckSpellCast(this) && CheckCast() && m_Caster.Region.OnBeginSpellCast(m_Caster, this)) { m_State = SpellState.Casting; m_Caster.Spell = this; if (!(m_Scroll is BaseWand) && RevealOnCast) { m_Caster.RevealingAction(); } SayMantra(); TimeSpan castDelay = GetCastDelay(); if (ShowHandMovement && (m_Caster.Body.IsHuman || (m_Caster.Player && m_Caster.Body.IsMonster))) { int count = (int)Math.Ceiling(castDelay.TotalSeconds / AnimateDelay.TotalSeconds); if (count != 0) { m_AnimTimer = new AnimTimer(this, count); m_AnimTimer.Start(); } if (m_Info.LeftHandEffect > 0) { Caster.FixedParticles(0, 10, 5, m_Info.LeftHandEffect, EffectLayer.LeftHand); } if (m_Info.RightHandEffect > 0) { Caster.FixedParticles(0, 10, 5, m_Info.RightHandEffect, EffectLayer.RightHand); } } if (ClearHandsOnCast) { m_Caster.ClearHands(); } if (Core.ML) { WeaponAbility.ClearCurrentAbility(m_Caster); } m_CastTimer = new CastTimer(this, castDelay); //m_CastTimer.Start(); OnBeginCast(); if (castDelay > TimeSpan.Zero) { m_CastTimer.Start(); } else { m_CastTimer.Tick(); } return true; } else { return false; } } else { m_Caster.LocalOverheadMessage(MessageType.Regular, 0x22, 502625); // Insufficient mana } return false; } public abstract void OnCast(); public virtual void OnBeginCast() { } public virtual void GetCastSkills(out double min, out double max) { min = max = 0; //Intended but not required for overriding. } public virtual bool CheckFizzle() { if (m_Scroll is BaseWand) { return true; } double minSkill, maxSkill; GetCastSkills(out minSkill, out maxSkill); if (DamageSkill != CastSkill) { Caster.CheckSkill(DamageSkill, 0.0, Caster.Skills[DamageSkill].Cap); } return Caster.CheckSkill(CastSkill, minSkill, maxSkill); } public abstract int GetMana(); public virtual int ScaleMana(int mana) { double scalar = 1.0; if (!MindRotSpell.GetMindRotScalar(Caster, ref scalar)) { scalar = 1.0; } // Lower Mana Cost = 40% int lmc = AosAttributes.GetValue(m_Caster, AosAttribute.LowerManaCost); if (lmc > 40) { lmc = 40; } scalar -= (double)lmc / 100; return (int)(mana * scalar); } public virtual TimeSpan GetDisturbRecovery() { if (Core.AOS) { return TimeSpan.Zero; } double delay = 1.0 - Math.Sqrt((Core.TickCount - m_StartCastTime) / 1000.0 / GetCastDelay().TotalSeconds); if (delay < 0.2) { delay = 0.2; } return TimeSpan.FromSeconds(delay); } public virtual int CastRecoveryBase { get { return 6; } } public virtual int CastRecoveryFastScalar { get { return 1; } } public virtual int CastRecoveryPerSecond { get { return 4; } } public virtual int CastRecoveryMinimum { get { return 0; } } public virtual TimeSpan GetCastRecovery() { if (!Core.AOS) { return NextSpellDelay; } int fcr = AosAttributes.GetValue(m_Caster, AosAttribute.CastRecovery); fcr -= ThunderstormSpell.GetCastRecoveryMalus(m_Caster); int fcrDelay = -(CastRecoveryFastScalar * fcr); int delay = CastRecoveryBase + fcrDelay; if (delay < CastRecoveryMinimum) { delay = CastRecoveryMinimum; } return TimeSpan.FromSeconds((double)delay / CastRecoveryPerSecond); } public abstract TimeSpan CastDelayBase { get; } public virtual double CastDelayFastScalar { get { return 1; } } public virtual double CastDelaySecondsPerTick { get { return 0.25; } } public virtual TimeSpan CastDelayMinimum { get { return TimeSpan.FromSeconds(0.25); } } //public virtual int CastDelayBase{ get{ return 3; } } //public virtual int CastDelayFastScalar{ get{ return 1; } } //public virtual int CastDelayPerSecond{ get{ return 4; } } //public virtual int CastDelayMinimum{ get{ return 1; } } public virtual TimeSpan GetCastDelay() { if (m_Scroll is BaseWand) { return Core.ML ? CastDelayBase : TimeSpan.Zero; // TODO: Should FC apply to wands? } // Faster casting cap of 2 (if not using the protection spell) // Faster casting cap of 0 (if using the protection spell) // Paladin spells are subject to a faster casting cap of 4 // Paladins with magery of 70.0 or above are subject to a faster casting cap of 2 int fcMax = 4; if (CastSkill == SkillName.Magery || CastSkill == SkillName.Necromancy || (CastSkill == SkillName.Chivalry && m_Caster.Skills[SkillName.Magery].Value >= 70.0)) { fcMax = 2; } int fc = AosAttributes.GetValue(m_Caster, AosAttribute.CastSpeed); if (fc > fcMax) { fc = fcMax; } if (ProtectionSpell.Registry.Contains(m_Caster)) { fc -= 2; } if (EssenceOfWindSpell.IsDebuffed(m_Caster)) { fc -= EssenceOfWindSpell.GetFCMalus(m_Caster); } TimeSpan baseDelay = CastDelayBase; TimeSpan fcDelay = TimeSpan.FromSeconds(-(CastDelayFastScalar * fc * CastDelaySecondsPerTick)); //int delay = CastDelayBase + circleDelay + fcDelay; TimeSpan delay = baseDelay + fcDelay; if (delay < CastDelayMinimum) { delay = CastDelayMinimum; } #region Mondain's Legacy if (DreadHorn.IsUnderInfluence(m_Caster)) { delay.Add(delay); } #endregion //return TimeSpan.FromSeconds( (double)delay / CastDelayPerSecond ); return delay; } public virtual void FinishSequence() { m_State = SpellState.None; if (m_Caster.Spell == this) { m_Caster.Spell = null; } } public virtual int ComputeKarmaAward() { return 0; } public virtual bool CheckSequence() { int mana = ScaleMana(GetMana()); if (m_Caster.Deleted || !m_Caster.Alive || m_Caster.Spell != this || m_State != SpellState.Sequencing) { DoFizzle(); } else if (m_Scroll != null && !(m_Scroll is Runebook) && (m_Scroll.Amount <= 0 || m_Scroll.Deleted || m_Scroll.RootParent != m_Caster || (m_Scroll is BaseWand && (((BaseWand)m_Scroll).Charges <= 0 || m_Scroll.Parent != m_Caster)))) { DoFizzle(); } else if (!ConsumeReagents()) { m_Caster.LocalOverheadMessage(MessageType.Regular, 0x22, 502630); // More reagents are needed for this spell. } else if (m_Caster.Mana < mana) { m_Caster.LocalOverheadMessage(MessageType.Regular, 0x22, 502625); // Insufficient mana for this spell. } else if (Core.AOS && (m_Caster.Frozen || m_Caster.Paralyzed)) { m_Caster.SendLocalizedMessage(502646); // You cannot cast a spell while frozen. DoFizzle(); } else if (m_Caster is PlayerMobile && ((PlayerMobile)m_Caster).PeacedUntil > DateTime.UtcNow) { m_Caster.SendLocalizedMessage(1072060); // You cannot cast a spell while calmed. DoFizzle(); } else if (CheckFizzle()) { m_Caster.Mana -= mana; if (m_Scroll is SpellScroll) { m_Scroll.Consume(); } #region SA else if (m_Scroll is SpellStone) { // The SpellScroll check above isn't removing the SpellStones for some reason. m_Scroll.Delete(); } #endregion else if (m_Scroll is BaseWand) { ((BaseWand)m_Scroll).ConsumeCharge(m_Caster); m_Caster.RevealingAction(); } if (m_Scroll is BaseWand) { bool m = m_Scroll.Movable; m_Scroll.Movable = false; if (ClearHandsOnCast) { m_Caster.ClearHands(); } m_Scroll.Movable = m; } else { if (ClearHandsOnCast) { m_Caster.ClearHands(); } } int karma = ComputeKarmaAward(); if (karma != 0) { Titles.AwardKarma(Caster, karma, true); } if (TransformationSpellHelper.UnderTransformation(m_Caster, typeof(VampiricEmbraceSpell))) { bool garlic = false; for (int i = 0; !garlic && i < m_Info.Reagents.Length; ++i) { garlic = (m_Info.Reagents[i] == Reagent.Garlic); } if (garlic) { m_Caster.SendLocalizedMessage(1061651); // The garlic burns you! AOS.Damage(m_Caster, Utility.RandomMinMax(17, 23), 100, 0, 0, 0, 0); } } return true; } else { DoFizzle(); } return false; } public bool CheckBSequence(Mobile target) { return CheckBSequence(target, false); } public bool CheckBSequence(Mobile target, bool allowDead) { if (!target.Alive && !allowDead) { m_Caster.SendLocalizedMessage(501857); // This spell won't work on that! return false; } else if (Caster.CanBeBeneficial(target, true, allowDead) && CheckSequence()) { Caster.DoBeneficial(target); return true; } else { return false; } } public bool CheckHSequence(Mobile target) { if (!target.Alive) { m_Caster.SendLocalizedMessage(501857); // This spell won't work on that! return false; } else if (Caster.CanBeHarmful(target) && CheckSequence()) { Caster.DoHarmful(target); return true; } else { return false; } } private class AnimTimer : Timer { private readonly Spell m_Spell; public AnimTimer(Spell spell, int count) : base(TimeSpan.Zero, AnimateDelay, count) { m_Spell = spell; Priority = TimerPriority.FiftyMS; } protected override void OnTick() { if (m_Spell.State != SpellState.Casting || m_Spell.m_Caster.Spell != m_Spell) { Stop(); return; } if (!m_Spell.Caster.Mounted && m_Spell.m_Info.Action >= 0) { if (m_Spell.Caster.Body.IsHuman) { m_Spell.Caster.Animate(m_Spell.m_Info.Action, 7, 1, true, false, 0); } else if (m_Spell.Caster.Player && m_Spell.Caster.Body.IsMonster) { m_Spell.Caster.Animate(12, 7, 1, true, false, 0); } } if (!Running) { m_Spell.m_AnimTimer = null; } } } private class CastTimer : Timer { private readonly Spell m_Spell; public CastTimer(Spell spell, TimeSpan castDelay) : base(castDelay) { m_Spell = spell; Priority = TimerPriority.TwentyFiveMS; } protected override void OnTick() { if (m_Spell == null || m_Spell.m_Caster == null) { return; } else if (m_Spell.m_State == SpellState.Casting && m_Spell.m_Caster.Spell == m_Spell) { m_Spell.m_State = SpellState.Sequencing; m_Spell.m_CastTimer = null; m_Spell.m_Caster.OnSpellCast(m_Spell); if (m_Spell.m_Caster.Region != null) { m_Spell.m_Caster.Region.OnSpellCast(m_Spell.m_Caster, m_Spell); } m_Spell.m_Caster.NextSpellTime = Core.TickCount + (int)m_Spell.GetCastRecovery().TotalMilliseconds; // Spell.NextSpellDelay; Target originalTarget = m_Spell.m_Caster.Target; m_Spell.OnCast(); if (m_Spell.m_Caster.Player && m_Spell.m_Caster.Target != originalTarget && m_Spell.Caster.Target != null) { m_Spell.m_Caster.Target.BeginTimeout(m_Spell.m_Caster, TimeSpan.FromSeconds(30.0)); } m_Spell.m_CastTimer = null; } } public void Tick() { OnTick(); } } } }
zerodowned/JustUO
Scripts/Spells/Base/Spell.cs
C#
gpl-3.0
28,192
<?php namespace App\Console\Commands; use App\Console\LnmsCommand; use App\Models\Device; use Illuminate\Database\Eloquent\Builder; use LibreNMS\Config; use LibreNMS\Polling\ConnectivityHelper; use Symfony\Component\Console\Input\InputArgument; class DevicePing extends LnmsCommand { protected $name = 'device:ping'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); $this->addArgument('device spec', InputArgument::REQUIRED); } /** * Execute the console command. * * @return int */ public function handle(): int { $spec = $this->argument('device spec'); $devices = Device::query()->when($spec !== 'all', function (Builder $query) use ($spec) { /** @phpstan-var Builder<Device> $query */ return $query->where('device_id', $spec) ->orWhere('hostname', $spec) ->limit(1); })->get(); if ($devices->isEmpty()) { $devices = [new Device(['hostname' => $spec])]; } Config::set('icmp_check', true); // ignore icmp disabled, this is an explicit user action /** @var Device $device */ foreach ($devices as $device) { $helper = new ConnectivityHelper($device); $response = $helper->isPingable(); $this->line($device->displayName() . ' : ' . ($response->wasSkipped() ? 'skipped' : $response)); } return 0; } }
arrmo/librenms
app/Console/Commands/DevicePing.php
PHP
gpl-3.0
1,546
package net.minecraft.server; import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit public class EntityPig extends EntityAnimal { private final PathfinderGoalPassengerCarrotStick bp; public EntityPig(World world) { super(world); this.a(0.9F, 0.9F); this.getNavigation().a(true); this.goalSelector.a(0, new PathfinderGoalFloat(this)); this.goalSelector.a(1, new PathfinderGoalPanic(this, 1.25D)); this.goalSelector.a(2, this.bp = new PathfinderGoalPassengerCarrotStick(this, 0.3F)); this.goalSelector.a(3, new PathfinderGoalBreed(this, 1.0D)); this.goalSelector.a(4, new PathfinderGoalTempt(this, 1.2D, Items.CARROT_STICK, false)); this.goalSelector.a(4, new PathfinderGoalTempt(this, 1.2D, Items.CARROT, false)); this.goalSelector.a(5, new PathfinderGoalFollowParent(this, 1.1D)); this.goalSelector.a(6, new PathfinderGoalRandomStroll(this, 1.0D)); this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); } public boolean bk() { return true; } protected void aD() { super.aD(); this.getAttributeInstance(GenericAttributes.maxHealth).setValue(10.0D); this.getAttributeInstance(GenericAttributes.d).setValue(0.25D); } protected void bn() { super.bn(); } public boolean bE() { ItemStack itemstack = ((EntityHuman) this.passenger).be(); return itemstack != null && itemstack.getItem() == Items.CARROT_STICK; } protected void c() { super.c(); this.datawatcher.a(16, Byte.valueOf((byte) 0)); } public void b(NBTTagCompound nbttagcompound) { super.b(nbttagcompound); nbttagcompound.setBoolean("Saddle", this.hasSaddle()); } public void a(NBTTagCompound nbttagcompound) { super.a(nbttagcompound); this.setSaddle(nbttagcompound.getBoolean("Saddle")); } protected String t() { return "mob.pig.say"; } protected String aT() { return "mob.pig.say"; } protected String aU() { return "mob.pig.death"; } protected void a(int i, int j, int k, Block block) { this.makeSound("mob.pig.step", 0.15F, 1.0F); } public boolean a(EntityHuman entityhuman) { if (super.a(entityhuman)) { return true; } else if (this.hasSaddle() && !this.world.isStatic && (this.passenger == null || this.passenger == entityhuman)) { entityhuman.mount(this); return true; } else { return false; } } protected Item getLoot() { return this.isBurning() ? Items.GRILLED_PORK : Items.PORK; } protected void dropDeathLoot(boolean flag, int i) { int j = this.random.nextInt(3) + 1 + this.random.nextInt(1 + i); for (int k = 0; k < j; ++k) { if (this.isBurning()) { this.a(Items.GRILLED_PORK, 1); } else { this.a(Items.PORK, 1); } } if (this.hasSaddle()) { this.a(Items.SADDLE, 1); } } public boolean hasSaddle() { return (this.datawatcher.getByte(16) & 1) != 0; } public void setSaddle(boolean flag) { if (flag) { this.datawatcher.watch(16, Byte.valueOf((byte) 1)); } else { this.datawatcher.watch(16, Byte.valueOf((byte) 0)); } } public void a(EntityLightning entitylightning) { if (!this.world.isStatic) { EntityPigZombie entitypigzombie = new EntityPigZombie(this.world); // CraftBukkit start if (CraftEventFactory.callPigZapEvent(this, entitylightning, entitypigzombie).isCancelled()) { return; } // CraftBukkit end entitypigzombie.setEquipment(0, new ItemStack(Items.GOLD_SWORD)); entitypigzombie.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, this.pitch); // CraftBukkit - added a reason for spawning this creature this.world.addEntity(entitypigzombie, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.LIGHTNING); this.die(); } } protected void b(float f) { super.b(f); if (f > 5.0F && this.passenger instanceof EntityHuman) { ((EntityHuman) this.passenger).a((Statistic) AchievementList.u); } } public EntityPig b(EntityAgeable entityageable) { return new EntityPig(this.world); } public boolean c(ItemStack itemstack) { return itemstack != null && itemstack.getItem() == Items.CARROT; } public PathfinderGoalPassengerCarrotStick ca() { return this.bp; } public EntityAgeable createChild(EntityAgeable entityageable) { return this.b(entityageable); } }
starlis/EMC-CraftBukkit
src/main/java/net/minecraft/server/EntityPig.java
Java
gpl-3.0
4,987
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package protoreflect provides interfaces to dynamically manipulate messages. // // This package includes type descriptors which describe the structure of types // defined in proto source files and value interfaces which provide the // ability to examine and manipulate the contents of messages. // // // Protocol Buffer Descriptors // // Protobuf descriptors (e.g., EnumDescriptor or MessageDescriptor) // are immutable objects that represent protobuf type information. // They are wrappers around the messages declared in descriptor.proto. // Protobuf descriptors alone lack any information regarding Go types. // // Enums and messages generated by this module implement Enum and ProtoMessage, // where the Descriptor and ProtoReflect.Descriptor accessors respectively // return the protobuf descriptor for the values. // // The protobuf descriptor interfaces are not meant to be implemented by // user code since they might need to be extended in the future to support // additions to the protobuf language. Protobuf descriptors can be constructed // using the "google.golang.org/protobuf/reflect/protodesc" package. // // // Go Type Descriptors // // A type descriptor (e.g., EnumType or MessageType) is a constructor for // a concrete Go type that represents the associated protobuf descriptor. // There is commonly a one-to-one relationship between protobuf descriptors and // Go type descriptors, but it can potentially be a one-to-many relationship. // // Enums and messages generated by this module implement Enum and ProtoMessage, // where the Type and ProtoReflect.Type accessors respectively // return the protobuf descriptor for the values. // // The "google.golang.org/protobuf/types/dynamicpb" package can be used to // create Go type descriptors from protobuf descriptors. // // // Value Interfaces // // The Enum and Message interfaces provide a reflective view over an // enum or message instance. For enums, it provides the ability to retrieve // the enum value number for any concrete enum type. For messages, it provides // the ability to access or manipulate fields of the message. // // To convert a proto.Message to a protoreflect.Message, use the // former's ProtoReflect method. Since the ProtoReflect method is new to the // v2 message interface, it may not be present on older message implementations. // The "github.com/golang/protobuf/proto".MessageReflect function can be used // to obtain a reflective view on older messages. // // // Relationships // // The following diagrams demonstrate the relationships between // various types declared in this package. // // // ┌───────────────────────────────────┐ // V │ // ┌────────────── New(n) ─────────────┐ │ // │ │ │ // │ ┌──── Descriptor() ──┐ │ ┌── Number() ──┐ │ // │ │ V V │ V │ // ╔════════════╗ ╔════════════════╗ ╔════════╗ ╔════════════╗ // ║ EnumType ║ ║ EnumDescriptor ║ ║ Enum ║ ║ EnumNumber ║ // ╚════════════╝ ╚════════════════╝ ╚════════╝ ╚════════════╝ // Λ Λ │ │ // │ └─── Descriptor() ──┘ │ // │ │ // └────────────────── Type() ───────┘ // // • An EnumType describes a concrete Go enum type. // It has an EnumDescriptor and can construct an Enum instance. // // • An EnumDescriptor describes an abstract protobuf enum type. // // • An Enum is a concrete enum instance. Generated enums implement Enum. // // // ┌──────────────── New() ─────────────────┐ // │ │ // │ ┌─── Descriptor() ─────┐ │ ┌── Interface() ───┐ // │ │ V V │ V // ╔═════════════╗ ╔═══════════════════╗ ╔═════════╗ ╔══════════════╗ // ║ MessageType ║ ║ MessageDescriptor ║ ║ Message ║ ║ ProtoMessage ║ // ╚═════════════╝ ╚═══════════════════╝ ╚═════════╝ ╚══════════════╝ // Λ Λ │ │ Λ │ // │ └──── Descriptor() ────┘ │ └─ ProtoReflect() ─┘ // │ │ // └─────────────────── Type() ─────────┘ // // • A MessageType describes a concrete Go message type. // It has a MessageDescriptor and can construct a Message instance. // // • A MessageDescriptor describes an abstract protobuf message type. // // • A Message is a concrete message instance. Generated messages implement // ProtoMessage, which can convert to/from a Message. // // // ┌── TypeDescriptor() ──┐ ┌───── Descriptor() ─────┐ // │ V │ V // ╔═══════════════╗ ╔═════════════════════════╗ ╔═════════════════════╗ // ║ ExtensionType ║ ║ ExtensionTypeDescriptor ║ ║ ExtensionDescriptor ║ // ╚═══════════════╝ ╚═════════════════════════╝ ╚═════════════════════╝ // Λ │ │ Λ │ Λ // └─────── Type() ───────┘ │ └─── may implement ────┘ │ // │ │ // └────── implements ────────┘ // // • An ExtensionType describes a concrete Go implementation of an extension. // It has an ExtensionTypeDescriptor and can convert to/from // abstract Values and Go values. // // • An ExtensionTypeDescriptor is an ExtensionDescriptor // which also has an ExtensionType. // // • An ExtensionDescriptor describes an abstract protobuf extension field and // may not always be an ExtensionTypeDescriptor. package protoreflect import ( "fmt" "regexp" "strings" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/pragma" ) type doNotImplement pragma.DoNotImplement // ProtoMessage is the top-level interface that all proto messages implement. // This is declared in the protoreflect package to avoid a cyclic dependency; // use the proto.Message type instead, which aliases this type. type ProtoMessage interface{ ProtoReflect() Message } // Syntax is the language version of the proto file. type Syntax syntax type syntax int8 // keep exact type opaque as the int type may change const ( Proto2 Syntax = 2 Proto3 Syntax = 3 ) // IsValid reports whether the syntax is valid. func (s Syntax) IsValid() bool { switch s { case Proto2, Proto3: return true default: return false } } // String returns s as a proto source identifier (e.g., "proto2"). func (s Syntax) String() string { switch s { case Proto2: return "proto2" case Proto3: return "proto3" default: return fmt.Sprintf("<unknown:%d>", s) } } // GoString returns s as a Go source identifier (e.g., "Proto2"). func (s Syntax) GoString() string { switch s { case Proto2: return "Proto2" case Proto3: return "Proto3" default: return fmt.Sprintf("Syntax(%d)", s) } } // Cardinality determines whether a field is optional, required, or repeated. type Cardinality cardinality type cardinality int8 // keep exact type opaque as the int type may change // Constants as defined by the google.protobuf.Cardinality enumeration. const ( Optional Cardinality = 1 // appears zero or one times Required Cardinality = 2 // appears exactly one time; invalid with Proto3 Repeated Cardinality = 3 // appears zero or more times ) // IsValid reports whether the cardinality is valid. func (c Cardinality) IsValid() bool { switch c { case Optional, Required, Repeated: return true default: return false } } // String returns c as a proto source identifier (e.g., "optional"). func (c Cardinality) String() string { switch c { case Optional: return "optional" case Required: return "required" case Repeated: return "repeated" default: return fmt.Sprintf("<unknown:%d>", c) } } // GoString returns c as a Go source identifier (e.g., "Optional"). func (c Cardinality) GoString() string { switch c { case Optional: return "Optional" case Required: return "Required" case Repeated: return "Repeated" default: return fmt.Sprintf("Cardinality(%d)", c) } } // Kind indicates the basic proto kind of a field. type Kind kind type kind int8 // keep exact type opaque as the int type may change // Constants as defined by the google.protobuf.Field.Kind enumeration. const ( BoolKind Kind = 8 EnumKind Kind = 14 Int32Kind Kind = 5 Sint32Kind Kind = 17 Uint32Kind Kind = 13 Int64Kind Kind = 3 Sint64Kind Kind = 18 Uint64Kind Kind = 4 Sfixed32Kind Kind = 15 Fixed32Kind Kind = 7 FloatKind Kind = 2 Sfixed64Kind Kind = 16 Fixed64Kind Kind = 6 DoubleKind Kind = 1 StringKind Kind = 9 BytesKind Kind = 12 MessageKind Kind = 11 GroupKind Kind = 10 ) // IsValid reports whether the kind is valid. func (k Kind) IsValid() bool { switch k { case BoolKind, EnumKind, Int32Kind, Sint32Kind, Uint32Kind, Int64Kind, Sint64Kind, Uint64Kind, Sfixed32Kind, Fixed32Kind, FloatKind, Sfixed64Kind, Fixed64Kind, DoubleKind, StringKind, BytesKind, MessageKind, GroupKind: return true default: return false } } // String returns k as a proto source identifier (e.g., "bool"). func (k Kind) String() string { switch k { case BoolKind: return "bool" case EnumKind: return "enum" case Int32Kind: return "int32" case Sint32Kind: return "sint32" case Uint32Kind: return "uint32" case Int64Kind: return "int64" case Sint64Kind: return "sint64" case Uint64Kind: return "uint64" case Sfixed32Kind: return "sfixed32" case Fixed32Kind: return "fixed32" case FloatKind: return "float" case Sfixed64Kind: return "sfixed64" case Fixed64Kind: return "fixed64" case DoubleKind: return "double" case StringKind: return "string" case BytesKind: return "bytes" case MessageKind: return "message" case GroupKind: return "group" default: return fmt.Sprintf("<unknown:%d>", k) } } // GoString returns k as a Go source identifier (e.g., "BoolKind"). func (k Kind) GoString() string { switch k { case BoolKind: return "BoolKind" case EnumKind: return "EnumKind" case Int32Kind: return "Int32Kind" case Sint32Kind: return "Sint32Kind" case Uint32Kind: return "Uint32Kind" case Int64Kind: return "Int64Kind" case Sint64Kind: return "Sint64Kind" case Uint64Kind: return "Uint64Kind" case Sfixed32Kind: return "Sfixed32Kind" case Fixed32Kind: return "Fixed32Kind" case FloatKind: return "FloatKind" case Sfixed64Kind: return "Sfixed64Kind" case Fixed64Kind: return "Fixed64Kind" case DoubleKind: return "DoubleKind" case StringKind: return "StringKind" case BytesKind: return "BytesKind" case MessageKind: return "MessageKind" case GroupKind: return "GroupKind" default: return fmt.Sprintf("Kind(%d)", k) } } // FieldNumber is the field number in a message. type FieldNumber = protowire.Number // FieldNumbers represent a list of field numbers. type FieldNumbers interface { // Len reports the number of fields in the list. Len() int // Get returns the ith field number. It panics if out of bounds. Get(i int) FieldNumber // Has reports whether n is within the list of fields. Has(n FieldNumber) bool doNotImplement } // FieldRanges represent a list of field number ranges. type FieldRanges interface { // Len reports the number of ranges in the list. Len() int // Get returns the ith range. It panics if out of bounds. Get(i int) [2]FieldNumber // start inclusive; end exclusive // Has reports whether n is within any of the ranges. Has(n FieldNumber) bool doNotImplement } // EnumNumber is the numeric value for an enum. type EnumNumber int32 // EnumRanges represent a list of enum number ranges. type EnumRanges interface { // Len reports the number of ranges in the list. Len() int // Get returns the ith range. It panics if out of bounds. Get(i int) [2]EnumNumber // start inclusive; end inclusive // Has reports whether n is within any of the ranges. Has(n EnumNumber) bool doNotImplement } var ( regexName = regexp.MustCompile(`^[_a-zA-Z][_a-zA-Z0-9]*$`) regexFullName = regexp.MustCompile(`^[_a-zA-Z][_a-zA-Z0-9]*(\.[_a-zA-Z][_a-zA-Z0-9]*)*$`) ) // Name is the short name for a proto declaration. This is not the name // as used in Go source code, which might not be identical to the proto name. type Name string // e.g., "Kind" // IsValid reports whether n is a syntactically valid name. // An empty name is invalid. func (n Name) IsValid() bool { return regexName.MatchString(string(n)) } // Names represent a list of names. type Names interface { // Len reports the number of names in the list. Len() int // Get returns the ith name. It panics if out of bounds. Get(i int) Name // Has reports whether s matches any names in the list. Has(s Name) bool doNotImplement } // FullName is a qualified name that uniquely identifies a proto declaration. // A qualified name is the concatenation of the proto package along with the // fully-declared name (i.e., name of parent preceding the name of the child), // with a '.' delimiter placed between each Name. // // This should not have any leading or trailing dots. type FullName string // e.g., "google.protobuf.Field.Kind" // IsValid reports whether n is a syntactically valid full name. // An empty full name is invalid. func (n FullName) IsValid() bool { return regexFullName.MatchString(string(n)) } // Name returns the short name, which is the last identifier segment. // A single segment FullName is the Name itself. func (n FullName) Name() Name { if i := strings.LastIndexByte(string(n), '.'); i >= 0 { return Name(n[i+1:]) } return Name(n) } // Parent returns the full name with the trailing identifier removed. // A single segment FullName has no parent. func (n FullName) Parent() FullName { if i := strings.LastIndexByte(string(n), '.'); i >= 0 { return n[:i] } return "" } // Append returns the qualified name appended with the provided short name. // // Invariant: n == n.Parent().Append(n.Name()) // assuming n is valid func (n FullName) Append(s Name) FullName { if n == "" { return FullName(s) } return n + "." + FullName(s) }
pberndro/smartpi_exporter
vendor/google.golang.org/protobuf/reflect/protoreflect/proto.go
GO
gpl-3.0
15,836
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.mozstumbler.service.stumblerthread.datahandling; import org.json.JSONObject; import org.mozilla.mozstumbler.service.stumblerthread.datahandling.base.SerializedJSONRows; import org.mozilla.mozstumbler.service.stumblerthread.datahandling.base.JSONRowsObjectBuilder; import org.mozilla.mozstumbler.service.utils.Zipper; /* ReportBatchBuilder accepts MLS GeoSubmit JSON blobs and serializes them to string form. */ public class ReportBatchBuilder extends JSONRowsObjectBuilder { public int getCellCount() { int result = 0; for (JSONObject obj: mJSONEntries) { assert(obj instanceof MLSJSONObject); result += ((MLSJSONObject) obj).getCellCount(); } return result; } public int getWifiCount() { int result = 0; for (JSONObject obj : mJSONEntries) { assert(obj instanceof MLSJSONObject); result += ((MLSJSONObject) obj).getWifiCount(); } return result; } @Override public SerializedJSONRows finalizeToJSONRowsObject() { int obs = entriesCount(); int wifis = getWifiCount(); int cells = getCellCount(); boolean preserveDataAfterGenerateJSON = false; byte[] zippedbytes = Zipper.zipData(generateJSON(preserveDataAfterGenerateJSON).getBytes()); return new ReportBatch(zippedbytes, SerializedJSONRows.StorageState.IN_MEMORY, obs, wifis, cells); } }
petercpg/MozStumbler
libraries/stumbler/src/main/java/org/mozilla/mozstumbler/service/stumblerthread/datahandling/ReportBatchBuilder.java
Java
mpl-2.0
1,691
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.core.util; import org.apache.log4j.Logger; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; /** * Provide an incremental per VM unique ID * * unique id starts from zero and is incremented each time getUniqID is called. * If Long.MAX_VALUE is reached then then IllegalStateArgument exception is thrown * * @See {@link ProActiveRandom} * */ public class ProActiveCounter { static Logger logger = ProActiveLogger.getLogger(Loggers.CORE); static long counter = 0; synchronized static public long getUniqID() { if (counter == Long.MAX_VALUE) { throw new IllegalStateException(ProActiveCounter.class.getSimpleName() + " counter reached max value"); } else { return counter++; } } }
moliva/proactive
src/Core/org/objectweb/proactive/core/util/ProActiveCounter.java
Java
agpl-3.0
2,303
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2013-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.features.vaadin.nodemaps.internal.gwt.client; import org.discotools.gwt.leaflet.client.jsobject.JSObject; import org.discotools.gwt.leaflet.client.types.LatLng; public class SearchResult extends JSObject { protected SearchResult() {} public static final SearchResult create(final String title, final LatLng latLng) { final SearchResult result = JSObject.createJSObject().cast(); result.setTitle(title); result.setLatLng(latLng); return result; } public final String getTitle() { return getPropertyAsString("title"); } public final SearchResult setTitle(final String title) { setProperty("title", title); return this; } public final LatLng getLatLng() { return new LatLng(getProperty("latLng")); } public final SearchResult setLatLng(final LatLng latLng) { setProperty("latLng", latLng.getJSObject()); return this; } }
rdkgit/opennms
features/vaadin-node-maps/src/main/java/org/opennms/features/vaadin/nodemaps/internal/gwt/client/SearchResult.java
Java
agpl-3.0
2,174
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.extensions.annotation.common; import com.sun.mirror.apt.AnnotationProcessor; /** This annotation processor processes the annotations provided by default * whith JDK 1.5. This is needed in order to suppress the unnecessary warnings that * apt generates for these default annotations. * See also http://forums.sun.com/thread.jspa?threadID=5345947 * @author fabratu * @version %G%, %I% * @since ProActive 4.10 */ public class BogusAnnotationProcessor implements AnnotationProcessor { public BogusAnnotationProcessor() { } public void process() { // nothing! } }
moliva/proactive
src/Extensions/org/objectweb/proactive/extensions/annotation/common/BogusAnnotationProcessor.java
Java
agpl-3.0
2,065
<?php /** * @package api * @subpackage filters.enum */ class KalturaFileAssetOrderBy extends KalturaStringEnum { const CREATED_AT_ASC = "+createdAt"; const CREATED_AT_DESC = "-createdAt"; const UPDATED_AT_ASC = "+updatedAt"; const UPDATED_AT_DESC = "-updatedAt"; }
ratliff/server
api_v3/lib/types/fileAsset/filters/orderEnums/KalturaFileAssetOrderBy.php
PHP
agpl-3.0
272
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.vacuumd; /** * <p>AutomationException class.</p> * * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> * @version $Id: $ */ public class AutomationException extends RuntimeException { private static final long serialVersionUID = -8873671974245928627L; /** * <p>Constructor for AutomationException.</p> * * @param arg0 a {@link java.lang.String} object. */ public AutomationException(String arg0) { super(arg0); } /** * <p>Constructor for AutomationException.</p> * * @param arg0 a {@link java.lang.Throwable} object. */ public AutomationException(Throwable arg0) { super(arg0); } /** * <p>Constructor for AutomationException.</p> * * @param arg0 a {@link java.lang.String} object. * @param arg1 a {@link java.lang.Throwable} object. */ public AutomationException(String arg0, Throwable arg1) { super(arg0, arg1); } }
tdefilip/opennms
opennms-services/src/main/java/org/opennms/netmgt/vacuumd/AutomationException.java
Java
agpl-3.0
2,125
# # Copyright (C) 2011 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require File.expand_path(File.dirname(__FILE__) + '/../views_helper') describe "/quizzes/submission_versions" do it "should render" do course_with_teacher(:active_all => true) course_quiz view_context ActiveRecord::Base.clear_cached_contexts assigns[:quiz] = @quiz assigns[:versions] = [] render "quizzes/submission_versions" response.should_not be_nil end end
SaranNV/canvas-lms
spec/views/quizzes/submission_versions.html.erb_spec.rb
Ruby
agpl-3.0
1,143
/* * Copyright (C) 2011 JTalks.org Team * 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 PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ var Utils = {}; function quote(postId, postNumber) { var callback = function (text) { $('#post').focus(); console.log(text); var answer = $('#postBody'); answer.focus(); if (answer) { answer.val(answer.val() + text); } } $.ajax({ url: baseUrl + '/posts/' + postId + '/quote', type: 'POST', data: { selection: getSelectedPostText(postNumber) }, success: function (data) { callback(data.result); }, error: function () { callback(''); } }); } function getSelectedPostText(postNumber) { var txt = ''; if (window.getSelection) { if (window.getSelection().toString().length > 0 && isRangeInPost(window.getSelection().getRangeAt(0)) && isSelectedPostQuoted(postNumber)) { txt = window.getSelection().toString(); } } else if (document.selection) { if (isRangeInPost(document.selection.createRange()) && isSelectedPostQuoted(postNumber)) { txt = document.selection.createRange().text; } } return txt; } /** * Checks if selected document fragment is a part of the post content. * @param {Range} range Range object which represent current selection. * @return {boolean} <b>true</b> if if selected document fragment is a part of the post content * <b>false</b> otherwise. */ function isRangeInPost(range) { return $(range.startContainer).closest(".post-content-body").length > 0; } /** * Checks if "quote" button pressed on the post which was selected. * @param {Number} postNumber number of the post on the page which "quote" button was pressed. * @return {boolean} <b>true</> if selected text is a part of the post which will be quoted * <b>false</b> otherwise. */ function isSelectedPostQuoted(postNumber) { return $(window.getSelection().getRangeAt(0).startContainer).closest('.post').prevAll().length == postNumber; } /** * Encodes given string by escaping special HTML characters * * @param s string to be encoded */ Utils.htmlEncode = function (s) { return $('<div/>').text(s).html(); }; /** * Do focus to element * * @param target selector of element to focus */ Utils.focusFirstEl = function (target) { $(target).focus(); } /** * Replaces all \n characters by <br> tags. Used for review comments. * * @param s string where perform replacing */ Utils.lf2br = function (s) { return s.replace(/\n/g, "<br>"); } /** * Replaces all \<br> tags by \n characters. Used for review comments. * * @param s string where perform replacing */ Utils.br2lf = function (s) { return s.replace(/<br>/gi, "\n"); } /** * Create form field with given label(placeholder), id, type, class and style. */ Utils.createFormElement = function (label, id, type, cls, style) { var elementHtml = ' \ <div class="control-group"> \ <div class="controls"> \ <input type="' + type + '" id="' + id + '" name="' + id + '" placeholder="' + label + '" class="input-xlarge ' + cls + '" style="'+ style +'" /> \ </div> \ </div> \ '; return elementHtml; } /** * Handling "onError" event for images if it's can't loaded. Invoke in config kefirbb.xml for [img] bbtag. * */ function imgError(image) { var imageDefault = baseUrl + "/resources/images/noimage.jpg"; image.src = imageDefault; image.className = "thumbnail-default"; image.parentNode.href = imageDefault; image.onerror = ""; }
illerax/jcommune
jcommune-view/jcommune-web-view/src/main/webapp/resources/javascript/app/utils.js
JavaScript
lgpl-2.1
4,376
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="hr" sourcelanguage="en"> <context> <name>CmdWebBrowserBack</name> <message> <location filename="../../Command.cpp" line="75"/> <source>Web</source> <translation type="unfinished">Web</translation> </message> <message> <location filename="../../Command.cpp" line="76"/> <source>Previous page</source> <translation type="unfinished">Previous page</translation> </message> <message> <location filename="../../Command.cpp" line="77"/> <source>Go back to the previous page</source> <translation type="unfinished">Go back to the previous page</translation> </message> </context> <context> <name>CmdWebBrowserNext</name> <message> <location filename="../../Command.cpp" line="103"/> <source>Web</source> <translation type="unfinished">Web</translation> </message> <message> <location filename="../../Command.cpp" line="104"/> <source>Next page</source> <translation type="unfinished">Next page</translation> </message> <message> <location filename="../../Command.cpp" line="105"/> <source>Go to the next page</source> <translation type="unfinished">Go to the next page</translation> </message> </context> <context> <name>CmdWebBrowserRefresh</name> <message> <location filename="../../Command.cpp" line="131"/> <source>Web</source> <translation type="unfinished">Web</translation> </message> <message> <location filename="../../Command.cpp" line="132"/> <location filename="../../Command.cpp" line="133"/> <source>Refresh web page</source> <translation type="unfinished">Refresh web page</translation> </message> </context> <context> <name>CmdWebBrowserStop</name> <message> <location filename="../../Command.cpp" line="158"/> <source>Web</source> <translation type="unfinished">Web</translation> </message> <message> <location filename="../../Command.cpp" line="159"/> <source>Stop loading</source> <translation type="unfinished">Stop loading</translation> </message> <message> <location filename="../../Command.cpp" line="160"/> <source>Stop the current loading</source> <translation type="unfinished">Stop the current loading</translation> </message> </context> <context> <name>CmdWebBrowserZoomIn</name> <message> <location filename="../../Command.cpp" line="187"/> <source>Web</source> <translation type="unfinished">Web</translation> </message> <message> <location filename="../../Command.cpp" line="188"/> <source>Zoom in</source> <translation type="unfinished">Zoom in</translation> </message> <message> <location filename="../../Command.cpp" line="189"/> <source>Zoom into the page</source> <translation type="unfinished">Zoom into the page</translation> </message> </context> <context> <name>CmdWebBrowserZoomOut</name> <message> <location filename="../../Command.cpp" line="215"/> <source>Web</source> <translation type="unfinished">Web</translation> </message> <message> <location filename="../../Command.cpp" line="216"/> <source>Zoom out</source> <translation type="unfinished">Zoom out</translation> </message> <message> <location filename="../../Command.cpp" line="217"/> <source>Zoom out of the page</source> <translation type="unfinished">Zoom out of the page</translation> </message> </context> <context> <name>CmdWebOpenWebsite</name> <message> <location filename="../../Command.cpp" line="50"/> <source>Web</source> <translation type="unfinished">Web</translation> </message> <message> <location filename="../../Command.cpp" line="51"/> <source>Open website...</source> <translation type="unfinished">Open website...</translation> </message> <message> <location filename="../../Command.cpp" line="52"/> <source>Opens a website in FreeCAD</source> <translation type="unfinished">Opens a website in FreeCAD</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../../AppWebGui.cpp" line="78"/> <location filename="../../BrowserView.cpp" line="348"/> <source>Browser</source> <translation type="unfinished">Browser</translation> </message> <message> <location filename="../../BrowserView.cpp" line="244"/> <source>File does not exist!</source> <translation type="unfinished">File does not exist!</translation> </message> </context> <context> <name>WebGui::BrowserView</name> <message> <location filename="../../BrowserView.cpp" line="239"/> <source>Error</source> <translation>Pogreška</translation> </message> <message> <location filename="../../BrowserView.cpp" line="319"/> <source>Loading %1...</source> <translation type="unfinished">Loading %1...</translation> </message> </context> <context> <name>WebGui::WebView</name> <message> <location filename="../../BrowserView.cpp" line="121"/> <source>Open in External Browser</source> <translation type="unfinished">Open in External Browser</translation> </message> <message> <location filename="../../BrowserView.cpp" line="125"/> <source>Open in new window</source> <translation type="unfinished">Open in new window</translation> </message> </context> <context> <name>Workbench</name> <message> <location filename="../../Workbench.cpp" line="46"/> <source>Navigation</source> <translation type="unfinished">Navigation</translation> </message> </context> </TS>
wood-galaxy/FreeCAD
src/Mod/Web/Gui/Resources/translations/Web_hr.ts
TypeScript
lgpl-2.1
6,073
'use strict'; /** * @module br/util/Number */ var StringUtility = require('br/util/StringUtility'); /** * @class * @alias module:br/util/Number * * @classdesc * Utility methods for numbers */ function NumberUtil() { } /** * Returns a numeric representation of the sign on the number. * * @param {Number} n The number (or a number as a string) * @return {int} 1 for positive values, -1 for negative values, or the original value for zero and non-numeric values. */ NumberUtil.sgn = function(n) { return n > 0 ? 1 : n < 0 ? -1 : n; }; /** * @param {Object} n * @return {boolean} true for numbers and their string representations and false for other values including non-numeric * strings, null, Infinity, NaN. */ NumberUtil.isNumber = function(n) { if (typeof n === 'string') { n = n.trim(); } return n != null && n !== '' && n - n === 0; }; /** * Formats the number to the specified number of decimal places. * * @param {Number} n The number (or a number as a string). * @param {Number} dp The number of decimal places. * @return {String} The formatted number. */ NumberUtil.toFixed = function(n, dp) { //return this.isNumber(n) && dp != null ? Number(n).toFixed(dp) : n; //Workaround for IE8/7/6 where toFixed returns 0 for (0.5).toFixed(0) and 0.0 for (0.05).toFixed(1) if (this.isNumber(n) && dp != null) { var sgn = NumberUtil.sgn(n); n = sgn * n; var nFixed = (Math.round(Math.pow(10, dp)*n)/Math.pow(10, dp)).toFixed(dp); return (sgn * nFixed).toFixed(dp); } return n; }; /** * Formats the number to the specified number of significant figures. This fixes the bugs in the native Number function * of the same name that are prevalent in various browsers. If the number of significant figures is less than one, * then the function has no effect. * * @param {Number} n The number (or a number as a string). * @param {Number} sf The number of significant figures. * @return {String} The formatted number. */ NumberUtil.toPrecision = function(n, sf) { return this.isNumber(n) && sf > 0 ? Number(n).toPrecision(sf) : n; }; /** * Formats the number to the specified number of decimal places, omitting any trailing zeros. * * @param {Number} n The number (or a number as a string). * @param {Number} rounding The number of decimal places to round. * @return {String} The rounded number. */ NumberUtil.toRounded = function(n, rounding) { //return this.isNumber(n) && rounding != null ? String(Number(Number(n).toFixed(rounding))) : n; //Workaround for IE8/7/6 where toFixed returns 0 for (0.5).toFixed(0) and 0.0 for (0.05).toFixed(1) if (this.isNumber(n) && rounding != null) { var sgn = NumberUtil.sgn(n); n = sgn * n; var nRounded = (Math.round(Math.pow(10, rounding)*n)/Math.pow(10, rounding)).toFixed(rounding); return sgn * nRounded; } return n; }; /** * Logarithm to base 10. * * @param {Number} n The number (or a number as a string). * @return {Number} The logarithm to base 10. */ NumberUtil.log10 = function(n) { return Math.log(n) / Math.LN10; }; /** * Rounds a floating point number * * @param {Number} n The number (or a number as a string). * @return {Number} The formatted number. */ NumberUtil.round = function(n) { var dp = 13 - (n ? Math.ceil(this.log10(Math.abs(n))) : 0); return this.isNumber(n) ? Number(Number(n).toFixed(dp)) : n; }; /** * Pads the integer part of a number with zeros to reach the specified length. * * @param {Number} value The number (or a number as a string). * @param {Number} numLength The required length of the number. * @return {String} The formatted number. */ NumberUtil.pad = function(value, numLength) { if (this.isNumber(value)) { var nAbsolute = Math.abs(value); var sInteger = new String(parseInt(nAbsolute)); var nSize = numLength || 0; var sSgn = value < 0 ? "-" : ""; value = sSgn + StringUtility.repeat("0", nSize - sInteger.length) + nAbsolute; } return value; }; /** * Counts the amount of decimal places within a number. * Also supports scientific notations * * @param {Number} n The number (or a number as a string). * @return {Number} The number of decimal places */ NumberUtil.decimalPlaces = function(n) { var match = (''+n).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); if (!match) { return 0; } return Math.max( 0, // Number of digits right of decimal point. (match[1] ? match[1].length : 0) // Adjust for scientific notation. - (match[2] ? +match[2] : 0)); } module.exports = NumberUtil;
andreoid/testing
brjs-sdk/workspace/sdk/libs/javascript/br-util/src/br/util/Number.js
JavaScript
lgpl-3.0
4,499
/* Copyright 2012 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.hraven.etl; import java.util.concurrent.Callable; import org.apache.hadoop.mapreduce.Job; /** * Can be used to run a single Hadoop job. The {@link #call()} method will block * until the job is complete and will return a non-null return value indicating * the success of the Hadoop job. */ public class JobRunner implements Callable<Boolean> { private volatile boolean isCalled = false; private final Job job; /** * Post processing step that gets called upon successful completion of the * Hadoop job. */ private final Callable<Boolean> postProcessor; /** * Constructor * * @param job * to job to run in the call method. * @param postProcessor * Post processing step that gets called upon successful completion * of the Hadoop job. Can be null, in which case it will be skipped. * Final results will be the return value of this final processing * step. */ public JobRunner(Job job, Callable<Boolean> postProcessor) { this.job = job; this.postProcessor = postProcessor; } /* * (non-Javadoc) * * @see java.util.concurrent.Callable#call() */ @Override public Boolean call() throws Exception { // Guard to make sure we get called only once. if (isCalled) { return false; } else { isCalled = true; } if (job == null) { return false; } boolean success = false; // Schedule the job on the JobTracker and wait for it to complete. try { success = job.waitForCompletion(true); } catch (InterruptedException interuptus) { // We're told to stop, so honor that. // And restore interupt status. Thread.currentThread().interrupt(); // Indicate that we should NOT run the postProcessor. success = false; } if (success && (postProcessor != null)) { success = postProcessor.call(); } return success; } }
ogre0403/hraven
hraven-etl/src/main/java/com/twitter/hraven/etl/JobRunner.java
Java
apache-2.0
2,525
//// [tests/cases/compiler/moduleAugmentationsImports4.ts] //// //// [a.ts] export class A {} //// [b.ts] export class B {x: number;} //// [c.d.ts] declare module "C" { class Cls {y: string; } } //// [d.d.ts] declare module "D" { import {A} from "a"; import {B} from "b"; module "a" { interface A { getB(): B; } } } //// [e.d.ts] /// <reference path="c.d.ts"/> declare module "E" { import {A} from "a"; import {Cls} from "C"; module "a" { interface A { getCls(): Cls; } } } //// [main.ts] /// <reference path="d.d.ts"/> /// <reference path="e.d.ts"/> import {A} from "./a"; import "D"; import "E"; let a: A; let b = a.getB().x.toFixed(); let c = a.getCls().y.toLowerCase(); //// [f.js] define("a", ["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; var A = /** @class */ (function () { function A() { } return A; }()); exports.A = A; }); define("b", ["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; var B = /** @class */ (function () { function B() { } return B; }()); exports.B = B; }); define("main", ["require", "exports", "D", "E"], function (require, exports) { "use strict"; exports.__esModule = true; var a; var b = a.getB().x.toFixed(); var c = a.getCls().y.toLowerCase(); }); //// [f.d.ts] /// <reference path="tests/cases/compiler/d.d.ts" /> /// <reference path="tests/cases/compiler/e.d.ts" /> declare module "a" { export class A { } } declare module "b" { export class B { x: number; } } declare module "main" { import "D"; import "E"; }
weswigham/TypeScript
tests/baselines/reference/moduleAugmentationsImports4.js
JavaScript
apache-2.0
1,844
""" Component-level Specification This module is called component to mirror organization of storm package. """ from ..storm.component import Component class Specification(object): def __init__(self, component_cls, name=None, parallelism=1): if not issubclass(component_cls, Component): raise TypeError("Invalid component: {}".format(component_cls)) if not isinstance(parallelism, int) or parallelism < 1: raise ValueError("Parallelism must be a integer greater than 0") self.component_cls = component_cls self.name = name self.parallelism = parallelism def resolve_dependencies(self, specifications): """Allows specification subclasses to resolve an dependencies that they may have on other specifications. :param specifications: all of the specification objects for this topology. :type specifications: dict """ pass
hodgesds/streamparse
streamparse/dsl/component.py
Python
apache-2.0
976
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.fuseki.servlets; import org.apache.jena.query.Dataset ; import org.apache.jena.query.DatasetFactory ; import org.apache.jena.query.Query ; import org.apache.jena.sparql.core.DatasetDescription ; import org.apache.jena.sparql.core.DatasetGraph ; import org.apache.jena.sparql.core.DynamicDatasets ; public class SPARQL_QueryDataset extends SPARQL_Query { public SPARQL_QueryDataset(boolean verbose) { super() ; } public SPARQL_QueryDataset() { this(false) ; } @Override protected void validateRequest(HttpAction action) { } @Override protected void validateQuery(HttpAction action, Query query) { } @Override protected Dataset decideDataset(HttpAction action, Query query, String queryStringLog) { DatasetGraph dsg = action.getActiveDSG() ; // query.getDatasetDescription() ; // Protocol. DatasetDescription dsDesc = getDatasetDescription(action) ; if (dsDesc != null ) { //errorBadRequest("SPARQL Query: Dataset description in the protocol request") ; dsg = DynamicDatasets.dynamicDataset(dsDesc, dsg, false) ; } return DatasetFactory.create(dsg) ; } }
adrapereira/jena
jena-fuseki2/jena-fuseki-core/src/main/java/org/apache/jena/fuseki/servlets/SPARQL_QueryDataset.java
Java
apache-2.0
2,072
/* * Copyright 2014 Click Travel Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.clicktravel.cheddar.rest.exception.mapper.cdm1; import static com.clicktravel.cheddar.rest.exception.mapper.cdm1.JsonProcessingExceptionMapperUtils.buildErrorResponse; import javax.annotation.Priority; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParseException; @Provider @Priority(Integer.MAX_VALUE) public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public Response toResponse(final JsonParseException exception) { if (logger.isDebugEnabled()) { logger.debug(exception.getMessage(), exception); } return Response.status(Response.Status.BAD_REQUEST).entity(buildErrorResponse(exception)).build(); } }
clicktravel-james/Cheddar
cheddar/cheddar-rest/src/main/java/com/clicktravel/cheddar/rest/exception/mapper/cdm1/JsonParseExceptionMapper.java
Java
apache-2.0
1,551
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl; import com.intellij.lang.ASTFactory; import com.intellij.lang.Commenter; import com.intellij.lang.Language; import com.intellij.lang.LanguageCommenters; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.impl.source.DummyHolderFactory; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.FileElement; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public final class PsiParserFacadeImpl implements PsiParserFacade { private final PsiManagerEx myManager; public PsiParserFacadeImpl(@NotNull Project project) { myManager = PsiManagerEx.getInstanceEx(project); } @Override @NotNull public PsiElement createWhiteSpaceFromText(@NotNull @NonNls String text) throws IncorrectOperationException { final FileElement holderElement = DummyHolderFactory.createHolder(myManager, null).getTreeElement(); final LeafElement newElement = ASTFactory.leaf(TokenType.WHITE_SPACE, holderElement.getCharTable().intern(text)); holderElement.rawAddChildren(newElement); GeneratedMarkerVisitor.markGenerated(newElement.getPsi()); return newElement.getPsi(); } @Override @NotNull public PsiComment createLineCommentFromText(@NotNull LanguageFileType fileType, @NotNull String text) throws IncorrectOperationException { return createLineCommentFromText(fileType.getLanguage(), text); } @Override @NotNull public PsiComment createLineCommentFromText(@NotNull final Language language, @NotNull final String text) throws IncorrectOperationException { Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(language); assert commenter != null; String prefix = commenter.getLineCommentPrefix(); if (prefix == null) { throw new IncorrectOperationException("No line comment prefix defined for language " + language.getID()); } PsiFile aFile = createDummyFile(language, prefix + text); return findPsiCommentChild(aFile); } @NotNull @Override public PsiComment createBlockCommentFromText(@NotNull Language language, @NotNull String text) throws IncorrectOperationException { Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(language); assert commenter != null : language; final String blockCommentPrefix = commenter.getBlockCommentPrefix(); final String blockCommentSuffix = commenter.getBlockCommentSuffix(); assert blockCommentPrefix != null && blockCommentSuffix != null; PsiFile aFile = createDummyFile(language, blockCommentPrefix + text + blockCommentSuffix); return findPsiCommentChild(aFile); } @Override @NotNull public PsiComment createLineOrBlockCommentFromText(@NotNull Language language, @NotNull String text) throws IncorrectOperationException { Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(language); assert commenter != null : language; String prefix = commenter.getLineCommentPrefix(); final String blockCommentPrefix = commenter.getBlockCommentPrefix(); final String blockCommentSuffix = commenter.getBlockCommentSuffix(); assert prefix != null || (blockCommentPrefix != null && blockCommentSuffix != null); PsiFile aFile = createDummyFile(language, prefix != null ? (prefix + text) : (blockCommentPrefix + text + blockCommentSuffix)); return findPsiCommentChild(aFile); } private PsiComment findPsiCommentChild(PsiFile aFile) { PsiComment comment = PsiTreeUtil.findChildOfType(aFile, PsiComment.class); if (comment == null) { throw new IncorrectOperationException("Incorrect comment \"" + aFile.getText() + "\"."); } DummyHolderFactory.createHolder(myManager, (TreeElement)SourceTreeToPsiMap.psiElementToTree(comment), null); return comment; } private PsiFile createDummyFile(final Language language, String text) { return PsiFileFactory.getInstance(myManager.getProject()).createFileFromText("_Dummy_", language, text); } }
siosio/intellij-community
platform/core-impl/src/com/intellij/psi/impl/PsiParserFacadeImpl.java
Java
apache-2.0
4,617
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.net.intent; import java.util.List; import java.util.Optional; import com.google.common.annotations.Beta; import org.onlab.packet.MplsLabel; import org.onosproject.core.ApplicationId; import org.onosproject.net.Path; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.TrafficTreatment; import static com.google.common.base.Preconditions.checkNotNull; /** * Abstraction of explicit MPLS label-switched path. */ @Beta public final class MplsPathIntent extends PathIntent { private final Optional<MplsLabel> ingressLabel; private final Optional<MplsLabel> egressLabel; /** * Creates a new point-to-point intent with the supplied ingress/egress * ports and using the specified explicit path. * * @param appId application identifier * @param selector traffic selector * @param treatment treatment * @param path traversed links * @param ingressLabel MPLS egress label * @param egressLabel MPLS ingress label * @param constraints optional list of constraints * @param priority priority to use for flows generated by this intent * @throws NullPointerException {@code path} is null */ private MplsPathIntent(ApplicationId appId, TrafficSelector selector, TrafficTreatment treatment, Path path, Optional<MplsLabel> ingressLabel, Optional<MplsLabel> egressLabel, List<Constraint> constraints, int priority) { super(appId, selector, treatment, path, constraints, priority); this.ingressLabel = checkNotNull(ingressLabel); this.egressLabel = checkNotNull(egressLabel); } /** * Returns a new host to host intent builder. * * @return host to host intent builder */ public static Builder builder() { return new Builder(); } /** * Builder of a host to host intent. */ public static final class Builder extends PathIntent.Builder { private Optional<MplsLabel> ingressLabel = Optional.empty(); private Optional<MplsLabel> egressLabel = Optional.empty(); private Builder() { // Hide constructor } @Override public Builder appId(ApplicationId appId) { return (Builder) super.appId(appId); } @Override public Builder key(Key key) { return (Builder) super.key(key); } @Override public Builder selector(TrafficSelector selector) { return (Builder) super.selector(selector); } @Override public Builder treatment(TrafficTreatment treatment) { return (Builder) super.treatment(treatment); } @Override public Builder constraints(List<Constraint> constraints) { return (Builder) super.constraints(constraints); } @Override public Builder priority(int priority) { return (Builder) super.priority(priority); } @Override public Builder path(Path path) { return (Builder) super.path(path); } /** * Sets the ingress label of the intent that will be built. * * @param ingressLabel ingress label * @return this builder */ public Builder ingressLabel(Optional<MplsLabel> ingressLabel) { this.ingressLabel = ingressLabel; return this; } /** * Sets the ingress label of the intent that will be built. * * @param egressLabel ingress label * @return this builder */ public Builder egressLabel(Optional<MplsLabel> egressLabel) { this.egressLabel = egressLabel; return this; } /** * Builds a host to host intent from the accumulated parameters. * * @return point to point intent */ public MplsPathIntent build() { return new MplsPathIntent( appId, selector, treatment, path, ingressLabel, egressLabel, constraints, priority ); } } /** * Returns the MPLS label which the ingress traffic should tagged. * * @return ingress MPLS label */ public Optional<MplsLabel> ingressLabel() { return ingressLabel; } /** * Returns the MPLS label which the egress traffic should tagged. * * @return egress MPLS label */ public Optional<MplsLabel> egressLabel() { return egressLabel; } }
Zhengzl15/onos-securearp
core/api/src/main/java/org/onosproject/net/intent/MplsPathIntent.java
Java
apache-2.0
5,350
interface JavaInterface { void foo(Object p); } class JavaClass1 implements JavaInterface { @Override public void foo(Object <caret>p) { System.out.println(<flown1>p); } } class JavaClass2 implements JavaInterface { @Override public void foo(Object p) { System.err.println(p); } }
siosio/intellij-community
java/java-tests/testData/codeInsight/slice/forward/OneInterfaceTwoImplementations.java
Java
apache-2.0
304
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.msgs.restricted; import com.google.template.soy.msgs.SoyMsgException; import java.util.EnumMap; import java.util.EnumSet; import java.util.Locale; import java.util.Objects; /** * Represents a plural case value. * * A plural case value can be either a number, or one of {@code ZERO}, {@code ONE}, {@code TWO}, * {@code FEW}, {@code MANY} or {@code OTHER}. Here, a number is represented by the number * {@code explicitValue} with status set to EXPLICIT and the remaining by an enum value. * */ public class SoyMsgPluralCaseSpec { /** The type. EXPLICIT indicating numeric, or one of the others indicating non-numeric. */ public enum Type { EXPLICIT, ZERO, ONE, TWO, FEW, MANY, OTHER } /** Internal mapping of Type to String, reduces memory usage */ private static final EnumMap<Type, String> TYPE_TO_STRING = new EnumMap<>(Type.class); static { for (Type t : EnumSet.allOf(Type.class)) { TYPE_TO_STRING.put(t, t.name().toLowerCase(Locale.ENGLISH)); } } /** ZERO, ONE, TWO, FEW, MANY or OTHER if the type is non-numeric, or EXPLICIT if numeric. */ private final Type type; /** The numeric value if the type is numeric, -1 otherwise. */ private final int explicitValue; /** * Constructs an object from a non-numeric value. * The field type is set to an enum value corresponding to the string given, and explicitValue * is set to -1. * @param typeStr String representation of the non-numeric value. * @throws IllegalArgumentException if typeStr (after converting to upper * case) does not match with any of the enum types. */ public SoyMsgPluralCaseSpec(String typeStr) { type = Type.valueOf(typeStr.toUpperCase(Locale.ENGLISH)); explicitValue = -1; } /** * Constructs an object from a numeric value. * The field type is set to EXPLICIT, and explicitValue is set to the numeric value given. * @param explicitValue The numeric value. * @throws SoyMsgException if invalid numeric value. */ public SoyMsgPluralCaseSpec(int explicitValue) { if (explicitValue >= 0) { type = Type.EXPLICIT; this.explicitValue = explicitValue; } else { throw new SoyMsgException("Negative plural case value."); } } /** * Get the type. * @return The type. EXPLICIT if numeric. */ public Type getType() { return type; } /** * Get the numeric value. * @return if numeric, return the numeric value, else -1. */ public int getExplicitValue() { return explicitValue; } @Override public String toString() { return (type == Type.EXPLICIT) ? "=" + explicitValue : TYPE_TO_STRING.get(type); } @Override public boolean equals(Object other) { if (!(other instanceof SoyMsgPluralCaseSpec)) { return false; } SoyMsgPluralCaseSpec otherSpec = (SoyMsgPluralCaseSpec) other; return type == otherSpec.type && explicitValue == otherSpec.explicitValue; } @Override public int hashCode() { return Objects.hash(SoyMsgPluralCaseSpec.class, type, explicitValue); } }
oujesky/closure-templates
java/src/com/google/template/soy/msgs/restricted/SoyMsgPluralCaseSpec.java
Java
apache-2.0
3,688
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.dmn.client.editors.included; import java.util.List; import com.google.gwtmockito.GwtMockitoTestRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.dmn.client.editors.included.common.IncludedModelsPageStateProvider; import org.mockito.Mock; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(GwtMockitoTestRunner.class) public class IncludedModelsPageStateTest { @Mock private IncludedModelsPageStateProvider pageProvider; private IncludedModelsPageState state; @Before public void setup() { state = new IncludedModelsPageState(); } @Test public void testGetCurrentDiagramNamespaceWhenPageProviderIsPresent() { final String expectedNamespace = "://namespace"; when(pageProvider.getCurrentDiagramNamespace()).thenReturn(expectedNamespace); state.init(pageProvider); final String actualNamespace = state.getCurrentDiagramNamespace(); assertEquals(expectedNamespace, actualNamespace); } @Test public void testGetCurrentDiagramNamespaceWhenPageProviderIsNotPresent() { final String expectedNamespace = ""; state.init(null); final String actualNamespace = state.getCurrentDiagramNamespace(); assertEquals(expectedNamespace, actualNamespace); } @Test public void testGenerateIncludedModelsWhenPageProviderIsNotPresent() { state.init(null); final List<BaseIncludedModelActiveRecord> actualIncludedModels = state.generateIncludedModels(); final List<BaseIncludedModelActiveRecord> expectedIncludedModels = emptyList(); assertEquals(expectedIncludedModels, actualIncludedModels); } @Test public void testGenerateIncludedModelsWhenPageProviderIsPresent() { final List<BaseIncludedModelActiveRecord> expectedIncludedModels = asList(mock(BaseIncludedModelActiveRecord.class), mock(BaseIncludedModelActiveRecord.class)); when(pageProvider.generateIncludedModels()).thenReturn(expectedIncludedModels); state.init(pageProvider); final List<BaseIncludedModelActiveRecord> actualIncludedModels = state.generateIncludedModels(); assertEquals(actualIncludedModels, expectedIncludedModels); } }
jomarko/kie-wb-common
kie-wb-common-dmn/kie-wb-common-dmn-client/src/test/java/org/kie/workbench/common/dmn/client/editors/included/IncludedModelsPageStateTest.java
Java
apache-2.0
3,116
/* * Copyright 2017 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.web.dao.stat; import com.navercorp.pinpoint.common.server.bo.stat.DeadlockThreadCountBo; /** * @author Taejin Koo */ public interface DeadlockDao extends AgentStatDao<DeadlockThreadCountBo> { }
barneykim/pinpoint
web/src/main/java/com/navercorp/pinpoint/web/dao/stat/DeadlockDao.java
Java
apache-2.0
825
/// <reference path='fourslash.ts' /> //@Filename: file.tsx //// declare module JSX { //// interface Element { } //// interface IntrinsicElements { //// [|[|{| "isWriteAccess": true, "isDefinition": true, "contextRangeIndex": 0 |}div|]: { //// name?: string; //// isOpen?: boolean; //// };|] //// span: { n: string; }; //// } //// } //// var x = [|<[|{| "contextRangeIndex": 2 |}div|] />|]; verify.singleReferenceGroup( `(property) JSX.IntrinsicElements.div: { name?: string; isOpen?: boolean; }`, "div");
microsoft/TypeScript
tests/cases/fourslash/tsxFindAllReferences1.ts
TypeScript
apache-2.0
600
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ #include <stdio.h> #include <string.h> #include <fcntl.h> #include <assert.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <net/if.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/if_packet.h> #include "base/logging.h" #include "cmn/agent_cmn.h" #include "sandesh/sandesh_types.h" #include "sandesh/sandesh.h" #include "sandesh/sandesh_trace.h" #include "pkt/pkt_types.h" #include "pkt/pkt_init.h" #include "../pkt0_interface.h" #define TUN_INTF_CLONE_DEV "/dev/net/tun" #define TAP_TRACE(obj, ...) \ do { \ Tap##obj::TraceMsg(PacketTraceBuf, __FILE__, __LINE__, __VA_ARGS__); \ } while (false) \ /////////////////////////////////////////////////////////////////////////////// void Pkt0Interface::InitControlInterface() { pkt_handler()->agent()->set_pkt_interface_name(name_); if ((tap_fd_ = open(TUN_INTF_CLONE_DEV, O_RDWR)) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> opening tap-device"); assert(0); } struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, name_.c_str(), IF_NAMESIZE); if (ioctl(tap_fd_, TUNSETIFF, (void *)&ifr) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> creating " << name_ << "tap-device"); assert(0); } // We dont want the fd to be inherited by child process such as // virsh etc... So, close tap fd on fork. if (fcntl(tap_fd_, F_SETFD, FD_CLOEXEC) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> setting fcntl on " << name_ ); assert(0); } if (ioctl(tap_fd_, TUNSETPERSIST, 0) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> making tap interface non-persistent"); assert(0); } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, name_.c_str(), IF_NAMESIZE); if (ioctl(tap_fd_, SIOCGIFHWADDR, (void *)&ifr) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> retrieving MAC address of the tap interface"); assert(0); } memcpy(mac_address_, ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN); int raw; if ((raw = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> creating socket"); assert(0); } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, name_.data(), IF_NAMESIZE); if (ioctl(raw, SIOCGIFINDEX, (void *)&ifr) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> getting ifindex of the tap interface"); assert(0); } struct sockaddr_ll sll; memset(&sll, 0, sizeof(struct sockaddr_ll)); sll.sll_family = AF_PACKET; sll.sll_ifindex = ifr.ifr_ifindex; sll.sll_protocol = htons(ETH_P_ALL); if (bind(raw, (struct sockaddr *)&sll, sizeof(struct sockaddr_ll)) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> binding the socket to the tap interface"); assert(0); } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, name_.data(), IF_NAMESIZE); if (ioctl(raw, SIOCGIFFLAGS, (void *)&ifr) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> getting socket flags"); assert(0); } ifr.ifr_flags |= IFF_UP; if (ioctl(raw, SIOCSIFFLAGS, (void *)&ifr) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> setting socket flags"); assert(0); } close(raw); boost::system::error_code ec; input_.assign(tap_fd_, ec); assert(ec == 0); VrouterControlInterface::InitControlInterface(); AsyncRead(); } void Pkt0RawInterface::InitControlInterface() { pkt_handler()->agent()->set_pkt_interface_name(name_); int raw_; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); if ((raw_ = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> creating socket"); assert(0); } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, pkt_handler()->agent()->pkt_interface_name().c_str(), IF_NAMESIZE); if (ioctl(raw_, SIOCGIFINDEX, (void *)&ifr) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> getting ifindex of the " << "expception packet interface"); assert(0); } struct sockaddr_ll sll; memset(&sll, 0, sizeof(struct sockaddr_ll)); sll.sll_family = AF_PACKET; sll.sll_ifindex = ifr.ifr_ifindex; sll.sll_protocol = htons(ETH_P_ALL); if (bind(raw_, (struct sockaddr *)&sll, sizeof(struct sockaddr_ll)) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> binding the socket to the tap interface"); assert(0); } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, name_.data(), IF_NAMESIZE); if (ioctl(raw_, SIOCGIFFLAGS, (void *)&ifr) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> getting socket flags"); assert(0); } ifr.ifr_flags |= IFF_UP; if (ioctl(raw_, SIOCSIFFLAGS, (void *)&ifr) < 0) { LOG(ERROR, "Packet Tap Error <" << errno << ": " << strerror(errno) << "> setting socket flags"); assert(0); } tap_fd_ = raw_; boost::system::error_code ec; input_.assign(tap_fd_, ec); assert(ec == 0); VrouterControlInterface::InitControlInterface(); AsyncRead(); }
facetothefate/contrail-controller
src/vnsw/agent/contrail/linux/pkt0_interface.cc
C++
apache-2.0
6,144
# Copyright 2013 Josh Durgin # Copyright 2013 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime from lxml import etree from oslo.config import cfg import webob from webob import exc from nova.api.openstack.compute.contrib import assisted_volume_snapshots as \ assisted_snaps from nova.api.openstack.compute.contrib import volumes from nova.api.openstack import extensions from nova.compute import api as compute_api from nova.compute import flavors from nova import context from nova import exception from nova.openstack.common import jsonutils from nova.openstack.common import timeutils from nova import test from nova.tests.api.openstack import fakes from nova.volume import cinder CONF = cfg.CONF CONF.import_opt('password_length', 'nova.utils') FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' FAKE_UUID_A = '00000000-aaaa-aaaa-aaaa-000000000000' FAKE_UUID_B = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb' FAKE_UUID_C = 'cccccccc-cccc-cccc-cccc-cccccccccccc' FAKE_UUID_D = 'dddddddd-dddd-dddd-dddd-dddddddddddd' IMAGE_UUID = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77' def fake_get_instance(self, context, instance_id, want_objects=False): return {'uuid': instance_id} def fake_get_volume(self, context, id): return {'id': 'woot'} def fake_attach_volume(self, context, instance, volume_id, device): pass def fake_detach_volume(self, context, instance, volume): pass def fake_swap_volume(self, context, instance, old_volume_id, new_volume_id): pass def fake_create_snapshot(self, context, volume, name, description): return {'id': 123, 'volume_id': 'fakeVolId', 'status': 'available', 'volume_size': 123, 'created_at': '2013-01-01 00:00:01', 'display_name': 'myVolumeName', 'display_description': 'myVolumeDescription'} def fake_delete_snapshot(self, context, snapshot_id): pass def fake_compute_volume_snapshot_delete(self, context, volume_id, snapshot_id, delete_info): pass def fake_compute_volume_snapshot_create(self, context, volume_id, create_info): pass def fake_get_instance_bdms(self, context, instance): return [{'id': 1, 'instance_uuid': instance['uuid'], 'device_name': '/dev/fake0', 'delete_on_termination': 'False', 'virtual_name': 'MyNamesVirtual', 'snapshot_id': None, 'volume_id': FAKE_UUID_A, 'volume_size': 1}, {'id': 2, 'instance_uuid': instance['uuid'], 'device_name': '/dev/fake1', 'delete_on_termination': 'False', 'virtual_name': 'MyNamesVirtual', 'snapshot_id': None, 'volume_id': FAKE_UUID_B, 'volume_size': 1}] class BootFromVolumeTest(test.TestCase): def setUp(self): super(BootFromVolumeTest, self).setUp() self.stubs.Set(compute_api.API, 'create', self._get_fake_compute_api_create()) fakes.stub_out_nw_api(self.stubs) self._block_device_mapping_seen = None self._legacy_bdm_seen = True self.flags( osapi_compute_extension=[ 'nova.api.openstack.compute.contrib.select_extensions'], osapi_compute_ext_list=['Volumes', 'Block_device_mapping_v2_boot']) def _get_fake_compute_api_create(self): def _fake_compute_api_create(cls, context, instance_type, image_href, **kwargs): self._block_device_mapping_seen = kwargs.get( 'block_device_mapping') self._legacy_bdm_seen = kwargs.get('legacy_bdm') inst_type = flavors.get_flavor_by_flavor_id(2) resv_id = None return ([{'id': 1, 'display_name': 'test_server', 'uuid': FAKE_UUID, 'instance_type': dict(inst_type), 'access_ip_v4': '1.2.3.4', 'access_ip_v6': 'fead::1234', 'image_ref': IMAGE_UUID, 'user_id': 'fake', 'project_id': 'fake', 'created_at': datetime.datetime(2010, 10, 10, 12, 0, 0), 'updated_at': datetime.datetime(2010, 11, 11, 11, 0, 0), 'progress': 0, 'fixed_ips': [] }], resv_id) return _fake_compute_api_create def test_create_root_volume(self): body = dict(server=dict( name='test_server', imageRef=IMAGE_UUID, flavorRef=2, min_count=1, max_count=1, block_device_mapping=[dict( volume_id=1, device_name='/dev/vda', virtual='root', delete_on_termination=False, )] )) req = webob.Request.blank('/v2/fake/os-volumes_boot') req.method = 'POST' req.body = jsonutils.dumps(body) req.headers['content-type'] = 'application/json' res = req.get_response(fakes.wsgi_app( init_only=('os-volumes_boot', 'servers'))) self.assertEqual(res.status_int, 202) server = jsonutils.loads(res.body)['server'] self.assertEqual(FAKE_UUID, server['id']) self.assertEqual(CONF.password_length, len(server['adminPass'])) self.assertEqual(len(self._block_device_mapping_seen), 1) self.assertTrue(self._legacy_bdm_seen) self.assertEqual(self._block_device_mapping_seen[0]['volume_id'], 1) self.assertEqual(self._block_device_mapping_seen[0]['device_name'], '/dev/vda') def test_create_root_volume_bdm_v2(self): body = dict(server=dict( name='test_server', imageRef=IMAGE_UUID, flavorRef=2, min_count=1, max_count=1, block_device_mapping_v2=[dict( source_type='volume', uuid=1, device_name='/dev/vda', boot_index=0, delete_on_termination=False, )] )) req = webob.Request.blank('/v2/fake/os-volumes_boot') req.method = 'POST' req.body = jsonutils.dumps(body) req.headers['content-type'] = 'application/json' res = req.get_response(fakes.wsgi_app( init_only=('os-volumes_boot', 'servers'))) self.assertEqual(res.status_int, 202) server = jsonutils.loads(res.body)['server'] self.assertEqual(FAKE_UUID, server['id']) self.assertEqual(CONF.password_length, len(server['adminPass'])) self.assertEqual(len(self._block_device_mapping_seen), 1) self.assertFalse(self._legacy_bdm_seen) self.assertEqual(self._block_device_mapping_seen[0]['volume_id'], 1) self.assertEqual(self._block_device_mapping_seen[0]['boot_index'], 0) self.assertEqual(self._block_device_mapping_seen[0]['device_name'], '/dev/vda') class VolumeApiTest(test.TestCase): def setUp(self): super(VolumeApiTest, self).setUp() fakes.stub_out_networking(self.stubs) fakes.stub_out_rate_limiting(self.stubs) self.stubs.Set(cinder.API, "delete", fakes.stub_volume_delete) self.stubs.Set(cinder.API, "get", fakes.stub_volume_get) self.stubs.Set(cinder.API, "get_all", fakes.stub_volume_get_all) self.flags( osapi_compute_extension=[ 'nova.api.openstack.compute.contrib.select_extensions'], osapi_compute_ext_list=['Volumes']) self.context = context.get_admin_context() self.app = fakes.wsgi_app(init_only=('os-volumes',)) def test_volume_create(self): self.stubs.Set(cinder.API, "create", fakes.stub_volume_create) vol = {"size": 100, "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "zone1:host1"} body = {"volume": vol} req = webob.Request.blank('/v2/fake/os-volumes') req.method = 'POST' req.body = jsonutils.dumps(body) req.headers['content-type'] = 'application/json' resp = req.get_response(self.app) self.assertEqual(resp.status_int, 200) resp_dict = jsonutils.loads(resp.body) self.assertTrue('volume' in resp_dict) self.assertEqual(resp_dict['volume']['size'], vol['size']) self.assertEqual(resp_dict['volume']['displayName'], vol['display_name']) self.assertEqual(resp_dict['volume']['displayDescription'], vol['display_description']) self.assertEqual(resp_dict['volume']['availabilityZone'], vol['availability_zone']) def test_volume_create_bad(self): def fake_volume_create(self, context, size, name, description, snapshot, **param): raise exception.InvalidInput(reason="bad request data") self.stubs.Set(cinder.API, "create", fake_volume_create) vol = {"size": '#$?', "display_name": "Volume Test Name", "display_description": "Volume Test Desc", "availability_zone": "zone1:host1"} body = {"volume": vol} req = fakes.HTTPRequest.blank('/v2/fake/os-volumes') self.assertRaises(webob.exc.HTTPBadRequest, volumes.VolumeController().create, req, body) def test_volume_index(self): req = webob.Request.blank('/v2/fake/os-volumes') resp = req.get_response(self.app) self.assertEqual(resp.status_int, 200) def test_volume_detail(self): req = webob.Request.blank('/v2/fake/os-volumes/detail') resp = req.get_response(self.app) self.assertEqual(resp.status_int, 200) def test_volume_show(self): req = webob.Request.blank('/v2/fake/os-volumes/123') resp = req.get_response(self.app) self.assertEqual(resp.status_int, 200) def test_volume_show_no_volume(self): self.stubs.Set(cinder.API, "get", fakes.stub_volume_notfound) req = webob.Request.blank('/v2/fake/os-volumes/456') resp = req.get_response(self.app) self.assertEqual(resp.status_int, 404) def test_volume_delete(self): req = webob.Request.blank('/v2/fake/os-volumes/123') req.method = 'DELETE' resp = req.get_response(self.app) self.assertEqual(resp.status_int, 202) def test_volume_delete_no_volume(self): self.stubs.Set(cinder.API, "delete", fakes.stub_volume_notfound) req = webob.Request.blank('/v2/fake/os-volumes/456') req.method = 'DELETE' resp = req.get_response(self.app) self.assertEqual(resp.status_int, 404) class VolumeAttachTests(test.TestCase): def setUp(self): super(VolumeAttachTests, self).setUp() self.stubs.Set(compute_api.API, 'get_instance_bdms', fake_get_instance_bdms) self.stubs.Set(compute_api.API, 'get', fake_get_instance) self.stubs.Set(cinder.API, 'get', fake_get_volume) self.context = context.get_admin_context() self.expected_show = {'volumeAttachment': {'device': '/dev/fake0', 'serverId': FAKE_UUID, 'id': FAKE_UUID_A, 'volumeId': FAKE_UUID_A }} self.ext_mgr = extensions.ExtensionManager() self.ext_mgr.extensions = {} self.attachments = volumes.VolumeAttachmentController(self.ext_mgr) def test_show(self): req = webob.Request.blank('/v2/servers/id/os-volume_attachments/uuid') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['nova.context'] = self.context result = self.attachments.show(req, FAKE_UUID, FAKE_UUID_A) self.assertEqual(self.expected_show, result) def test_detach(self): self.stubs.Set(compute_api.API, 'detach_volume', fake_detach_volume) req = webob.Request.blank('/v2/servers/id/os-volume_attachments/uuid') req.method = 'DELETE' req.headers['content-type'] = 'application/json' req.environ['nova.context'] = self.context result = self.attachments.delete(req, FAKE_UUID, FAKE_UUID_A) self.assertEqual('202 Accepted', result.status) def test_detach_vol_not_found(self): self.stubs.Set(compute_api.API, 'detach_volume', fake_detach_volume) req = webob.Request.blank('/v2/servers/id/os-volume_attachments/uuid') req.method = 'DELETE' req.headers['content-type'] = 'application/json' req.environ['nova.context'] = self.context self.assertRaises(exc.HTTPNotFound, self.attachments.delete, req, FAKE_UUID, FAKE_UUID_C) def test_attach_volume(self): self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume) body = {'volumeAttachment': {'volumeId': FAKE_UUID_A, 'device': '/dev/fake'}} req = webob.Request.blank('/v2/servers/id/os-volume_attachments') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['nova.context'] = self.context result = self.attachments.create(req, FAKE_UUID, body) self.assertEqual(result['volumeAttachment']['id'], '00000000-aaaa-aaaa-aaaa-000000000000') def test_attach_volume_bad_id(self): self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume) body = { 'volumeAttachment': { 'device': None, 'volumeId': 'TESTVOLUME', } } req = webob.Request.blank('/v2/servers/id/os-volume_attachments') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['nova.context'] = self.context self.assertRaises(webob.exc.HTTPBadRequest, self.attachments.create, req, FAKE_UUID, body) def _test_swap(self, uuid=FAKE_UUID_A): self.stubs.Set(compute_api.API, 'swap_volume', fake_swap_volume) body = {'volumeAttachment': {'volumeId': FAKE_UUID_B, 'device': '/dev/fake'}} req = webob.Request.blank('/v2/servers/id/os-volume_attachments/uuid') req.method = 'PUT' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['nova.context'] = self.context return self.attachments.update(req, FAKE_UUID, uuid, body) def test_swap_volume_no_extension(self): self.assertRaises(webob.exc.HTTPBadRequest, self._test_swap) def test_swap_volume(self): self.ext_mgr.extensions['os-volume-attachment-update'] = True result = self._test_swap() self.assertEqual('202 Accepted', result.status) def test_swap_volume_no_attachment(self): self.ext_mgr.extensions['os-volume-attachment-update'] = True self.assertRaises(exc.HTTPNotFound, self._test_swap, FAKE_UUID_C) class VolumeSerializerTest(test.TestCase): def _verify_volume_attachment(self, attach, tree): for attr in ('id', 'volumeId', 'serverId', 'device'): self.assertEqual(str(attach[attr]), tree.get(attr)) def _verify_volume(self, vol, tree): self.assertEqual(tree.tag, 'volume') for attr in ('id', 'status', 'size', 'availabilityZone', 'createdAt', 'displayName', 'displayDescription', 'volumeType', 'snapshotId'): self.assertEqual(str(vol[attr]), tree.get(attr)) for child in tree: self.assertTrue(child.tag in ('attachments', 'metadata')) if child.tag == 'attachments': self.assertEqual(1, len(child)) self.assertEqual('attachment', child[0].tag) self._verify_volume_attachment(vol['attachments'][0], child[0]) elif child.tag == 'metadata': not_seen = set(vol['metadata'].keys()) for gr_child in child: self.assertTrue(gr_child.get("key") in not_seen) self.assertEqual(str(vol['metadata'][gr_child.get("key")]), gr_child.text) not_seen.remove(gr_child.get("key")) self.assertEqual(0, len(not_seen)) def test_attach_show_create_serializer(self): serializer = volumes.VolumeAttachmentTemplate() raw_attach = dict( id='vol_id', volumeId='vol_id', serverId='instance_uuid', device='/foo') text = serializer.serialize(dict(volumeAttachment=raw_attach)) tree = etree.fromstring(text) self.assertEqual('volumeAttachment', tree.tag) self._verify_volume_attachment(raw_attach, tree) def test_attach_index_serializer(self): serializer = volumes.VolumeAttachmentsTemplate() raw_attaches = [dict( id='vol_id1', volumeId='vol_id1', serverId='instance1_uuid', device='/foo1'), dict( id='vol_id2', volumeId='vol_id2', serverId='instance2_uuid', device='/foo2')] text = serializer.serialize(dict(volumeAttachments=raw_attaches)) tree = etree.fromstring(text) self.assertEqual('volumeAttachments', tree.tag) self.assertEqual(len(raw_attaches), len(tree)) for idx, child in enumerate(tree): self.assertEqual('volumeAttachment', child.tag) self._verify_volume_attachment(raw_attaches[idx], child) def test_volume_show_create_serializer(self): serializer = volumes.VolumeTemplate() raw_volume = dict( id='vol_id', status='vol_status', size=1024, availabilityZone='vol_availability', createdAt=timeutils.utcnow(), attachments=[dict( id='vol_id', volumeId='vol_id', serverId='instance_uuid', device='/foo')], displayName='vol_name', displayDescription='vol_desc', volumeType='vol_type', snapshotId='snap_id', metadata=dict( foo='bar', baz='quux', ), ) text = serializer.serialize(dict(volume=raw_volume)) tree = etree.fromstring(text) self._verify_volume(raw_volume, tree) def test_volume_index_detail_serializer(self): serializer = volumes.VolumesTemplate() raw_volumes = [dict( id='vol1_id', status='vol1_status', size=1024, availabilityZone='vol1_availability', createdAt=timeutils.utcnow(), attachments=[dict( id='vol1_id', volumeId='vol1_id', serverId='instance_uuid', device='/foo1')], displayName='vol1_name', displayDescription='vol1_desc', volumeType='vol1_type', snapshotId='snap1_id', metadata=dict( foo='vol1_foo', bar='vol1_bar', ), ), dict( id='vol2_id', status='vol2_status', size=1024, availabilityZone='vol2_availability', createdAt=timeutils.utcnow(), attachments=[dict( id='vol2_id', volumeId='vol2_id', serverId='instance_uuid', device='/foo2')], displayName='vol2_name', displayDescription='vol2_desc', volumeType='vol2_type', snapshotId='snap2_id', metadata=dict( foo='vol2_foo', bar='vol2_bar', ), )] text = serializer.serialize(dict(volumes=raw_volumes)) tree = etree.fromstring(text) self.assertEqual('volumes', tree.tag) self.assertEqual(len(raw_volumes), len(tree)) for idx, child in enumerate(tree): self._verify_volume(raw_volumes[idx], child) class TestVolumeCreateRequestXMLDeserializer(test.TestCase): def setUp(self): super(TestVolumeCreateRequestXMLDeserializer, self).setUp() self.deserializer = volumes.CreateDeserializer() def test_minimal_volume(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", }, } self.assertEquals(request['body'], expected) def test_display_name(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", }, } self.assertEquals(request['body'], expected) def test_display_description(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml" display_description="description"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", }, } self.assertEquals(request['body'], expected) def test_volume_type(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml" display_description="description" volume_type="289da7f8-6440-407c-9fb4-7db01ec49164"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "display_name": "Volume-xml", "size": "1", "display_name": "Volume-xml", "display_description": "description", "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", }, } self.assertEquals(request['body'], expected) def test_availability_zone(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml" display_description="description" volume_type="289da7f8-6440-407c-9fb4-7db01ec49164" availability_zone="us-east1"></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", "availability_zone": "us-east1", }, } self.assertEquals(request['body'], expected) def test_metadata(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" display_name="Volume-xml" size="1"> <metadata><meta key="Type">work</meta></metadata></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "display_name": "Volume-xml", "size": "1", "metadata": { "Type": "work", }, }, } self.assertEquals(request['body'], expected) def test_full_volume(self): self_request = """ <volume xmlns="http://docs.openstack.org/compute/api/v1.1" size="1" display_name="Volume-xml" display_description="description" volume_type="289da7f8-6440-407c-9fb4-7db01ec49164" availability_zone="us-east1"> <metadata><meta key="Type">work</meta></metadata></volume>""" request = self.deserializer.deserialize(self_request) expected = { "volume": { "size": "1", "display_name": "Volume-xml", "display_description": "description", "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", "availability_zone": "us-east1", "metadata": { "Type": "work", }, }, } self.maxDiff = None self.assertEquals(request['body'], expected) class CommonUnprocessableEntityTestCase(object): resource = None entity_name = None controller_cls = None kwargs = {} """ Tests of places we throw 422 Unprocessable Entity from """ def setUp(self): super(CommonUnprocessableEntityTestCase, self).setUp() self.controller = self.controller_cls() def _unprocessable_create(self, body): req = fakes.HTTPRequest.blank('/v2/fake/' + self.resource) req.method = 'POST' kwargs = self.kwargs.copy() kwargs['body'] = body self.assertRaises(webob.exc.HTTPUnprocessableEntity, self.controller.create, req, **kwargs) def test_create_no_body(self): self._unprocessable_create(body=None) def test_create_missing_volume(self): body = {'foo': {'a': 'b'}} self._unprocessable_create(body=body) def test_create_malformed_entity(self): body = {self.entity_name: 'string'} self._unprocessable_create(body=body) class UnprocessableVolumeTestCase(CommonUnprocessableEntityTestCase, test.TestCase): resource = 'os-volumes' entity_name = 'volume' controller_cls = volumes.VolumeController class UnprocessableAttachmentTestCase(CommonUnprocessableEntityTestCase, test.TestCase): resource = 'servers/' + FAKE_UUID + '/os-volume_attachments' entity_name = 'volumeAttachment' controller_cls = volumes.VolumeAttachmentController kwargs = {'server_id': FAKE_UUID} class UnprocessableSnapshotTestCase(CommonUnprocessableEntityTestCase, test.TestCase): resource = 'os-snapshots' entity_name = 'snapshot' controller_cls = volumes.SnapshotController class CreateSnapshotTestCase(test.TestCase): def setUp(self): super(CreateSnapshotTestCase, self).setUp() self.controller = volumes.SnapshotController() self.stubs.Set(cinder.API, 'get', fake_get_volume) self.stubs.Set(cinder.API, 'create_snapshot_force', fake_create_snapshot) self.stubs.Set(cinder.API, 'create_snapshot', fake_create_snapshot) self.req = fakes.HTTPRequest.blank('/v2/fake/os-snapshots') self.req.method = 'POST' self.body = {'snapshot': {'volume_id': 1}} def test_force_true(self): self.body['snapshot']['force'] = 'True' self.controller.create(self.req, body=self.body) def test_force_false(self): self.body['snapshot']['force'] = 'f' self.controller.create(self.req, body=self.body) def test_force_invalid(self): self.body['snapshot']['force'] = 'foo' self.assertRaises(exception.InvalidParameterValue, self.controller.create, self.req, body=self.body) class DeleteSnapshotTestCase(test.TestCase): def setUp(self): super(DeleteSnapshotTestCase, self).setUp() self.controller = volumes.SnapshotController() self.stubs.Set(cinder.API, 'get', fake_get_volume) self.stubs.Set(cinder.API, 'create_snapshot_force', fake_create_snapshot) self.stubs.Set(cinder.API, 'create_snapshot', fake_create_snapshot) self.stubs.Set(cinder.API, 'delete_snapshot', fake_delete_snapshot) self.req = fakes.HTTPRequest.blank('/v2/fake/os-snapshots') def test_normal_delete(self): self.req.method = 'POST' self.body = {'snapshot': {'volume_id': 1}} result = self.controller.create(self.req, body=self.body) self.req.method = 'DELETE' result = self.controller.delete(self.req, result['snapshot']['id']) self.assertEqual(result.status_int, 202) class AssistedSnapshotCreateTestCase(test.TestCase): def setUp(self): super(AssistedSnapshotCreateTestCase, self).setUp() self.controller = assisted_snaps.AssistedVolumeSnapshotsController() self.stubs.Set(compute_api.API, 'volume_snapshot_create', fake_compute_volume_snapshot_create) def test_assisted_create(self): req = fakes.HTTPRequest.blank('/v2/fake/os-assisted-volume-snapshots') body = {'snapshot': {'volume_id': 1, 'create_info': {}}} req.method = 'POST' self.controller.create(req, body=body) def test_assisted_create_missing_create_info(self): req = fakes.HTTPRequest.blank('/v2/fake/os-assisted-volume-snapshots') body = {'snapshot': {'volume_id': 1}} req.method = 'POST' self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, req, body=body) class AssistedSnapshotDeleteTestCase(test.TestCase): def setUp(self): super(AssistedSnapshotDeleteTestCase, self).setUp() self.controller = assisted_snaps.AssistedVolumeSnapshotsController() self.stubs.Set(compute_api.API, 'volume_snapshot_delete', fake_compute_volume_snapshot_delete) def test_assisted_delete(self): params = { 'delete_info': jsonutils.dumps({'volume_id': 1}), } req = fakes.HTTPRequest.blank( '/v2/fake/os-assisted-volume-snapshots?%s' % '&'.join(['%s=%s' % (k, v) for k, v in params.iteritems()])) req.method = 'DELETE' result = self.controller.delete(req, '5') self.assertEqual(result.status_int, 204) def test_assisted_delete_missing_delete_info(self): req = fakes.HTTPRequest.blank('/v2/fake/os-assisted-volume-snapshots') req.method = 'DELETE' self.assertRaises(webob.exc.HTTPBadRequest, self.controller.delete, req, '5')
ntt-sic/nova
nova/tests/api/openstack/compute/contrib/test_volumes.py
Python
apache-2.0
32,169
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.core.persistence.api.entity.anyobject; import org.apache.syncope.core.persistence.api.entity.Relationship; public interface ARelationship extends Relationship<AnyObject, AnyObject> { }
tmess567/syncope
core/persistence-api/src/main/java/org/apache/syncope/core/persistence/api/entity/anyobject/ARelationship.java
Java
apache-2.0
1,023
package org.apache.maven.plugins.install.stubs; import java.io.File; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public class AttachedArtifactStub0 extends InstallArtifactStub { public String getArtifactId() { return "attached-artifact-test-0"; } public File getFile() { return new File( System.getProperty( "basedir" ), "target/test-classes/unit/basic-install-test-with-attached-artifacts/" + "target/maven-install-test-1.0-SNAPSHOT.jar" ); } }
apache/maven-plugins
maven-install-plugin/src/test/java/org/apache/maven/plugins/install/stubs/AttachedArtifactStub0.java
Java
apache-2.0
1,311
/* * Copyright 2018 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.common.server.cluster.zookeeper.exception; /** * @author koo.taejin */ public class NoNodeException extends PinpointZookeeperException { public NoNodeException() { } public NoNodeException(String message) { super(message); } public NoNodeException(String message, Throwable cause) { super(message, cause); } public NoNodeException(Throwable cause) { super(cause); } }
barneykim/pinpoint
commons-server/src/main/java/com/navercorp/pinpoint/common/server/cluster/zookeeper/exception/NoNodeException.java
Java
apache-2.0
1,056
//// [augmentedTypesExternalModule1.ts] export var a = 1; class c5 { public foo() { } } module c5 { } // should be ok everywhere //// [augmentedTypesExternalModule1.js] define(["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; exports.a = 1; var c5 = /** @class */ (function () { function c5() { } c5.prototype.foo = function () { }; return c5; }()); });
domchen/typescript-plus
tests/baselines/reference/augmentedTypesExternalModule1.js
JavaScript
apache-2.0
467
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.resource; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Locale; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.request.Url; import org.apache.wicket.request.resource.ResourceReference; import org.apache.wicket.util.io.IOUtils; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.resource.IResourceStream; import org.apache.wicket.util.resource.ResourceStreamNotFoundException; import org.apache.wicket.util.string.Strings; /** * Utilities for resources. * * @author Jeremy Thomerson */ public class ResourceUtil { /** * Reads resource reference attributes (style, locale, variation) encoded in the given string. * * @param encodedAttributes * the string containing the resource attributes * @return the encoded attributes * * @see ResourceReference.UrlAttributes */ public static ResourceReference.UrlAttributes decodeResourceReferenceAttributes(String encodedAttributes) { Locale locale = null; String style = null; String variation = null; if (Strings.isEmpty(encodedAttributes) == false) { String split[] = Strings.split(encodedAttributes, '-'); locale = parseLocale(split[0]); if (split.length == 2) { style = Strings.defaultIfEmpty(unescapeAttributesSeparator(split[1]), null); } else if (split.length == 3) { style = Strings.defaultIfEmpty(unescapeAttributesSeparator(split[1]), null); variation = Strings.defaultIfEmpty(unescapeAttributesSeparator(split[2]), null); } } return new ResourceReference.UrlAttributes(locale, style, variation); } /** * Reads resource reference attributes (style, locale, variation) encoded in the given URL. * * @param url * the url containing the resource attributes * @return the encoded attributes * * @see ResourceReference.UrlAttributes */ public static ResourceReference.UrlAttributes decodeResourceReferenceAttributes(Url url) { Args.notNull(url, "url"); if (url.getQueryParameters().size() > 0) { Url.QueryParameter param = url.getQueryParameters().get(0); if (Strings.isEmpty(param.getValue())) { return decodeResourceReferenceAttributes(param.getName()); } } return new ResourceReference.UrlAttributes(null, null, null); } /** * Encodes the given resource reference attributes returning the corresponding textual representation. * * @param attributes * the resource reference attributes to encode * @return the textual representation for the given attributes * * @see ResourceReference.UrlAttributes */ public static String encodeResourceReferenceAttributes(ResourceReference.UrlAttributes attributes) { if (attributes == null || (attributes.getLocale() == null && attributes.getStyle() == null && attributes.getVariation() == null)) { return null; } else { StringBuilder res = new StringBuilder(32); if (attributes.getLocale() != null) { res.append(attributes.getLocale()); } boolean styleEmpty = Strings.isEmpty(attributes.getStyle()); if (!styleEmpty) { res.append('-'); res.append(escapeAttributesSeparator(attributes.getStyle())); } if (!Strings.isEmpty(attributes.getVariation())) { if (styleEmpty) { res.append("--"); } else { res.append('-'); } res.append(escapeAttributesSeparator(attributes.getVariation())); } return res.toString(); } } /** * Encodes the attributes of the given resource reference in the specified url. * * @param url * the resource reference attributes to encode * @param reference * * @see ResourceReference.UrlAttributes * @see Url */ public static void encodeResourceReferenceAttributes(Url url, ResourceReference reference) { Args.notNull(url, "url"); Args.notNull(reference, "reference"); String encoded = encodeResourceReferenceAttributes(reference.getUrlAttributes()); if (!Strings.isEmpty(encoded)) { url.getQueryParameters().add(new Url.QueryParameter(encoded, "")); } } /** * Escapes any occurrences of <em>-</em> character in the style and variation * attributes with <em>~</em>. Any occurrence of <em>~</em> is encoded as <em>~~</em>. * * @param attribute * the attribute to escape * @return the attribute with escaped separator character */ public static CharSequence escapeAttributesSeparator(String attribute) { CharSequence tmp = Strings.replaceAll(attribute, "~", "~~"); return Strings.replaceAll(tmp, "-", "~"); } /** * Parses the string representation of a {@link java.util.Locale} (for example 'en_GB'). * * @param locale * the string representation of a {@link java.util.Locale} * @return the corresponding {@link java.util.Locale} instance */ public static Locale parseLocale(String locale) { if (Strings.isEmpty(locale)) { return null; } else { String parts[] = locale.toLowerCase().split("_", 3); if (parts.length == 1) { return new Locale(parts[0]); } else if (parts.length == 2) { return new Locale(parts[0], parts[1]); } else if (parts.length == 3) { return new Locale(parts[0], parts[1], parts[2]); } else { return null; } } } /** * read string with platform default encoding from resource stream * * @param resourceStream * @return string read from resource stream * * @see #readString(org.apache.wicket.util.resource.IResourceStream, java.nio.charset.Charset) */ public static String readString(IResourceStream resourceStream) { return readString(resourceStream, null); } /** * read string with specified encoding from resource stream * * @param resourceStream * string source * @param charset * charset for the string encoding (use <code>null</code> for platform default) * @return string read from resource stream */ public static String readString(IResourceStream resourceStream, Charset charset) { try { InputStream stream = resourceStream.getInputStream(); try { byte[] bytes = IOUtils.toByteArray(stream); if (charset == null) { charset = Charset.defaultCharset(); } return new String(bytes, charset.name()); } finally { resourceStream.close(); } } catch (IOException e) { throw new WicketRuntimeException("failed to read string from " + resourceStream, e); } catch (ResourceStreamNotFoundException e) { throw new WicketRuntimeException("failed to locate stream from " + resourceStream, e); } } /** * Reverts the escaping applied by {@linkplain #escapeAttributesSeparator(String)} - unescapes * occurrences of <em>~</em> character in the style and variation attributes with <em>-</em>. * * @param attribute * the attribute to unescape * @return the attribute with escaped separator character */ public static String unescapeAttributesSeparator(String attribute) { String tmp = attribute.replaceAll("(\\w)~(\\w)", "$1-$2"); return Strings.replaceAll(tmp, "~~", "~").toString(); } private ResourceUtil() { // no-op } }
AlienQueen/wicket
wicket-core/src/main/java/org/apache/wicket/resource/ResourceUtil.java
Java
apache-2.0
8,028
/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "vulkanCore.h" #include "util/gvr_log.h" #include <assert.h> #include <cstring> VulkanCore* VulkanCore::theInstance = NULL; bool VulkanCore::CreateInstance(){ VkResult ret = VK_SUCCESS; // Discover the number of extensions listed in the instance properties in order to allocate // a buffer large enough to hold them. uint32_t instanceExtensionCount = 0; ret = vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr); GVR_VK_CHECK(!ret); VkBool32 surfaceExtFound = 0; VkBool32 platformSurfaceExtFound = 0; VkExtensionProperties* instanceExtensions = nullptr; instanceExtensions = new VkExtensionProperties[instanceExtensionCount]; // Now request instanceExtensionCount VkExtensionProperties elements be read into out buffer ret = vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, instanceExtensions); GVR_VK_CHECK(!ret); // We require two extensions, VK_KHR_surface and VK_KHR_android_surface. If they are found, // add them to the extensionNames list that we'll use to initialize our instance with later. uint32_t enabledExtensionCount = 0; const char* extensionNames[16]; for (uint32_t i = 0; i < instanceExtensionCount; i++) { if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instanceExtensions[i].extensionName)) { surfaceExtFound = 1; extensionNames[enabledExtensionCount++] = VK_KHR_SURFACE_EXTENSION_NAME; } if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, instanceExtensions[i].extensionName)) { platformSurfaceExtFound = 1; extensionNames[enabledExtensionCount++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME; } GVR_VK_CHECK(enabledExtensionCount < 16); } if (!surfaceExtFound) { LOGE("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME" extension."); return false; } if (!platformSurfaceExtFound) { LOGE("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME" extension."); return false; } // We specify the Vulkan version our application was built with, // as well as names and versions for our application and engine, // if applicable. This allows the driver to gain insight to what // is utilizing the vulkan driver, and serve appropriate versions. VkApplicationInfo applicationInfo = {}; applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; applicationInfo.pNext = nullptr; applicationInfo.pApplicationName = GVR_VK_SAMPLE_NAME; applicationInfo.applicationVersion = 0; applicationInfo.pEngineName = "VkSample"; applicationInfo.engineVersion = 1; applicationInfo.apiVersion = VK_API_VERSION_1_0; // Creation information for the instance points to details about // the application, and also the list of extensions to enable. VkInstanceCreateInfo instanceCreateInfo = {}; instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceCreateInfo.pNext = nullptr; instanceCreateInfo.pApplicationInfo = &applicationInfo; instanceCreateInfo.enabledLayerCount = 0; instanceCreateInfo.ppEnabledLayerNames = nullptr; instanceCreateInfo.enabledExtensionCount = enabledExtensionCount; instanceCreateInfo.ppEnabledExtensionNames = extensionNames; // The main Vulkan instance is created with the creation infos above. // We do not specify a custom memory allocator for instance creation. ret = vkCreateInstance(&instanceCreateInfo, nullptr, &(m_instance)); // we can delete the list of extensions after calling vkCreateInstance delete[] instanceExtensions; // Vulkan API return values can expose further information on a failure. // For instance, INCOMPATIBLE_DRIVER may be returned if the API level // an application is built with, exposed through VkApplicationInfo, is // newer than the driver present on a device. if (ret == VK_ERROR_INCOMPATIBLE_DRIVER) { LOGE("Cannot find a compatible Vulkan installable client driver: vkCreateInstance Failure"); return false; } else if (ret == VK_ERROR_EXTENSION_NOT_PRESENT) { LOGE("Cannot find a specified extension library: vkCreateInstance Failure"); return false; } else { GVR_VK_CHECK(!ret); } return true; } bool VulkanCore::GetPhysicalDevices(){ VkResult ret = VK_SUCCESS; // Query number of physical devices available ret = vkEnumeratePhysicalDevices(m_instance, &(m_physicalDeviceCount), nullptr); GVR_VK_CHECK(!ret); if (m_physicalDeviceCount == 0) { LOGE("No physical devices detected."); return false; } // Allocate space the the correct number of devices, before requesting their data m_pPhysicalDevices = new VkPhysicalDevice[m_physicalDeviceCount]; ret = vkEnumeratePhysicalDevices(m_instance, &(m_physicalDeviceCount), m_pPhysicalDevices); GVR_VK_CHECK(!ret); // For purposes of this sample, we simply use the first device. m_physicalDevice = m_pPhysicalDevices[0]; // By querying the device properties, we learn the device name, amongst // other details. vkGetPhysicalDeviceProperties(m_physicalDevice, &(m_physicalDeviceProperties)); LOGI("Vulkan Device: %s", m_physicalDeviceProperties.deviceName); // Get Memory information and properties - this is required later, when we begin // allocating buffers to store data. vkGetPhysicalDeviceMemoryProperties(m_physicalDevice, &(m_physicalDeviceMemoryProperties)); return true; } void VulkanCore::InitDevice() { VkResult ret = VK_SUCCESS; // Akin to when creating the instance, we can query extensions supported by the physical device // that we have selected to use. uint32_t deviceExtensionCount = 0; VkExtensionProperties *device_extensions = nullptr; ret = vkEnumerateDeviceExtensionProperties(m_physicalDevice, nullptr, &deviceExtensionCount, nullptr); GVR_VK_CHECK(!ret); VkBool32 swapchainExtFound = 0; VkExtensionProperties* deviceExtensions = new VkExtensionProperties[deviceExtensionCount]; ret = vkEnumerateDeviceExtensionProperties(m_physicalDevice, nullptr, &deviceExtensionCount, deviceExtensions); GVR_VK_CHECK(!ret); // For our example, we require the swapchain extension, which is used to present backbuffers efficiently // to the users screen. uint32_t enabledExtensionCount = 0; const char* extensionNames[16] = {0}; for (uint32_t i = 0; i < deviceExtensionCount; i++) { if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, deviceExtensions[i].extensionName)) { swapchainExtFound = 1; extensionNames[enabledExtensionCount++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME; } GVR_VK_CHECK(enabledExtensionCount < 16); } if (!swapchainExtFound) { LOGE("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME " extension: vkCreateInstance Failure"); // Always attempt to enable the swapchain extensionNames[enabledExtensionCount++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME; } //InitSurface(); // Before we create our main Vulkan device, we must ensure our physical device // has queue families which can perform the actions we require. For this, we request // the number of queue families, and their properties. uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(m_physicalDevice, &queueFamilyCount, nullptr); VkQueueFamilyProperties* queueProperties = new VkQueueFamilyProperties[queueFamilyCount]; vkGetPhysicalDeviceQueueFamilyProperties(m_physicalDevice, &queueFamilyCount, queueProperties); GVR_VK_CHECK(queueFamilyCount >= 1); // We query each queue family in turn for the ability to support the android surface // that was created earlier. We need the device to be able to present its images to // this surface, so it is important to test for this. VkBool32* supportsPresent = new VkBool32[queueFamilyCount]; for (uint32_t i = 0; i < queueFamilyCount; i++) { vkGetPhysicalDeviceSurfaceSupportKHR(m_physicalDevice, i, m_surface, &supportsPresent[i]); } // Search for a graphics queue, and ensure it also supports our surface. We want a // queue which can be used for both, as to simplify operations. uint32_t queueIndex = queueFamilyCount + 1; for (uint32_t i = 0; i < queueFamilyCount; i++) { if ((queueProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { if (supportsPresent[i] == VK_TRUE) { queueIndex = i; break; } } } delete [] supportsPresent; delete [] queueProperties; if (queueIndex == (queueFamilyCount + 1)) { GVR_VK_CHECK("Could not obtain a queue family for both graphics and presentation." && 0); } // We have identified a queue family which both supports our android surface, // and can be used for graphics operations. m_queueFamilyIndex = queueIndex; // As we create the device, we state we will be creating a queue of the // family type required. 1.0 is the highest priority and we use that. float queuePriorities[1] = { 1.0 }; VkDeviceQueueCreateInfo deviceQueueCreateInfo = {}; deviceQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; deviceQueueCreateInfo.pNext = nullptr; deviceQueueCreateInfo.queueFamilyIndex = m_queueFamilyIndex; deviceQueueCreateInfo.queueCount = 1; deviceQueueCreateInfo.pQueuePriorities = queuePriorities; // Now we pass the queue create info, as well as our requested extensions, // into our DeviceCreateInfo structure. VkDeviceCreateInfo deviceCreateInfo = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.pNext = nullptr; deviceCreateInfo.queueCreateInfoCount = 1; deviceCreateInfo.pQueueCreateInfos = &deviceQueueCreateInfo; deviceCreateInfo.enabledLayerCount = 0; deviceCreateInfo.ppEnabledLayerNames = nullptr; deviceCreateInfo.enabledExtensionCount = enabledExtensionCount; deviceCreateInfo.ppEnabledExtensionNames = extensionNames; // Create the device. ret = vkCreateDevice(m_physicalDevice, &deviceCreateInfo, nullptr, &m_device); GVR_VK_CHECK(!ret); // Obtain the device queue that we requested. vkGetDeviceQueue(m_device, m_queueFamilyIndex, 0, &m_queue); } void VulkanCore::InitSwapchain(uint32_t width, uint32_t height){ VkResult ret = VK_SUCCESS; m_width = width;// 320;//surfaceCapabilities.currentExtent.width; m_height = height;//240;//surfaceCapabilities.currentExtent.height; VkImageCreateInfo imageCreateInfo = {}; imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCreateInfo.pNext = nullptr; imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = VK_FORMAT_R8G8B8A8_UINT;//VK_FORMAT_R8G8B8A8_UNORM;//m_surfaceFormat.format;//VK_FORMAT_R32G32B32A32_SFLOAT; imageCreateInfo.extent = {m_width, m_height, 1}; imageCreateInfo .mipLevels = 1; imageCreateInfo .arrayLayers = 1; imageCreateInfo .samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_LINEAR; imageCreateInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT ; imageCreateInfo .flags = 0; imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; //LOGI("Vulkan Format %d ", m_surfaceFormat.format); // Create the image with details as imageCreateInfo m_swapchainImageCount = 2; m_swapchainBuffers = new GVR_VK_SwapchainBuffer[m_swapchainImageCount]; GVR_VK_CHECK(m_swapchainBuffers); for(int i = 0; i < m_swapchainImageCount; i++) { VkMemoryRequirements mem_reqs; VkResult err; bool pass; ret = vkCreateImage(m_device, &imageCreateInfo, nullptr, &m_swapchainBuffers[i].image); GVR_VK_CHECK(!ret); // discover what memory requirements are for this image. vkGetImageMemoryRequirements(m_device, m_swapchainBuffers[i].image, &mem_reqs); //LOGD("Vulkan image memreq %d", mem_reqs.size); m_swapchainBuffers[i].size = mem_reqs.size; // Allocate memory according to requirements VkMemoryAllocateInfo memoryAllocateInfo = {}; memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memoryAllocateInfo.pNext = nullptr; memoryAllocateInfo.allocationSize = 0; memoryAllocateInfo.memoryTypeIndex = 0; memoryAllocateInfo.allocationSize = mem_reqs.size; pass = GetMemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memoryAllocateInfo.memoryTypeIndex); GVR_VK_CHECK(pass); err = vkAllocateMemory(m_device, &memoryAllocateInfo, nullptr, &m_swapchainBuffers[i].mem); GVR_VK_CHECK(!err); // Bind memory to the image err = vkBindImageMemory(m_device, m_swapchainBuffers[i].image, m_swapchainBuffers[i].mem, 0); GVR_VK_CHECK(!err); VkImageViewCreateInfo imageViewCreateInfo = {}; imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewCreateInfo.pNext = nullptr; imageViewCreateInfo.format = VK_FORMAT_R8G8B8A8_UINT;//VK_FORMAT_R8G8B8A8_UNORM;//m_surfaceFormat.format; imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_R; imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_G; imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_B; imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_A; imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imageViewCreateInfo.subresourceRange.baseMipLevel = 0; imageViewCreateInfo.subresourceRange.levelCount = 1; imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; imageViewCreateInfo.subresourceRange.layerCount = 1; imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewCreateInfo.flags = 0; imageViewCreateInfo.image = m_swapchainBuffers[i].image; err = vkCreateImageView(m_device, &imageViewCreateInfo, nullptr, &m_swapchainBuffers[i].view); GVR_VK_CHECK(!err); } m_depthBuffers = new GVR_VK_DepthBuffer[m_swapchainImageCount]; for (int i = 0; i < m_swapchainImageCount; i++) { const VkFormat depthFormat = VK_FORMAT_D16_UNORM; VkImageCreateInfo imageCreateInfo = {}; imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCreateInfo.pNext = nullptr; imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = depthFormat; imageCreateInfo.extent = {m_width, m_height, 1}; imageCreateInfo .mipLevels = 1; imageCreateInfo .arrayLayers = 1; imageCreateInfo .samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageCreateInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; imageCreateInfo .flags = 0; VkImageViewCreateInfo imageViewCreateInfo = {}; imageViewCreateInfo .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewCreateInfo .pNext = nullptr; imageViewCreateInfo .image = VK_NULL_HANDLE; imageViewCreateInfo.format = depthFormat; imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; imageViewCreateInfo.subresourceRange.baseMipLevel = 0; imageViewCreateInfo.subresourceRange.levelCount = 1; imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; imageViewCreateInfo.subresourceRange.layerCount = 1; imageViewCreateInfo.flags = 0; imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; VkMemoryRequirements mem_reqs; VkResult err; bool pass; m_depthBuffers[i].format = depthFormat; // Create the image with details as imageCreateInfo err = vkCreateImage(m_device, &imageCreateInfo, nullptr, &m_depthBuffers[i].image); GVR_VK_CHECK(!err); // discover what memory requirements are for this image. vkGetImageMemoryRequirements(m_device, m_depthBuffers[i].image, &mem_reqs); // Allocate memory according to requirements VkMemoryAllocateInfo memoryAllocateInfo = {}; memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memoryAllocateInfo.pNext = nullptr; memoryAllocateInfo.allocationSize = 0; memoryAllocateInfo.memoryTypeIndex = 0; memoryAllocateInfo.allocationSize = mem_reqs.size; pass = GetMemoryTypeFromProperties(mem_reqs.memoryTypeBits, 0, &memoryAllocateInfo.memoryTypeIndex); GVR_VK_CHECK(pass); err = vkAllocateMemory(m_device, &memoryAllocateInfo, nullptr, &m_depthBuffers[i].mem); GVR_VK_CHECK(!err); // Bind memory to the image err = vkBindImageMemory(m_device, m_depthBuffers[i].image, m_depthBuffers[i].mem, 0); GVR_VK_CHECK(!err); // Create the view for this image imageViewCreateInfo.image = m_depthBuffers[i].image; err = vkCreateImageView(m_device, &imageViewCreateInfo, nullptr, &m_depthBuffers[i].view); GVR_VK_CHECK(!err); } } bool VulkanCore::GetMemoryTypeFromProperties( uint32_t typeBits, VkFlags requirements_mask, uint32_t* typeIndex) { GVR_VK_CHECK(typeIndex != nullptr); // Search memtypes to find first index with those properties for (uint32_t i = 0; i < 32; i++) { if ((typeBits & 1) == 1) { // Type is available, does it match user properties? if ((m_physicalDeviceMemoryProperties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { *typeIndex = i; return true; } } typeBits >>= 1; } // No memory types matched, return failure return false; } void VulkanCore::InitCommandbuffers(){ VkResult ret = VK_SUCCESS; // Command buffers are allocated from a pool; we define that pool here and create it. VkCommandPoolCreateInfo commandPoolCreateInfo = {}; commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; commandPoolCreateInfo.pNext = nullptr; commandPoolCreateInfo.queueFamilyIndex = m_queueFamilyIndex; commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; ret = vkCreateCommandPool(m_device, &commandPoolCreateInfo, nullptr, &m_commandPool); GVR_VK_CHECK(!ret); VkCommandBufferAllocateInfo commandBufferAllocateInfo = {}; commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; commandBufferAllocateInfo.pNext = nullptr; commandBufferAllocateInfo.commandPool = m_commandPool; commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; commandBufferAllocateInfo.commandBufferCount = 1; // Create render command buffers, one per swapchain image for (int i=0; i < m_swapchainImageCount; i++) { ret = vkAllocateCommandBuffers(m_device, &commandBufferAllocateInfo, &m_swapchainBuffers[i].cmdBuffer); GVR_VK_CHECK(!ret); } } void VulkanCore::InitVertexBuffers(){ // Our vertex buffer data is a simple triangle, with associated vertex colors. const float vb[3][7] = { // position color { -0.9f, -0.9f, 0.9f, 1.0f, 0.0f, 0.0f, 1.0f }, { 0.9f, -0.9f, 0.9f, 1.0f, 0.0f, 0.0f, 1.0f }, { 0.0f, 0.9f, 0.9f, 1.0f, 0.0f, 0.0f, 1.0f }, }; VkResult err; bool pass; // Our m_vertices member contains the types required for storing // and defining our vertex buffer within the graphics pipeline. memset(&m_vertices, 0, sizeof(m_vertices)); // Create our buffer object. VkBufferCreateInfo bufferCreateInfo = {}; bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreateInfo.pNext = nullptr; bufferCreateInfo.size = sizeof(vb); bufferCreateInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; bufferCreateInfo.flags = 0; err = vkCreateBuffer(m_device, &bufferCreateInfo, nullptr, &m_vertices.buf); GVR_VK_CHECK(!err); // Obtain the memory requirements for this buffer. VkMemoryRequirements mem_reqs; vkGetBufferMemoryRequirements(m_device, m_vertices.buf, &mem_reqs); GVR_VK_CHECK(!err); // And allocate memory according to those requirements. VkMemoryAllocateInfo memoryAllocateInfo = {}; memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memoryAllocateInfo.pNext = nullptr; memoryAllocateInfo.allocationSize = 0; memoryAllocateInfo.memoryTypeIndex = 0; memoryAllocateInfo.allocationSize = mem_reqs.size; pass = GetMemoryTypeFromProperties(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memoryAllocateInfo.memoryTypeIndex); GVR_VK_CHECK(pass); err = vkAllocateMemory(m_device, &memoryAllocateInfo, nullptr, &m_vertices.mem); GVR_VK_CHECK(!err); // Now we need to map the memory of this new allocation so the CPU can edit it. void *data; err = vkMapMemory(m_device, m_vertices.mem, 0, memoryAllocateInfo.allocationSize, 0, &data); GVR_VK_CHECK(!err); // Copy our triangle verticies and colors into the mapped memory area. memcpy(data, vb, sizeof(vb)); // Unmap the memory back from the CPU. vkUnmapMemory(m_device, m_vertices.mem); // Bind our buffer to the memory. err = vkBindBufferMemory(m_device, m_vertices.buf, m_vertices.mem, 0); GVR_VK_CHECK(!err); // The vertices need to be defined so that the pipeline understands how the // data is laid out. This is done by providing a VkPipelineVertexInputStateCreateInfo // structure with the correct information. m_vertices.vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; m_vertices.vi.pNext = nullptr; m_vertices.vi.vertexBindingDescriptionCount = 1; m_vertices.vi.pVertexBindingDescriptions = m_vertices.vi_bindings; m_vertices.vi.vertexAttributeDescriptionCount = 2; m_vertices.vi.pVertexAttributeDescriptions = m_vertices.vi_attrs; // We bind the buffer as a whole, using the correct buffer ID. // This defines the stride for each element of the vertex array. m_vertices.vi_bindings[0].binding = GVR_VK_VERTEX_BUFFER_BIND_ID; m_vertices.vi_bindings[0].stride = sizeof(vb[0]); m_vertices.vi_bindings[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // Within each element, we define the attributes. At location 0, // the vertex positions, in float3 format, with offset 0 as they are // first in the array structure. m_vertices.vi_attrs[0].binding = GVR_VK_VERTEX_BUFFER_BIND_ID; m_vertices.vi_attrs[0].location = 0; m_vertices.vi_attrs[0].format = VK_FORMAT_R32G32B32_SFLOAT; //float3 m_vertices.vi_attrs[0].offset = 0; // The second location is the vertex colors, in RGBA float4 format. // These appear in each element in memory after the float3 vertex // positions, so the offset is set accordingly. m_vertices.vi_attrs[1].binding = GVR_VK_VERTEX_BUFFER_BIND_ID; m_vertices.vi_attrs[1].location = 1; m_vertices.vi_attrs[1].format = VK_FORMAT_R32G32B32A32_SFLOAT; //float4 m_vertices.vi_attrs[1].offset = sizeof(float) * 3; } void VulkanCore::InitLayouts(){ VkResult ret = VK_SUCCESS; // This sample has no bindings, so the layout is empty. VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = {}; descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorSetLayoutCreateInfo.pNext = nullptr; descriptorSetLayoutCreateInfo.bindingCount = 0; descriptorSetLayoutCreateInfo.pBindings = nullptr; ret = vkCreateDescriptorSetLayout(m_device, &descriptorSetLayoutCreateInfo, nullptr, &m_descriptorLayout); GVR_VK_CHECK(!ret); // Our pipeline layout simply points to the empty descriptor layout. VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {}; pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutCreateInfo.pNext = nullptr; pipelineLayoutCreateInfo.setLayoutCount = 1; pipelineLayoutCreateInfo.pSetLayouts = &m_descriptorLayout; ret = vkCreatePipelineLayout(m_device, &pipelineLayoutCreateInfo, nullptr, &m_pipelineLayout); GVR_VK_CHECK(!ret); } void VulkanCore::InitRenderPass(){ // The renderpass defines the attachments to the framebuffer object that gets // used in the pipeline. We have two attachments, the colour buffer, and the // depth buffer. The operations and layouts are set to defaults for this type // of attachment. VkAttachmentDescription attachmentDescriptions[2] = {}; attachmentDescriptions[0].flags = 0; attachmentDescriptions[0].format = m_surfaceFormat.format; attachmentDescriptions[0].samples = VK_SAMPLE_COUNT_1_BIT; attachmentDescriptions[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachmentDescriptions[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachmentDescriptions[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescriptions[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescriptions[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachmentDescriptions[0].finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; attachmentDescriptions[1].flags = 0; attachmentDescriptions[1].format = m_depthBuffers[0].format; attachmentDescriptions[1].samples = VK_SAMPLE_COUNT_1_BIT; attachmentDescriptions[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attachmentDescriptions[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescriptions[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescriptions[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachmentDescriptions[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachmentDescriptions[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; // We have references to the attachment offsets, stating the layout type. VkAttachmentReference colorReference = {}; colorReference.attachment = 0; colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference depthReference = {}; depthReference.attachment = 1; depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; // There can be multiple subpasses in a renderpass, but this example has only one. // We set the color and depth references at the grahics bind point in the pipeline. VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.flags = 0; subpassDescription.inputAttachmentCount = 0; subpassDescription.pInputAttachments = nullptr; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorReference; subpassDescription.pResolveAttachments = nullptr; subpassDescription.pDepthStencilAttachment = nullptr;//&depthReference; subpassDescription.preserveAttachmentCount = 0; subpassDescription.pPreserveAttachments = nullptr; // The renderpass itself is created with the number of subpasses, and the // list of attachments which those subpasses can reference. VkRenderPassCreateInfo renderPassCreateInfo = {}; renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassCreateInfo.pNext = nullptr; renderPassCreateInfo.attachmentCount = 2; renderPassCreateInfo.pAttachments = attachmentDescriptions; renderPassCreateInfo.subpassCount = 1; renderPassCreateInfo.pSubpasses = &subpassDescription; renderPassCreateInfo.dependencyCount = 0; renderPassCreateInfo.pDependencies = nullptr; VkResult ret; ret = vkCreateRenderPass(m_device, &renderPassCreateInfo, nullptr, &m_renderPass); GVR_VK_CHECK(!ret); } void VulkanCore::InitPipeline(){ #if 0 VkResult err; // The pipeline contains all major state for rendering. // Our vertex input is a single vertex buffer, and its layout is defined // in our m_vertices object already. Use this when creating the pipeline. VkPipelineVertexInputStateCreateInfo vi = {}; vi = m_vertices.vi; // Our vertex buffer describes a triangle list. VkPipelineInputAssemblyStateCreateInfo ia = {}; ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // State for rasterization, such as polygon fill mode is defined. VkPipelineRasterizationStateCreateInfo rs = {}; rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rs.polygonMode = VK_POLYGON_MODE_FILL; rs.cullMode = VK_CULL_MODE_BACK_BIT; rs.frontFace = VK_FRONT_FACE_CLOCKWISE; rs.depthClampEnable = VK_FALSE; rs.rasterizerDiscardEnable = VK_FALSE; rs.depthBiasEnable = VK_FALSE; // For this example we do not do blending, so it is disabled. VkPipelineColorBlendAttachmentState att_state[1] = {}; att_state[0].colorWriteMask = 0xf; att_state[0].blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo cb = {}; cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; cb.attachmentCount = 1; cb.pAttachments = &att_state[0]; // We define a simple viewport and scissor. It does not change during rendering // in this sample. VkPipelineViewportStateCreateInfo vp = {}; vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; vp.viewportCount = 1; vp.scissorCount = 1; VkViewport viewport = {}; viewport.height = (float) m_height; viewport.width = (float) m_width; viewport.minDepth = (float) 0.0f; viewport.maxDepth = (float) 1.0f; vp.pViewports = &viewport; VkRect2D scissor = {}; scissor.extent.width = m_width; scissor.extent.height = m_height; scissor.offset.x = 0; scissor.offset.y = 0; vp.pScissors = &scissor; // Standard depth and stencil state is defined VkPipelineDepthStencilStateCreateInfo ds = {}; ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; ds.depthTestEnable = VK_TRUE; ds.depthWriteEnable = VK_TRUE; ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; ds.depthBoundsTestEnable = VK_FALSE; ds.back.failOp = VK_STENCIL_OP_KEEP; ds.back.passOp = VK_STENCIL_OP_KEEP; ds.back.compareOp = VK_COMPARE_OP_ALWAYS; ds.stencilTestEnable = VK_FALSE; ds.front = ds.back; // We do not use multisample VkPipelineMultisampleStateCreateInfo ms = {}; ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; ms.pSampleMask = nullptr; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; // We define two shader stages: our vertex and fragment shader. // they are embedded as SPIR-V into a header file for ease of deployment. VkPipelineShaderStageCreateInfo shaderStages[2] = {}; shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; shaderStages[0].module = CreateShaderModule( (const uint32_t*)&shader_tri_vert[0], shader_tri_vert_size); shaderStages[0].pName = "main"; shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; shaderStages[1].module = CreateShaderModule( (const uint32_t*)&shader_tri_frag[0], shader_tri_frag_size); shaderStages[1].pName = "main"; // Pipelines are allocated from pipeline caches. VkPipelineCacheCreateInfo pipelineCache = {}; pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; pipelineCache.pNext = nullptr; pipelineCache.flags = 0; VkPipelineCache piplineCache; err = vkCreatePipelineCache(m_device, &pipelineCache, nullptr, &piplineCache); GVR_VK_CHECK(!err); // Out graphics pipeline records all state information, including our renderpass // and pipeline layout. We do not have any dynamic state in this example. VkGraphicsPipelineCreateInfo pipelineCreateInfo = {}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.layout = m_pipelineLayout; pipelineCreateInfo.pVertexInputState = &vi; pipelineCreateInfo.pInputAssemblyState = &ia; pipelineCreateInfo.pRasterizationState = &rs; pipelineCreateInfo.pColorBlendState = &cb; pipelineCreateInfo.pMultisampleState = &ms; pipelineCreateInfo.pViewportState = &vp; pipelineCreateInfo.pDepthStencilState = nullptr;//&ds; pipelineCreateInfo.pStages = &shaderStages[0]; pipelineCreateInfo.renderPass = m_renderPass; pipelineCreateInfo.pDynamicState = nullptr; pipelineCreateInfo.stageCount = 2; //vertex and fragment err = vkCreateGraphicsPipelines(m_device, piplineCache, 1, &pipelineCreateInfo, nullptr, &m_pipeline); GVR_VK_CHECK(!err); // We can destroy the cache now as we do not need it. The shader modules also // can be destroyed after the pipeline is created. vkDestroyPipelineCache(m_device, piplineCache, nullptr); vkDestroyShaderModule(m_device, shaderStages[0].module, nullptr); vkDestroyShaderModule(m_device, shaderStages[1].module, nullptr); #endif } void VulkanCore::InitFrameBuffers(){ //The framebuffer objects reference the renderpass, and allow // the references defined in that renderpass to now attach to views. // The views in this example are the colour view, which is our swapchain image, // and the depth buffer created manually earlier. VkImageView attachments [2] = {}; VkFramebufferCreateInfo framebufferCreateInfo = {}; framebufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferCreateInfo.pNext = nullptr; framebufferCreateInfo.renderPass = m_renderPass; framebufferCreateInfo.attachmentCount = 2; framebufferCreateInfo.pAttachments = attachments; framebufferCreateInfo.width = m_width; framebufferCreateInfo.height = m_height; framebufferCreateInfo.layers = 1; VkResult ret; m_frameBuffers = new VkFramebuffer[m_swapchainImageCount]; // Reusing the framebufferCreateInfo to create m_swapchainImageCount framebuffers, // only the attachments to the relevent image views change each time. for (uint32_t i = 0; i < m_swapchainImageCount; i++) { attachments[0] = m_swapchainBuffers[i].view; //framebufferCreateInfo.pAttachments = &m_swapchainBuffers[i].view; attachments[1] = m_depthBuffers[i].view; LOGI("Vulkan view %d created", i); if((m_swapchainBuffers[i].view == VK_NULL_HANDLE) || (m_renderPass == VK_NULL_HANDLE)){ LOGI("Vulkan image view null"); } else LOGI("Vulkan image view not null"); ret = vkCreateFramebuffer(m_device, &framebufferCreateInfo, nullptr, &m_frameBuffers[i]); GVR_VK_CHECK(!ret); } } void VulkanCore::InitSync(){ VkResult ret = VK_SUCCESS; // For synchronization, we have semaphores for rendering and backbuffer signalling. VkSemaphoreCreateInfo semaphoreCreateInfo = {}; semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; semaphoreCreateInfo.pNext = nullptr; semaphoreCreateInfo.flags = 0; ret = vkCreateSemaphore(m_device, &semaphoreCreateInfo, nullptr, &m_backBufferSemaphore); GVR_VK_CHECK(!ret); ret = vkCreateSemaphore(m_device, &semaphoreCreateInfo, nullptr, &m_renderCompleteSemaphore); GVR_VK_CHECK(!ret); } void VulkanCore::BuildCmdBuffer() { // For the triangle sample, we pre-record our command buffer, as it is static. // We have a buffer per swap chain image, so loop over the creation process. for (uint32_t i = 0; i < m_swapchainImageCount; i++) { VkCommandBuffer &cmdBuffer = m_swapchainBuffers[i].cmdBuffer; // vkBeginCommandBuffer should reset the command buffer, but Reset can be called // to make it more explicit. VkResult err; err = vkResetCommandBuffer(cmdBuffer, 0); GVR_VK_CHECK(!err); VkCommandBufferInheritanceInfo cmd_buf_hinfo = {}; cmd_buf_hinfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO; cmd_buf_hinfo.pNext = nullptr; cmd_buf_hinfo.renderPass = VK_NULL_HANDLE; cmd_buf_hinfo.subpass = 0; cmd_buf_hinfo.framebuffer = VK_NULL_HANDLE; cmd_buf_hinfo.occlusionQueryEnable = VK_FALSE; cmd_buf_hinfo.queryFlags = 0; cmd_buf_hinfo.pipelineStatistics = 0; VkCommandBufferBeginInfo cmd_buf_info = {}; cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmd_buf_info.pNext = nullptr; cmd_buf_info.flags = 0; cmd_buf_info.pInheritanceInfo = &cmd_buf_hinfo; // By calling vkBeginCommandBuffer, cmdBuffer is put into the recording state. err = vkBeginCommandBuffer(cmdBuffer, &cmd_buf_info); GVR_VK_CHECK(!err); // Before we can use the back buffer from the swapchain, we must change the // image layout from the PRESENT mode to the COLOR_ATTACHMENT mode. // PRESENT mode is optimal for sending to the screen for users to see, so the // image will be set back to that mode after we have completed rendering. VkImageMemoryBarrier preRenderBarrier = {}; preRenderBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; preRenderBarrier.pNext = nullptr; preRenderBarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; preRenderBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; preRenderBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; preRenderBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; preRenderBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; preRenderBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; preRenderBarrier.image = m_swapchainBuffers[i].image; preRenderBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; preRenderBarrier.subresourceRange.baseArrayLayer = 0; preRenderBarrier.subresourceRange.baseMipLevel = 1; preRenderBarrier.subresourceRange.layerCount = 0; preRenderBarrier.subresourceRange.levelCount = 1; // Thie PipelineBarrier function can operate on memoryBarriers, // bufferMemory and imageMemory buffers. We only provide a single // imageMemoryBarrier. vkCmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, &preRenderBarrier); // When starting the render pass, we can set clear values. VkClearValue clear_values[2] = {}; clear_values[0].color.float32[0] = 0.3f; clear_values[0].color.float32[1] = 0.3f; clear_values[0].color.float32[2] = 0.3f; clear_values[0].color.float32[3] = 1.0f; clear_values[1].depthStencil.depth = 1.0f; clear_values[1].depthStencil.stencil = 0; VkRenderPassBeginInfo rp_begin = {}; rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; rp_begin.pNext = nullptr; rp_begin.renderPass = m_renderPass; rp_begin.framebuffer = m_frameBuffers[i]; rp_begin.renderArea.offset.x = 0; rp_begin.renderArea.offset.y = 0; rp_begin.renderArea.extent.width = m_width; rp_begin.renderArea.extent.height = m_height; rp_begin.clearValueCount = 2; rp_begin.pClearValues = clear_values; vkCmdBeginRenderPass(cmdBuffer, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); // Set our pipeline. This holds all major state // the pipeline defines, for example, that the vertex buffer is a triangle list. vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline); // Bind our vertex buffer, with a 0 offset. VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(cmdBuffer, GVR_VK_VERTEX_BUFFER_BIND_ID, 1, &m_vertices.buf, offsets); // Issue a draw command, with our 3 vertices. vkCmdDraw(cmdBuffer, 3, 1, 0, 0); // Copy Image to Buffer VkOffset3D off = {}; off.x = 0; off.y = 0; off.z = 0; VkExtent3D extent3D = {}; extent3D.width = 320; extent3D.height = 240; VkImageSubresourceLayers subResource = {}; subResource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subResource.baseArrayLayer = 0; subResource.mipLevel = 0; subResource.layerCount = 1; VkBufferImageCopy someDetails = {}; someDetails.bufferOffset = 0; someDetails.bufferRowLength = 0; someDetails.bufferImageHeight = 0; someDetails.imageSubresource = subResource; someDetails.imageOffset = off; someDetails.imageExtent = extent3D; VkBufferImageCopy region = { 0 }; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.layerCount = 1; region.imageExtent.width = m_width; region.imageExtent.height = m_height; region.imageExtent.depth = 1; // Now our render pass has ended. vkCmdEndRenderPass(cmdBuffer); //vkCmdCopyImageToBuffer(cmdBuffer, m_swapchainBuffers[i].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, m_outputBuffers[i].imageOutputBuffer, 1, &region); // As stated earlier, now transition the swapchain image to the PRESENT mode. VkImageMemoryBarrier prePresentBarrier = {}; prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; prePresentBarrier.pNext = nullptr; prePresentBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; prePresentBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; prePresentBarrier.image = m_swapchainBuffers[i].image; prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; prePresentBarrier.subresourceRange.baseArrayLayer = 0; prePresentBarrier.subresourceRange.baseMipLevel = 1; prePresentBarrier.subresourceRange.layerCount = 0; vkCmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &prePresentBarrier); // By ending the command buffer, it is put out of record mode. err = vkEndCommandBuffer(cmdBuffer); GVR_VK_CHECK(!err); } VkFence nullFence = VK_NULL_HANDLE; VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.pNext = nullptr; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &m_backBufferSemaphore; submitInfo.pWaitDstStageMask = nullptr; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &m_swapchainBuffers[m_swapchainCurrentIdx].cmdBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &m_renderCompleteSemaphore; VkResult err; err = vkQueueSubmit(m_queue, 1, &submitInfo, VK_NULL_HANDLE); GVR_VK_CHECK(!err); err = vkQueueWaitIdle(m_queue); if(err != VK_SUCCESS) LOGI("Vulkan vkQueueWaitIdle submit failed"); LOGI("Vulkan vkQueueWaitIdle submitted"); uint8_t * data; static bool printflag = true; if(printflag){ uint8_t * data; err = vkMapMemory(m_device, m_swapchainBuffers[m_swapchainCurrentIdx].mem, 0, m_swapchainBuffers[m_swapchainCurrentIdx].size, 0, (void **)&data); GVR_VK_CHECK(!err); //void* data; uint8_t *finaloutput = (uint8_t*)malloc(m_width*m_height*4* sizeof(uint8_t)); for(int i = 0; i < (320); i++) finaloutput[i] = 0; LOGI("Vulkna size of %d", sizeof(finaloutput)); //while(1) { memcpy(finaloutput, data, (m_width*m_height*4* sizeof(uint8_t))); LOGI("Vulkan memcpy map done"); float tt; for (int i = 0; i < (m_width*m_height)-4; i++) { //tt = (float) data[i]; LOGI("Vulkan Data %u, %u %u %u", data[i], data[i+1], data[i+2], data[i+3]); i+=3; } texDataVulkan = data;//finaloutput; LOGI("Vulkan data reading done"); vkUnmapMemory(m_device,m_swapchainBuffers[m_swapchainCurrentIdx].mem); printflag = false; } } void VulkanCore::initVulkanCore() { #if 0 InitVulkan(); CreateInstance(); GetPhysicalDevices(); InitDevice(); InitSwapchain(1024 , 1024); LOGI("Vulkan after swap chain"); InitCommandbuffers(); LOGI("Vulkan after cmd buffers"); InitVertexBuffers(); LOGI("Vulkan after vert buf"); InitLayouts(); LOGI("Vulkan after layout"); InitRenderPass(); LOGI("Vulkan after render pass"); InitPipeline(); LOGI("Vulkan after piplen"); InitFrameBuffers(); LOGI("Vulkan after FBO"); InitSync(); LOGI("Vulkan after synch"); // Initialize our command buffers BuildCmdBuffer(); #endif }
rahul27/GearVRf
GVRf/Framework/framework/src/main/jni/vulkan/vulkanCore.cpp
C++
apache-2.0
46,740
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.configurable; import com.intellij.ide.actions.ShowFilePathAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx; import com.intellij.openapi.vcs.readOnlyHandler.ReadonlyStatusHandlerImpl; import com.intellij.openapi.vfs.ReadonlyStatusHandler; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.*; import java.util.List; public class VcsGeneralConfigurationPanel { private JCheckBox myShowReadOnlyStatusDialog; private JRadioButton myShowDialogOnAddingFile; private JRadioButton myPerformActionOnAddingFile; private JRadioButton myDoNothingOnAddingFile; private JRadioButton myShowDialogOnRemovingFile; private JRadioButton myPerformActionOnRemovingFile; private JRadioButton myDoNothingOnRemovingFile; private JPanel myPanel; private final JRadioButton[] myOnFileAddingGroup; private final JRadioButton[] myOnFileRemovingGroup; private final Project myProject; private JPanel myPromptsPanel; Map<VcsShowOptionsSettingImpl, JCheckBox> myPromptOptions = new LinkedHashMap<>(); private JPanel myRemoveConfirmationPanel; private JPanel myAddConfirmationPanel; private JComboBox myOnPatchCreation; private JCheckBox myReloadContext; private ButtonGroup myEmptyChangelistRemovingGroup; public VcsGeneralConfigurationPanel(final Project project) { myProject = project; myOnFileAddingGroup = new JRadioButton[]{ myShowDialogOnAddingFile, myPerformActionOnAddingFile, myDoNothingOnAddingFile }; myOnFileRemovingGroup = new JRadioButton[]{ myShowDialogOnRemovingFile, myPerformActionOnRemovingFile, myDoNothingOnRemovingFile }; myPromptsPanel.setLayout(new GridLayout(3, 0)); List<VcsShowOptionsSettingImpl> options = ProjectLevelVcsManagerEx.getInstanceEx(project).getAllOptions(); for (VcsShowOptionsSettingImpl setting : options) { if (!setting.getApplicableVcses().isEmpty() || project.isDefault()) { final JCheckBox checkBox = new JCheckBox(setting.getDisplayName()); myPromptsPanel.add(checkBox); myPromptOptions.put(setting, checkBox); } } myPromptsPanel.setSize(myPromptsPanel.getPreferredSize()); // todo check text! myOnPatchCreation.setName((SystemInfo.isMac ? "Reveal patch in" : "Show patch in ") + ShowFilePathAction.getFileManagerName() + " after creation:"); } public void apply() { VcsConfiguration settings = VcsConfiguration.getInstance(myProject); settings.REMOVE_EMPTY_INACTIVE_CHANGELISTS = getSelected(myEmptyChangelistRemovingGroup); settings.RELOAD_CONTEXT = myReloadContext.isSelected(); for (VcsShowOptionsSettingImpl setting : myPromptOptions.keySet()) { setting.setValue(myPromptOptions.get(setting).isSelected()); } getAddConfirmation().setValue(getSelected(myOnFileAddingGroup)); getRemoveConfirmation().setValue(getSelected(myOnFileRemovingGroup)); applyPatchOption(settings); getReadOnlyStatusHandler().getState().SHOW_DIALOG = myShowReadOnlyStatusDialog.isSelected(); } private void applyPatchOption(VcsConfiguration settings) { settings.SHOW_PATCH_IN_EXPLORER = getShowPatchValue(); } @Nullable private Boolean getShowPatchValue() { final int index = myOnPatchCreation.getSelectedIndex(); if (index == 0) { return null; } else if (index == 1) { return true; } else { return false; } } private VcsShowConfirmationOption getAddConfirmation() { return ProjectLevelVcsManagerEx.getInstanceEx(myProject) .getConfirmation(VcsConfiguration.StandardConfirmation.ADD); } private VcsShowConfirmationOption getRemoveConfirmation() { return ProjectLevelVcsManagerEx.getInstanceEx(myProject) .getConfirmation(VcsConfiguration.StandardConfirmation.REMOVE); } private static VcsShowConfirmationOption.Value getSelected(JRadioButton[] group) { if (group[0].isSelected()) return VcsShowConfirmationOption.Value.SHOW_CONFIRMATION; if (group[1].isSelected()) return VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY; return VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY; } private static VcsShowConfirmationOption.Value getSelected(ButtonGroup group) { switch (UIUtil.getSelectedButton(group)) { case 0: return VcsShowConfirmationOption.Value.SHOW_CONFIRMATION; case 1: return VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY; } return VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY; } private ReadonlyStatusHandlerImpl getReadOnlyStatusHandler() { return ((ReadonlyStatusHandlerImpl)ReadonlyStatusHandler.getInstance(myProject)); } public boolean isModified() { VcsConfiguration settings = VcsConfiguration.getInstance(myProject); if (settings.REMOVE_EMPTY_INACTIVE_CHANGELISTS != getSelected(myEmptyChangelistRemovingGroup)){ return true; } if (settings.RELOAD_CONTEXT != myReloadContext.isSelected()) return true; if (getReadOnlyStatusHandler().getState().SHOW_DIALOG != myShowReadOnlyStatusDialog.isSelected()) { return true; } for (VcsShowOptionsSettingImpl setting : myPromptOptions.keySet()) { if (setting.getValue() != myPromptOptions.get(setting).isSelected()) return true; } if (getSelected(myOnFileAddingGroup) != getAddConfirmation().getValue()) return true; if (getSelected(myOnFileRemovingGroup) != getRemoveConfirmation().getValue()) return true; if (! Comparing.equal(settings.SHOW_PATCH_IN_EXPLORER, getShowPatchValue())) return true; return false; } public void reset() { VcsConfiguration settings = VcsConfiguration.getInstance(myProject); myReloadContext.setSelected(settings.RELOAD_CONTEXT); VcsShowConfirmationOption.Value value = settings.REMOVE_EMPTY_INACTIVE_CHANGELISTS; UIUtil.setSelectedButton(myEmptyChangelistRemovingGroup, value == VcsShowConfirmationOption.Value.SHOW_CONFIRMATION ? 0 : value == VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY ? 2 : 1); myShowReadOnlyStatusDialog.setSelected(getReadOnlyStatusHandler().getState().SHOW_DIALOG); for (VcsShowOptionsSettingImpl setting : myPromptOptions.keySet()) { myPromptOptions.get(setting).setSelected(setting.getValue()); } selectInGroup(myOnFileAddingGroup, getAddConfirmation()); selectInGroup(myOnFileRemovingGroup, getRemoveConfirmation()); if (settings.SHOW_PATCH_IN_EXPLORER == null) { myOnPatchCreation.setSelectedIndex(0); } else if (Boolean.TRUE.equals(settings.SHOW_PATCH_IN_EXPLORER)) { myOnPatchCreation.setSelectedIndex(1); } else { myOnPatchCreation.setSelectedIndex(2); } } private static void selectInGroup(final JRadioButton[] group, final VcsShowConfirmationOption confirmation) { final VcsShowConfirmationOption.Value value = confirmation.getValue(); final int index; //noinspection EnumSwitchStatementWhichMissesCases switch(value) { case SHOW_CONFIRMATION: index = 0; break; case DO_ACTION_SILENTLY: index = 1; break; default: index = 2; } group[index].setSelected(true); } public JComponent getPanel() { return myPanel; } public void updateAvailableOptions(final Collection<AbstractVcs> activeVcses) { for (VcsShowOptionsSettingImpl setting : myPromptOptions.keySet()) { final JCheckBox checkBox = myPromptOptions.get(setting); checkBox.setEnabled(setting.isApplicableTo(activeVcses) || myProject.isDefault()); if (!myProject.isDefault()) { checkBox.setToolTipText(VcsBundle.message("tooltip.text.action.applicable.to.vcses", composeText(setting.getApplicableVcses()))); } } if (!myProject.isDefault()) { final ProjectLevelVcsManagerEx vcsManager = ProjectLevelVcsManagerEx.getInstanceEx(myProject); final VcsShowConfirmationOptionImpl addConfirmation = vcsManager.getConfirmation(VcsConfiguration.StandardConfirmation.ADD); UIUtil.setEnabled(myAddConfirmationPanel, addConfirmation.isApplicableTo(activeVcses), true); myAddConfirmationPanel.setToolTipText( VcsBundle.message("tooltip.text.action.applicable.to.vcses", composeText(addConfirmation.getApplicableVcses()))); final VcsShowConfirmationOptionImpl removeConfirmation = vcsManager.getConfirmation(VcsConfiguration.StandardConfirmation.REMOVE); UIUtil.setEnabled(myRemoveConfirmationPanel, removeConfirmation.isApplicableTo(activeVcses), true); myRemoveConfirmationPanel.setToolTipText( VcsBundle.message("tooltip.text.action.applicable.to.vcses", composeText(removeConfirmation.getApplicableVcses()))); } } private static String composeText(final List<AbstractVcs> applicableVcses) { final TreeSet<String> result = new TreeSet<>(); for (AbstractVcs abstractVcs : applicableVcses) { result.add(abstractVcs.getDisplayName()); } return StringUtil.join(result, ", "); } }
jk1/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/VcsGeneralConfigurationPanel.java
Java
apache-2.0
10,031
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Xunit; namespace Apache.Arrow.Tests { public class BitUtilityTests { public class ByteCount { [Theory] [InlineData(0, 0)] [InlineData(1, 1)] [InlineData(8, 1)] [InlineData(9, 2)] [InlineData(32, 4)] public void HasExpectedResult(int n, int expected) { var count = BitUtility.ByteCount(n); Assert.Equal(expected, count); } } public class CountBits { [Theory] [InlineData(new byte[] { 0b00000000 }, 0)] [InlineData(new byte[] { 0b00000001 }, 1)] [InlineData(new byte[] { 0b11111111 }, 8)] [InlineData(new byte[] { 0b01001001, 0b01010010 }, 6)] public void CountsAllOneBits(byte[] data, int expectedCount) { Assert.Equal(expectedCount, BitUtility.CountBits(data)); } [Theory] [InlineData(new byte[] { 0b11111111 }, 0, 8)] [InlineData(new byte[] { 0b11111111 }, 3, 5)] [InlineData(new byte[] { 0b11111111, 0b11111111 }, 9, 7)] [InlineData(new byte[] { 0b11111111 }, -1, 0)] public void CountsAllOneBitsFromAnOffset(byte[] data, int offset, int expectedCount) { Assert.Equal(expectedCount, BitUtility.CountBits(data, offset)); } [Theory] [InlineData(new byte[] { 0b11111111 }, 0, 8, 8)] [InlineData(new byte[] { 0b11111111 }, 0, 4, 4)] [InlineData(new byte[] { 0b11111111 }, 3, 2, 2)] [InlineData(new byte[] { 0b11111111 }, 3, 5, 5)] [InlineData(new byte[] { 0b11111111, 0b11111111 }, 9, 7, 7)] [InlineData(new byte[] { 0b11111111, 0b11111111 }, 7, 2, 2)] [InlineData(new byte[] { 0b11111111, 0b11111111, 0b11111111 }, 0, 24, 24)] [InlineData(new byte[] { 0b11111111, 0b11111111, 0b11111111 }, 8, 16, 16)] [InlineData(new byte[] { 0b11111111, 0b11111111, 0b11111111 }, 0, 16, 16)] [InlineData(new byte[] { 0b11111111, 0b11111111, 0b11111111 }, 3, 18, 18)] [InlineData(new byte[] { 0b11111111 }, -1, 0, 0)] public void CountsAllOneBitsFromOffsetWithinLength(byte[] data, int offset, int length, int expectedCount) { var actualCount = BitUtility.CountBits(data, offset, length); Assert.Equal(expectedCount, actualCount); } [Fact] public void CountsZeroBitsWhenDataIsEmpty() { Assert.Equal(0, BitUtility.CountBits(null)); } } public class GetBit { [Theory] [InlineData(new byte[] { 0b01001001 }, 0, true)] [InlineData(new byte[] { 0b01001001 }, 1, false)] [InlineData(new byte[] { 0b01001001 }, 2, false)] [InlineData(new byte[] { 0b01001001 }, 3, true)] [InlineData(new byte[] { 0b01001001 }, 4, false)] [InlineData(new byte[] { 0b01001001 }, 5, false)] [InlineData(new byte[] { 0b01001001 }, 6, true)] [InlineData(new byte[] { 0b01001001 }, 7, false)] [InlineData(new byte[] { 0b01001001, 0b01010010 }, 8, false)] [InlineData(new byte[] { 0b01001001, 0b01010010 }, 14, true)] public void GetsCorrectBitForIndex(byte[] data, int index, bool expectedValue) { Assert.Equal(expectedValue, BitUtility.GetBit(data, index)); } [Theory] [InlineData(null, 0)] [InlineData(new byte[] { 0b00000000 }, -1)] public void ThrowsWhenBitIndexOutOfRange(byte[] data, int index) { Assert.Throws<IndexOutOfRangeException>(() => BitUtility.GetBit(data, index)); } } public class SetBit { [Theory] [InlineData(new byte[] { 0b00000000 }, 0, new byte[] { 0b00000001 })] [InlineData(new byte[] { 0b00000000 }, 2, new byte[] { 0b00000100 })] [InlineData(new byte[] { 0b00000000 }, 7, new byte[] { 0b10000000 })] [InlineData(new byte[] { 0b00000000, 0b00000000 }, 8, new byte[] { 0b00000000, 0b00000001 })] [InlineData(new byte[] { 0b00000000, 0b00000000 }, 15, new byte[] { 0b00000000, 0b10000000 })] public void SetsBitAtIndex(byte[] data, int index, byte[] expectedValue) { BitUtility.SetBit(data, index); Assert.Equal(expectedValue, data); } } public class ClearBit { [Theory] [InlineData(new byte[] { 0b00000001 }, 0, new byte[] { 0b00000000 })] [InlineData(new byte[] { 0b00000010 }, 1, new byte[] { 0b00000000 })] [InlineData(new byte[] { 0b10000001 }, 7, new byte[] { 0b00000001 })] [InlineData(new byte[] { 0b11111111, 0b11111111 }, 15, new byte[] { 0b11111111, 0b01111111 })] public void ClearsBitAtIndex(byte[] data, int index, byte[] expectedValue) { BitUtility.ClearBit(data, index); Assert.Equal(expectedValue, data); } } public class RoundUpToMultipleOf64 { [Theory] [InlineData(0, 0)] [InlineData(1, 64)] [InlineData(63, 64)] [InlineData(64, 64)] [InlineData(65, 128)] [InlineData(129, 192)] public void ReturnsNextMultiple(int size, int expectedSize) { Assert.Equal(expectedSize, BitUtility.RoundUpToMultipleOf64(size)); } [Theory] [InlineData(0)] [InlineData(-1)] public void ReturnsZeroWhenSizeIsLessThanOrEqualToZero(int size) { Assert.Equal(0, BitUtility.RoundUpToMultipleOf64(size)); } } } }
cpcloud/arrow
csharp/test/Apache.Arrow.Tests/BitUtilityTests.cs
C#
apache-2.0
7,010
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/ecs/model/RegisterContainerInstanceRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ECS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; RegisterContainerInstanceRequest::RegisterContainerInstanceRequest() : m_clusterHasBeenSet(false), m_instanceIdentityDocumentHasBeenSet(false), m_instanceIdentityDocumentSignatureHasBeenSet(false), m_totalResourcesHasBeenSet(false), m_versionInfoHasBeenSet(false), m_containerInstanceArnHasBeenSet(false) { } Aws::String RegisterContainerInstanceRequest::SerializePayload() const { JsonValue payload; if(m_clusterHasBeenSet) { payload.WithString("cluster", m_cluster); } if(m_instanceIdentityDocumentHasBeenSet) { payload.WithString("instanceIdentityDocument", m_instanceIdentityDocument); } if(m_instanceIdentityDocumentSignatureHasBeenSet) { payload.WithString("instanceIdentityDocumentSignature", m_instanceIdentityDocumentSignature); } if(m_totalResourcesHasBeenSet) { Array<JsonValue> totalResourcesJsonList(m_totalResources.size()); for(unsigned totalResourcesIndex = 0; totalResourcesIndex < totalResourcesJsonList.GetLength(); ++totalResourcesIndex) { totalResourcesJsonList[totalResourcesIndex].AsObject(m_totalResources[totalResourcesIndex].Jsonize()); } payload.WithArray("totalResources", std::move(totalResourcesJsonList)); } if(m_versionInfoHasBeenSet) { payload.WithObject("versionInfo", m_versionInfo.Jsonize()); } if(m_containerInstanceArnHasBeenSet) { payload.WithString("containerInstanceArn", m_containerInstanceArn); } return payload.WriteReadable(); } Aws::Http::HeaderValueCollection RegisterContainerInstanceRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.RegisterContainerInstance")); return std::move(headers); }
bmildner/aws-sdk-cpp
aws-cpp-sdk-ecs/source/model/RegisterContainerInstanceRequest.cpp
C++
apache-2.0
2,594
/* * Copyright 2019 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.util.internal.svm; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.RecomputeFieldValue; import com.oracle.svm.core.annotate.TargetClass; @TargetClass(className = "io.netty.util.internal.shaded.org.jctools.util.UnsafeRefArrayAccess") final class UnsafeRefArrayAccessSubstitution { private UnsafeRefArrayAccessSubstitution() { } @Alias @RecomputeFieldValue( kind = RecomputeFieldValue.Kind.ArrayIndexShift, declClass = Object[].class) public static int REF_ELEMENT_SHIFT; }
bryce-anderson/netty
common/src/main/java/io/netty/util/internal/svm/UnsafeRefArrayAccessSubstitution.java
Java
apache-2.0
1,194
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.xdebugger.impl.breakpoints; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author nik */ public class CustomizedBreakpointPresentation { private Icon myIcon; private String myErrorMessage; public void setIcon(final Icon icon) { myIcon = icon; } public void setErrorMessage(final String errorMessage) { myErrorMessage = errorMessage; } @Nullable public Icon getIcon() { return myIcon; } public String getErrorMessage() { return myErrorMessage; } }
android-ia/platform_tools_idea
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/CustomizedBreakpointPresentation.java
Java
apache-2.0
1,141
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CParseHandlerQueryOutput.cpp // // @doc: // Implementation of the SAX parse handler class parsing the list of // output column references in a DXL query. //--------------------------------------------------------------------------- #include "naucrates/dxl/parser/CParseHandlerQueryOutput.h" #include "naucrates/dxl/operators/CDXLOperatorFactory.h" #include "naucrates/dxl/parser/CParseHandlerFactory.h" #include "naucrates/dxl/parser/CParseHandlerScalarIdent.h" using namespace gpdxl; XERCES_CPP_NAMESPACE_USE //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::CParseHandlerQueryOutput // // @doc: // Constructor // //--------------------------------------------------------------------------- CParseHandlerQueryOutput::CParseHandlerQueryOutput( CMemoryPool *mp, CParseHandlerManager *parse_handler_mgr, CParseHandlerBase *parse_handler_root) : CParseHandlerBase(mp, parse_handler_mgr, parse_handler_root), m_dxl_array(nullptr) { } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::~CParseHandlerQueryOutput // // @doc: // Destructor // //--------------------------------------------------------------------------- CParseHandlerQueryOutput::~CParseHandlerQueryOutput() { m_dxl_array->Release(); } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::GetOutputColumnsDXLArray // // @doc: // Return the list of query output columns // //--------------------------------------------------------------------------- CDXLNodeArray * CParseHandlerQueryOutput::GetOutputColumnsDXLArray() { GPOS_ASSERT(nullptr != m_dxl_array); return m_dxl_array; } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::StartElement // // @doc: // Invoked by Xerces to process an opening tag // //--------------------------------------------------------------------------- void CParseHandlerQueryOutput::StartElement(const XMLCh *const element_uri, const XMLCh *const element_local_name, const XMLCh *const element_qname, const Attributes &attrs) { if (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenQueryOutput), element_local_name)) { // start the query output section in the DXL document GPOS_ASSERT(nullptr == m_dxl_array); m_dxl_array = GPOS_NEW(m_mp) CDXLNodeArray(m_mp); } else if (0 == XMLString::compareString( CDXLTokens::XmlstrToken(EdxltokenScalarIdent), element_local_name)) { // we must have seen a proj list already and initialized the proj list node GPOS_ASSERT(nullptr != m_dxl_array); // start new scalar ident element CParseHandlerBase *child_parse_handler = CParseHandlerFactory::GetParseHandler( m_mp, CDXLTokens::XmlstrToken(EdxltokenScalarIdent), m_parse_handler_mgr, this); m_parse_handler_mgr->ActivateParseHandler(child_parse_handler); // store parse handler this->Append(child_parse_handler); child_parse_handler->startElement(element_uri, element_local_name, element_qname, attrs); } else { CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray( m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name); GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, str->GetBuffer()); } } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::EndElement // // @doc: // Invoked by Xerces to process a closing tag // //--------------------------------------------------------------------------- void CParseHandlerQueryOutput::EndElement(const XMLCh *const, // element_uri, const XMLCh *const element_local_name, const XMLCh *const // element_qname ) { if (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenQueryOutput), element_local_name)) { CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray( m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name); GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, str->GetBuffer()); } const ULONG size = this->Length(); for (ULONG ul = 0; ul < size; ul++) { CParseHandlerScalarIdent *child_parse_handler = dynamic_cast<CParseHandlerScalarIdent *>((*this)[ul]); GPOS_ASSERT(nullptr != child_parse_handler); CDXLNode *pdxlnIdent = child_parse_handler->CreateDXLNode(); pdxlnIdent->AddRef(); m_dxl_array->Append(pdxlnIdent); } // deactivate handler m_parse_handler_mgr->DeactivateHandler(); } // EOF
50wu/gpdb
src/backend/gporca/libnaucrates/src/parser/CParseHandlerQueryOutput.cpp
C++
apache-2.0
4,849
class PerlBuild < Formula desc "Perl builder" homepage "https://github.com/tokuhirom/Perl-Build" url "https://github.com/tokuhirom/Perl-Build/archive/1.32.tar.gz" sha256 "ba86d74ff9718977637806ef650c85615534f0b17023a72f447587676d7f66fd" license any_of: ["Artistic-1.0", "GPL-1.0-or-later"] head "https://github.com/tokuhirom/perl-build.git", branch: "master" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "a9d4cdf8f97ae6c7aaafc8cb6e6d5099ec97f6ec0632a33af90e70766c9e497e" sha256 cellar: :any_skip_relocation, arm64_big_sur: "b662afe3c5e833e08c5e0a425f5597ab159b808e6285e90f96ee48e1f8d8d9a8" sha256 cellar: :any_skip_relocation, monterey: "e05da78d5eab2ca95b3bdc567a1d8ef81d60c932af55420958f2e6538b18c89e" sha256 cellar: :any_skip_relocation, big_sur: "a24fadf986032226343c74378f0344b15729687d9b0679f64e859e41a4f165db" sha256 cellar: :any_skip_relocation, catalina: "e2b99b05c34a89e8706810730e8ac6da7d98c76025b72d86eb2a6003a47a4b85" sha256 cellar: :any_skip_relocation, mojave: "5ae631c827ab5b58f0e2bafa3b5470f3b2f2236802942c3d4454ab96fd212aa8" sha256 cellar: :any_skip_relocation, x86_64_linux: "7e55952e9cc4849a4a6da657c0b9e52f93da495518b9c0db1da64efab51ced28" end uses_from_macos "perl" resource "Module::Build" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/Module-Build-0.4231.tar.gz" sha256 "7e0f4c692c1740c1ac84ea14d7ea3d8bc798b2fb26c09877229e04f430b2b717" end resource "Module::Build::Tiny" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/Module-Build-Tiny-0.039.tar.gz" sha256 "7d580ff6ace0cbe555bf36b86dc8ea232581530cbeaaea09bccb57b55797f11c" end resource "ExtUtils::Config" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-Config-0.008.tar.gz" sha256 "ae5104f634650dce8a79b7ed13fb59d67a39c213a6776cfdaa3ee749e62f1a8c" end resource "ExtUtils::Helpers" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-Helpers-0.026.tar.gz" sha256 "de901b6790a4557cf4ec908149e035783b125bf115eb9640feb1bc1c24c33416" end resource "ExtUtils::InstallPaths" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-InstallPaths-0.012.tar.gz" sha256 "84735e3037bab1fdffa3c2508567ad412a785c91599db3c12593a50a1dd434ed" end resource "HTTP::Tinyish" do url "https://cpan.metacpan.org/authors/id/M/MI/MIYAGAWA/HTTP-Tinyish-0.17.tar.gz" sha256 "47bd111e474566d733c41870e2374c81689db5e0b5a43adc48adb665d89fb067" end resource "CPAN::Perl::Releases" do url "https://cpan.metacpan.org/authors/id/B/BI/BINGOS/CPAN-Perl-Releases-5.20210220.tar.gz" sha256 "c88ba6bba670bfc36bcb10adcceab83428ab3b3363ac9bb11f374a88f52466be" end resource "CPAN::Perl::Releases::MetaCPAN" do url "https://cpan.metacpan.org/authors/id/S/SK/SKAJI/CPAN-Perl-Releases-MetaCPAN-0.006.tar.gz" sha256 "d78ef4ee4f0bc6d95c38bbcb0d2af81cf59a31bde979431c1b54ec50d71d0e1b" end resource "File::pushd" do url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/File-pushd-1.016.tar.gz" sha256 "d73a7f09442983b098260df3df7a832a5f660773a313ca273fa8b56665f97cdc" end resource "HTTP::Tiny" do url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/HTTP-Tiny-0.076.tar.gz" sha256 "ddbdaa2fb511339fa621a80021bf1b9733fddafc4fe0245f26c8b92171ef9387" end # Devel::PatchPerl dependency resource "Module::Pluggable" do url "https://cpan.metacpan.org/authors/id/S/SI/SIMONW/Module-Pluggable-5.2.tar.gz" sha256 "b3f2ad45e4fd10b3fb90d912d78d8b795ab295480db56dc64e86b9fa75c5a6df" end resource "Devel::PatchPerl" do url "https://cpan.metacpan.org/authors/id/B/BI/BINGOS/Devel-PatchPerl-2.08.tar.gz" sha256 "69c6e97016260f408e9d7e448f942b36a6d49df5af07340f1d65d7e230167419" end # Pod::Usage dependency resource "Pod::Text" do url "https://cpan.metacpan.org/authors/id/R/RR/RRA/podlators-4.12.tar.gz" sha256 "948717da19630a5f003da4406da90fe1cbdec9ae493671c90dfb6d8b3d63b7eb" end resource "Pod::Usage" do url "https://cpan.metacpan.org/authors/id/M/MA/MAREKR/Pod-Usage-1.69.tar.gz" sha256 "1a920c067b3c905b72291a76efcdf1935ba5423ab0187b9a5a63cfc930965132" end def install ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5" # Ensure we don't install the pre-packed script (buildpath/"perl-build").unlink # Remove this apparently dead symlink. (buildpath/"bin/perl-build").unlink build_pl = ["Module::Build::Tiny", "CPAN::Perl::Releases::MetaCPAN"] resources.each do |r| r.stage do next if build_pl.include? r.name system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}" system "make" system "make", "install" end end build_pl.each do |name| resource(name).stage do system "perl", "Build.PL", "--install_base", libexec system "./Build" system "./Build", "install" end end ENV.prepend_path "PATH", libexec/"bin" system "perl", "Build.PL", "--install_base", libexec # Replace the dead symlink we removed earlier. (buildpath/"bin").install_symlink buildpath/"script/perl-build" system "./Build" system "./Build", "install" %w[perl-build plenv-install plenv-uninstall].each do |cmd| (bin/cmd).write_env_script(libexec/"bin/#{cmd}", PERL5LIB: ENV["PERL5LIB"]) end end test do assert_match version.to_s, shell_output("#{bin}/perl-build --version") end end
sjackman/homebrew-core
Formula/perl-build.rb
Ruby
bsd-2-clause
5,489
cask 'astropad' do version '3.1' sha256 '4082c09dd4aa440a2b8bd25104d98d3f431fbca2fc4f139d3e390632f4903f22' url "https://astropad.com/downloads/Astropad-#{version}.zip" appcast 'https://astropad.com/downloads/sparkle.xml' name 'Astropad' homepage 'https://astropad.com/' app 'Astropad.app' uninstall quit: 'com.astro-hq.AstropadMac' zap trash: [ '~/Library/Caches/Astropad', '~/Library/Caches/com.astro-hq.AstropadMac', '~/Library/Preferences/com.astro-hq.AstropadMac.plist', '~/Library/Saved Application State/com.astro-hq.AstropadMac.savedState', ] end
josa42/homebrew-cask
Casks/astropad.rb
Ruby
bsd-2-clause
649
goog.provide('ol.test.extent'); goog.require('ol.extent'); goog.require('ol.proj'); describe('ol.extent', function() { describe('buffer', function() { it('buffers an extent by some value', function() { var extent = [-10, -20, 10, 20]; expect(ol.extent.buffer(extent, 15)).to.eql([-25, -35, 25, 35]); }); }); describe('clone', function() { it('creates a copy of an extent', function() { var extent = ol.extent.createOrUpdate(1, 2, 3, 4); var clone = ol.extent.clone(extent); expect(ol.extent.equals(extent, clone)).to.be(true); ol.extent.extendCoordinate(extent, [10, 20]); expect(ol.extent.equals(extent, clone)).to.be(false); }); }); describe('closestSquaredDistanceXY', function() { it('returns correct result when x left of extent', function() { var extent = ol.extent.createOrUpdate(0, 0, 1, 1); var x = -2; var y = 0; expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result when x right of extent', function() { var extent = ol.extent.createOrUpdate(0, 0, 1, 1); var x = 3; var y = 0; expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result for other x values', function() { var extent = ol.extent.createOrUpdate(0, 0, 1, 1); var x = 0.5; var y = 3; expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result when y below extent', function() { var extent = ol.extent.createOrUpdate(0, 0, 1, 1); var x = 0; var y = -2; expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result when y above extent', function() { var extent = ol.extent.createOrUpdate(0, 0, 1, 1); var x = 0; var y = 3; expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); it('returns correct result for other y values', function() { var extent = ol.extent.createOrUpdate(0, 0, 1, 1); var x = 3; var y = 0.5; expect(ol.extent.closestSquaredDistanceXY(extent, x, y)).to.be(4); }); }); describe('createOrUpdateFromCoordinate', function() { it('works when no extent passed', function() { var coords = [0, 1]; var expected = [0, 1, 0, 1]; var got = ol.extent.createOrUpdateFromCoordinate(coords); expect(got).to.eql(expected); }); it('updates a passed extent', function() { var extent = ol.extent.createOrUpdate(-4, -7, -3, -6); var coords = [0, 1]; var expected = [0, 1, 0, 1]; ol.extent.createOrUpdateFromCoordinate(coords, extent); expect(extent).to.eql(expected); }); }); describe('createOrUpdateFromCoordinates', function() { it('works when single coordinate and no extent passed', function() { var coords = [[0, 1]]; var expected = [0, 1, 0, 1]; var got = ol.extent.createOrUpdateFromCoordinates(coords); expect(got).to.eql(expected); }); it('changes the passed extent when single coordinate', function() { var extent = ol.extent.createOrUpdate(-4, -7, -3, -6); var coords = [[0, 1]]; var expected = [0, 1, 0, 1]; ol.extent.createOrUpdateFromCoordinates(coords, extent); expect(extent).to.eql(expected); }); it('works when multiple coordinates and no extent passed', function() { var coords = [[0, 1], [2, 3]]; var expected = [0, 1, 2, 3]; var got = ol.extent.createOrUpdateFromCoordinates(coords); expect(got).to.eql(expected); }); it('changes the passed extent when multiple coordinates given', function() { var extent = ol.extent.createOrUpdate(-4, -7, -3, -6); var coords = [[0, 1], [-2, -1]]; var expected = [-2, -1, 0, 1]; ol.extent.createOrUpdateFromCoordinates(coords, extent); expect(extent).to.eql(expected); }); }); describe('createOrUpdateFromRings', function() { it('works when single ring and no extent passed', function() { var ring = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; var rings = [ring]; var expected = [0, 0, 2, 2]; var got = ol.extent.createOrUpdateFromRings(rings); expect(got).to.eql(expected); }); it('changes the passed extent when single ring given', function() { var ring = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; var rings = [ring]; var extent = [1, 1, 4, 7]; var expected = [0, 0, 2, 2]; ol.extent.createOrUpdateFromRings(rings, extent); expect(extent).to.eql(expected); }); it('works when multiple rings and no extent passed', function() { var ring1 = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; var ring2 = [[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]; var rings = [ring1, ring2]; var expected = [0, 0, 3, 3]; var got = ol.extent.createOrUpdateFromRings(rings); expect(got).to.eql(expected); }); it('changes the passed extent when multiple rings given', function() { var ring1 = [[0, 0], [0, 2], [2, 2], [2, 0], [0, 0]]; var ring2 = [[1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]; var rings = [ring1, ring2]; var extent = [1, 1, 4, 7]; var expected = [0, 0, 3, 3]; ol.extent.createOrUpdateFromRings(rings, extent); expect(extent).to.eql(expected); }); }); describe('forEachCorner', function() { var callbackFalse; var callbackTrue; beforeEach(function() { callbackFalse = sinon.spy(function() { return false; }); callbackTrue = sinon.spy(function() { return true; }); }); it('calls the passed callback for each corner', function() { var extent = [1, 2, 3, 4]; ol.extent.forEachCorner(extent, callbackFalse); expect(callbackFalse.callCount).to.be(4); }); it('calls the passed callback with each corner', function() { var extent = [1, 2, 3, 4]; ol.extent.forEachCorner(extent, callbackFalse); var firstCallFirstArg = callbackFalse.args[0][0]; var secondCallFirstArg = callbackFalse.args[1][0]; var thirdCallFirstArg = callbackFalse.args[2][0]; var fourthCallFirstArg = callbackFalse.args[3][0]; expect(firstCallFirstArg).to.eql([1, 2]); // bl expect(secondCallFirstArg).to.eql([3, 2]); // br expect(thirdCallFirstArg).to.eql([3, 4]); // tr expect(fourthCallFirstArg).to.eql([1, 4]); // tl }); it('calls a truthy callback only once', function() { var extent = [1, 2, 3, 4]; ol.extent.forEachCorner(extent, callbackTrue); expect(callbackTrue.callCount).to.be(1); }); it('ensures that any corner can cancel the callback execution', function() { var extent = [1, 2, 3, 4]; var bottomLeftSpy = sinon.spy(function(corner) { return (corner[0] === 1 && corner[1] === 2) ? true : false; }); var bottomRightSpy = sinon.spy(function(corner) { return (corner[0] === 3 && corner[1] === 2) ? true : false; }); var topRightSpy = sinon.spy(function(corner) { return (corner[0] === 3 && corner[1] === 4) ? true : false; }); var topLeftSpy = sinon.spy(function(corner) { return (corner[0] === 1 && corner[1] === 4) ? true : false; }); ol.extent.forEachCorner(extent, bottomLeftSpy); ol.extent.forEachCorner(extent, bottomRightSpy); ol.extent.forEachCorner(extent, topRightSpy); ol.extent.forEachCorner(extent, topLeftSpy); expect(bottomLeftSpy.callCount).to.be(1); expect(bottomRightSpy.callCount).to.be(2); expect(topRightSpy.callCount).to.be(3); expect(topLeftSpy.callCount).to.be(4); }); it('returns false eventually, if no invocation returned a truthy value', function() { var extent = [1, 2, 3, 4]; var spy = sinon.spy(); // will return undefined for each corner var got = ol.extent.forEachCorner(extent, spy); expect(spy.callCount).to.be(4); expect(got).to.be(false); } ); it('calls the callback with given scope', function() { var extent = [1, 2, 3, 4]; var scope = {humpty: 'dumpty'}; ol.extent.forEachCorner(extent, callbackTrue, scope); expect(callbackTrue.calledOn(scope)).to.be(true); }); }); describe('getArea', function() { it('returns zero for empty extents', function() { var emptyExtent = ol.extent.createEmpty(); var areaEmpty = ol.extent.getArea(emptyExtent); expect(areaEmpty).to.be(0); var extentDeltaXZero = [45, 67, 45, 78]; var areaDeltaXZero = ol.extent.getArea(extentDeltaXZero); expect(areaDeltaXZero).to.be(0); var extentDeltaYZero = [11, 67, 45, 67]; var areaDeltaYZero = ol.extent.getArea(extentDeltaYZero); expect(areaDeltaYZero).to.be(0); }); it('calculates correct area for other extents', function() { var extent = [0, 0, 10, 10]; var area = ol.extent.getArea(extent); expect(area).to.be(100); }); }); describe('getIntersection()', function() { it('returns the intersection of two extents', function() { var world = [-180, -90, 180, 90]; var north = [-180, 0, 180, 90]; var farNorth = [-180, 45, 180, 90]; var east = [0, -90, 180, 90]; var farEast = [90, -90, 180, 90]; var south = [-180, -90, 180, 0]; var farSouth = [-180, -90, 180, -45]; var west = [-180, -90, 0, 90]; var farWest = [-180, -90, -90, 90]; var none = ol.extent.createEmpty(); expect(ol.extent.getIntersection(world, none)).to.eql(none); expect(ol.extent.getIntersection(world, north)).to.eql(north); expect(ol.extent.getIntersection(world, east)).to.eql(east); expect(ol.extent.getIntersection(world, south)).to.eql(south); expect(ol.extent.getIntersection(world, west)).to.eql(west); expect(ol.extent.getIntersection(farEast, farWest)).to.eql(none); expect(ol.extent.getIntersection(farNorth, farSouth)).to.eql(none); expect(ol.extent.getIntersection(north, west)).to.eql([-180, 0, 0, 90]); expect(ol.extent.getIntersection(east, south)).to.eql([0, -90, 180, 0]); }); }); describe('containsCoordinate', function() { describe('positive', function() { it('returns true', function() { var extent = [1, 2, 3, 4]; expect(ol.extent.containsCoordinate(extent, [1, 2])).to.be.ok(); expect(ol.extent.containsCoordinate(extent, [1, 3])).to.be.ok(); expect(ol.extent.containsCoordinate(extent, [1, 4])).to.be.ok(); expect(ol.extent.containsCoordinate(extent, [2, 2])).to.be.ok(); expect(ol.extent.containsCoordinate(extent, [2, 3])).to.be.ok(); expect(ol.extent.containsCoordinate(extent, [2, 4])).to.be.ok(); expect(ol.extent.containsCoordinate(extent, [3, 2])).to.be.ok(); expect(ol.extent.containsCoordinate(extent, [3, 3])).to.be.ok(); expect(ol.extent.containsCoordinate(extent, [3, 4])).to.be.ok(); }); }); describe('negative', function() { it('returns false', function() { var extent = [1, 2, 3, 4]; expect(ol.extent.containsCoordinate(extent, [0, 1])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [0, 2])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [0, 3])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [0, 4])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [0, 5])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [1, 1])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [1, 5])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [2, 1])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [2, 5])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [3, 1])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [3, 5])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [4, 1])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [4, 2])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [4, 3])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [4, 4])).to.not.be(); expect(ol.extent.containsCoordinate(extent, [4, 5])).to.not.be(); }); }); }); describe('coordinateRelationship()', function() { var extent = [-180, -90, 180, 90]; var INTERSECTING = 1; var ABOVE = 2; var RIGHT = 4; var BELOW = 8; var LEFT = 16; it('returns intersecting for within', function() { var rel = ol.extent.coordinateRelationship(extent, [0, 0]); expect(rel).to.be(INTERSECTING); }); it('returns intersecting for touching top', function() { var rel = ol.extent.coordinateRelationship(extent, [0, 90]); expect(rel).to.be(INTERSECTING); }); it('returns intersecting for touching right', function() { var rel = ol.extent.coordinateRelationship(extent, [180, 0]); expect(rel).to.be(INTERSECTING); }); it('returns intersecting for touching bottom', function() { var rel = ol.extent.coordinateRelationship(extent, [0, -90]); expect(rel).to.be(INTERSECTING); }); it('returns intersecting for touching left', function() { var rel = ol.extent.coordinateRelationship(extent, [-180, 0]); expect(rel).to.be(INTERSECTING); }); it('above for north', function() { var rel = ol.extent.coordinateRelationship(extent, [0, 100]); expect(rel).to.be(ABOVE); }); it('above and right for northeast', function() { var rel = ol.extent.coordinateRelationship(extent, [190, 100]); expect(rel & ABOVE).to.be(ABOVE); expect(rel & RIGHT).to.be(RIGHT); }); it('right for east', function() { var rel = ol.extent.coordinateRelationship(extent, [190, 0]); expect(rel).to.be(RIGHT); }); it('below and right for southeast', function() { var rel = ol.extent.coordinateRelationship(extent, [190, -100]); expect(rel & BELOW).to.be(BELOW); expect(rel & RIGHT).to.be(RIGHT); }); it('below for south', function() { var rel = ol.extent.coordinateRelationship(extent, [0, -100]); expect(rel).to.be(BELOW); }); it('below and left for southwest', function() { var rel = ol.extent.coordinateRelationship(extent, [-190, -100]); expect(rel & BELOW).to.be(BELOW); expect(rel & LEFT).to.be(LEFT); }); it('left for west', function() { var rel = ol.extent.coordinateRelationship(extent, [-190, 0]); expect(rel).to.be(LEFT); }); it('above and left for northwest', function() { var rel = ol.extent.coordinateRelationship(extent, [-190, 100]); expect(rel & ABOVE).to.be(ABOVE); expect(rel & LEFT).to.be(LEFT); }); }); describe('getCenter', function() { it('returns the expected center', function() { var extent = [1, 2, 3, 4]; var center = ol.extent.getCenter(extent); expect(center[0]).to.eql(2); expect(center[1]).to.eql(3); }); it('returns [NaN, NaN] for empty extents', function() { var extent = ol.extent.createEmpty(); var center = ol.extent.getCenter(extent); expect('' + center[0]).to.be('NaN'); expect('' + center[1]).to.be('NaN'); }); }); describe('getCorner', function() { var extent = [1, 2, 3, 4]; it('gets the bottom left', function() { var corner = 'bottom-left'; expect(ol.extent.getCorner(extent, corner)).to.eql([1, 2]); }); it('gets the bottom right', function() { var corner = 'bottom-right'; expect(ol.extent.getCorner(extent, corner)).to.eql([3, 2]); }); it('gets the top left', function() { var corner = 'top-left'; expect(ol.extent.getCorner(extent, corner)).to.eql([1, 4]); }); it('gets the top right', function() { var corner = 'top-right'; expect(ol.extent.getCorner(extent, corner)).to.eql([3, 4]); }); it('throws exception for unexpected corner', function() { expect(function() { ol.extent.getCorner(extent, 'foobar'); }).to.throwException(); }); }); describe('getEnlargedArea', function() { it('returns enlarged area of two extents', function() { var extent1 = [-1, -1, 0, 0]; var extent2 = [0, 0, 1, 1]; var enlargedArea = ol.extent.getEnlargedArea(extent1, extent2); expect(enlargedArea).to.be(4); }); }); describe('getForViewAndSize', function() { it('works for a unit square', function() { var extent = ol.extent.getForViewAndSize( [0, 0], 1, 0, [1, 1]); expect(extent[0]).to.be(-0.5); expect(extent[2]).to.be(0.5); expect(extent[1]).to.be(-0.5); expect(extent[3]).to.be(0.5); }); it('works for center', function() { var extent = ol.extent.getForViewAndSize( [5, 10], 1, 0, [1, 1]); expect(extent[0]).to.be(4.5); expect(extent[2]).to.be(5.5); expect(extent[1]).to.be(9.5); expect(extent[3]).to.be(10.5); }); it('works for rotation', function() { var extent = ol.extent.getForViewAndSize( [0, 0], 1, Math.PI / 4, [1, 1]); expect(extent[0]).to.roughlyEqual(-Math.sqrt(0.5), 1e-9); expect(extent[2]).to.roughlyEqual(Math.sqrt(0.5), 1e-9); expect(extent[1]).to.roughlyEqual(-Math.sqrt(0.5), 1e-9); expect(extent[3]).to.roughlyEqual(Math.sqrt(0.5), 1e-9); }); it('works for resolution', function() { var extent = ol.extent.getForViewAndSize( [0, 0], 2, 0, [1, 1]); expect(extent[0]).to.be(-1); expect(extent[2]).to.be(1); expect(extent[1]).to.be(-1); expect(extent[3]).to.be(1); }); it('works for size', function() { var extent = ol.extent.getForViewAndSize( [0, 0], 1, 0, [10, 5]); expect(extent[0]).to.be(-5); expect(extent[2]).to.be(5); expect(extent[1]).to.be(-2.5); expect(extent[3]).to.be(2.5); }); }); describe('getSize', function() { it('returns the expected size', function() { var extent = [0, 1, 2, 4]; var size = ol.extent.getSize(extent); expect(size).to.eql([2, 3]); }); }); describe('getIntersectionArea', function() { it('returns correct area when extents intersect', function() { var extent1 = [0, 0, 2, 2]; var extent2 = [1, 1, 3, 3]; var intersectionArea = ol.extent.getIntersectionArea(extent1, extent2); expect(intersectionArea).to.be(1); }); it('returns 0 when extents do not intersect', function() { var extent1 = [0, 0, 1, 1]; var extent2 = [2, 2, 3, 3]; var intersectionArea = ol.extent.getIntersectionArea(extent1, extent2); expect(intersectionArea).to.be(0); }); }); describe('getMargin', function() { it('returns the correct margin (sum of width and height)', function() { var extent = [1, 2, 3, 4]; expect(ol.extent.getMargin(extent)).to.be(4); }); }); describe('intersects', function() { it('returns the expected value', function() { var intersects = ol.extent.intersects; var extent = [50, 50, 100, 100]; expect(intersects(extent, extent)).to.be(true); expect(intersects(extent, [20, 20, 80, 80])).to.be(true); expect(intersects(extent, [20, 50, 80, 100])).to.be(true); expect(intersects(extent, [20, 80, 80, 120])).to.be(true); expect(intersects(extent, [50, 20, 100, 80])).to.be(true); expect(intersects(extent, [50, 80, 100, 120])).to.be(true); expect(intersects(extent, [80, 20, 120, 80])).to.be(true); expect(intersects(extent, [80, 50, 120, 100])).to.be(true); expect(intersects(extent, [80, 80, 120, 120])).to.be(true); expect(intersects(extent, [20, 20, 120, 120])).to.be(true); expect(intersects(extent, [70, 70, 80, 80])).to.be(true); expect(intersects(extent, [10, 10, 30, 30])).to.be(false); expect(intersects(extent, [30, 10, 70, 30])).to.be(false); expect(intersects(extent, [50, 10, 100, 30])).to.be(false); expect(intersects(extent, [80, 10, 120, 30])).to.be(false); expect(intersects(extent, [120, 10, 140, 30])).to.be(false); expect(intersects(extent, [10, 30, 30, 70])).to.be(false); expect(intersects(extent, [120, 30, 140, 70])).to.be(false); expect(intersects(extent, [10, 50, 30, 100])).to.be(false); expect(intersects(extent, [120, 50, 140, 100])).to.be(false); expect(intersects(extent, [10, 80, 30, 120])).to.be(false); expect(intersects(extent, [120, 80, 140, 120])).to.be(false); expect(intersects(extent, [10, 120, 30, 140])).to.be(false); expect(intersects(extent, [30, 120, 70, 140])).to.be(false); expect(intersects(extent, [50, 120, 100, 140])).to.be(false); expect(intersects(extent, [80, 120, 120, 140])).to.be(false); expect(intersects(extent, [120, 120, 140, 140])).to.be(false); }); }); describe('scaleFromCenter', function() { it('scales the extent from its center', function() { var extent = [1, 1, 3, 3]; ol.extent.scaleFromCenter(extent, 2); expect(extent[0]).to.eql(0); expect(extent[2]).to.eql(4); expect(extent[1]).to.eql(0); expect(extent[3]).to.eql(4); }); }); describe('intersectsSegment()', function() { var extent = [-180, -90, 180, 90]; var north = [0, 100]; var northeast = [190, 100]; var east = [190, 0]; var southeast = [190, -100]; var south = [0, -100]; var southwest = [-190, -100]; var west = [-190, 0]; var northwest = [-190, 100]; var center = [0, 0]; var top = [0, 90]; var right = [180, 0]; var bottom = [-90, 0]; var left = [-180, 0]; var inside = [10, 10]; it('returns true if contained', function() { var intersects = ol.extent.intersectsSegment(extent, center, inside); expect(intersects).to.be(true); }); it('returns true if crosses top', function() { var intersects = ol.extent.intersectsSegment(extent, center, north); expect(intersects).to.be(true); }); it('returns true if crosses right', function() { var intersects = ol.extent.intersectsSegment(extent, center, east); expect(intersects).to.be(true); }); it('returns true if crosses bottom', function() { var intersects = ol.extent.intersectsSegment(extent, center, south); expect(intersects).to.be(true); }); it('returns true if crosses left', function() { var intersects = ol.extent.intersectsSegment(extent, center, west); expect(intersects).to.be(true); }); it('returns false if above', function() { var intersects = ol.extent.intersectsSegment(extent, northwest, north); expect(intersects).to.be(false); }); it('returns false if right', function() { var intersects = ol.extent.intersectsSegment(extent, northeast, east); expect(intersects).to.be(false); }); it('returns false if below', function() { var intersects = ol.extent.intersectsSegment(extent, south, southwest); expect(intersects).to.be(false); }); it('returns false if left', function() { var intersects = ol.extent.intersectsSegment(extent, west, southwest); expect(intersects).to.be(false); }); it('returns true if crosses top to bottom', function() { var intersects = ol.extent.intersectsSegment(extent, north, south); expect(intersects).to.be(true); }); it('returns true if crosses bottom to top', function() { var intersects = ol.extent.intersectsSegment(extent, south, north); expect(intersects).to.be(true); }); it('returns true if crosses left to right', function() { var intersects = ol.extent.intersectsSegment(extent, west, east); expect(intersects).to.be(true); }); it('returns true if crosses right to left', function() { var intersects = ol.extent.intersectsSegment(extent, east, west); expect(intersects).to.be(true); }); it('returns true if crosses northwest to east', function() { var intersects = ol.extent.intersectsSegment(extent, northwest, east); expect(intersects).to.be(true); }); it('returns true if crosses south to west', function() { var intersects = ol.extent.intersectsSegment(extent, south, west); expect(intersects).to.be(true); }); it('returns true if touches top', function() { var intersects = ol.extent.intersectsSegment(extent, northwest, top); expect(intersects).to.be(true); }); it('returns true if touches right', function() { var intersects = ol.extent.intersectsSegment(extent, southeast, right); expect(intersects).to.be(true); }); it('returns true if touches bottom', function() { var intersects = ol.extent.intersectsSegment(extent, bottom, south); expect(intersects).to.be(true); }); it('returns true if touches left', function() { var intersects = ol.extent.intersectsSegment(extent, left, west); expect(intersects).to.be(true); }); it('works for zero length inside', function() { var intersects = ol.extent.intersectsSegment(extent, center, center); expect(intersects).to.be(true); }); it('works for zero length outside', function() { var intersects = ol.extent.intersectsSegment(extent, north, north); expect(intersects).to.be(false); }); it('works for left/right intersection spanning top to bottom', function() { var extent = [2, 1, 3, 4]; var start = [0, 0]; var end = [5, 5]; expect(ol.extent.intersectsSegment(extent, start, end)).to.be(true); expect(ol.extent.intersectsSegment(extent, end, start)).to.be(true); }); it('works for top/bottom intersection spanning left to right', function() { var extent = [1, 2, 4, 3]; var start = [0, 0]; var end = [5, 5]; expect(ol.extent.intersectsSegment(extent, start, end)).to.be(true); expect(ol.extent.intersectsSegment(extent, end, start)).to.be(true); }); }); describe('#applyTransform()', function() { it('does transform', function() { var transformFn = ol.proj.getTransform('EPSG:4326', 'EPSG:3857'); var sourceExtent = [-15, -30, 45, 60]; var destinationExtent = ol.extent.applyTransform( sourceExtent, transformFn); expect(destinationExtent).not.to.be(undefined); expect(destinationExtent).not.to.be(null); // FIXME check values with third-party tool expect(destinationExtent[0]) .to.roughlyEqual(-1669792.3618991037, 1e-9); expect(destinationExtent[2]).to.roughlyEqual(5009377.085697311, 1e-9); expect(destinationExtent[1]).to.roughlyEqual(-3503549.843504376, 1e-8); expect(destinationExtent[3]).to.roughlyEqual(8399737.889818361, 1e-8); }); it('takes arbitrary function', function() { var transformFn = function(input, output, opt_dimension) { var dimension = opt_dimension !== undefined ? opt_dimension : 2; if (output === undefined) { output = new Array(input.length); } var n = input.length; var i; for (i = 0; i < n; i += dimension) { output[i] = -input[i]; output[i + 1] = -input[i + 1]; } return output; }; var sourceExtent = [-15, -30, 45, 60]; var destinationExtent = ol.extent.applyTransform( sourceExtent, transformFn); expect(destinationExtent).not.to.be(undefined); expect(destinationExtent).not.to.be(null); expect(destinationExtent[0]).to.be(-45); expect(destinationExtent[2]).to.be(15); expect(destinationExtent[1]).to.be(-60); expect(destinationExtent[3]).to.be(30); }); }); });
wet-boew/openlayers-dist
test/spec/ol/extent.test.js
JavaScript
bsd-2-clause
27,991
/** * Copyright (c) 2005-2007, Paul Tuckey * All rights reserved. * ==================================================================== * Licensed under the BSD License. Text as follows. * * 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 tuckey.org 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. * ==================================================================== */ package org.tuckey.web.filters.urlrewrite; import org.tuckey.web.filters.urlrewrite.gzip.GzipFilter; import org.tuckey.web.filters.urlrewrite.utils.Log; import org.tuckey.web.filters.urlrewrite.utils.ModRewriteConfLoader; import org.tuckey.web.filters.urlrewrite.utils.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXParseException; import javax.servlet.ServletContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Configuration object for urlrewrite filter. * * @author Paul Tuckey * @version $Revision: 43 $ $Date: 2006-10-31 17:29:59 +1300 (Tue, 31 Oct 2006) $ */ public class Conf { private static Log log = Log.getLog(Conf.class); private final List errors = new ArrayList(); private final List rules = new ArrayList(50); private final List catchElems = new ArrayList(10); private List outboundRules = new ArrayList(50); private boolean ok = false; private Date loadedDate = null; private int ruleIdCounter = 0; private int outboundRuleIdCounter = 0; private String fileName; private String confSystemId; protected boolean useQueryString; protected boolean useContext; private static final String NONE_DECODE_USING = "null"; private static final String HEADER_DECODE_USING = "header"; private static final String DEFAULT_DECODE_USING = "header,utf-8"; protected String decodeUsing = DEFAULT_DECODE_USING; private boolean decodeUsingEncodingHeader; protected String defaultMatchType = null; private ServletContext context; private boolean docProcessed = false; private boolean engineEnabled = true; /** * Empty const for testing etc. */ public Conf() { loadedDate = new Date(); } /** * Constructor for use only when loading XML style configuration. * * @param fileName to display on status screen */ public Conf(ServletContext context, final InputStream inputStream, String fileName, String systemId) { this(context, inputStream, fileName, systemId, false); } /** * Normal constructor. * * @param fileName to display on status screen * @param modRewriteStyleConf true if loading mod_rewrite style conf */ public Conf(ServletContext context, final InputStream inputStream, String fileName, String systemId, boolean modRewriteStyleConf) { // make sure context is setup before calling initialise() this.context = context; this.fileName = fileName; this.confSystemId = systemId; if (modRewriteStyleConf) { loadModRewriteStyle(inputStream); } else { loadDom(inputStream); } if (docProcessed) initialise(); loadedDate = new Date(); } protected void loadModRewriteStyle(InputStream inputStream) { ModRewriteConfLoader loader = new ModRewriteConfLoader(); try { loader.process(inputStream, this); docProcessed = true; // fixed } catch (IOException e) { addError("Exception loading conf " + " " + e.getMessage(), e); } } /** * Constructor when run elements don't need to be initialised correctly, for docuementation etc. */ public Conf(URL confUrl) { // make sure context is setup before calling initialise() this.context = null; this.fileName = confUrl.getFile(); this.confSystemId = confUrl.toString(); try { loadDom(confUrl.openStream()); } catch (IOException e) { addError("Exception loading conf " + " " + e.getMessage(), e); } if (docProcessed) initialise(); loadedDate = new Date(); } /** * Constructor when run elements don't need to be initialised correctly, for docuementation etc. */ public Conf(InputStream inputStream, String conffile) { this(null, inputStream, conffile, conffile); } /** * Load the dom document from the inputstream * <p/> * Note, protected so that is can be extended. * * @param inputStream stream of the conf file to load */ protected synchronized void loadDom(final InputStream inputStream) { if (inputStream == null) { log.error("inputstream is null"); return; } DocumentBuilder parser; /** * the thing that resolves dtd's and other xml entities. */ ConfHandler handler = new ConfHandler(confSystemId); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); log.debug("XML builder factory is: " + factory.getClass().getName()); factory.setValidating(true); factory.setNamespaceAware(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); try { parser = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("Unable to setup XML parser for reading conf", e); return; } log.debug("XML Parser: " + parser.getClass().getName()); parser.setErrorHandler(handler); parser.setEntityResolver(handler); try { log.debug("about to parse conf"); Document doc = parser.parse(inputStream, confSystemId); processConfDoc(doc); } catch (SAXParseException e) { addError("Parse error on line " + e.getLineNumber() + " " + e.getMessage(), e); } catch (Exception e) { addError("Exception loading conf " + " " + e.getMessage(), e); } } /** * Process dom document and populate Conf object. * <p/> * Note, protected so that is can be extended. */ protected void processConfDoc(Document doc) { Element rootElement = doc.getDocumentElement(); if ("true".equalsIgnoreCase(getAttrValue(rootElement, "use-query-string"))) setUseQueryString(true); if ("true".equalsIgnoreCase(getAttrValue(rootElement, "use-context"))) { log.debug("use-context set to true"); setUseContext(true); } setDecodeUsing(getAttrValue(rootElement, "decode-using")); setDefaultMatchType(getAttrValue(rootElement, "default-match-type")); NodeList rootElementList = rootElement.getChildNodes(); for (int i = 0; i < rootElementList.getLength(); i++) { Node node = rootElementList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getTagName().equals("rule")) { Element ruleElement = (Element) node; // we have a rule node NormalRule rule = new NormalRule(); processRuleBasics(ruleElement, rule); procesConditions(ruleElement, rule); processRuns(ruleElement, rule); Node toNode = ruleElement.getElementsByTagName("to").item(0); rule.setTo(getNodeValue(toNode)); rule.setToType(getAttrValue(toNode, "type")); rule.setToContextStr(getAttrValue(toNode, "context")); rule.setToLast(getAttrValue(toNode, "last")); rule.setQueryStringAppend(getAttrValue(toNode, "qsappend")); if ("true".equalsIgnoreCase(getAttrValue(toNode, "encode"))) rule.setEncodeToUrl(true); processSetAttributes(ruleElement, rule); addRule(rule); } else if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getTagName().equals("class-rule")) { Element ruleElement = (Element) node; ClassRule classRule = new ClassRule(); if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "enabled"))) classRule.setEnabled(false); if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "last"))) classRule.setLast(false); classRule.setClassStr(getAttrValue(ruleElement, "class")); classRule.setMethodStr(getAttrValue(ruleElement, "method")); addRule(classRule); } else if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getTagName().equals("outbound-rule")) { Element ruleElement = (Element) node; // we have a rule node OutboundRule rule = new OutboundRule(); processRuleBasics(ruleElement, rule); if ("true".equalsIgnoreCase(getAttrValue(ruleElement, "encodefirst"))) rule.setEncodeFirst(true); procesConditions(ruleElement, rule); processRuns(ruleElement, rule); Node toNode = ruleElement.getElementsByTagName("to").item(0); rule.setTo(getNodeValue(toNode)); rule.setToLast(getAttrValue(toNode, "last")); if ("false".equalsIgnoreCase(getAttrValue(toNode, "encode"))) rule.setEncodeToUrl(false); processSetAttributes(ruleElement, rule); addOutboundRule(rule); } else if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getTagName().equals("catch")) { Element catchXMLElement = (Element) node; // we have a rule node CatchElem catchElem = new CatchElem(); catchElem.setClassStr(getAttrValue(catchXMLElement, "class")); processRuns(catchXMLElement, catchElem); catchElems.add(catchElem); } } docProcessed = true; } private void processRuleBasics(Element ruleElement, RuleBase rule) { if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "enabled"))) rule.setEnabled(false); String ruleMatchType = getAttrValue(ruleElement, "match-type"); if (StringUtils.isBlank(ruleMatchType)) ruleMatchType = defaultMatchType; rule.setMatchType(ruleMatchType); Node nameNode = ruleElement.getElementsByTagName("name").item(0); rule.setName(getNodeValue(nameNode)); Node noteNode = ruleElement.getElementsByTagName("note").item(0); rule.setNote(getNodeValue(noteNode)); Node fromNode = ruleElement.getElementsByTagName("from").item(0); rule.setFrom(getNodeValue(fromNode)); if ("true".equalsIgnoreCase(getAttrValue(fromNode, "casesensitive"))) rule.setFromCaseSensitive(true); } private static void processSetAttributes(Element ruleElement, RuleBase rule) { NodeList setNodes = ruleElement.getElementsByTagName("set"); for (int j = 0; j < setNodes.getLength(); j++) { Node setNode = setNodes.item(j); if (setNode == null) continue; SetAttribute setAttribute = new SetAttribute(); setAttribute.setValue(getNodeValue(setNode)); setAttribute.setType(getAttrValue(setNode, "type")); setAttribute.setName(getAttrValue(setNode, "name")); rule.addSetAttribute(setAttribute); } } private static void processRuns(Element ruleElement, Runnable runnable) { NodeList runNodes = ruleElement.getElementsByTagName("run"); for (int j = 0; j < runNodes.getLength(); j++) { Node runNode = runNodes.item(j); if (runNode == null) continue; Run run = new Run(); processInitParams(runNode, run); run.setClassStr(getAttrValue(runNode, "class")); run.setMethodStr(getAttrValue(runNode, "method")); run.setJsonHandler("true".equalsIgnoreCase(getAttrValue(runNode, "jsonhandler"))); run.setNewEachTime("true".equalsIgnoreCase(getAttrValue(runNode, "neweachtime"))); runnable.addRun(run); } // gzip element is just a shortcut to run: org.tuckey.web.filters.urlrewrite.gzip.GzipFilter NodeList gzipNodes = ruleElement.getElementsByTagName("gzip"); for (int j = 0; j < gzipNodes.getLength(); j++) { Node runNode = gzipNodes.item(j); if (runNode == null) continue; Run run = new Run(); run.setClassStr(GzipFilter.class.getName()); run.setMethodStr("doFilter(ServletRequest, ServletResponse, FilterChain)"); processInitParams(runNode, run); runnable.addRun(run); } } private static void processInitParams(Node runNode, Run run) { if (runNode.getNodeType() == Node.ELEMENT_NODE) { Element runElement = (Element) runNode; NodeList initParamsNodeList = runElement.getElementsByTagName("init-param"); for (int k = 0; k < initParamsNodeList.getLength(); k++) { Node initParamNode = initParamsNodeList.item(k); if (initParamNode == null) continue; if (initParamNode.getNodeType() != Node.ELEMENT_NODE) continue; Element initParamElement = (Element) initParamNode; Node paramNameNode = initParamElement.getElementsByTagName("param-name").item(0); Node paramValueNode = initParamElement.getElementsByTagName("param-value").item(0); run.addInitParam(getNodeValue(paramNameNode), getNodeValue(paramValueNode)); } } } private static void procesConditions(Element ruleElement, RuleBase rule) { NodeList conditionNodes = ruleElement.getElementsByTagName("condition"); for (int j = 0; j < conditionNodes.getLength(); j++) { Node conditionNode = conditionNodes.item(j); if (conditionNode == null) continue; Condition condition = new Condition(); condition.setValue(getNodeValue(conditionNode)); condition.setType(getAttrValue(conditionNode, "type")); condition.setName(getAttrValue(conditionNode, "name")); condition.setNext(getAttrValue(conditionNode, "next")); condition.setCaseSensitive("true".equalsIgnoreCase(getAttrValue(conditionNode, "casesensitive"))); condition.setOperator(getAttrValue(conditionNode, "operator")); rule.addCondition(condition); } } private static String getNodeValue(Node node) { if (node == null) return null; NodeList nodeList = node.getChildNodes(); if (nodeList == null) return null; Node child = nodeList.item(0); if (child == null) return null; if ((child.getNodeType() == Node.TEXT_NODE)) { String value = ((Text) child).getData(); return value.trim(); } return null; } private static String getAttrValue(Node n, String attrName) { if (n == null) return null; NamedNodeMap attrs = n.getAttributes(); if (attrs == null) return null; Node attr = attrs.getNamedItem(attrName); if (attr == null) return null; String val = attr.getNodeValue(); if (val == null) return null; return val.trim(); } /** * Initialise the conf file. This will run initialise on each rule and condition in the conf file. */ public void initialise() { if (log.isDebugEnabled()) { log.debug("now initialising conf"); } initDecodeUsing(decodeUsing); boolean rulesOk = true; for (int i = 0; i < rules.size(); i++) { final Rule rule = (Rule) rules.get(i); if (!rule.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } for (int i = 0; i < outboundRules.size(); i++) { final OutboundRule outboundRule = (OutboundRule) outboundRules.get(i); if (!outboundRule.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } for (int i = 0; i < catchElems.size(); i++) { final CatchElem catchElem = (CatchElem) catchElems.get(i); if (!catchElem.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } if (rulesOk) { ok = true; } if (log.isDebugEnabled()) { log.debug("conf status " + ok); } } private void initDecodeUsing(String decodeUsingSetting) { decodeUsingSetting = StringUtils.trimToNull(decodeUsingSetting); if (decodeUsingSetting == null) decodeUsingSetting = DEFAULT_DECODE_USING; if ( decodeUsingSetting.equalsIgnoreCase(HEADER_DECODE_USING)) { // is 'header' decodeUsingEncodingHeader = true; decodeUsingSetting = null; } else if ( decodeUsingSetting.startsWith(HEADER_DECODE_USING + ",")) { // is 'header,xxx' decodeUsingEncodingHeader = true; decodeUsingSetting = decodeUsingSetting.substring((HEADER_DECODE_USING + ",").length()); } if (NONE_DECODE_USING.equalsIgnoreCase(decodeUsingSetting)) { decodeUsingSetting = null; } if ( decodeUsingSetting != null ) { try { URLDecoder.decode("testUrl", decodeUsingSetting); this.decodeUsing = decodeUsingSetting; } catch (UnsupportedEncodingException e) { addError("unsupported 'decodeusing' " + decodeUsingSetting + " see Java SDK docs for supported encodings"); } } else { this.decodeUsing = null; } } /** * Destory the conf gracefully. */ public void destroy() { for (int i = 0; i < rules.size(); i++) { final Rule rule = (Rule) rules.get(i); rule.destroy(); } } /** * Will add the rule to the rules list. * * @param rule The Rule to add */ public void addRule(final Rule rule) { rule.setId(ruleIdCounter++); rules.add(rule); } /** * Will add the rule to the rules list. * * @param outboundRule The outbound rule to add */ public void addOutboundRule(final OutboundRule outboundRule) { outboundRule.setId(outboundRuleIdCounter++); outboundRules.add(outboundRule); } /** * Will get the List of errors. * * @return the List of errors */ public List getErrors() { return errors; } /** * Will get the List of rules. * * @return the List of rules */ public List getRules() { return rules; } /** * Will get the List of outbound rules. * * @return the List of outbound rules */ public List getOutboundRules() { return outboundRules; } /** * true if the conf has been loaded ok. * * @return boolean */ public boolean isOk() { return ok; } private void addError(final String errorMsg, final Exception e) { errors.add(errorMsg); log.error(errorMsg, e); } private void addError(final String errorMsg) { errors.add(errorMsg); } public Date getLoadedDate() { return (Date) loadedDate.clone(); } public String getFileName() { return fileName; } public boolean isUseQueryString() { return useQueryString; } public void setUseQueryString(boolean useQueryString) { this.useQueryString = useQueryString; } public boolean isUseContext() { return useContext; } public void setUseContext(boolean useContext) { this.useContext = useContext; } public String getDecodeUsing() { return decodeUsing; } public void setDecodeUsing(String decodeUsing) { this.decodeUsing = decodeUsing; } public void setDefaultMatchType(String defaultMatchType) { if (RuleBase.MATCH_TYPE_WILDCARD.equalsIgnoreCase(defaultMatchType)) { this.defaultMatchType = RuleBase.MATCH_TYPE_WILDCARD; } else { this.defaultMatchType = RuleBase.DEFAULT_MATCH_TYPE; } } public String getDefaultMatchType() { return defaultMatchType; } public List getCatchElems() { return catchElems; } public boolean isDecodeUsingCustomCharsetRequired() { return decodeUsing != null; } public boolean isEngineEnabled() { return engineEnabled; } public void setEngineEnabled(boolean engineEnabled) { this.engineEnabled = engineEnabled; } public boolean isLoadedFromFile() { return fileName != null; } public boolean isDecodeUsingEncodingHeader() { return decodeUsingEncodingHeader; } }
safarijv/urlrewritefilter
src/main/java/org/tuckey/web/filters/urlrewrite/Conf.java
Java
bsd-3-clause
23,779
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // template<> struct char_traits<char32_t> // static constexpr int_type eof(); #include <string> #include <cassert> int main() { #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS std::char_traits<char32_t>::int_type i = std::char_traits<char32_t>::eof(); ((void)i); // Prevent unused warning #endif }
youtube/cobalt
third_party/llvm-project/libcxx/test/std/strings/char.traits/char.traits.specializations/char.traits.specializations.char32_t/eof.pass.cpp
C++
bsd-3-clause
669
<?php /** * Manage views in a database * * $Id: views.php,v 1.75 2007/12/15 22:57:43 ioguix Exp $ */ // Include application functions include_once('./libraries/lib.inc.php'); include_once('./classes/Gui.php'); $action = (isset($_REQUEST['action'])) ? $_REQUEST['action'] : ''; if (!isset($msg)) $msg = ''; /** * Ask for select parameters and perform select */ function doSelectRows($confirm, $msg = '') { global $data, $misc, $_no_output; global $lang; if ($confirm) { $misc->printTrail('view'); $misc->printTitle($lang['strselect'], 'pg.sql.select'); $misc->printMsg($msg); $attrs = $data->getTableAttributes($_REQUEST['view']); echo "<form action=\"views.php\" method=\"post\" id=\"selectform\">\n"; if ($attrs->recordCount() > 0) { // JavaScript for select all feature echo "<script type=\"text/javascript\">\n"; echo "//<![CDATA[\n"; echo " function selectAll() {\n"; echo " for (var i=0; i<document.getElementById('selectform').elements.length; i++) {\n"; echo " var e = document.getElementById('selectform').elements[i];\n"; echo " if (e.name.indexOf('show') == 0) e.checked = document.getElementById('selectform').selectall.checked;\n"; echo " }\n"; echo " }\n"; echo "//]]>\n"; echo "</script>\n"; echo "<table>\n"; // Output table header echo "<tr><th class=\"data\">{$lang['strshow']}</th><th class=\"data\">{$lang['strcolumn']}</th>"; echo "<th class=\"data\">{$lang['strtype']}</th><th class=\"data\">{$lang['stroperator']}</th>"; echo "<th class=\"data\">{$lang['strvalue']}</th></tr>"; $i = 0; while (!$attrs->EOF) { $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']); // Set up default value if there isn't one already if (!isset($_REQUEST['values'][$attrs->fields['attname']])) $_REQUEST['values'][$attrs->fields['attname']] = null; if (!isset($_REQUEST['ops'][$attrs->fields['attname']])) $_REQUEST['ops'][$attrs->fields['attname']] = null; // Continue drawing row $id = (($i % 2) == 0 ? '1' : '2'); echo "<tr class=\"data{$id}\">\n"; echo "<td style=\"white-space:nowrap;\">"; echo "<input type=\"checkbox\" name=\"show[", htmlspecialchars($attrs->fields['attname']), "]\"", isset($_REQUEST['show'][$attrs->fields['attname']]) ? ' checked="checked"' : '', " /></td>"; echo "<td style=\"white-space:nowrap;\">", $misc->printVal($attrs->fields['attname']), "</td>"; echo "<td style=\"white-space:nowrap;\">", $misc->printVal($data->formatType($attrs->fields['type'], $attrs->fields['atttypmod'])), "</td>"; echo "<td style=\"white-space:nowrap;\">"; echo "<select name=\"ops[{$attrs->fields['attname']}]\">\n"; foreach (array_keys($data->selectOps) as $v) { echo "<option value=\"", htmlspecialchars($v), "\"", ($v == $_REQUEST['ops'][$attrs->fields['attname']]) ? ' selected="selected"' : '', ">", htmlspecialchars($v), "</option>\n"; } echo "</select></td>\n"; echo "<td style=\"white-space:nowrap;\">", $data->printField("values[{$attrs->fields['attname']}]", $_REQUEST['values'][$attrs->fields['attname']], $attrs->fields['type']), "</td>"; echo "</tr>\n"; $i++; $attrs->moveNext(); } // Select all checkbox echo "<tr><td colspan=\"5\"><input type=\"checkbox\" id=\"selectall\" name=\"selectall\" onclick=\"javascript:selectAll()\" /><label for=\"selectall\">{$lang['strselectallfields']}</label></td></tr>"; echo "</table>\n"; } else echo "<p>{$lang['strinvalidparam']}</p>\n"; echo "<p><input type=\"hidden\" name=\"action\" value=\"selectrows\" />\n"; echo "<input type=\"hidden\" name=\"view\" value=\"", htmlspecialchars($_REQUEST['view']), "\" />\n"; echo "<input type=\"hidden\" name=\"subject\" value=\"view\" />\n"; echo $misc->form; echo "<input type=\"submit\" name=\"select\" value=\"{$lang['strselect']}\" />\n"; echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" /></p>\n"; echo "</form>\n"; } else { if (!isset($_POST['show'])) $_POST['show'] = array(); if (!isset($_POST['values'])) $_POST['values'] = array(); if (!isset($_POST['nulls'])) $_POST['nulls'] = array(); // Verify that they haven't supplied a value for unary operators foreach ($_POST['ops'] as $k => $v) { if ($data->selectOps[$v] == 'p' && $_POST['values'][$k] != '') { doSelectRows(true, $lang['strselectunary']); return; } } if (sizeof($_POST['show']) == 0) doSelectRows(true, $lang['strselectneedscol']); else { // Generate query SQL $query = $data->getSelectSQL($_REQUEST['view'], array_keys($_POST['show']), $_POST['values'], $_POST['ops']); $_REQUEST['query'] = $query; $_REQUEST['return'] = "schema"; $_no_output = true; include('./display.php'); exit; } } } /** * Show confirmation of drop and perform actual drop */ function doDrop($confirm) { global $data, $misc; global $lang, $_reload_browser; if (empty($_REQUEST['view']) && empty($_REQUEST['ma'])) { doDefault($lang['strspecifyviewtodrop']); exit(); } if ($confirm) { $misc->printTrail('view'); $misc->printTitle($lang['strdrop'],'pg.view.drop'); echo "<form action=\"views.php\" method=\"post\">\n"; //If multi drop if (isset($_REQUEST['ma'])) { foreach($_REQUEST['ma'] as $v) { $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES)); echo "<p>", sprintf($lang['strconfdropview'], $misc->printVal($a['view'])), "</p>\n"; echo '<input type="hidden" name="view[]" value="', htmlspecialchars($a['view']), "\" />\n"; } } else { echo "<p>", sprintf($lang['strconfdropview'], $misc->printVal($_REQUEST['view'])), "</p>\n"; echo "<input type=\"hidden\" name=\"view\" value=\"", htmlspecialchars($_REQUEST['view']), "\" />\n"; } echo "<input type=\"hidden\" name=\"action\" value=\"drop\" />\n"; echo $misc->form; echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$lang['strcascade']}</label></p>\n"; echo "<input type=\"submit\" name=\"drop\" value=\"{$lang['strdrop']}\" />\n"; echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" />\n"; echo "</form>\n"; } else { if (is_array($_POST['view'])) { $msg=''; $status = $data->beginTransaction(); if ($status == 0) { foreach($_POST['view'] as $s) { $status = $data->dropView($s, isset($_POST['cascade'])); if ($status == 0) $msg.= sprintf('%s: %s<br />', htmlentities($s, ENT_QUOTES, 'UTF-8'), $lang['strviewdropped']); else { $data->endTransaction(); doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($s, ENT_QUOTES, 'UTF-8'), $lang['strviewdroppedbad'])); return; } } } if($data->endTransaction() == 0) { // Everything went fine, back to the Default page.... $_reload_browser = true; doDefault($msg); } else doDefault($lang['strviewdroppedbad']); } else{ $status = $data->dropView($_POST['view'], isset($_POST['cascade'])); if ($status == 0) { $_reload_browser = true; doDefault($lang['strviewdropped']); } else doDefault($lang['strviewdroppedbad']); } } } /** * Sets up choices for table linkage, and which fields to select for the view we're creating */ function doSetParamsCreate($msg = '') { global $data, $misc; global $lang; // Check that they've chosen tables for the view definition if (!isset($_POST['formTables']) ) doWizardCreate($lang['strviewneedsdef']); else { // Initialise variables if (!isset($_REQUEST['formView'])) $_REQUEST['formView'] = ''; if (!isset($_REQUEST['formComment'])) $_REQUEST['formComment'] = ''; $misc->printTrail('schema'); $misc->printTitle($lang['strcreateviewwiz'], 'pg.view.create'); $misc->printMsg($msg); $tblCount = sizeof($_POST['formTables']); //unserialize our schema/table information and store in arrSelTables for ($i = 0; $i < $tblCount; $i++) { $arrSelTables[] = unserialize($_POST['formTables'][$i]); } $linkCount = $tblCount; //get linking keys $rsLinkKeys = $data->getLinkingKeys($arrSelTables); $linkCount = $rsLinkKeys->recordCount() > $tblCount ? $rsLinkKeys->recordCount() : $tblCount; $arrFields = array(); //array that will hold all our table/field names //if we have schemas we need to specify the correct schema for each table we're retrieiving //with getTableAttributes $curSchema = $data->_schema; for ($i = 0; $i < $tblCount; $i++) { if ($data->_schema != $arrSelTables[$i]['schemaname']) { $data->setSchema($arrSelTables[$i]['schemaname']); } $attrs = $data->getTableAttributes($arrSelTables[$i]['tablename']); while (!$attrs->EOF) { $arrFields["{$arrSelTables[$i]['schemaname']}.{$arrSelTables[$i]['tablename']}.{$attrs->fields['attname']}"] = serialize(array( 'schemaname' => $arrSelTables[$i]['schemaname'], 'tablename' => $arrSelTables[$i]['tablename'], 'fieldname' => $attrs->fields['attname']) ); $attrs->moveNext(); } $data->setSchema($curSchema); } asort($arrFields); echo "<form action=\"views.php\" method=\"post\">\n"; echo "<table>\n"; echo "<tr><th class=\"data\">{$lang['strviewname']}</th></tr>"; echo "<tr>\n<td class=\"data1\">\n"; // View name echo "<input name=\"formView\" value=\"", htmlspecialchars($_REQUEST['formView']), "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" />\n"; echo "</td>\n</tr>\n"; echo "<tr><th class=\"data\">{$lang['strcomment']}</th></tr>"; echo "<tr>\n<td class=\"data1\">\n"; // View comments echo "<textarea name=\"formComment\" rows=\"3\" cols=\"32\">", htmlspecialchars($_REQUEST['formComment']), "</textarea>\n"; echo "</td>\n</tr>\n"; echo "</table>\n"; // Output selector for fields to be retrieved from view echo "<table>\n"; echo "<tr><th class=\"data\">{$lang['strcolumns']}</th></tr>"; echo "<tr>\n<td class=\"data1\">\n"; echo GUI::printCombo($arrFields, 'formFields[]', false, '', true); echo "</td>\n</tr>"; echo "<tr><td><input type=\"radio\" name=\"dblFldMeth\" id=\"dblFldMeth1\" value=\"rename\" /><label for=\"dblFldMeth1\">{$lang['strrenamedupfields']}</label>"; echo "<br /><input type=\"radio\" name=\"dblFldMeth\" id=\"dblFldMeth2\" value=\"drop\" /><label for=\"dblFldMeth2\">{$lang['strdropdupfields']}</label>"; echo "<br /><input type=\"radio\" name=\"dblFldMeth\" id=\"dblFldMeth3\" value=\"\" checked=\"checked\" /><label for=\"dblFldMeth3\">{$lang['strerrordupfields']}</label></td></tr></table><br />"; // Output the Linking keys combo boxes echo "<table>\n"; echo "<tr><th class=\"data\">{$lang['strviewlink']}</th></tr>"; $rowClass = 'data1'; for ($i = 0; $i < $linkCount; $i++) { // Initialise variables if (!isset($formLink[$i]['operator'])) $formLink[$i]['operator'] = 'INNER JOIN'; echo "<tr>\n<td class=\"$rowClass\">\n"; if (!$rsLinkKeys->EOF) { $curLeftLink = htmlspecialchars(serialize(array('schemaname' => $rsLinkKeys->fields['p_schema'], 'tablename' => $rsLinkKeys->fields['p_table'], 'fieldname' => $rsLinkKeys->fields['p_field']) ) ); $curRightLink = htmlspecialchars(serialize(array('schemaname' => $rsLinkKeys->fields['f_schema'], 'tablename' => $rsLinkKeys->fields['f_table'], 'fieldname' => $rsLinkKeys->fields['f_field']) ) ); $rsLinkKeys->moveNext(); } else { $curLeftLink = ''; $curRightLink = ''; } echo GUI::printCombo($arrFields, "formLink[$i][leftlink]", true, $curLeftLink, false ); echo GUI::printCombo($data->joinOps, "formLink[$i][operator]", true, $formLink[$i]['operator']); echo GUI::printCombo($arrFields, "formLink[$i][rightlink]", true, $curRightLink, false ); echo "</td>\n</tr>\n"; $rowClass = $rowClass == 'data1' ? 'data2' : 'data1'; } echo "</table>\n<br />\n"; // Build list of available operators (infix only) $arrOperators = array(); foreach ($data->selectOps as $k => $v) { if ($v == 'i') $arrOperators[$k] = $k; } // Output additional conditions, note that this portion of the wizard treats the right hand side as literal values //(not as database objects) so field names will be treated as strings, use the above linking keys section to perform joins echo "<table>\n"; echo "<tr><th class=\"data\">{$lang['strviewconditions']}</th></tr>"; $rowClass = 'data1'; for ($i = 0; $i < $linkCount; $i++) { echo "<tr>\n<td class=\"$rowClass\">\n"; echo GUI::printCombo($arrFields, "formCondition[$i][field]"); echo GUI::printCombo($arrOperators, "formCondition[$i][operator]", false, false); echo "<input type=\"text\" name=\"formCondition[$i][txt]\" />\n"; echo "</td>\n</tr>\n"; $rowClass = $rowClass == 'data1' ? 'data2' : 'data1'; } echo "</table>\n"; echo "<p><input type=\"hidden\" name=\"action\" value=\"save_create_wiz\" />\n"; foreach ($arrSelTables AS $curTable) { echo "<input type=\"hidden\" name=\"formTables[]\" value=\"" . htmlspecialchars(serialize($curTable) ) . "\" />\n"; } echo $misc->form; echo "<input type=\"submit\" value=\"{$lang['strcreate']}\" />\n"; echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" /></p>\n"; echo "</form>\n"; } } /** * Display a wizard where they can enter a new view */ function doWizardCreate($msg = '') { global $data, $misc; global $lang; $tables = $data->getTables(true); $misc->printTrail('schema'); $misc->printTitle($lang['strcreateviewwiz'], 'pg.view.create'); $misc->printMsg($msg); echo "<form action=\"views.php\" method=\"post\">\n"; echo "<table>\n"; echo "<tr><th class=\"data\">{$lang['strtables']}</th></tr>"; echo "<tr>\n<td class=\"data1\">\n"; $arrTables = array(); while (!$tables->EOF) { $arrTmp = array(); $arrTmp['schemaname'] = $tables->fields['nspname']; $arrTmp['tablename'] = $tables->fields['relname']; $arrTables[$tables->fields['nspname'] . '.' . $tables->fields['relname']] = serialize($arrTmp); $tables->moveNext(); } echo GUI::printCombo($arrTables, 'formTables[]', false, '', true); echo "</td>\n</tr>\n"; echo "</table>\n"; echo "<p><input type=\"hidden\" name=\"action\" value=\"set_params_create\" />\n"; echo $misc->form; echo "<input type=\"submit\" value=\"{$lang['strnext']}\" />\n"; echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" /></p>\n"; echo "</form>\n"; } /** * Displays a screen where they can enter a new view */ function doCreate($msg = '') { global $data, $misc, $conf; global $lang; if (!isset($_REQUEST['formView'])) $_REQUEST['formView'] = ''; if (!isset($_REQUEST['formDefinition'])) $_REQUEST['formDefinition'] = 'SELECT '; if (!isset($_REQUEST['formComment'])) $_REQUEST['formComment'] = ''; $misc->printTrail('schema'); $misc->printTitle($lang['strcreateview'], 'pg.view.create'); $misc->printMsg($msg); echo "<form action=\"views.php\" method=\"post\">\n"; echo "<table style=\"width: 100%\">\n"; echo "\t<tr>\n\t\t<th class=\"data left required\">{$lang['strname']}</th>\n"; echo "\t<td class=\"data1\"><input name=\"formView\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"", htmlspecialchars($_REQUEST['formView']), "\" /></td>\n\t</tr>\n"; echo "\t<tr>\n\t\t<th class=\"data left required\">{$lang['strdefinition']}</th>\n"; echo "\t<td class=\"data1\"><textarea style=\"width:100%;\" rows=\"10\" cols=\"50\" name=\"formDefinition\">", htmlspecialchars($_REQUEST['formDefinition']), "</textarea></td>\n\t</tr>\n"; echo "\t<tr>\n\t\t<th class=\"data left\">{$lang['strcomment']}</th>\n"; echo "\t\t<td class=\"data1\"><textarea name=\"formComment\" rows=\"3\" cols=\"32\">", htmlspecialchars($_REQUEST['formComment']), "</textarea></td>\n\t</tr>\n"; echo "</table>\n"; echo "<p><input type=\"hidden\" name=\"action\" value=\"save_create\" />\n"; echo $misc->form; echo "<input type=\"submit\" value=\"{$lang['strcreate']}\" />\n"; echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" /></p>\n"; echo "</form>\n"; } /** * Actually creates the new view in the database */ function doSaveCreate() { global $data, $lang, $_reload_browser; // Check that they've given a name and a definition if ($_POST['formView'] == '') doCreate($lang['strviewneedsname']); elseif ($_POST['formDefinition'] == '') doCreate($lang['strviewneedsdef']); else { $status = $data->createView($_POST['formView'], $_POST['formDefinition'], false, $_POST['formComment']); if ($status == 0) { $_reload_browser = true; doDefault($lang['strviewcreated']); } else doCreate($lang['strviewcreatedbad']); } } /** * Actually creates the new wizard view in the database */ function doSaveCreateWiz() { global $data, $lang, $_reload_browser; // Check that they've given a name and fields they want to select if (!strlen($_POST['formView']) ) doSetParamsCreate($lang['strviewneedsname']); else if (!isset($_POST['formFields']) || !count($_POST['formFields']) ) doSetParamsCreate($lang['strviewneedsfields']); else { $selFields = ''; if (! empty($_POST['dblFldMeth']) ) $tmpHsh = array(); foreach ($_POST['formFields'] AS $curField) { $arrTmp = unserialize($curField); $data->fieldArrayClean($arrTmp); if (! empty($_POST['dblFldMeth']) ) { // doublon control if (empty($tmpHsh[$arrTmp['fieldname']])) { // field does not exist $selFields .= "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\", "; $tmpHsh[$arrTmp['fieldname']] = 1; } else if ($_POST['dblFldMeth'] == 'rename') { // field exist and must be renamed $tmpHsh[$arrTmp['fieldname']]++; $selFields .= "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\" AS \"{$arrTmp['schemaname']}_{$arrTmp['tablename']}_{$arrTmp['fieldname']}{$tmpHsh[$arrTmp['fieldname']]}\", "; } /* field already exist, just ignore this one */ } else { // no doublon control $selFields .= "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\", "; } } $selFields = substr($selFields, 0, -2); unset($arrTmp, $tmpHsh); $linkFields = ''; // If we have links, out put the JOIN ... ON statements if (is_array($_POST['formLink']) ) { // Filter out invalid/blank entries for our links $arrLinks = array(); foreach ($_POST['formLink'] AS $curLink) { if (strlen($curLink['leftlink']) && strlen($curLink['rightlink']) && strlen($curLink['operator'])) { $arrLinks[] = $curLink; } } // We must perform some magic to make sure that we have a valid join order $count = sizeof($arrLinks); $arrJoined = array(); $arrUsedTbls = array(); // If we have at least one join condition, output it if ($count > 0) { $j = 0; while ($j < $count) { foreach ($arrLinks AS $curLink) { $arrLeftLink = unserialize($curLink['leftlink']); $arrRightLink = unserialize($curLink['rightlink']); $data->fieldArrayClean($arrLeftLink); $data->fieldArrayClean($arrRightLink); $tbl1 = "\"{$arrLeftLink['schemaname']}\".\"{$arrLeftLink['tablename']}\""; $tbl2 = "\"{$arrRightLink['schemaname']}\".\"{$arrRightLink['tablename']}\""; if ( (!in_array($curLink, $arrJoined) && in_array($tbl1, $arrUsedTbls)) || !count($arrJoined) ) { // Make sure for multi-column foreign keys that we use a table alias tables joined to more than once // This can (and should be) more optimized for multi-column foreign keys $adj_tbl2 = in_array($tbl2, $arrUsedTbls) ? "$tbl2 AS alias_ppa_" . mktime() : $tbl2; $linkFields .= strlen($linkFields) ? "{$curLink['operator']} $adj_tbl2 ON (\"{$arrLeftLink['schemaname']}\".\"{$arrLeftLink['tablename']}\".\"{$arrLeftLink['fieldname']}\" = \"{$arrRightLink['schemaname']}\".\"{$arrRightLink['tablename']}\".\"{$arrRightLink['fieldname']}\") " : "$tbl1 {$curLink['operator']} $adj_tbl2 ON (\"{$arrLeftLink['schemaname']}\".\"{$arrLeftLink['tablename']}\".\"{$arrLeftLink['fieldname']}\" = \"{$arrRightLink['schemaname']}\".\"{$arrRightLink['tablename']}\".\"{$arrRightLink['fieldname']}\") "; $arrJoined[] = $curLink; if (!in_array($tbl1, $arrUsedTbls) ) $arrUsedTbls[] = $tbl1; if (!in_array($tbl2, $arrUsedTbls) ) $arrUsedTbls[] = $tbl2; } } $j++; } } } //if linkfields has no length then either _POST['formLink'] was not set, or there were no join conditions //just select from all seleted tables - a cartesian join do a if (!strlen($linkFields) ) { foreach ($_POST['formTables'] AS $curTable) { $arrTmp = unserialize($curTable); $data->fieldArrayClean($arrTmp); $linkFields .= strlen($linkFields) ? ", \"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\"" : "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\""; } } $addConditions = ''; if (is_array($_POST['formCondition']) ) { foreach ($_POST['formCondition'] AS $curCondition) { if (strlen($curCondition['field']) && strlen($curCondition['txt']) ) { $arrTmp = unserialize($curCondition['field']); $data->fieldArrayClean($arrTmp); $addConditions .= strlen($addConditions) ? " AND \"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\" {$curCondition['operator']} '{$curCondition['txt']}' " : " \"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\" {$curCondition['operator']} '{$curCondition['txt']}' "; } } } $viewQuery = "SELECT $selFields FROM $linkFields "; //add where from additional conditions if (strlen($addConditions) ) $viewQuery .= ' WHERE ' . $addConditions; $status = $data->createView($_POST['formView'], $viewQuery, false, $_POST['formComment']); if ($status == 0) { $_reload_browser = true; doDefault($lang['strviewcreated']); } else doSetParamsCreate($lang['strviewcreatedbad']); } } /** * Show default list of views in the database */ function doDefault($msg = '') { global $data, $misc, $conf; global $lang; $misc->printTrail('schema'); $misc->printTabs('schema','views'); $misc->printMsg($msg); $views = $data->getViews(); $columns = array( 'view' => array( 'title' => $lang['strview'], 'field' => field('relname'), 'url' => "redirect.php?subject=view&amp;{$misc->href}&amp;", 'vars' => array('view' => 'relname'), ), 'owner' => array( 'title' => $lang['strowner'], 'field' => field('relowner'), ), 'actions' => array( 'title' => $lang['stractions'], ), 'comment' => array( 'title' => $lang['strcomment'], 'field' => field('relcomment'), ), ); $actions = array( 'multiactions' => array( 'keycols' => array('view' => 'relname'), 'url' => 'views.php', ), 'browse' => array( 'content' => $lang['strbrowse'], 'attr'=> array ( 'href' => array ( 'url' => 'display.php', 'urlvars' => array ( 'action' => 'confselectrows', 'subject' => 'view', 'return' => 'schema', 'view' => field('relname') ) ) ) ), 'select' => array( 'content' => $lang['strselect'], 'attr'=> array ( 'href' => array ( 'url' => 'views.php', 'urlvars' => array ( 'action' => 'confselectrows', 'view' => field('relname') ) ) ) ), // Insert is possible if the relevant rule for the view has been created. // 'insert' => array( // 'title' => $lang['strinsert'], // 'url' => "views.php?action=confinsertrow&amp;{$misc->href}&amp;", // 'vars' => array('view' => 'relname'), // ), 'alter' => array( 'content' => $lang['stralter'], 'attr'=> array ( 'href' => array ( 'url' => 'viewproperties.php', 'urlvars' => array ( 'action' => 'confirm_alter', 'view' => field('relname') ) ) ) ), 'drop' => array( 'multiaction' => 'confirm_drop', 'content' => $lang['strdrop'], 'attr'=> array ( 'href' => array ( 'url' => 'views.php', 'urlvars' => array ( 'action' => 'confirm_drop', 'view' => field('relname') ) ) ) ), ); $misc->printTable($views, $columns, $actions, 'views-views', $lang['strnoviews']); $navlinks = array ( 'create' => array ( 'attr'=> array ( 'href' => array ( 'url' => 'views.php', 'urlvars' => array ( 'action' => 'create', 'server' => $_REQUEST['server'], 'database' => $_REQUEST['database'], 'schema' => $_REQUEST['schema'] ) ) ), 'content' => $lang['strcreateview'] ), 'createwiz' => array ( 'attr'=> array ( 'href' => array ( 'url' => 'views.php', 'urlvars' => array ( 'action' => 'wiz_create', 'server' => $_REQUEST['server'], 'database' => $_REQUEST['database'], 'schema' => $_REQUEST['schema'] ) ) ), 'content' => $lang['strcreateviewwiz'] ) ); $misc->printNavLinks($navlinks, 'views-views', get_defined_vars()); } /** * Generate XML for the browser tree. */ function doTree() { global $misc, $data; $views = $data->getViews(); $reqvars = $misc->getRequestVars('view'); $attrs = array( 'text' => field('relname'), 'icon' => 'View', 'iconAction' => url('display.php', $reqvars, array('view' => field('relname'))), 'toolTip'=> field('relcomment'), 'action' => url('redirect.php', $reqvars, array('view' => field('relname'))), 'branch' => url('views.php', $reqvars, array ( 'action' => 'subtree', 'view' => field('relname') ) ) ); $misc->printTree($views, $attrs, 'views'); exit; } function doSubTree() { global $misc, $data; $tabs = $misc->getNavTabs('view'); $items = $misc->adjustTabsForTree($tabs); $reqvars = $misc->getRequestVars('view'); $attrs = array( 'text' => field('title'), 'icon' => field('icon'), 'action' => url(field('url'), $reqvars, field('urlvars'), array('view' => $_REQUEST['view'])), 'branch' => ifempty( field('branch'), '', url(field('url'), field('urlvars'), $reqvars, array( 'action' => 'tree', 'view' => $_REQUEST['view'] ) ) ), ); $misc->printTree($items, $attrs, 'view'); exit; } if ($action == 'tree') doTree(); if ($action == 'subtree') dosubTree(); $misc->printHeader($lang['strviews']); $misc->printBody(); switch ($action) { case 'selectrows': if (!isset($_REQUEST['cancel'])) doSelectRows(false); else doDefault(); break; case 'confselectrows': doSelectRows(true); break; case 'save_create_wiz': if (isset($_REQUEST['cancel'])) doDefault(); else doSaveCreateWiz(); break; case 'wiz_create': doWizardCreate(); break; case 'set_params_create': if (isset($_POST['cancel'])) doDefault(); else doSetParamsCreate(); break; case 'save_create': if (isset($_REQUEST['cancel'])) doDefault(); else doSaveCreate(); break; case 'create': doCreate(); break; case 'drop': if (isset($_POST['drop'])) doDrop(false); else doDefault(); break; case 'confirm_drop': doDrop(true); break; default: doDefault(); break; } $misc->printFooter(); ?>
juanchi008/playa_auto
web/phppgadmin/views.php
PHP
bsd-3-clause
27,911
# This migration comes from spree (originally 20130417120035) class UpdateAdjustmentStates < ActiveRecord::Migration[4.2] def up Spree::Order.complete.find_each do |order| order.adjustments.update_all(state: 'closed') end Spree::Shipment.shipped.includes(:adjustment).find_each do |shipment| shipment.adjustment.update_column(:state, 'finalized') if shipment.adjustment end Spree::Adjustment.where(state: nil).update_all(state: 'open') end def down end end
andreinabgomezg29/spree_out_stock
spec/dummy/db/migrate/20170904174291_update_adjustment_states.spree.rb
Ruby
bsd-3-clause
500
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays options for exporting the captured data. */ var ExportView = (function() { 'use strict'; // We inherit from DivView. var superClass = DivView; /** * @constructor */ function ExportView() { assertFirstConstructorCall(ExportView); // Call superclass's constructor. superClass.call(this, ExportView.MAIN_BOX_ID); var privacyStrippingCheckbox = $(ExportView.PRIVACY_STRIPPING_CHECKBOX_ID); privacyStrippingCheckbox.onclick = this.onSetPrivacyStripping_.bind(this, privacyStrippingCheckbox); this.saveFileButton_ = $(ExportView.SAVE_FILE_BUTTON_ID); this.saveFileButton_.onclick = this.onSaveFile_.bind(this); this.saveStatusText_ = $(ExportView.SAVE_STATUS_TEXT_ID); this.userCommentsTextArea_ = $(ExportView.USER_COMMENTS_TEXT_AREA_ID); // Track blob for previous log dump so it can be revoked when a new dump is // saved. this.lastBlobURL_ = null; // Cached copy of the last loaded log dump, for use when exporting. this.loadedLogDump_ = null; } // ID for special HTML element in category_tabs.html ExportView.TAB_HANDLE_ID = 'tab-handle-export'; // IDs for special HTML elements in export_view.html ExportView.MAIN_BOX_ID = 'export-view-tab-content'; ExportView.DOWNLOAD_ANCHOR_ID = 'export-view-download-anchor'; ExportView.SAVE_FILE_BUTTON_ID = 'export-view-save-log-file'; ExportView.SAVE_STATUS_TEXT_ID = 'export-view-save-status-text'; ExportView.PRIVACY_STRIPPING_CHECKBOX_ID = 'export-view-privacy-stripping-checkbox'; ExportView.USER_COMMENTS_TEXT_AREA_ID = 'export-view-user-comments'; ExportView.PRIVACY_WARNING_ID = 'export-view-privacy-warning'; cr.addSingletonGetter(ExportView); ExportView.prototype = { // Inherit the superclass's methods. __proto__: superClass.prototype, /** * Depending on the value of the checkbox, enables or disables stripping * cookies and passwords from log dumps and displayed events. */ onSetPrivacyStripping_: function(privacyStrippingCheckbox) { SourceTracker.getInstance().setPrivacyStripping( privacyStrippingCheckbox.checked); }, /** * When loading a log dump, cache it for future export and continue showing * the ExportView. */ onLoadLogFinish: function(polledData, tabData, logDump) { this.loadedLogDump_ = logDump; this.setUserComments_(logDump.userComments); return true; }, /** * Sets the save to file status text, displayed below the save to file * button, to |text|. Also enables or disables the save button based on the * value of |isSaving|, which must be true if the save process is still * ongoing, and false when the operation has stopped, regardless of success * of failure. */ setSaveFileStatus: function(text, isSaving) { this.enableSaveFileButton_(!isSaving); this.saveStatusText_.textContent = text; }, enableSaveFileButton_: function(enabled) { this.saveFileButton_.disabled = !enabled; }, showPrivacyWarning: function() { setNodeDisplay($(ExportView.PRIVACY_WARNING_ID), true); $(ExportView.PRIVACY_STRIPPING_CHECKBOX_ID).checked = false; $(ExportView.PRIVACY_STRIPPING_CHECKBOX_ID).disabled = true; // Updating the checkbox doesn't actually disable privacy stripping, since // the onclick function will not be called. this.onSetPrivacyStripping_($(ExportView.PRIVACY_STRIPPING_CHECKBOX_ID)); }, /** * If not already busy saving a log dump, triggers asynchronous * generation of log dump and starts waiting for it to complete. */ onSaveFile_: function() { if (this.saveFileButton_.disabled) return; // Clean up previous blob, if any, to reduce resource usage. if (this.lastBlobURL_) { window.webkitURL.revokeObjectURL(this.lastBlobURL_); this.lastBlobURL_ = null; } this.createLogDump_(this.onLogDumpCreated_.bind(this)); }, /** * Creates a log dump, and either synchronously or asynchronously calls * |callback| if it succeeds. Separate from onSaveFile_ for unit tests. */ createLogDump_: function(callback) { // Get an explanation for the dump file (this is mandatory!) var userComments = this.getNonEmptyUserComments_(); if (userComments == undefined) { return; } this.setSaveFileStatus('Preparing data...', true); var privacyStripping = SourceTracker.getInstance().getPrivacyStripping(); // If we have a cached log dump, update it synchronously. if (this.loadedLogDump_) { var dumpText = log_util.createUpdatedLogDump(userComments, this.loadedLogDump_, privacyStripping); callback(dumpText); return; } // Otherwise, poll information from the browser before creating one. log_util.createLogDumpAsync(userComments, callback, privacyStripping); }, /** * Sets the user comments. */ setUserComments_: function(userComments) { this.userCommentsTextArea_.value = userComments; }, /** * Fetches the user comments for this dump. If none were entered, warns the * user and returns undefined. Otherwise returns the comments text. */ getNonEmptyUserComments_: function() { var value = this.userCommentsTextArea_.value; // Reset the class name in case we had hilighted it earlier. this.userCommentsTextArea_.className = ''; // We don't accept empty explanations. We don't care what is entered, as // long as there is something (a single whitespace would work). if (value == '') { // Put a big obnoxious red border around the text area. this.userCommentsTextArea_.className = 'export-view-explanation-warning'; alert('Please fill in the text field!'); return undefined; } return value; }, /** * Creates a blob url and starts downloading it. */ onLogDumpCreated_: function(dumpText) { var textBlob = new Blob([dumpText], {type: 'octet/stream'}); this.lastBlobURL_ = window.webkitURL.createObjectURL(textBlob); // Update the anchor tag and simulate a click on it to start the // download. var downloadAnchor = $(ExportView.DOWNLOAD_ANCHOR_ID); downloadAnchor.href = this.lastBlobURL_; downloadAnchor.click(); this.setSaveFileStatus('Dump successful', false); } }; return ExportView; })();
zcbenz/cefode-chromium
chrome/browser/resources/net_internals/export_view.js
JavaScript
bsd-3-clause
6,896
# frozen_string_literal: true module Spree module Admin class PropertiesController < ResourceController def index respond_with(@collection) end private def collection return @collection if @collection # params[:q] can be blank upon pagination params[:q] = {} if params[:q].blank? @collection = super @search = @collection.ransack(params[:q]) @collection = @search.result. page(params[:page]). per(Spree::Config[:properties_per_page]) @collection end end end end
pervino/solidus
backend/app/controllers/spree/admin/properties_controller.rb
Ruby
bsd-3-clause
601
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Variable = void 0; const variable_1 = __importDefault(require("eslint-scope/lib/variable")); const Variable = variable_1.default; exports.Variable = Variable; //# sourceMappingURL=Variable.js.map
ChromeDevTools/devtools-frontend
node_modules/@typescript-eslint/experimental-utils/dist/ts-eslint-scope/Variable.js
JavaScript
bsd-3-clause
419
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/device/hid/hid_preparsed_data.h" #include <cstddef> #include <cstdint> #include "base/debug/dump_without_crashing.h" #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "components/device_event_log/device_event_log.h" namespace device { namespace { // Windows parses HID report descriptors into opaque _HIDP_PREPARSED_DATA // objects. The internal structure of _HIDP_PREPARSED_DATA is reserved for // internal system use. The structs below are inferred and may be wrong or // incomplete. // https://docs.microsoft.com/en-us/windows-hardware/drivers/hid/preparsed-data // // _HIDP_PREPARSED_DATA begins with a fixed-sized header containing information // about a single top-level HID collection. The header is followed by a // variable-sized array describing the fields that make up each report. // // Input report items appear first in the array, followed by output report items // and feature report items. The number of items of each type is given by // |input_item_count|, |output_item_count| and |feature_item_count|. The sum of // these counts should equal |item_count|. The total size in bytes of all report // items is |size_bytes|. #pragma pack(push, 1) struct PreparsedDataHeader { // Unknown constant value. _HIDP_PREPARSED_DATA identifier? uint64_t magic; // Top-level collection usage information. uint16_t usage; uint16_t usage_page; uint16_t unknown[3]; // Number of report items for input reports. Includes unused items. uint16_t input_item_count; uint16_t unknown2; // Maximum input report size, in bytes. Includes the report ID byte. Zero if // there are no input reports. uint16_t input_report_byte_length; uint16_t unknown3; // Number of report items for output reports. Includes unused items. uint16_t output_item_count; uint16_t unknown4; // Maximum output report size, in bytes. Includes the report ID byte. Zero if // there are no output reports. uint16_t output_report_byte_length; uint16_t unknown5; // Number of report items for feature reports. Includes unused items. uint16_t feature_item_count; // Total number of report items (input, output, and feature). Unused items are // excluded. uint16_t item_count; // Maximum feature report size, in bytes. Includes the report ID byte. Zero if // there are no feature reports. uint16_t feature_report_byte_length; // Total size of all report items, in bytes. uint16_t size_bytes; uint16_t unknown6; }; #pragma pack(pop) static_assert(sizeof(PreparsedDataHeader) == 44, "PreparsedDataHeader has incorrect size"); #pragma pack(push, 1) struct PreparsedDataItem { // Usage page for |usage_minimum| and |usage_maximum|. uint16_t usage_page; // Report ID for the report containing this item. uint8_t report_id; // Bit offset from |byte_index|. uint8_t bit_index; // Bit width of a single field defined by this item. uint16_t bit_size; // The number of fields defined by this item. uint16_t report_count; // Byte offset from the start of the report containing this item, including // the report ID byte. uint16_t byte_index; // The total number of bits for all fields defined by this item. uint16_t bit_count; // The bit field for the corresponding main item in the HID report. This bit // field is defined in the Device Class Definition for HID v1.11 section // 6.2.2.5. // https://www.usb.org/document-library/device-class-definition-hid-111 uint32_t bit_field; uint32_t unknown; // Usage information for the collection containing this item. uint16_t link_usage_page; uint16_t link_usage; uint32_t unknown2[9]; // The usage range for this item. uint16_t usage_minimum; uint16_t usage_maximum; // The string descriptor index range associated with this item. If the item // has no string descriptors, |string_minimum| and |string_maximum| are set to // zero. uint16_t string_minimum; uint16_t string_maximum; // The designator index range associated with this item. If the item has no // designators, |designator_minimum| and |designator_maximum| are set to zero. uint16_t designator_minimum; uint16_t designator_maximum; // The data index range associated with this item. uint16_t data_index_minimum; uint16_t data_index_maximum; uint32_t unknown3; // The range of fields defined by this item in logical units. int32_t logical_minimum; int32_t logical_maximum; // The range of fields defined by this item in units defined by |unit| and // |unit_exponent|. If this item does not use physical units, // |physical_minimum| and |physical_maximum| are set to zero. int32_t physical_minimum; int32_t physical_maximum; // The unit definition for this item. The format for this definition is // described in the Device Class Definition for HID v1.11 section 6.2.2.7. // https://www.usb.org/document-library/device-class-definition-hid-111 uint32_t unit; uint32_t unit_exponent; }; #pragma pack(pop) static_assert(sizeof(PreparsedDataItem) == 104, "PreparsedDataItem has incorrect size"); bool ValidatePreparsedDataHeader(const PreparsedDataHeader& header) { static bool has_dumped_without_crashing = false; // _HIDP_PREPARSED_DATA objects are expected to start with a known constant // value. constexpr uint64_t kHidPreparsedDataMagic = 0x52444B2050646948; // Require a matching magic value. The details of _HIDP_PREPARSED_DATA are // proprietary and the magic constant may change. If DCHECKS are on, trigger // a CHECK failure and crash. Otherwise, generate a non-crash dump. DCHECK_EQ(header.magic, kHidPreparsedDataMagic); if (header.magic != kHidPreparsedDataMagic) { HID_LOG(ERROR) << "Unexpected magic value."; if (has_dumped_without_crashing) { base::debug::DumpWithoutCrashing(); has_dumped_without_crashing = true; } return false; } if (header.input_report_byte_length == 0 && header.input_item_count > 0) return false; if (header.output_report_byte_length == 0 && header.output_item_count > 0) return false; if (header.feature_report_byte_length == 0 && header.feature_item_count > 0) return false; // Calculate the expected total size of report items in the // _HIDP_PREPARSED_DATA object. Use the individual item counts for each report // type instead of the total |item_count|. In some cases additional items are // allocated but are not used for any reports. Unused items are excluded from // |item_count| but are included in the item counts for each report type and // contribute to the total size of the object. See crbug.com/1199890 for more // information. uint16_t total_item_size = (header.input_item_count + header.output_item_count + header.feature_item_count) * sizeof(PreparsedDataItem); if (total_item_size != header.size_bytes) return false; return true; } bool ValidatePreparsedDataItem(const PreparsedDataItem& item) { // Check that the item does not overlap with the report ID byte. if (item.byte_index == 0) return false; // Check that the bit index does not exceed the maximum bit index in one byte. if (item.bit_index >= CHAR_BIT) return false; // Check that the item occupies at least one bit in the report. if (item.report_count == 0 || item.bit_size == 0 || item.bit_count == 0) return false; return true; } HidServiceWin::PreparsedData::ReportItem MakeReportItemFromPreparsedData( const PreparsedDataItem& item) { size_t bit_index = (item.byte_index - 1) * CHAR_BIT + item.bit_index; return {item.report_id, item.bit_field, item.bit_size, item.report_count, item.usage_page, item.usage_minimum, item.usage_maximum, item.designator_minimum, item.designator_maximum, item.string_minimum, item.string_maximum, item.logical_minimum, item.logical_maximum, item.physical_minimum, item.physical_maximum, item.unit, item.unit_exponent, bit_index}; } } // namespace // static std::unique_ptr<HidPreparsedData> HidPreparsedData::Create( HANDLE device_handle) { PHIDP_PREPARSED_DATA preparsed_data; if (!HidD_GetPreparsedData(device_handle, &preparsed_data) || !preparsed_data) { HID_PLOG(EVENT) << "Failed to get device data"; return nullptr; } HIDP_CAPS capabilities; if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) { HID_PLOG(EVENT) << "Failed to get device capabilities"; HidD_FreePreparsedData(preparsed_data); return nullptr; } return base::WrapUnique(new HidPreparsedData(preparsed_data, capabilities)); } HidPreparsedData::HidPreparsedData(PHIDP_PREPARSED_DATA preparsed_data, HIDP_CAPS capabilities) : preparsed_data_(preparsed_data), capabilities_(capabilities) { DCHECK(preparsed_data_); } HidPreparsedData::~HidPreparsedData() { HidD_FreePreparsedData(preparsed_data_); } const HIDP_CAPS& HidPreparsedData::GetCaps() const { return capabilities_; } std::vector<HidServiceWin::PreparsedData::ReportItem> HidPreparsedData::GetReportItems(HIDP_REPORT_TYPE report_type) const { const auto& header = *reinterpret_cast<const PreparsedDataHeader*>(preparsed_data_); if (!ValidatePreparsedDataHeader(header)) return {}; size_t min_index; size_t item_count; switch (report_type) { case HidP_Input: min_index = 0; item_count = header.input_item_count; break; case HidP_Output: min_index = header.input_item_count; item_count = header.output_item_count; break; case HidP_Feature: min_index = header.input_item_count + header.output_item_count; item_count = header.feature_item_count; break; default: return {}; } if (item_count == 0) return {}; const auto* data = reinterpret_cast<const uint8_t*>(preparsed_data_); const auto* items = reinterpret_cast<const PreparsedDataItem*>( data + sizeof(PreparsedDataHeader)); std::vector<ReportItem> report_items; for (size_t i = min_index; i < min_index + item_count; ++i) { if (ValidatePreparsedDataItem(items[i])) report_items.push_back(MakeReportItemFromPreparsedData(items[i])); } return report_items; } } // namespace device
chromium/chromium
services/device/hid/hid_preparsed_data.cc
C++
bsd-3-clause
10,536
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/timer/lap_timer.h" #include "testing/perf/perf_test.h" #include "ui/aura/window.h" #include "ui/compositor/layer.h" #include "ui/compositor/test/draw_waiter_for_test.h" namespace ash { namespace { // TODO(wutao): On chromeos_linux builds, the tests only run with // use_ozone = false. class AshBackgroundFilterBlurPerfTest : public AshTestBase { public: AshBackgroundFilterBlurPerfTest() : timer_(0, base::TimeDelta(), 1) {} AshBackgroundFilterBlurPerfTest(const AshBackgroundFilterBlurPerfTest&) = delete; AshBackgroundFilterBlurPerfTest& operator=( const AshBackgroundFilterBlurPerfTest&) = delete; ~AshBackgroundFilterBlurPerfTest() override = default; // AshTestBase: void SetUp() override; protected: std::unique_ptr<ui::Layer> CreateSolidColorLayer(SkColor color); void WithBoundsChange(ui::Layer* layer, int num_iteration, const std::string& test_name); void WithOpacityChange(ui::Layer* layer, int num_iteration, const std::string& test_name); std::unique_ptr<ui::Layer> background_layer_; std::unique_ptr<ui::Layer> blur_layer_; private: ui::Layer* root_layer_ = nullptr; ui::Compositor* compositor_ = nullptr; base::LapTimer timer_; }; void AshBackgroundFilterBlurPerfTest::SetUp() { AshTestBase::SetUp(); // This is for consistency even if the default display size changed. UpdateDisplay("800x600"); root_layer_ = Shell::GetAllRootWindows()[0]->layer(); compositor_ = root_layer_->GetCompositor(); background_layer_ = CreateSolidColorLayer(SK_ColorGREEN); blur_layer_ = CreateSolidColorLayer(SK_ColorBLACK); } std::unique_ptr<ui::Layer> AshBackgroundFilterBlurPerfTest::CreateSolidColorLayer(SkColor color) { std::unique_ptr<ui::Layer> layer = std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR); layer->SetBounds(root_layer_->bounds()); layer->SetColor(color); root_layer_->Add(layer.get()); root_layer_->StackAtTop(layer.get()); return layer; } void AshBackgroundFilterBlurPerfTest::WithBoundsChange( ui::Layer* layer, int num_iteration, const std::string& test_name) { const gfx::Rect init_bounds = layer->GetTargetBounds(); // Wait for a DidCommit before starts the loop, and do not measure the last // iteration of the loop. ui::DrawWaiterForTest::WaitForCommit(compositor_); timer_.Reset(); for (int i = 1; i <= num_iteration + 1; ++i) { float fraction = (static_cast<float>(i) / num_iteration); const gfx::Rect bounds = gfx::Rect(0, 0, static_cast<int>(init_bounds.width() * fraction), static_cast<int>(init_bounds.height() * fraction)); layer->SetBounds(bounds); ui::DrawWaiterForTest::WaitForCommit(compositor_); if (i <= num_iteration) timer_.NextLap(); } perf_test::PrintResult("AshBackgroundFilterBlurPerfTest", std::string(), test_name, timer_.LapsPerSecond(), "runs/s", true); } void AshBackgroundFilterBlurPerfTest::WithOpacityChange( ui::Layer* layer, int num_iteration, const std::string& test_name) { float init_opacity = layer->GetTargetOpacity(); // Wait for a DidCommit before starts the loop, and do not measure the last // iteration of the loop. ui::DrawWaiterForTest::WaitForCommit(compositor_); timer_.Reset(); for (int i = 1; i <= num_iteration + 1; ++i) { float fraction = (static_cast<float>(i) / num_iteration); float opacity = std::min(1.0f, init_opacity * fraction); layer->SetOpacity(opacity); ui::DrawWaiterForTest::WaitForCommit(compositor_); if (i <= num_iteration) timer_.NextLap(); } perf_test::PrintResult("AshBackgroundFilterBlurPerfTest", std::string(), test_name, timer_.LapsPerSecond(), "runs/s", true); } TEST_F(AshBackgroundFilterBlurPerfTest, NoBlurBackgroundLayerBoundsChange) { WithBoundsChange(background_layer_.get(), 100, "no_blur_background_layer_bounds_change"); } TEST_F(AshBackgroundFilterBlurPerfTest, NoBlurBlurLayerBoundsChange) { WithBoundsChange(blur_layer_.get(), 100, "no_blur_blur_layer_bounds_change"); } TEST_F(AshBackgroundFilterBlurPerfTest, BackgroundLayerBoundsChange) { blur_layer_->SetBackgroundBlur(10.f); WithBoundsChange(background_layer_.get(), 100, "background_layer_bounds_change"); } TEST_F(AshBackgroundFilterBlurPerfTest, BlurLayerBoundsChange) { blur_layer_->SetBackgroundBlur(10.f); WithBoundsChange(blur_layer_.get(), 100, "blur_layer_bounds_change"); } TEST_F(AshBackgroundFilterBlurPerfTest, NoBlurBackgroundLayerOpacityChange) { WithOpacityChange(background_layer_.get(), 100, "no_blur_background_layer_opacity_change"); } TEST_F(AshBackgroundFilterBlurPerfTest, NoBlurBlurLayerOpacityChange) { WithOpacityChange(blur_layer_.get(), 100, "no_blur_blur_layer_opacity_change"); } TEST_F(AshBackgroundFilterBlurPerfTest, BackgroundLayerOpacityChange) { blur_layer_->SetBackgroundBlur(10.f); WithOpacityChange(background_layer_.get(), 100, "background_layer_opacity_change"); } TEST_F(AshBackgroundFilterBlurPerfTest, BlurLayerOpacityChange) { blur_layer_->SetBackgroundBlur(10.f); WithOpacityChange(blur_layer_.get(), 100, "blur_layer_opacity_change"); } } // namespace } // namespace ash
ric2b/Vivaldi-browser
chromium/ash/perftests/ash_background_filter_blur_perftest.cc
C++
bsd-3-clause
5,648
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Mock ServerConnectionManager class for use in client regression tests. #include "sync/test/engine/mock_connection_manager.h" #include <map> #include "base/location.h" #include "base/strings/stringprintf.h" #include "sync/engine/syncer_proto_util.h" #include "sync/protocol/bookmark_specifics.pb.h" #include "sync/syncable/directory.h" #include "sync/syncable/syncable_write_transaction.h" #include "sync/test/engine/test_id_factory.h" #include "testing/gtest/include/gtest/gtest.h" using std::find; using std::map; using std::string; using sync_pb::ClientToServerMessage; using sync_pb::CommitMessage; using sync_pb::CommitResponse; using sync_pb::GetUpdatesMessage; using sync_pb::SyncEnums; namespace syncer { using syncable::WriteTransaction; static char kValidAuthToken[] = "AuthToken"; static char kCacheGuid[] = "kqyg7097kro6GSUod+GSg=="; MockConnectionManager::MockConnectionManager(syncable::Directory* directory, CancelationSignal* signal) : ServerConnectionManager("unused", 0, false, signal), server_reachable_(true), conflict_all_commits_(false), conflict_n_commits_(0), next_new_id_(10000), store_birthday_("Store BDay!"), store_birthday_sent_(false), client_stuck_(false), countdown_to_postbuffer_fail_(0), directory_(directory), mid_commit_observer_(NULL), throttling_(false), partialThrottling_(false), fail_with_auth_invalid_(false), fail_non_periodic_get_updates_(false), next_position_in_parent_(2), use_legacy_bookmarks_protocol_(false), num_get_updates_requests_(0) { SetNewTimestamp(0); SetAuthToken(kValidAuthToken); } MockConnectionManager::~MockConnectionManager() { EXPECT_TRUE(update_queue_.empty()) << "Unfetched updates."; } void MockConnectionManager::SetCommitTimeRename(string prepend) { commit_time_rename_prepended_string_ = prepend; } void MockConnectionManager::SetMidCommitCallback( const base::Closure& callback) { mid_commit_callback_ = callback; } void MockConnectionManager::SetMidCommitObserver( MockConnectionManager::MidCommitObserver* observer) { mid_commit_observer_ = observer; } bool MockConnectionManager::PostBufferToPath(PostBufferParams* params, const string& path, const string& auth_token, ScopedServerStatusWatcher* watcher) { ClientToServerMessage post; CHECK(post.ParseFromString(params->buffer_in)); CHECK(post.has_protocol_version()); CHECK(post.has_api_key()); CHECK(post.has_bag_of_chips()); requests_.push_back(post); client_stuck_ = post.sync_problem_detected(); sync_pb::ClientToServerResponse response; response.Clear(); if (directory_) { // If the Directory's locked when we do this, it's a problem as in normal // use this function could take a while to return because it accesses the // network. As we can't test this we do the next best thing and hang here // when there's an issue. CHECK(directory_->good()); WriteTransaction wt(FROM_HERE, syncable::UNITTEST, directory_); } if (auth_token.empty()) { params->response.server_status = HttpResponse::SYNC_AUTH_ERROR; return false; } if (auth_token != kValidAuthToken) { // Simulate server-side auth failure. params->response.server_status = HttpResponse::SYNC_AUTH_ERROR; InvalidateAndClearAuthToken(); } if (--countdown_to_postbuffer_fail_ == 0) { // Fail as countdown hits zero. params->response.server_status = HttpResponse::SYNC_SERVER_ERROR; return false; } if (!server_reachable_) { params->response.server_status = HttpResponse::CONNECTION_UNAVAILABLE; return false; } // Default to an ok connection. params->response.server_status = HttpResponse::SERVER_CONNECTION_OK; response.set_error_code(SyncEnums::SUCCESS); const string current_store_birthday = store_birthday(); response.set_store_birthday(current_store_birthday); if (post.has_store_birthday() && post.store_birthday() != current_store_birthday) { response.set_error_code(SyncEnums::NOT_MY_BIRTHDAY); response.set_error_message("Merry Unbirthday!"); response.SerializeToString(&params->buffer_out); store_birthday_sent_ = true; return true; } bool result = true; EXPECT_TRUE(!store_birthday_sent_ || post.has_store_birthday() || post.message_contents() == ClientToServerMessage::AUTHENTICATE); store_birthday_sent_ = true; if (post.message_contents() == ClientToServerMessage::COMMIT) { ProcessCommit(&post, &response); } else if (post.message_contents() == ClientToServerMessage::GET_UPDATES) { ProcessGetUpdates(&post, &response); } else { EXPECT_TRUE(false) << "Unknown/unsupported ClientToServerMessage"; return false; } { base::AutoLock lock(response_code_override_lock_); if (throttling_) { response.set_error_code(SyncEnums::THROTTLED); throttling_ = false; } if (partialThrottling_) { sync_pb::ClientToServerResponse_Error* response_error = response.mutable_error(); response_error->set_error_type(SyncEnums::PARTIAL_FAILURE); for (ModelTypeSet::Iterator it = throttled_type_.First(); it.Good(); it.Inc()) { response_error->add_error_data_type_ids( GetSpecificsFieldNumberFromModelType(it.Get())); } partialThrottling_ = false; } if (fail_with_auth_invalid_) response.set_error_code(SyncEnums::AUTH_INVALID); } response.SerializeToString(&params->buffer_out); if (post.message_contents() == ClientToServerMessage::COMMIT && !mid_commit_callback_.is_null()) { mid_commit_callback_.Run(); mid_commit_callback_.Reset(); } if (mid_commit_observer_) { mid_commit_observer_->Observe(); } return result; } sync_pb::GetUpdatesResponse* MockConnectionManager::GetUpdateResponse() { if (update_queue_.empty()) { NextUpdateBatch(); } return &update_queue_.back(); } void MockConnectionManager::AddDefaultBookmarkData(sync_pb::SyncEntity* entity, bool is_folder) { if (use_legacy_bookmarks_protocol_) { sync_pb::SyncEntity_BookmarkData* data = entity->mutable_bookmarkdata(); data->set_bookmark_folder(is_folder); if (!is_folder) { data->set_bookmark_url("http://google.com"); } } else { entity->set_folder(is_folder); entity->mutable_specifics()->mutable_bookmark(); if (!is_folder) { entity->mutable_specifics()->mutable_bookmark()-> set_url("http://google.com"); } } } sync_pb::SyncEntity* MockConnectionManager::AddUpdateDirectory( int id, int parent_id, string name, int64 version, int64 sync_ts, std::string originator_cache_guid, std::string originator_client_item_id) { return AddUpdateDirectory(TestIdFactory::FromNumber(id), TestIdFactory::FromNumber(parent_id), name, version, sync_ts, originator_cache_guid, originator_client_item_id); } void MockConnectionManager::SetGUClientCommand( sync_pb::ClientCommand* command) { gu_client_command_.reset(command); } void MockConnectionManager::SetCommitClientCommand( sync_pb::ClientCommand* command) { commit_client_command_.reset(command); } void MockConnectionManager::SetTransientErrorId(syncable::Id id) { transient_error_ids_.push_back(id); } sync_pb::SyncEntity* MockConnectionManager::AddUpdateBookmark( int id, int parent_id, string name, int64 version, int64 sync_ts, string originator_client_item_id, string originator_cache_guid) { return AddUpdateBookmark(TestIdFactory::FromNumber(id), TestIdFactory::FromNumber(parent_id), name, version, sync_ts, originator_client_item_id, originator_cache_guid); } sync_pb::SyncEntity* MockConnectionManager::AddUpdateSpecifics( int id, int parent_id, string name, int64 version, int64 sync_ts, bool is_dir, int64 position, const sync_pb::EntitySpecifics& specifics) { sync_pb::SyncEntity* ent = AddUpdateMeta( TestIdFactory::FromNumber(id).GetServerId(), TestIdFactory::FromNumber(parent_id).GetServerId(), name, version, sync_ts); ent->set_position_in_parent(position); ent->mutable_specifics()->CopyFrom(specifics); ent->set_folder(is_dir); return ent; } sync_pb::SyncEntity* MockConnectionManager::AddUpdateSpecifics( int id, int parent_id, string name, int64 version, int64 sync_ts, bool is_dir, int64 position, const sync_pb::EntitySpecifics& specifics, string originator_cache_guid, string originator_client_item_id) { sync_pb::SyncEntity* ent = AddUpdateSpecifics( id, parent_id, name, version, sync_ts, is_dir, position, specifics); ent->set_originator_cache_guid(originator_cache_guid); ent->set_originator_client_item_id(originator_client_item_id); return ent; } sync_pb::SyncEntity* MockConnectionManager::SetNigori( int id, int64 version, int64 sync_ts, const sync_pb::EntitySpecifics& specifics) { sync_pb::SyncEntity* ent = GetUpdateResponse()->add_entries(); ent->set_id_string(TestIdFactory::FromNumber(id).GetServerId()); ent->set_parent_id_string(TestIdFactory::FromNumber(0).GetServerId()); ent->set_server_defined_unique_tag(ModelTypeToRootTag(NIGORI)); ent->set_name("Nigori"); ent->set_non_unique_name("Nigori"); ent->set_version(version); ent->set_sync_timestamp(sync_ts); ent->set_mtime(sync_ts); ent->set_ctime(1); ent->set_position_in_parent(0); ent->set_folder(false); ent->mutable_specifics()->CopyFrom(specifics); return ent; } sync_pb::SyncEntity* MockConnectionManager::AddUpdatePref(string id, string parent_id, string client_tag, int64 version, int64 sync_ts) { sync_pb::SyncEntity* ent = AddUpdateMeta(id, parent_id, " ", version, sync_ts); ent->set_client_defined_unique_tag(client_tag); sync_pb::EntitySpecifics specifics; AddDefaultFieldValue(PREFERENCES, &specifics); ent->mutable_specifics()->CopyFrom(specifics); return ent; } sync_pb::SyncEntity* MockConnectionManager::AddUpdateFull( string id, string parent_id, string name, int64 version, int64 sync_ts, bool is_dir) { sync_pb::SyncEntity* ent = AddUpdateMeta(id, parent_id, name, version, sync_ts); AddDefaultBookmarkData(ent, is_dir); return ent; } sync_pb::SyncEntity* MockConnectionManager::AddUpdateMeta( string id, string parent_id, string name, int64 version, int64 sync_ts) { sync_pb::SyncEntity* ent = GetUpdateResponse()->add_entries(); ent->set_id_string(id); ent->set_parent_id_string(parent_id); ent->set_non_unique_name(name); ent->set_name(name); ent->set_version(version); ent->set_sync_timestamp(sync_ts); ent->set_mtime(sync_ts); ent->set_ctime(1); ent->set_position_in_parent(GeneratePositionInParent()); // This isn't perfect, but it works well enough. This is an update, which // means the ID is a server ID, which means it never changes. By making // kCacheGuid also never change, we guarantee that the same item always has // the same originator_cache_guid and originator_client_item_id. // // Unfortunately, neither this class nor the tests that use it explicitly // track sync entitites, so supporting proper cache guids and client item IDs // would require major refactoring. The ID used here ought to be the "c-" // style ID that was sent up on the commit. ent->set_originator_cache_guid(kCacheGuid); ent->set_originator_client_item_id(id); return ent; } sync_pb::SyncEntity* MockConnectionManager::AddUpdateDirectory( string id, string parent_id, string name, int64 version, int64 sync_ts, std::string originator_cache_guid, std::string originator_client_item_id) { sync_pb::SyncEntity* ret = AddUpdateFull(id, parent_id, name, version, sync_ts, true); ret->set_originator_cache_guid(originator_cache_guid); ret->set_originator_client_item_id(originator_client_item_id); return ret; } sync_pb::SyncEntity* MockConnectionManager::AddUpdateBookmark( string id, string parent_id, string name, int64 version, int64 sync_ts, string originator_cache_guid, string originator_client_item_id) { sync_pb::SyncEntity* ret = AddUpdateFull(id, parent_id, name, version, sync_ts, false); ret->set_originator_cache_guid(originator_cache_guid); ret->set_originator_client_item_id(originator_client_item_id); return ret; } sync_pb::SyncEntity* MockConnectionManager::AddUpdateFromLastCommit() { EXPECT_EQ(1, last_sent_commit().entries_size()); EXPECT_EQ(1, last_commit_response().entryresponse_size()); EXPECT_EQ(CommitResponse::SUCCESS, last_commit_response().entryresponse(0).response_type()); if (last_sent_commit().entries(0).deleted()) { ModelType type = GetModelType(last_sent_commit().entries(0)); AddUpdateTombstone(syncable::Id::CreateFromServerId( last_sent_commit().entries(0).id_string()), type); } else { sync_pb::SyncEntity* ent = GetUpdateResponse()->add_entries(); ent->CopyFrom(last_sent_commit().entries(0)); ent->clear_insert_after_item_id(); ent->clear_old_parent_id(); ent->set_position_in_parent( last_commit_response().entryresponse(0).position_in_parent()); ent->set_version( last_commit_response().entryresponse(0).version()); ent->set_id_string( last_commit_response().entryresponse(0).id_string()); // This is the same hack as in AddUpdateMeta. See the comment in that // function for more information. ent->set_originator_cache_guid(kCacheGuid); ent->set_originator_client_item_id( last_commit_response().entryresponse(0).id_string()); if (last_sent_commit().entries(0).has_unique_position()) { ent->mutable_unique_position()->CopyFrom( last_sent_commit().entries(0).unique_position()); } // Tests don't currently care about the following: // parent_id_string, name, non_unique_name. } return GetMutableLastUpdate(); } void MockConnectionManager::AddUpdateTombstone( const syncable::Id& id, ModelType type) { // Tombstones have only the ID set and dummy values for the required fields. sync_pb::SyncEntity* ent = GetUpdateResponse()->add_entries(); ent->set_id_string(id.GetServerId()); ent->set_version(0); ent->set_name(""); ent->set_deleted(true); // Make sure we can still extract the ModelType from this tombstone. AddDefaultFieldValue(type, ent->mutable_specifics()); } void MockConnectionManager::SetLastUpdateDeleted() { // Tombstones have only the ID set. Wipe anything else. string id_string = GetMutableLastUpdate()->id_string(); ModelType type = GetModelType(*GetMutableLastUpdate()); GetUpdateResponse()->mutable_entries()->RemoveLast(); AddUpdateTombstone(syncable::Id::CreateFromServerId(id_string), type); } void MockConnectionManager::SetLastUpdateOriginatorFields( const string& client_id, const string& entry_id) { GetMutableLastUpdate()->set_originator_cache_guid(client_id); GetMutableLastUpdate()->set_originator_client_item_id(entry_id); } void MockConnectionManager::SetLastUpdateServerTag(const string& tag) { GetMutableLastUpdate()->set_server_defined_unique_tag(tag); } void MockConnectionManager::SetLastUpdateClientTag(const string& tag) { GetMutableLastUpdate()->set_client_defined_unique_tag(tag); } void MockConnectionManager::SetLastUpdatePosition(int64 server_position) { GetMutableLastUpdate()->set_position_in_parent(server_position); } void MockConnectionManager::SetNewTimestamp(int ts) { next_token_ = base::StringPrintf("mock connection ts = %d", ts); ApplyToken(); } void MockConnectionManager::ApplyToken() { if (!update_queue_.empty()) { GetUpdateResponse()->clear_new_progress_marker(); sync_pb::DataTypeProgressMarker* new_marker = GetUpdateResponse()->add_new_progress_marker(); new_marker->set_data_type_id(-1); // Invalid -- clients shouldn't see. new_marker->set_token(next_token_); } } void MockConnectionManager::SetChangesRemaining(int64 timestamp) { GetUpdateResponse()->set_changes_remaining(timestamp); } void MockConnectionManager::ProcessGetUpdates( sync_pb::ClientToServerMessage* csm, sync_pb::ClientToServerResponse* response) { CHECK(csm->has_get_updates()); ASSERT_EQ(csm->message_contents(), ClientToServerMessage::GET_UPDATES); const GetUpdatesMessage& gu = csm->get_updates(); num_get_updates_requests_++; EXPECT_FALSE(gu.has_from_timestamp()); EXPECT_FALSE(gu.has_requested_types()); if (fail_non_periodic_get_updates_) { EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::PERIODIC, gu.caller_info().source()); } // Verify that the items we're about to send back to the client are of // the types requested by the client. If this fails, it probably indicates // a test bug. EXPECT_TRUE(gu.fetch_folders()); EXPECT_FALSE(gu.has_requested_types()); if (update_queue_.empty()) { GetUpdateResponse(); } sync_pb::GetUpdatesResponse* updates = &update_queue_.front(); for (int i = 0; i < updates->entries_size(); ++i) { if (!updates->entries(i).deleted()) { ModelType entry_type = GetModelType(updates->entries(i)); EXPECT_TRUE( IsModelTypePresentInSpecifics(gu.from_progress_marker(), entry_type)) << "Syncer did not request updates being provided by the test."; } } response->mutable_get_updates()->CopyFrom(*updates); // Set appropriate progress markers, overriding the value squirreled // away by ApplyToken(). std::string token = response->get_updates().new_progress_marker(0).token(); response->mutable_get_updates()->clear_new_progress_marker(); for (int i = 0; i < gu.from_progress_marker_size(); ++i) { sync_pb::DataTypeProgressMarker* new_marker = response->mutable_get_updates()->add_new_progress_marker(); new_marker->set_data_type_id(gu.from_progress_marker(i).data_type_id()); new_marker->set_token(token); } // Fill the keystore key if requested. if (gu.need_encryption_key()) response->mutable_get_updates()->add_encryption_keys(keystore_key_); update_queue_.pop_front(); if (gu_client_command_) { response->mutable_client_command()->CopyFrom(*gu_client_command_.get()); } } void MockConnectionManager::SetKeystoreKey(const std::string& key) { // Note: this is not a thread-safe set, ok for now. NOT ok if tests // run the syncer on the background thread while this method is called. keystore_key_ = key; } bool MockConnectionManager::ShouldConflictThisCommit() { bool conflict = false; if (conflict_all_commits_) { conflict = true; } else if (conflict_n_commits_ > 0) { conflict = true; --conflict_n_commits_; } return conflict; } bool MockConnectionManager::ShouldTransientErrorThisId(syncable::Id id) { return find(transient_error_ids_.begin(), transient_error_ids_.end(), id) != transient_error_ids_.end(); } void MockConnectionManager::ProcessCommit( sync_pb::ClientToServerMessage* csm, sync_pb::ClientToServerResponse* response_buffer) { CHECK(csm->has_commit()); ASSERT_EQ(csm->message_contents(), ClientToServerMessage::COMMIT); map <string, string> changed_ids; const CommitMessage& commit_message = csm->commit(); CommitResponse* commit_response = response_buffer->mutable_commit(); commit_messages_.push_back(new CommitMessage); commit_messages_.back()->CopyFrom(commit_message); map<string, sync_pb::CommitResponse_EntryResponse*> response_map; for (int i = 0; i < commit_message.entries_size() ; i++) { const sync_pb::SyncEntity& entry = commit_message.entries(i); CHECK(entry.has_id_string()); string id_string = entry.id_string(); ASSERT_LT(entry.name().length(), 256ul) << " name probably too long. True " "server name checking not implemented"; syncable::Id id; if (entry.version() == 0) { // Relies on our new item string id format. (string representation of a // negative number). id = syncable::Id::CreateFromClientString(id_string); } else { id = syncable::Id::CreateFromServerId(id_string); } committed_ids_.push_back(id); if (response_map.end() == response_map.find(id_string)) response_map[id_string] = commit_response->add_entryresponse(); sync_pb::CommitResponse_EntryResponse* er = response_map[id_string]; if (ShouldConflictThisCommit()) { er->set_response_type(CommitResponse::CONFLICT); continue; } if (ShouldTransientErrorThisId(id)) { er->set_response_type(CommitResponse::TRANSIENT_ERROR); continue; } er->set_response_type(CommitResponse::SUCCESS); er->set_version(entry.version() + 1); if (!commit_time_rename_prepended_string_.empty()) { // Commit time rename sent down from the server. er->set_name(commit_time_rename_prepended_string_ + entry.name()); } string parent_id_string = entry.parent_id_string(); // Remap id's we've already assigned. if (changed_ids.end() != changed_ids.find(parent_id_string)) { parent_id_string = changed_ids[parent_id_string]; er->set_parent_id_string(parent_id_string); } if (entry.has_version() && 0 != entry.version()) { er->set_id_string(id_string); // Allows verification. } else { string new_id = base::StringPrintf("mock_server:%d", next_new_id_++); changed_ids[id_string] = new_id; er->set_id_string(new_id); } } commit_responses_.push_back(new CommitResponse(*commit_response)); if (commit_client_command_) { response_buffer->mutable_client_command()->CopyFrom( *commit_client_command_.get()); } } sync_pb::SyncEntity* MockConnectionManager::AddUpdateDirectory( syncable::Id id, syncable::Id parent_id, string name, int64 version, int64 sync_ts, string originator_cache_guid, string originator_client_item_id) { return AddUpdateDirectory(id.GetServerId(), parent_id.GetServerId(), name, version, sync_ts, originator_cache_guid, originator_client_item_id); } sync_pb::SyncEntity* MockConnectionManager::AddUpdateBookmark( syncable::Id id, syncable::Id parent_id, string name, int64 version, int64 sync_ts, string originator_cache_guid, string originator_client_item_id) { return AddUpdateBookmark(id.GetServerId(), parent_id.GetServerId(), name, version, sync_ts, originator_cache_guid, originator_client_item_id); } sync_pb::SyncEntity* MockConnectionManager::GetMutableLastUpdate() { sync_pb::GetUpdatesResponse* updates = GetUpdateResponse(); EXPECT_GT(updates->entries_size(), 0); return updates->mutable_entries()->Mutable(updates->entries_size() - 1); } void MockConnectionManager::NextUpdateBatch() { update_queue_.push_back(sync_pb::GetUpdatesResponse::default_instance()); SetChangesRemaining(0); ApplyToken(); } const CommitMessage& MockConnectionManager::last_sent_commit() const { EXPECT_TRUE(!commit_messages_.empty()); return *commit_messages_.back(); } const CommitResponse& MockConnectionManager::last_commit_response() const { EXPECT_TRUE(!commit_responses_.empty()); return *commit_responses_.back(); } const sync_pb::ClientToServerMessage& MockConnectionManager::last_request() const { EXPECT_TRUE(!requests_.empty()); return requests_.back(); } const std::vector<sync_pb::ClientToServerMessage>& MockConnectionManager::requests() const { return requests_; } bool MockConnectionManager::IsModelTypePresentInSpecifics( const google::protobuf::RepeatedPtrField< sync_pb::DataTypeProgressMarker>& filter, ModelType value) { int data_type_id = GetSpecificsFieldNumberFromModelType(value); for (int i = 0; i < filter.size(); ++i) { if (filter.Get(i).data_type_id() == data_type_id) { return true; } } return false; } sync_pb::DataTypeProgressMarker const* MockConnectionManager::GetProgressMarkerForType( const google::protobuf::RepeatedPtrField< sync_pb::DataTypeProgressMarker>& filter, ModelType value) { int data_type_id = GetSpecificsFieldNumberFromModelType(value); for (int i = 0; i < filter.size(); ++i) { if (filter.Get(i).data_type_id() == data_type_id) { return &(filter.Get(i)); } } return NULL; } void MockConnectionManager::SetServerReachable() { server_reachable_ = true; } void MockConnectionManager::SetServerNotReachable() { server_reachable_ = false; } void MockConnectionManager::UpdateConnectionStatus() { if (!server_reachable_) { server_status_ = HttpResponse::CONNECTION_UNAVAILABLE; } else { server_status_ = HttpResponse::SERVER_CONNECTION_OK; } } void MockConnectionManager::SetServerStatus( HttpResponse::ServerConnectionCode server_status) { server_status_ = server_status; } } // namespace syncer
guorendong/iridium-browser-ubuntu
sync/test/engine/mock_connection_manager.cc
C++
bsd-3-clause
25,782
/*jslint sloppy: true, nomen: true */ /*global exports:true */ /* This file is part of the PhantomJS project from Ofi Labs. Copyright (C) 2013 Joseph Rollinson, jtrollinson@gmail.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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. */ /* Takes in a QtCookieJar and decorates it with useful functions. */ function decorateCookieJar(jar) { /* Allows one to add a cookie to the cookie jar from inside JavaScript */ jar.addCookie = function(cookie) { jar.addCookieFromMap(cookie); }; /* Getting and Setting jar.cookies gets and sets all the cookies in the * cookie jar. */ jar.__defineGetter__('cookies', function() { return this.cookiesToMap(); }); jar.__defineSetter__('cookies', function(cookies) { this.addCookiesFromMap(cookies); }); return jar; } /* Creates and decorates a new cookie jar. * path is the file path where Phantomjs will store the cookie jar persistently. * path is not mandatory. */ exports.create = function (path) { if (arguments.length < 1) { path = ""; } return decorateCookieJar(phantom.createCookieJar(path)); }; /* Exports the decorateCookieJar function */ exports.decorate = decorateCookieJar;
tianzhihen/phantomjs
src/modules/cookiejar.js
JavaScript
bsd-3-clause
2,651
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/passwords/bubble_controllers/move_to_account_store_bubble_controller.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/sync/sync_service_factory.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" #include "chrome/grit/generated_resources.h" #include "components/favicon/core/favicon_util.h" #include "components/password_manager/core/browser/password_feature_manager.h" #include "components/password_manager/core/browser/password_manager_features_util.h" #include "components/password_manager/core/common/password_manager_ui.h" #include "components/signin/public/base/consent_level.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" namespace metrics_util = password_manager::metrics_util; MoveToAccountStoreBubbleController::MoveToAccountStoreBubbleController( base::WeakPtr<PasswordsModelDelegate> delegate) : PasswordBubbleControllerBase( std::move(delegate), password_manager::metrics_util::AUTOMATIC_MOVE_TO_ACCOUNT_STORE) {} MoveToAccountStoreBubbleController::~MoveToAccountStoreBubbleController() { // Make sure the interactions are reported even if Views didn't notify the // controller about the bubble being closed. if (!interaction_reported_) OnBubbleClosing(); } void MoveToAccountStoreBubbleController::RequestFavicon( base::OnceCallback<void(const gfx::Image&)> favicon_ready_callback) { favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(GetProfile(), ServiceAccessType::EXPLICIT_ACCESS); favicon::GetFaviconImageForPageURL( favicon_service, delegate_->GetPendingPassword().url, favicon_base::IconType::kFavicon, base::BindOnce(&MoveToAccountStoreBubbleController::OnFaviconReady, base::Unretained(this), std::move(favicon_ready_callback)), &favicon_tracker_); } void MoveToAccountStoreBubbleController::OnFaviconReady( base::OnceCallback<void(const gfx::Image&)> favicon_ready_callback, const favicon_base::FaviconImageResult& result) { std::move(favicon_ready_callback).Run(result.image); } std::u16string MoveToAccountStoreBubbleController::GetTitle() const { return l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_MOVE_TITLE); } void MoveToAccountStoreBubbleController::AcceptMove() { dismissal_reason_ = metrics_util::CLICKED_ACCEPT; if (delegate_->GetPasswordFeatureManager()->IsOptedInForAccountStorage()) { // User has already opted in to the account store. Move without reauth. return delegate_->MovePasswordToAccountStore(); } // Otherwise, we should invoke the reauth flow before saving. return delegate_->AuthenticateUserForAccountStoreOptInAndMovePassword(); } void MoveToAccountStoreBubbleController::RejectMove() { dismissal_reason_ = metrics_util::CLICKED_NEVER; return delegate_->BlockMovingPasswordToAccountStore(); } gfx::Image MoveToAccountStoreBubbleController::GetProfileIcon(int size) { if (!GetProfile()) return gfx::Image(); signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile()); if (!identity_manager) return gfx::Image(); AccountInfo primary_account_info = identity_manager->FindExtendedAccountInfo( identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin)); DCHECK(!primary_account_info.IsEmpty()); gfx::Image account_icon = primary_account_info.account_image; if (account_icon.IsEmpty()) { account_icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed( profiles::GetPlaceholderAvatarIconResourceID()); } return profiles::GetSizedAvatarIcon(account_icon, /*is_rectangle=*/true, /*width=*/size, /*height=*/size, profiles::SHAPE_CIRCLE); } void MoveToAccountStoreBubbleController::ReportInteractions() { Profile* profile = GetProfile(); if (!profile) return; metrics_util::LogMoveUIDismissalReason( dismissal_reason_, password_manager::features_util::ComputePasswordAccountStorageUserState( profile->GetPrefs(), SyncServiceFactory::GetForProfile(profile))); // TODO(crbug.com/1063852): Consider recording UKM here, via: // metrics_recorder_->RecordUIDismissalReason(dismissal_reason_) }
ric2b/Vivaldi-browser
chromium/chrome/browser/ui/passwords/bubble_controllers/move_to_account_store_bubble_controller.cc
C++
bsd-3-clause
4,892
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import base64 import hashlib import os import string import win32api import win32file import win32com.client from win32com.shell import shell, shellcon import win32security def _GetFileVersion(file_path): """Returns the file version of the given file.""" return win32com.client.Dispatch( 'Scripting.FileSystemObject').GetFileVersion(file_path) def _GetFileBitness(file_path): """Returns the bitness of the given file.""" if win32file.GetBinaryType(file_path) == win32file.SCS_32BIT_BINARY: return '32' return '64' def _GetProductName(file_path): """Returns the product name of the given file. Args: file_path: The absolute or relative path to the file. Returns: A string representing the product name of the file, or None if the product name was not found. """ language_and_codepage_pairs = win32api.GetFileVersionInfo( file_path, '\\VarFileInfo\\Translation') if not language_and_codepage_pairs: return None product_name_entry = ('\\StringFileInfo\\%04x%04x\\ProductName' % language_and_codepage_pairs[0]) return win32api.GetFileVersionInfo(file_path, product_name_entry) def _GetUserSpecificRegistrySuffix(): """Returns '.' + the unpadded Base32 encoding of the MD5 of the user's SID. The result must match the output from the method UserSpecificRegistrySuffix::GetSuffix() in chrome/installer/util/shell_util.cc. It will always be 27 characters long. """ token_handle = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32security.TOKEN_QUERY) user_sid, _ = win32security.GetTokenInformation(token_handle, win32security.TokenUser) user_sid_string = win32security.ConvertSidToStringSid(user_sid) md5_digest = hashlib.md5(user_sid_string).digest() return '.' + base64.b32encode(md5_digest).rstrip('=') class VariableExpander: """Expands variables in strings.""" def __init__(self, mini_installer_path, previous_version_mini_installer_path, chromedriver_path, quiet, output_dir): """Constructor. The constructor initializes a variable dictionary that maps variables to their values. These are the only acceptable variables: * $BRAND: the browser brand (e.g., "Google Chrome" or "Chromium"). * $CHROME_DIR: the directory of Chrome (or Chromium) from the base installation directory. * $CHROME_HTML_PROG_ID: 'ChromeHTML' (or 'ChromiumHTM'). * $CHROME_LONG_NAME: 'Google Chrome' (or 'Chromium'). * $CHROME_LONG_NAME_BETA: 'Google Chrome Beta' if $BRAND is 'Google * Chrome'. * $CHROME_LONG_NAME_DEV: 'Google Chrome Dev' if $BRAND is 'Google * Chrome'. * $CHROME_LONG_NAME_SXS: 'Google Chrome SxS' if $BRAND is 'Google * Chrome'. * $CHROME_SHORT_NAME: 'Chrome' (or 'Chromium'). * $CHROME_SHORT_NAME_BETA: 'ChromeBeta' if $BRAND is 'Google Chrome'. * $CHROME_SHORT_NAME_DEV: 'ChromeDev' if $BRAND is 'Google Chrome'. * $CHROME_SHORT_NAME_SXS: 'ChromeCanary' if $BRAND is 'Google Chrome'. * $CHROME_UPDATE_REGISTRY_SUBKEY: the registry key, excluding the root key, of Chrome for Google Update. * $CHROME_UPDATE_REGISTRY_SUBKEY_DEV: the registry key, excluding the root key, of Chrome Dev for Google Update. * $CHROME_UPDATE_REGISTRY_SUBKEY_BETA: the registry key, excluding the root key, of Chrome Beta for Google Update. * $CHROME_UPDATE_REGISTRY_SUBKEY_SXS: the registry key, excluding the root key, of Chrome SxS for Google Update. * $CHROMEDRIVER_PATH: Path to chromedriver. * $QUIET: Supress output. * $OUTPUT_DIR: "--output-dir=DIR" or an empty string. * $LAUNCHER_UPDATE_REGISTRY_SUBKEY: the registry key, excluding the root key, of the app launcher for Google Update if $BRAND is 'Google * Chrome'. * $LOCAL_APPDATA: the unquoted path to the Local Application Data folder. * $LOG_FILE: "--log-file=FILE" or an empty string. * $MINI_INSTALLER: the unquoted path to the mini_installer. * $MINI_INSTALLER_BITNESS: the bitness of the mini_installer. * $MINI_INSTALLER_FILE_VERSION: the file version of $MINI_INSTALLER. * $PREVIOUS_VERSION_MINI_INSTALLER: the unquoted path to a mini_installer whose version is lower than $MINI_INSTALLER. * $PREVIOUS_VERSION_MINI_INSTALLER_FILE_VERSION: the file version of $PREVIOUS_VERSION_MINI_INSTALLER. * $PROGRAM_FILES: the unquoted path to the Program Files folder. * $USER_SPECIFIC_REGISTRY_SUFFIX: the output from the function _GetUserSpecificRegistrySuffix(). * $VERSION_[XP/SERVER_2003/VISTA/WIN7/WIN8/WIN8_1/WIN10]: a 2-tuple representing the version of the corresponding OS. * $WINDOWS_VERSION: a 2-tuple representing the current Windows version. * $CHROME_TOAST_ACTIVATOR_CLSID: NotificationActivator's CLSID for Chrome. * $CHROME_TOAST_ACTIVATOR_CLSID_BETA: NotificationActivator's CLSID for Chrome Beta. * $CHROME_TOAST_ACTIVATOR_CLSID_DEV: NotificationActivator's CLSID for Chrome Dev. * $CHROME_TOAST_ACTIVATOR_CLSID_SXS: NotificationActivator's CLSID for Chrome SxS. * $CHROME_ELEVATOR_CLSID: Elevator Service CLSID for Chrome. * $CHROME_ELEVATOR_CLSID_BETA: Elevator Service CLSID for Chrome Beta. * $CHROME_ELEVATOR_CLSID_DEV: Elevator Service CLSID for Chrome Dev. * $CHROME_ELEVATOR_CLSID_SXS: Elevator Service CLSID for Chrome SxS. * $CHROME_ELEVATOR_IID: IElevator IID for Chrome. * $CHROME_ELEVATOR_IID_BETA: IElevator IID for Chrome Beta. * $CHROME_ELEVATOR_IID_DEV: IElevator IID for Chrome Dev. * $CHROME_ELEVATOR_IID_SXS: IElevator IID for Chrome SxS. * $CHROME_ELEVATION_SERVICE_NAME: Elevation Service Name for Chrome. * $CHROME_ELEVATION_SERVICE_NAME_BETA: Elevation Service Name for Chrome Beta. * $CHROME_ELEVATION_SERVICE_NAME_DEV: Elevation Service Name for Chrome Dev. * $CHROME_ELEVATION_SERVICE_NAME_SXS: Elevation Service Name for Chrome SxS. * $CHROME_ELEVATION_SERVICE_DISPLAY_NAME: Elevation Service Display Name for Chrome. * $CHROME_ELEVATION_SERVICE_DISPLAY_NAME_BETA: Elevation Service Display Name for Chrome Beta. * $CHROME_ELEVATION_SERVICE_DISPLAY_NAME_DEV: Elevation Service Display Name for Chrome Dev. * $CHROME_ELEVATION_SERVICE_DISPLAY_NAME_SXS: Elevation Service Display Name for Chrome SxS. * $LAST_INSTALLER_BREAKING_VERSION: The last installer version that had breaking changes. Args: mini_installer_path: The path to a mini_installer. previous_version_mini_installer_path: The path to a mini_installer whose version is lower than |mini_installer_path|. """ mini_installer_abspath = os.path.abspath(mini_installer_path) previous_version_mini_installer_abspath = os.path.abspath( previous_version_mini_installer_path) windows_major_ver, windows_minor_ver, _, _, _ = win32api.GetVersionEx() self._variable_mapping = { 'CHROMEDRIVER_PATH': chromedriver_path, 'QUIET': '-q' if quiet else '', 'OUTPUT_DIR': '"--output-dir=%s"' % output_dir if output_dir else '', 'LAST_INSTALLER_BREAKING_VERSION': '85.0.4169.0', 'LOCAL_APPDATA': shell.SHGetFolderPath(0, shellcon.CSIDL_LOCAL_APPDATA, None, 0), 'LOG_FILE': '', 'MINI_INSTALLER': mini_installer_abspath, 'MINI_INSTALLER_FILE_VERSION': _GetFileVersion(mini_installer_abspath), 'MINI_INSTALLER_BITNESS': _GetFileBitness(mini_installer_abspath), 'PREVIOUS_VERSION_MINI_INSTALLER': previous_version_mini_installer_abspath, 'PREVIOUS_VERSION_MINI_INSTALLER_FILE_VERSION': _GetFileVersion(previous_version_mini_installer_abspath), 'PROGRAM_FILES': shell.SHGetFolderPath( 0, shellcon.CSIDL_PROGRAM_FILES if _GetFileBitness(mini_installer_abspath) == '64' else shellcon.CSIDL_PROGRAM_FILESX86, None, 0), 'USER_SPECIFIC_REGISTRY_SUFFIX': _GetUserSpecificRegistrySuffix(), 'VERSION_SERVER_2003': '(5, 2)', 'VERSION_VISTA': '(6, 0)', 'VERSION_WIN10': '(10, 0)', 'VERSION_WIN7': '(6, 1)', 'VERSION_WIN8': '(6, 2)', 'VERSION_WIN8_1': '(6, 3)', 'VERSION_XP': '(5, 1)', 'WINDOWS_VERSION': '(%s, %s)' % (windows_major_ver, windows_minor_ver) } mini_installer_product_name = _GetProductName(mini_installer_abspath) if mini_installer_product_name == 'Google Chrome Installer': self._variable_mapping.update({ 'BRAND': 'Google Chrome', 'BINARIES_UPDATE_REGISTRY_SUBKEY': ('Software\\Google\\Update\\Clients\\' '{4DC8B4CA-1BDA-483e-B5FA-D3C12E15B62D}'), 'CHROME_DIR': 'Google\\Chrome', 'CHROME_HTML_PROG_ID': 'ChromeHTML', 'CHROME_HTML_PROG_ID_BETA': 'ChromeBHTML', 'CHROME_HTML_PROG_ID_DEV': 'ChromeDHTML', 'CHROME_HTML_PROG_ID_SXS': 'ChromeSSHTM', 'CHROME_LONG_NAME': 'Google Chrome', 'CHROME_SHORT_NAME': 'Chrome', 'CHROME_UPDATE_REGISTRY_SUBKEY': ('Software\\Google\\Update\\Clients\\' '{8A69D345-D564-463c-AFF1-A69D9E530F96}'), 'CHROME_CLIENT_STATE_KEY_BETA': ('Software\\Google\\Update\\ClientState\\' '{8237E44A-0054-442C-B6B6-EA0509993955}'), 'CHROME_CLIENT_STATE_KEY_DEV': ('Software\\Google\\Update\\ClientState\\' '{401C381F-E0DE-4B85-8BD8-3F3F14FBDA57}'), 'CHROME_CLIENT_STATE_KEY_SXS': ('Software\\Google\\Update\\ClientState\\' '{4ea16ac7-fd5a-47c3-875b-dbf4a2008c20}'), 'CHROME_CLIENT_STATE_KEY': ('Software\\Google\\Update\\ClientState\\' '{8A69D345-D564-463c-AFF1-A69D9E530F96}'), 'CHROME_TOAST_ACTIVATOR_CLSID': ('{A2C6CB58-C076-425C-ACB7-6D19D64428CD}'), 'CHROME_DIR_BETA': 'Google\\Chrome Beta', 'CHROME_DIR_DEV': 'Google\\Chrome Dev', 'CHROME_DIR_SXS': 'Google\\Chrome SxS', 'CHROME_LONG_NAME_BETA': 'Google Chrome Beta', 'CHROME_LONG_NAME_DEV': 'Google Chrome Dev', 'CHROME_LONG_NAME_SXS': 'Google Chrome SxS', 'CHROME_SHORT_NAME_BETA': 'ChromeBeta', 'CHROME_SHORT_NAME_DEV': 'ChromeDev', 'CHROME_SHORT_NAME_SXS': 'ChromeCanary', 'CHROME_UPDATE_REGISTRY_SUBKEY_BETA': ('Software\\Google\\Update\\Clients\\' '{8237E44A-0054-442C-B6B6-EA0509993955}'), 'CHROME_UPDATE_REGISTRY_SUBKEY_DEV': ('Software\\Google\\Update\\Clients\\' '{401C381F-E0DE-4B85-8BD8-3F3F14FBDA57}'), 'CHROME_UPDATE_REGISTRY_SUBKEY_SXS': ('Software\\Google\\Update\\Clients\\' '{4ea16ac7-fd5a-47c3-875b-dbf4a2008c20}'), 'LAUNCHER_UPDATE_REGISTRY_SUBKEY': ('Software\\Google\\Update\\Clients\\' '{FDA71E6F-AC4C-4a00-8B70-9958A68906BF}'), 'CHROME_TOAST_ACTIVATOR_CLSID_BETA': ('{B89B137F-96AA-4AE2-98C4-6373EAA1EA4D}'), 'CHROME_TOAST_ACTIVATOR_CLSID_DEV': ('{F01C03EB-D431-4C83-8D7A-902771E732FA}'), 'CHROME_TOAST_ACTIVATOR_CLSID_SXS': ('{FA372A6E-149F-4E95-832D-8F698D40AD7F}'), 'CHROME_ELEVATOR_CLSID': ('{708860E0-F641-4611-8895-7D867DD3675B}'), 'CHROME_ELEVATOR_CLSID_BETA': ('{DD2646BA-3707-4BF8-B9A7-038691A68FC2}'), 'CHROME_ELEVATOR_CLSID_DEV': ('{DA7FDCA5-2CAA-4637-AA17-0740584DE7DA}'), 'CHROME_ELEVATOR_CLSID_SXS': ('{704C2872-2049-435E-A469-0A534313C42B}'), 'CHROME_ELEVATOR_IID': ('{463ABECF-410D-407F-8AF5-0DF35A005CC8}'), 'CHROME_ELEVATOR_IID_BETA': ('{A2721D66-376E-4D2F-9F0F-9070E9A42B5F}'), 'CHROME_ELEVATOR_IID_DEV': ('{BB2AA26B-343A-4072-8B6F-80557B8CE571}'), 'CHROME_ELEVATOR_IID_SXS': ('{4F7CE041-28E9-484F-9DD0-61A8CACEFEE4}'), 'CHROME_ELEVATION_SERVICE_NAME': ('GoogleChromeElevationService'), 'CHROME_ELEVATION_SERVICE_NAME_BETA': ('GoogleChromeBetaElevationService'), 'CHROME_ELEVATION_SERVICE_NAME_DEV': ('GoogleChromeDevElevationService'), 'CHROME_ELEVATION_SERVICE_NAME_SXS': ('GoogleChromeCanaryElevationService'), 'CHROME_ELEVATION_SERVICE_DISPLAY_NAME': ('Google Chrome Elevation Service ' + '(GoogleChromeElevationService)'), 'CHROME_ELEVATION_SERVICE_DISPLAY_NAME_BETA': ('Google Chrome Beta Elevation Service' ' (GoogleChromeBetaElevationService)'), 'CHROME_ELEVATION_SERVICE_DISPLAY_NAME_DEV': ('Google Chrome Dev Elevation Service' ' (GoogleChromeDevElevationService)'), 'CHROME_ELEVATION_SERVICE_DISPLAY_NAME_SXS': ('Google Chrome Canary Elevation Service'), }) elif mini_installer_product_name == 'Chromium Installer': self._variable_mapping.update({ 'BRAND': 'Chromium', 'BINARIES_UPDATE_REGISTRY_SUBKEY': 'Software\\Chromium Binaries', 'CHROME_DIR': 'Chromium', 'CHROME_HTML_PROG_ID': 'ChromiumHTM', 'CHROME_LONG_NAME': 'Chromium', 'CHROME_SHORT_NAME': 'Chromium', 'CHROME_UPDATE_REGISTRY_SUBKEY': 'Software\\Chromium', 'CHROME_CLIENT_STATE_KEY': 'Software\\Chromium', 'CHROME_TOAST_ACTIVATOR_CLSID': ('{635EFA6F-08D6-4EC9-BD14-8A0FDE975159}'), 'CHROME_ELEVATOR_CLSID': ('{D133B120-6DB4-4D6B-8BFE-83BF8CA1B1B0}'), 'CHROME_ELEVATOR_IID': ('{B88C45B9-8825-4629-B83E-77CC67D9CEED}'), 'CHROME_ELEVATION_SERVICE_NAME': 'ChromiumElevationService', 'CHROME_ELEVATION_SERVICE_DISPLAY_NAME': ('Chromium Elevation Service (ChromiumElevationService)'), }) else: raise KeyError("Unknown mini_installer product name '%s'" % mini_installer_product_name) def SetLogFile(self, log_file): """Updates the value for the LOG_FILE variable""" self._variable_mapping['LOG_FILE'] = ('"--log-file=%s"' % log_file if log_file else '') def Expand(self, a_string): """Expands variables in the given string. This method resolves only variables defined in the constructor. It does not resolve environment variables. Any dollar signs that are not part of variables must be escaped with $$, otherwise a KeyError or a ValueError will be raised. Args: a_string: A string. Returns: A new string created by replacing variables with their values. """ return string.Template(a_string).substitute(self._variable_mapping)
ric2b/Vivaldi-browser
chromium/chrome/test/mini_installer/variable_expander.py
Python
bsd-3-clause
17,079
<?php namespace Drupal\Core\Render\Element; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Render\Element; /** * Provides an action button form element. * * When the button is pressed, the form will be submitted to Drupal, where it is * validated and rebuilt. The submit handler is not invoked. * * Properties: * - #limit_validation_errors: An array of form element keys that will block * form submission when validation for these elements or any child elements * fails. Specify an empty array to suppress all form validation errors. * - #value: The text to be shown on the button. * * * Usage Example: * @code * $form['actions']['preview'] = array( * '#type' => 'button', * '#value' => $this->t('Preview'), * ); * @endcode * * @see \Drupal\Core\Render\Element\Submit * * @FormElement("button") */ class Button extends FormElement { /** * {@inheritdoc} */ public function getInfo() { $class = get_class($this); return array( '#input' => TRUE, '#name' => 'op', '#is_button' => TRUE, '#executes_submit_callback' => FALSE, '#limit_validation_errors' => FALSE, '#process' => array( array($class, 'processButton'), array($class, 'processAjaxForm'), ), '#pre_render' => array( array($class, 'preRenderButton'), ), '#theme_wrappers' => array('input__submit'), ); } /** * Processes a form button element. */ public static function processButton(&$element, FormStateInterface $form_state, &$complete_form) { // If this is a button intentionally allowing incomplete form submission // (e.g., a "Previous" or "Add another item" button), then also skip // client-side validation. if (isset($element['#limit_validation_errors']) && $element['#limit_validation_errors'] !== FALSE) { $element['#attributes']['formnovalidate'] = 'formnovalidate'; } return $element; } /** * Prepares a #type 'button' render element for input.html.twig. * * @param array $element * An associative array containing the properties of the element. * Properties used: #attributes, #button_type, #name, #value. The * #button_type property accepts any value, though core themes have CSS that * styles the following button_types appropriately: 'primary', 'danger'. * * @return array * The $element with prepared variables ready for input.html.twig. */ public static function preRenderButton($element) { $element['#attributes']['type'] = 'submit'; Element::setAttributes($element, array('id', 'name', 'value')); $element['#attributes']['class'][] = 'button'; if (!empty($element['#button_type'])) { $element['#attributes']['class'][] = 'button--' . $element['#button_type']; } $element['#attributes']['class'][] = 'js-form-submit'; $element['#attributes']['class'][] = 'form-submit'; if (!empty($element['#attributes']['disabled'])) { $element['#attributes']['class'][] = 'is-disabled'; } return $element; } }
windtrader/drupalvm-d8
web/core/lib/Drupal/Core/Render/Element/Button.php
PHP
gpl-2.0
3,071
import { Directive, EventEmitter } from '@angular/core'; import { KmlLayerManager } from './../services/managers/kml-layer-manager'; var layerId = 0; export var SebmGoogleMapKmlLayer = (function () { function SebmGoogleMapKmlLayer(_manager) { this._manager = _manager; this._addedToManager = false; this._id = (layerId++).toString(); this._subscriptions = []; /** * If true, the layer receives mouse events. Default value is true. */ this.clickable = true; /** * By default, the input map is centered and zoomed to the bounding box of the contents of the * layer. * If this option is set to true, the viewport is left unchanged, unless the map's center and zoom * were never set. */ this.preserveViewport = false; /** * Whether to render the screen overlays. Default true. */ this.screenOverlays = true; /** * Suppress the rendering of info windows when layer features are clicked. */ this.suppressInfoWindows = false; /** * The URL of the KML document to display. */ this.url = null; /** * The z-index of the layer. */ this.zIndex = null; /** * This event is fired when a feature in the layer is clicked. */ this.layerClick = new EventEmitter(); /** * This event is fired when the KML layers default viewport has changed. */ this.defaultViewportChange = new EventEmitter(); /** * This event is fired when the KML layer has finished loading. * At this point it is safe to read the status property to determine if the layer loaded * successfully. */ this.statusChange = new EventEmitter(); } SebmGoogleMapKmlLayer.prototype.ngOnInit = function () { if (this._addedToManager) { return; } this._manager.addKmlLayer(this); this._addedToManager = true; this._addEventListeners(); }; SebmGoogleMapKmlLayer.prototype.ngOnChanges = function (changes) { if (!this._addedToManager) { return; } this._updatePolygonOptions(changes); }; SebmGoogleMapKmlLayer.prototype._updatePolygonOptions = function (changes) { var options = Object.keys(changes) .filter(function (k) { return SebmGoogleMapKmlLayer._kmlLayerOptions.indexOf(k) !== -1; }) .reduce(function (obj, k) { obj[k] = changes[k].currentValue; return obj; }, {}); if (Object.keys(options).length > 0) { this._manager.setOptions(this, options); } }; SebmGoogleMapKmlLayer.prototype._addEventListeners = function () { var _this = this; var listeners = [ { name: 'click', handler: function (ev) { return _this.layerClick.emit(ev); } }, { name: 'defaultviewport_changed', handler: function () { return _this.defaultViewportChange.emit(); } }, { name: 'status_changed', handler: function () { return _this.statusChange.emit(); } }, ]; listeners.forEach(function (obj) { var os = _this._manager.createEventObservable(obj.name, _this).subscribe(obj.handler); _this._subscriptions.push(os); }); }; /** @internal */ SebmGoogleMapKmlLayer.prototype.id = function () { return this._id; }; /** @internal */ SebmGoogleMapKmlLayer.prototype.toString = function () { return "SebmGoogleMapKmlLayer-" + this._id.toString(); }; /** @internal */ SebmGoogleMapKmlLayer.prototype.ngOnDestroy = function () { this._manager.deleteKmlLayer(this); // unsubscribe all registered observable subscriptions this._subscriptions.forEach(function (s) { return s.unsubscribe(); }); }; SebmGoogleMapKmlLayer._kmlLayerOptions = ['clickable', 'preserveViewport', 'screenOverlays', 'suppressInfoWindows', 'url', 'zIndex']; SebmGoogleMapKmlLayer.decorators = [ { type: Directive, args: [{ selector: 'sebm-google-map-kml-layer', inputs: ['clickable', 'preserveViewport', 'screenOverlays', 'suppressInfoWindows', 'url', 'zIndex'], outputs: ['layerClick', 'defaultViewportChange', 'statusChange'] },] }, ]; /** @nocollapse */ SebmGoogleMapKmlLayer.ctorParameters = function () { return [ { type: KmlLayerManager, }, ]; }; return SebmGoogleMapKmlLayer; }()); //# sourceMappingURL=google-map-kml-layer.js.map
Oussemalaamiri/guidemeAngular
src/node_modules/angular2-google-maps/esm/core/directives/google-map-kml-layer.js
JavaScript
mit
4,685
module CatsHelper end
metaminded/cruddler
test/dummy/app/helpers/cats_helper.rb
Ruby
mit
22
<?php return [ 'Names' => [ 'Aran' => 'nasta’liq', 'Armn' => 'arménio', 'Beng' => 'bengalês', 'Egyd' => 'egípcio demótico', 'Egyh' => 'egípcio hierático', 'Ethi' => 'etíope', 'Hanb' => 'han com bopomofo', 'Inds' => 'indus', 'Orya' => 'odia', 'Sylo' => 'siloti nagri', 'Tale' => 'tai le', 'Telu' => 'telugu', 'Zsym' => 'símbolos', 'Zxxx' => 'não escrito', ], ];
derrabus/symfony
src/Symfony/Component/Intl/Resources/data/scripts/pt_PT.php
PHP
mit
493
<?php namespace SMW; use SMWQueryResult; use Title; /** * Printer for embedded data. * * Embeds in the page output the contents of the pages in the query result set. * Printouts are ignored: it only matters which pages were returned by the query. * The optional "titlestyle" formatting parameter can be used to apply a format to * the headings for the page titles. If "titlestyle" is not specified, a <h1> tag is * used. * * @license GNU GPL v2+ * @since 1.7 * * @author Fernando Correia * @author Markus Krötzsch */ class EmbeddedResultPrinter extends ResultPrinter { protected $m_showhead; protected $m_embedformat; /** * @see SMWResultPrinter::handleParameters * * @since 1.7 * * @param array $params * @param $outputmode */ protected function handleParameters( array $params, $outputmode ) { parent::handleParameters( $params, $outputmode ); $this->m_showhead = !$params['embedonly']; $this->m_embedformat = $params['embedformat']; } public function getName() { return wfMessage( 'smw_printername_embedded' )->text(); } protected function getResultText( SMWQueryResult $res, $outputMode ) { global $wgParser; // No page should embed itself, find out who we are: if ( $wgParser->getTitle() instanceof Title ) { $title = $wgParser->getTitle()->getPrefixedText(); } else { // this is likely to be in vain -- this case is typical if we run on special pages global $wgTitle; $title = $wgTitle->getPrefixedText(); } // print header $result = ''; $footer = ''; $embstart = ''; $embend = ''; $headstart = ''; $headend = ''; $this->hasTemplates = true; switch ( $this->m_embedformat ) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': $headstart = '<' . $this->m_embedformat . '>'; $headend = '</' . $this->m_embedformat . ">\n"; break; case 'ul': case 'ol': $result .= '<' . $this->m_embedformat . '>'; $footer = '</' . $this->m_embedformat . '>'; $embstart = '<li>'; $headend = "<br />\n"; $embend = "</li>\n"; break; } // Print all result rows: foreach ( $res->getResults() as $diWikiPage ) { if ( $diWikiPage instanceof DIWikiPage ) { // ensure that we deal with title-likes $dvWikiPage = DataValueFactory::getInstance()->newDataItemValue( $diWikiPage, null ); $result .= $embstart; if ( $this->m_showhead ) { $result .= $headstart . $dvWikiPage->getLongWikiText( $this->mLinker ) . $headend; } if ( $dvWikiPage->getLongWikiText() != $title ) { if ( $diWikiPage->getNamespace() == NS_MAIN ) { $result .= '{{:' . $diWikiPage->getDBkey() . '}}'; } else { $result .= '{{' . $dvWikiPage->getLongWikiText() . '}}'; } } else { // block recursion $result .= '<b>' . $dvWikiPage->getLongWikiText() . '</b>'; } $result .= $embend; } } // show link to more results if ( $this->linkFurtherResults( $res ) ) { $result .= $embstart . $this->getFurtherResultsLink( $res, $outputMode )->getText( SMW_OUTPUT_WIKI, $this->mLinker ) . $embend; } $result .= $footer; return $result; } public function getParameters() { $params = parent::getParameters(); $params[] = array( 'name' => 'embedformat', 'message' => 'smw-paramdesc-embedformat', 'default' => 'h1', 'values' => array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul' ), ); $params[] = array( 'name' => 'embedonly', 'type' => 'boolean', 'message' => 'smw-paramdesc-embedonly', 'default' => false, ); return $params; } }
owen-kellie-smith/mediawiki
wiki/extensions/SemanticMediaWiki/includes/queryprinters/EmbeddedResultPrinter.php
PHP
mit
3,564
require File.dirname(__FILE__) + '/../spec_helper' require 'mspec/guards/conflict' describe Object, "#conflicts_with" do before :each do ScratchPad.clear end it "does not yield if Object.constants includes any of the arguments" do Object.stub!(:constants).and_return(["SomeClass", "OtherClass"]) conflicts_with(:SomeClass, :AClass, :BClass) { ScratchPad.record :yield } ScratchPad.recorded.should_not == :yield end it "does not yield if Object.constants (as Symbols) includes any of the arguments" do Object.stub!(:constants).and_return([:SomeClass, :OtherClass]) conflicts_with(:SomeClass, :AClass, :BClass) { ScratchPad.record :yield } ScratchPad.recorded.should_not == :yield end it "yields if Object.constants does not include any of the arguments" do Object.stub!(:constants).and_return(["SomeClass", "OtherClass"]) conflicts_with(:AClass, :BClass) { ScratchPad.record :yield } ScratchPad.recorded.should == :yield end it "yields if Object.constants (as Symbols) does not include any of the arguments" do Object.stub!(:constants).and_return([:SomeClass, :OtherClass]) conflicts_with(:AClass, :BClass) { ScratchPad.record :yield } ScratchPad.recorded.should == :yield end end describe Object, "#conflicts_with" do before :each do @guard = ConflictsGuard.new ConflictsGuard.stub!(:new).and_return(@guard) end it "sets the name of the guard to :conflicts_with" do conflicts_with(:AClass, :BClass) { } @guard.name.should == :conflicts_with end it "calls #unregister even when an exception is raised in the guard block" do @guard.should_receive(:unregister) lambda do conflicts_with(:AClass, :BClass) { raise Exception } end.should raise_error(Exception) end end
timfel/mspec
spec/guards/conflict_spec.rb
Ruby
mit
1,789
# -*- encoding: ascii-8bit -*- require File.expand_path('../../../spec_helper', __FILE__) with_feature :encoding do # TODO: add IO describe "Encoding.compatible? String, String" do describe "when the first's Encoding is valid US-ASCII" do before :each do @str = "abc".force_encoding Encoding::US_ASCII end it "returns US-ASCII when the second's is US-ASCII" do Encoding.compatible?(@str, "def".encode("us-ascii")).should == Encoding::US_ASCII end it "returns US-ASCII if the second String is ASCII-8BIT and ASCII only" do Encoding.compatible?(@str, "\x7f").should == Encoding::US_ASCII end it "returns ASCII-8BIT if the second String is ASCII-8BIT but not ASCII only" do Encoding.compatible?(@str, "\xff").should == Encoding::ASCII_8BIT end it "returns US-ASCII if the second String is UTF-8 and ASCII only" do Encoding.compatible?(@str, "\x7f".encode("utf-8")).should == Encoding::US_ASCII end it "returns UTF-8 if the second String is UTF-8 but not ASCII only" do Encoding.compatible?(@str, "\u3042".encode("utf-8")).should == Encoding::UTF_8 end end describe "when the first's Encoding is ASCII compatible and ASCII only" do it "returns the first's Encoding if the second is ASCII compatible and ASCII only" do [ [Encoding, "abc".force_encoding("UTF-8"), "123".force_encoding("Shift_JIS"), Encoding::UTF_8], [Encoding, "123".force_encoding("Shift_JIS"), "abc".force_encoding("UTF-8"), Encoding::Shift_JIS] ].should be_computed_by(:compatible?) end it "returns the first's Encoding if the second is ASCII compatible and ASCII only" do [ [Encoding, "abc".force_encoding("ASCII-8BIT"), "123".force_encoding("US-ASCII"), Encoding::ASCII_8BIT], [Encoding, "123".force_encoding("US-ASCII"), "abc".force_encoding("ASCII-8BIT"), Encoding::US_ASCII] ].should be_computed_by(:compatible?) end it "returns the second's Encoding if the second is ASCII compatible but not ASCII only" do [ [Encoding, "abc".force_encoding("UTF-8"), "\xff".force_encoding("Shift_JIS"), Encoding::Shift_JIS], [Encoding, "123".force_encoding("Shift_JIS"), "\xff".force_encoding("UTF-8"), Encoding::UTF_8], [Encoding, "abc".force_encoding("ASCII-8BIT"), "\xff".force_encoding("US-ASCII"), Encoding::US_ASCII], [Encoding, "123".force_encoding("US-ASCII"), "\xff".force_encoding("ASCII-8BIT"), Encoding::ASCII_8BIT], ].should be_computed_by(:compatible?) end it "returns nil if the second's Encoding is not ASCII compatible" do a = "abc".force_encoding("UTF-8") b = "123".force_encoding("UTF-16LE") Encoding.compatible?(a, b).should be_nil end end describe "when the first's Encoding is ASCII compatible but not ASCII only" do it "returns the first's Encoding if the second's is valid US-ASCII" do Encoding.compatible?("\xff", "def".encode("us-ascii")).should == Encoding::ASCII_8BIT end it "returns the first's Encoding if the second's is UTF-8 and ASCII only" do Encoding.compatible?("\xff", "\u{7f}".encode("utf-8")).should == Encoding::ASCII_8BIT end it "returns nil if the second encoding is ASCII compatible but neither String's encoding is ASCII only" do Encoding.compatible?("\xff", "\u3042".encode("utf-8")).should be_nil end end describe "when the first's Encoding is not ASCII compatible" do before :each do @str = "abc".force_encoding Encoding::UTF_7 end it "returns nil when the second String is US-ASCII" do Encoding.compatible?(@str, "def".encode("us-ascii")).should be_nil end it "returns nil when the second String is ASCII-8BIT and ASCII only" do Encoding.compatible?(@str, "\x7f").should be_nil end it "returns nil when the second String is ASCII-8BIT but not ASCII only" do Encoding.compatible?(@str, "\xff").should be_nil end it "returns the Encoding when the second's Encoding is not ASCII compatible but the same as the first's Encoding" do encoding = Encoding.compatible?(@str, "def".force_encoding("utf-7")) encoding.should == Encoding::UTF_7 end end describe "when the first's Encoding is invalid" do before :each do @str = "\xff".force_encoding Encoding::UTF_8 end it "returns the first's Encoding when the second's Encoding is US-ASCII" do Encoding.compatible?(@str, "def".encode("us-ascii")).should == Encoding::UTF_8 end it "returns the first's Encoding when the second String is ASCII only" do Encoding.compatible?(@str, "\x7f").should == Encoding::UTF_8 end it "returns nil when the second's Encoding is ASCII-8BIT but not ASCII only" do Encoding.compatible?(@str, "\xff").should be_nil end it "returns nil when the second's Encoding is invalid and ASCII only" do Encoding.compatible?(@str, "\x7f".force_encoding("utf-16be")).should be_nil end it "returns nil when the second's Encoding is invalid and not ASCII only" do Encoding.compatible?(@str, "\xff".force_encoding("utf-16be")).should be_nil end it "returns the Encoding when the second's Encoding is invalid but the same as the first" do Encoding.compatible?(@str, @str).should == Encoding::UTF_8 end end end describe "Encoding.compatible? String, Regexp" do it "returns US-ASCII if both are US-ASCII" do str = "abc".force_encoding("us-ascii") Encoding.compatible?(str, /abc/).should == Encoding::US_ASCII end it "returns the String's Encoding if it is not US-ASCII but both are ASCII only" do [ [Encoding, "abc", Encoding::ASCII_8BIT], [Encoding, "abc".encode("utf-8"), Encoding::UTF_8], [Encoding, "abc".encode("euc-jp"), Encoding::EUC_JP], [Encoding, "abc".encode("shift_jis"), Encoding::Shift_JIS], ].should be_computed_by(:compatible?, /abc/) end it "returns the String's Encoding if the String is not ASCII only" do [ [Encoding, "\xff", Encoding::ASCII_8BIT], [Encoding, "\u3042".encode("utf-8"), Encoding::UTF_8], [Encoding, "\xa4\xa2".force_encoding("euc-jp"), Encoding::EUC_JP], [Encoding, "\x82\xa0".force_encoding("shift_jis"), Encoding::Shift_JIS], ].should be_computed_by(:compatible?, /abc/) end end describe "Encoding.compatible? String, Symbol" do it "returns US-ASCII if both are ASCII only" do str = "abc".force_encoding("us-ascii") Encoding.compatible?(str, :abc).should == Encoding::US_ASCII end it "returns the String's Encoding if it is not US-ASCII but both are ASCII only" do [ [Encoding, "abc", Encoding::ASCII_8BIT], [Encoding, "abc".encode("utf-8"), Encoding::UTF_8], [Encoding, "abc".encode("euc-jp"), Encoding::EUC_JP], [Encoding, "abc".encode("shift_jis"), Encoding::Shift_JIS], ].should be_computed_by(:compatible?, :abc) end it "returns the String's Encoding if the String is not ASCII only" do [ [Encoding, "\xff", Encoding::ASCII_8BIT], [Encoding, "\u3042".encode("utf-8"), Encoding::UTF_8], [Encoding, "\xa4\xa2".force_encoding("euc-jp"), Encoding::EUC_JP], [Encoding, "\x82\xa0".force_encoding("shift_jis"), Encoding::Shift_JIS], ].should be_computed_by(:compatible?, :abc) end end describe "Encoding.compatible? Regexp, String" do it "returns US-ASCII if both are US-ASCII" do str = "abc".force_encoding("us-ascii") Encoding.compatible?(/abc/, str).should == Encoding::US_ASCII end end describe "Encoding.compatible? Regexp, Regexp" do it "returns US-ASCII if both are US-ASCII" do Encoding.compatible?(/abc/, /def/).should == Encoding::US_ASCII end it "returns the first's Encoding if it is not US-ASCII and not ASCII only" do [ [Encoding, Regexp.new("\xff"), Encoding::ASCII_8BIT], [Encoding, Regexp.new("\u3042".encode("utf-8")), Encoding::UTF_8], [Encoding, Regexp.new("\xa4\xa2".force_encoding("euc-jp")), Encoding::EUC_JP], [Encoding, Regexp.new("\x82\xa0".force_encoding("shift_jis")), Encoding::Shift_JIS], ].should be_computed_by(:compatible?, /abc/) end end describe "Encoding.compatible? Regexp, Symbol" do it "returns US-ASCII if both are US-ASCII" do Encoding.compatible?(/abc/, :def).should == Encoding::US_ASCII end it "returns the first's Encoding if it is not US-ASCII and not ASCII only" do [ [Encoding, Regexp.new("\xff"), Encoding::ASCII_8BIT], [Encoding, Regexp.new("\u3042".encode("utf-8")), Encoding::UTF_8], [Encoding, Regexp.new("\xa4\xa2".force_encoding("euc-jp")), Encoding::EUC_JP], [Encoding, Regexp.new("\x82\xa0".force_encoding("shift_jis")), Encoding::Shift_JIS], ].should be_computed_by(:compatible?, /abc/) end end describe "Encoding.compatible? Symbol, String" do it "returns US-ASCII if both are ASCII only" do str = "abc".force_encoding("us-ascii") Encoding.compatible?(str, :abc).should == Encoding::US_ASCII end end describe "Encoding.compatible? Symbol, Regexp" do it "returns US-ASCII if both are US-ASCII" do Encoding.compatible?(:abc, /def/).should == Encoding::US_ASCII end it "returns the Regexp's Encoding if it is not US-ASCII and not ASCII only" do a = Regexp.new("\xff") b = Regexp.new("\u3042".encode("utf-8")) c = Regexp.new("\xa4\xa2".force_encoding("euc-jp")) d = Regexp.new("\x82\xa0".force_encoding("shift_jis")) [ [Encoding, :abc, a, Encoding::ASCII_8BIT], [Encoding, :abc, b, Encoding::UTF_8], [Encoding, :abc, c, Encoding::EUC_JP], [Encoding, :abc, d, Encoding::Shift_JIS], ].should be_computed_by(:compatible?) end end describe "Encoding.compatible? Symbol, Symbol" do it "returns US-ASCII if both are US-ASCII" do Encoding.compatible?(:abc, :def).should == Encoding::US_ASCII end it "returns the first's Encoding if it is not ASCII only" do [ [Encoding, "\xff".to_sym, Encoding::ASCII_8BIT], [Encoding, "\u3042".encode("utf-8").to_sym, Encoding::UTF_8], [Encoding, "\xa4\xa2".force_encoding("euc-jp").to_sym, Encoding::EUC_JP], [Encoding, "\x82\xa0".force_encoding("shift_jis").to_sym, Encoding::Shift_JIS], ].should be_computed_by(:compatible?, :abc) end end describe "Encoding.compatible? Encoding, Encoding" do it "returns nil if one of the encodings is a dummy encoding" do [ [Encoding, Encoding::UTF_7, Encoding::US_ASCII, nil], [Encoding, Encoding::US_ASCII, Encoding::UTF_7, nil], [Encoding, Encoding::EUC_JP, Encoding::UTF_7, nil], [Encoding, Encoding::UTF_7, Encoding::EUC_JP, nil], [Encoding, Encoding::UTF_7, Encoding::ASCII_8BIT, nil], [Encoding, Encoding::ASCII_8BIT, Encoding::UTF_7, nil], ].should be_computed_by(:compatible?) end it "returns nil if one of the encodings is not US-ASCII" do [ [Encoding, Encoding::UTF_8, Encoding::ASCII_8BIT, nil], [Encoding, Encoding::ASCII_8BIT, Encoding::UTF_8, nil], [Encoding, Encoding::ASCII_8BIT, Encoding::EUC_JP, nil], [Encoding, Encoding::Shift_JIS, Encoding::EUC_JP, nil], ].should be_computed_by(:compatible?) end it "returns the first if the second is US-ASCII" do [ [Encoding, Encoding::UTF_8, Encoding::US_ASCII, Encoding::UTF_8], [Encoding, Encoding::EUC_JP, Encoding::US_ASCII, Encoding::EUC_JP], [Encoding, Encoding::Shift_JIS, Encoding::US_ASCII, Encoding::Shift_JIS], [Encoding, Encoding::ASCII_8BIT, Encoding::US_ASCII, Encoding::ASCII_8BIT], ].should be_computed_by(:compatible?) end it "returns the Encoding if both are the same" do [ [Encoding, Encoding::UTF_8, Encoding::UTF_8, Encoding::UTF_8], [Encoding, Encoding::US_ASCII, Encoding::US_ASCII, Encoding::US_ASCII], [Encoding, Encoding::ASCII_8BIT, Encoding::ASCII_8BIT, Encoding::ASCII_8BIT], [Encoding, Encoding::UTF_7, Encoding::UTF_7, Encoding::UTF_7], ].should be_computed_by(:compatible?) end end describe "Encoding.compatible? Object, Object" do it "returns nil for Object, String" do Encoding.compatible?(Object.new, "abc").should be_nil end it "returns nil for Object, Regexp" do Encoding.compatible?(Object.new, /./).should be_nil end it "returns nil for Object, Symbol" do Encoding.compatible?(Object.new, :sym).should be_nil end it "returns nil for String, Object" do Encoding.compatible?("abc", Object.new).should be_nil end it "returns nil for Regexp, Object" do Encoding.compatible?(/./, Object.new).should be_nil end it "returns nil for Symbol, Object" do Encoding.compatible?(:sym, Object.new).should be_nil end end end
askl56/rubyspec
core/encoding/compatible_spec.rb
Ruby
mit
13,521
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Mailer\Bridge\Amazon\Tests\Transport; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; use Symfony\Component\Mailer\Bridge\Amazon\Transport\SesApiTransport; use Symfony\Component\Mailer\Exception\HttpTransportException; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; use Symfony\Contracts\HttpClient\ResponseInterface; class SesApiTransportTest extends TestCase { /** * @dataProvider getTransportData */ public function testToString(SesApiTransport $transport, string $expected) { $this->assertSame($expected, (string) $transport); } public function getTransportData() { return [ [ new SesApiTransport('ACCESS_KEY', 'SECRET_KEY'), 'ses+api://ACCESS_KEY@email.eu-west-1.amazonaws.com', ], [ new SesApiTransport('ACCESS_KEY', 'SECRET_KEY', 'us-east-1'), 'ses+api://ACCESS_KEY@email.us-east-1.amazonaws.com', ], [ (new SesApiTransport('ACCESS_KEY', 'SECRET_KEY'))->setHost('example.com'), 'ses+api://ACCESS_KEY@example.com', ], [ (new SesApiTransport('ACCESS_KEY', 'SECRET_KEY'))->setHost('example.com')->setPort(99), 'ses+api://ACCESS_KEY@example.com:99', ], ]; } public function testSend() { $client = new MockHttpClient(function (string $method, string $url, array $options): ResponseInterface { $this->assertSame('POST', $method); $this->assertSame('https://email.eu-west-1.amazonaws.com:8984/', $url); $this->assertStringContainsStringIgnoringCase('X-Amzn-Authorization: AWS3-HTTPS AWSAccessKeyId=ACCESS_KEY,Algorithm=HmacSHA256,Signature=', $options['headers'][0] ?? $options['request_headers'][0]); parse_str($options['body'], $content); $this->assertSame('Hello!', $content['Message_Subject_Data']); $this->assertSame('Saif Eddin <saif.gmati@symfony.com>', $content['Destination_ToAddresses_member'][0]); $this->assertSame('Fabien <fabpot@symfony.com>', $content['Source']); $this->assertSame('Hello There!', $content['Message_Body_Text_Data']); $xml = '<SendEmailResponse xmlns="https://email.amazonaws.com/doc/2010-03-31/"> <SendEmailResult> <MessageId>foobar</MessageId> </SendEmailResult> </SendEmailResponse>'; return new MockResponse($xml, [ 'http_code' => 200, ]); }); $transport = new SesApiTransport('ACCESS_KEY', 'SECRET_KEY', null, $client); $transport->setPort(8984); $mail = new Email(); $mail->subject('Hello!') ->to(new Address('saif.gmati@symfony.com', 'Saif Eddin')) ->from(new Address('fabpot@symfony.com', 'Fabien')) ->text('Hello There!'); $message = $transport->send($mail); $this->assertSame('foobar', $message->getMessageId()); } public function testSendThrowsForErrorResponse() { $client = new MockHttpClient(function (string $method, string $url, array $options): ResponseInterface { $xml = "<SendEmailResponse xmlns=\"https://email.amazonaws.com/doc/2010-03-31/\"> <Error> <Message>i'm a teapot</Message> <Code>418</Code> </Error> </SendEmailResponse>"; return new MockResponse($xml, [ 'http_code' => 418, ]); }); $transport = new SesApiTransport('ACCESS_KEY', 'SECRET_KEY', null, $client); $transport->setPort(8984); $mail = new Email(); $mail->subject('Hello!') ->to(new Address('saif.gmati@symfony.com', 'Saif Eddin')) ->from(new Address('fabpot@symfony.com', 'Fabien')) ->text('Hello There!'); $this->expectException(HttpTransportException::class); $this->expectExceptionMessage('Unable to send an email: i\'m a teapot (code 418).'); $transport->send($mail); } }
localheinz/symfony
src/Symfony/Component/Mailer/Bridge/Amazon/Tests/Transport/SesApiTransportTest.php
PHP
mit
4,500
function makeData() { "use strict"; return [makeRandomData(10), makeRandomData(10)]; } function run(svg, data, Plottable) { "use strict"; var largeX = function(d, i){ d.x = Math.pow(10, i); }; var bigNumbers = []; deepCopy(data[0], bigNumbers); bigNumbers.forEach(largeX); var dataseries1 = new Plottable.Dataset(bigNumbers); //Axis var xScale = new Plottable.Scales.Linear(); var yScale = new Plottable.Scales.Linear(); var xAxis = new Plottable.Axes.Numeric(xScale, "bottom"); var yAxis = new Plottable.Axes.Numeric(yScale, "left"); var IdTitle = new Plottable.Components.Label("Identity"); var GenTitle = new Plottable.Components.Label("General"); var FixTitle = new Plottable.Components.Label("Fixed"); var CurrTitle = new Plottable.Components.Label("Currency"); var PerTitle = new Plottable.Components.Label("Percentage"); var SITitle = new Plottable.Components.Label("SI"); var SSTitle = new Plottable.Components.Label("Short Scale"); var plot = new Plottable.Plots.Line().addDataset(dataseries1); plot.x(function(d) { return d.x; }, xScale).y(function(d) { return d.y; }, yScale); var basicTable = new Plottable.Components.Table([[yAxis, plot], [null, xAxis]]); var formatChoices = new Plottable.Components.Table([[IdTitle, GenTitle, FixTitle], [CurrTitle, null, PerTitle], [SITitle, null, SSTitle]]); var bigTable = new Plottable.Components.Table([[basicTable], [formatChoices]]); formatChoices.xAlignment("center"); bigTable.renderTo(svg); function useIdentityFormatter() { xAxis.formatter(Plottable.Formatters.identity(2.1)); yAxis.formatter(Plottable.Formatters.identity()); } function useGeneralFormatter() { xAxis.formatter(Plottable.Formatters.general(7)); yAxis.formatter(Plottable.Formatters.general(3)); } function useFixedFormatter() { xAxis.formatter(Plottable.Formatters.fixed(2.00)); yAxis.formatter(Plottable.Formatters.fixed(7.00)); } function useCurrencyFormatter() { xAxis.formatter(Plottable.Formatters.currency(3, "$", true)); yAxis.formatter(Plottable.Formatters.currency(3, "$", true)); } function usePercentageFormatter() { xAxis.formatter(Plottable.Formatters.percentage(12.3 - 11.3)); yAxis.formatter(Plottable.Formatters.percentage(2.5 + 1.5)); } function useSIFormatter() { xAxis.formatter(Plottable.Formatters.siSuffix(7)); yAxis.formatter(Plottable.Formatters.siSuffix(14)); } function useSSFormatter() { xAxis.formatter(Plottable.Formatters.shortScale(0)); yAxis.formatter(Plottable.Formatters.shortScale(0)); } new Plottable.Interactions.Click().onClick(useIdentityFormatter).attachTo(IdTitle); new Plottable.Interactions.Click().onClick(useGeneralFormatter).attachTo(GenTitle); new Plottable.Interactions.Click().onClick(useFixedFormatter).attachTo(FixTitle); new Plottable.Interactions.Click().onClick(useCurrencyFormatter).attachTo(CurrTitle); new Plottable.Interactions.Click().onClick(usePercentageFormatter).attachTo(PerTitle); new Plottable.Interactions.Click().onClick(useSIFormatter).attachTo(SITitle); new Plottable.Interactions.Click().onClick(useSSFormatter).attachTo(SSTitle); }
iobeam/plottable
quicktests/overlaying/tests/functional/formatter.js
JavaScript
mit
3,212
JsonRoutes.add('post', '/' + Meteor.settings.private.stripe.webhookEndpoint, function (req, res) { Letterpress.Services.Buy.handleEvent(req.body); JsonRoutes.sendResult(res, 200); });
FleetingClouds/Letterpress
server/api/webhooks-api.js
JavaScript
mit
187
'use strict'; var spawn = require('child_process').spawn; var os = require('os'); var pathlib = require('path'); var fs = require('fs'); var net = require('net'); var crypto = require('crypto'); var which = require('which'); var pathOpenSSL; var tempDir = process.env.PEMJS_TMPDIR || (os.tmpdir || os.tmpDir) && (os.tmpdir || os.tmpDir)() || '/tmp'; module.exports.createPrivateKey = createPrivateKey; module.exports.createDhparam = createDhparam; module.exports.createCSR = createCSR; module.exports.createCertificate = createCertificate; module.exports.readCertificateInfo = readCertificateInfo; module.exports.getPublicKey = getPublicKey; module.exports.getFingerprint = getFingerprint; module.exports.getModulus = getModulus; module.exports.config = config; // PUBLIC API /** * Creates a private key * * @param {Number} [keyBitsize=2048] Size of the key, defaults to 2048bit * @param {Object} [options] object of cipher and password {cipher:'aes128',password:'xxx'}, defaults empty object * @param {Function} callback Callback function with an error object and {key} */ function createPrivateKey(keyBitsize, options, callback) { var clientKeyPassword; if (!callback && !options && typeof keyBitsize === 'function') { callback = keyBitsize; keyBitsize = undefined; options = {}; } else if (!callback && keyBitsize && typeof options === 'function') { callback = options; options = {}; } keyBitsize = Number(keyBitsize) || 2048; var params = ['genrsa', '-rand', '/var/log/mail:/var/log/messages' ]; var cipher = ["aes128", "aes192", "aes256", "camellia128", "camellia192", "camellia256", "des", "des3", "idea"]; if (options && options.cipher && ( -1 !== Number(cipher.indexOf(options.cipher)) ) && options.password){ clientKeyPassword = pathlib.join(tempDir, crypto.randomBytes(20).toString('hex')); fs.writeFileSync(clientKeyPassword, options.password); params.push( '-' + options.cipher ); params.push( '-passout' ); params.push( 'file:' + clientKeyPassword ); } params.push(keyBitsize); execOpenSSL(params, 'RSA PRIVATE KEY', function(error, key) { if(clientKeyPassword) { fs.unlink(clientKeyPassword); } if (error) { return callback(error); } return callback(null, { key: key }); }); } /** * Creates a dhparam key * * @param {Number} [keyBitsize=512] Size of the key, defaults to 512bit * @param {Function} callback Callback function with an error object and {dhparam} */ function createDhparam(keyBitsize, callback) { if (!callback && typeof keyBitsize === 'function') { callback = keyBitsize; keyBitsize = undefined; } keyBitsize = Number(keyBitsize) || 512; var params = ['dhparam', '-outform', 'PEM', keyBitsize ]; execOpenSSL(params, 'DH PARAMETERS', function(error, dhparam) { if (error) { return callback(error); } return callback(null, { dhparam: dhparam }); }); } /** * Creates a Certificate Signing Request * * If client key is undefined, a new key is created automatically. The used key is included * in the callback return as clientKey * * @param {Object} [options] Optional options object * @param {String} [options.clientKey] Optional client key to use * @param {Number} [options.keyBitsize] If clientKey is undefined, bit size to use for generating a new key (defaults to 2048) * @param {String} [options.hash] Hash function to use (either md5 sha1 or sha256, defaults to sha256) * @param {String} [options.country] CSR country field * @param {String} [options.state] CSR state field * @param {String} [options.locality] CSR locality field * @param {String} [options.organization] CSR organization field * @param {String} [options.organizationUnit] CSR organizational unit field * @param {String} [options.commonName='localhost'] CSR common name field * @param {String} [options.emailAddress] CSR email address field * @param {Array} [options.altNames] is a list of subjectAltNames in the subjectAltName field * @param {Function} callback Callback function with an error object and {csr, clientKey} */ function createCSR(options, callback) { if (!callback && typeof options === 'function') { callback = options; options = undefined; } options = options || {}; // http://stackoverflow.com/questions/14089872/why-does-node-js-accept-ip-addresses-in-certificates-only-for-san-not-for-cn if (options.commonName && (net.isIPv4(options.commonName) || net.isIPv6(options.commonName))) { if (!options.altNames) { options.altNames = [options.commonName]; } else if (options.altNames.indexOf(options.commonName) === -1) { options.altNames = options.altNames.concat([options.commonName]); } } if (!options.clientKey) { createPrivateKey(options.keyBitsize || 2048, function(error, keyData) { if (error) { return callback(error); } options.clientKey = keyData.key; createCSR(options, callback); }); return; } var params = ['req', '-new', '-' + (options.hash || 'sha256'), '-subj', generateCSRSubject(options), '-key', '--TMPFILE--' ]; var tmpfiles = [options.clientKey]; var config = null; if (options.altNames) { params.push('-extensions'); params.push('v3_req'); params.push('-config'); params.push('--TMPFILE--'); var altNamesRep = []; for (var i = 0; i < options.altNames.length; i++) { altNamesRep.push((net.isIP(options.altNames[i]) ? 'IP' : 'DNS') + '.' + (i + 1) + ' = ' + options.altNames[i]); } tmpfiles.push(config = [ '[req]', 'req_extensions = v3_req', 'distinguished_name = req_distinguished_name', '[v3_req]', 'subjectAltName = @alt_names', '[alt_names]', altNamesRep.join('\n'), '[req_distinguished_name]', 'commonName = Common Name', 'commonName_max = 64', ].join('\n')); } var passwordFilePath = null; if (options.clientKeyPassword) { passwordFilePath = pathlib.join(tempDir, crypto.randomBytes(20).toString('hex')); fs.writeFileSync(passwordFilePath, options.clientKeyPassword); params.push('-passin'); params.push('file:' + passwordFilePath); } execOpenSSL(params, 'CERTIFICATE REQUEST', tmpfiles, function(error, data) { if (passwordFilePath) { fs.unlink(passwordFilePath); } if (error) { return callback(error); } var response = { csr: data, config: config, clientKey: options.clientKey }; return callback(null, response); }); } /** * Creates a certificate based on a CSR. If CSR is not defined, a new one * will be generated automatically. For CSR generation all the options values * can be used as with createCSR. * * @param {Object} [options] Optional options object * @param {String} [options.serviceKey] Private key for signing the certificate, if not defined a new one is generated * @param {Boolean} [options.selfSigned] If set to true and serviceKey is not defined, use clientKey for signing * @param {String} [options.hash] Hash function to use (either md5 sha1 or sha256, defaults to sha256) * @param {String} [options.csr] CSR for the certificate, if not defined a new one is generated * @param {Number} [options.days] Certificate expire time in days * @param {Function} callback Callback function with an error object and {certificate, csr, clientKey, serviceKey} */ function createCertificate(options, callback) { if (!callback && typeof options === 'function') { callback = options; options = undefined; } options = options || {}; if (!options.csr) { createCSR(options, function(error, keyData) { if (error) { return callback(error); } options.csr = keyData.csr; options.config = keyData.config; options.clientKey = keyData.clientKey; createCertificate(options, callback); }); return; } if (!options.serviceKey) { if (options.selfSigned) { options.serviceKey = options.clientKey; } else { createPrivateKey(options.keyBitsize || 2048, function(error, keyData) { if (error) { return callback(error); } options.serviceKey = keyData.key; createCertificate(options, callback); }); return; } } var params = ['x509', '-req', '-' + (options.hash || 'sha256'), '-days', Number(options.days) || '365', '-in', '--TMPFILE--' ]; var tmpfiles = [options.csr]; if (options.serviceCertificate) { if (!options.serial) { return callback(new Error('serial option required for CA signing')); } params.push('-CA'); params.push('--TMPFILE--'); params.push('-CAkey'); params.push('--TMPFILE--'); params.push('-set_serial'); params.push('0x' + ('00000000' + options.serial.toString(16)).slice(-8)); tmpfiles.push(options.serviceCertificate); tmpfiles.push(options.serviceKey); } else { params.push('-signkey'); params.push('--TMPFILE--'); tmpfiles.push(options.serviceKey); } if (options.config) { params.push('-extensions'); params.push('v3_req'); params.push('-extfile'); params.push('--TMPFILE--'); tmpfiles.push(options.config); } execOpenSSL(params, 'CERTIFICATE', tmpfiles, function(error, data) { if (error) { return callback(error); } var response = { csr: options.csr, clientKey: options.clientKey, certificate: data, serviceKey: options.serviceKey }; return callback(null, response); }); } /** * Exports a public key from a private key, CSR or certificate * * @param {String} certificate PEM encoded private key, CSR or certificate * @param {Function} callback Callback function with an error object and {publicKey} */ function getPublicKey(certificate, callback) { if (!callback && typeof certificate === 'function') { callback = certificate; certificate = undefined; } certificate = (certificate || '').toString(); var params; if (certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)) { params = ['req', '-in', '--TMPFILE--', '-pubkey', '-noout' ]; } else if (certificate.match(/BEGIN RSA PRIVATE KEY/)) { params = ['rsa', '-in', '--TMPFILE--', '-pubout' ]; } else { params = ['x509', '-in', '--TMPFILE--', '-pubkey', '-noout' ]; } execOpenSSL(params, 'PUBLIC KEY', certificate, function(error, key) { if (error) { return callback(error); } return callback(null, { publicKey: key }); }); } /** * Reads subject data from a certificate or a CSR * * @param {String} certificate PEM encoded CSR or certificate * @param {Function} callback Callback function with an error object and {country, state, locality, organization, organizationUnit, commonName, emailAddress} */ function readCertificateInfo(certificate, callback) { if (!callback && typeof certificate === 'function') { callback = certificate; certificate = undefined; } certificate = (certificate || '').toString(); var type = certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/) ? 'req' : 'x509', params = [type, '-noout', '-text', '-in', '--TMPFILE--' ]; spawnWrapper(params, certificate, function(err, code, stdout) { if (err) { return callback(err); } return fetchCertificateData(stdout, callback); }); } /** * get the modulus from a certificate, a CSR or a private key * * @param {String} certificate PEM encoded, CSR PEM encoded, or private key * @param {Function} callback Callback function with an error object and {modulus} */ function getModulus(certificate, callback) { certificate = Buffer.isBuffer(certificate) && certificate.toString() || certificate; var type = ''; if (certificate.match(/BEGIN(\sNEW)? CERTIFICATE REQUEST/)) { type = 'req'; } else if (certificate.match(/BEGIN RSA PRIVATE KEY/)) { type = 'rsa'; } else { type = 'x509'; } var params = [type, '-noout', '-modulus', '-in', '--TMPFILE--' ]; spawnWrapper(params, certificate, function(err, code, stdout) { if (err) { return callback(err); } var match = stdout.match(/Modulus=([0-9a-fA-F]+)$/m); if (match) { return callback(null, { modulus: match[1] }); } else { return callback(new Error('No modulus')); } }); } /** * config the pem module * @param {Object} options */ function config(options) { if (options.pathOpenSSL) { pathOpenSSL = options.pathOpenSSL; } } /** * Gets the fingerprint for a certificate * * @param {String} PEM encoded certificate * @param {Function} callback Callback function with an error object and {fingerprint} */ function getFingerprint(certificate, hash, callback) { if (!callback && typeof hash === 'function') { callback = hash; hash = undefined; } hash = hash || 'sha1'; var params = ['x509', '-in', '--TMPFILE--', '-fingerprint', '-noout', '-' + hash ]; spawnWrapper(params, certificate, function(err, code, stdout) { if (err) { return callback(err); } var match = stdout.match(/Fingerprint=([0-9a-fA-F:]+)$/m); if (match) { return callback(null, { fingerprint: match[1] }); } else { return callback(new Error('No fingerprint')); } }); } // HELPER FUNCTIONS function fetchCertificateData(certData, callback) { certData = (certData || '').toString(); var subject, subject2, extra, tmp, certValues = {}; var validity = {}; var san; if ((subject = certData.match(/Subject:([^\n]*)\n/)) && subject.length > 1) { subject2 = linebrakes(subject[1] + '\n'); subject = subject[1]; extra = subject.split('/'); subject = extra.shift() + '\n'; extra = extra.join('/') + '\n'; // country tmp = subject2.match(/\sC=([^\n].*?)[\n]/); certValues.country = tmp && tmp[1] || ''; // state tmp = subject2.match(/\sST=([^\n].*?)[\n]/); certValues.state = tmp && tmp[1] || ''; // locality tmp = subject2.match(/\sL=([^\n].*?)[\n]/); certValues.locality = tmp && tmp[1] || ''; // organization tmp = subject2.match(/\sO=([^\n].*?)[\n]/); certValues.organization = tmp && tmp[1] || ''; // unit tmp = subject2.match(/\sOU=([^\n].*?)[\n]/); certValues.organizationUnit = tmp && tmp[1] || ''; // common name tmp = subject2.match(/\sCN=([^\n].*?)[\n]/); certValues.commonName = tmp && tmp[1] || ''; //email tmp = extra.match(/emailAddress=([^\n\/].*?)[\n\/]/); certValues.emailAddress = tmp && tmp[1] || ''; } if ((san = certData.match(/X509v3 Subject Alternative Name: \n([^\n]*)\n/)) && san.length > 1) { san = san[1].trim() + '\n'; certValues.san = {}; // country tmp = preg_match_all('DNS:([^,\\n].*?)[,\\n]', san); certValues.san.dns = tmp || ''; // country tmp = preg_match_all('IP Address:([^,\\n].*?)[,\\n\\s]', san); certValues.san.ip = tmp || ''; } if ((tmp = certData.match(/Not Before\s?:\s?([^\n]*)\n/)) && tmp.length > 1) { validity.start = Date.parse(tmp && tmp[1] || ''); } if ((tmp = certData.match(/Not After\s?:\s?([^\n]*)\n/)) && tmp.length > 1) { validity.end = Date.parse(tmp && tmp[1] || ''); } if (validity.start && validity.end) { certValues.validity = validity; } callback(null, certValues); } function linebrakes(content) { var helper_x, p, subject; helper_x = content.replace(/(C|L|O|OU|ST|CN)=/g, '\n$1='); helper_x = preg_match_all('((C|L|O|OU|ST|CN)=[^\n].*)', helper_x); for (p in helper_x) { subject = helper_x[p].trim(); content = subject.split('/'); subject = content.shift(); helper_x[p] = rtrim(subject, ','); } return ' ' + helper_x.join('\n') + '\n'; } function rtrim(str, charlist) { charlist = !charlist ? ' \\s\u00A0' : (charlist + '') .replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1'); var re = new RegExp('[' + charlist + ']+$', 'g'); return (str + '') .replace(re, ''); } function preg_match_all(regex, haystack) { var globalRegex = new RegExp(regex, 'g'); var globalMatch = haystack.match(globalRegex); var matchArray = [], nonGlobalRegex, nonGlobalMatch; for (var i in globalMatch) { nonGlobalRegex = new RegExp(regex); nonGlobalMatch = globalMatch[i].match(nonGlobalRegex); matchArray.push(nonGlobalMatch[1]); } return matchArray; } function generateCSRSubject(options) { options = options || {}; var csrData = { C: options.country || options.C || '', ST: options.state || options.ST || '', L: options.locality || options.L || '', O: options.organization || options.O || '', OU: options.organizationUnit || options.OU || '', CN: options.commonName || options.CN || 'localhost', emailAddress: options.emailAddress || '' }, csrBuilder = []; Object.keys(csrData).forEach(function(key) { if (csrData[key]) { csrBuilder.push('/' + key + '=' + csrData[key].replace(/[^\w \.\*\-@]+/g, ' ').trim()); } }); return csrBuilder.join(''); } /** * Generically spawn openSSL, without processing the result * * @param {Array} params The parameters to pass to openssl * @param {String|Array} tmpfiles Stuff to pass to tmpfiles * @param {Function} callback Called with (error, exitCode, stdout, stderr) */ function spawnOpenSSL(params, callback) { var pathBin = pathOpenSSL || process.env.OPENSSL_BIN || 'openssl'; testOpenSSLPath(pathBin, function(err) { if (err) { return callback(err); } var openssl = spawn(pathBin, params), stdout = '', stderr = ''; openssl.stdout.on('data', function(data) { stdout += (data || '').toString('binary'); }); openssl.stderr.on('data', function(data) { stderr += (data || '').toString('binary'); }); // We need both the return code and access to all of stdout. Stdout isn't // *really* available until the close event fires; the timing nuance was // making this fail periodically. var needed = 2; // wait for both exit and close. var code = -1; var finished = false; var done = function(err) { if (finished) { return; } if (err) { finished = true; return callback(err); } if (--needed < 1) { finished = true; if (code) { callback(new Error('Invalid openssl exit code: ' + code + '\n% openssl ' + params.join(' ') + '\n' + stderr), code); } else { callback(null, code, stdout, stderr); } } }; openssl.on('error', done); openssl.on('exit', function(ret) { code = ret; done(); }); openssl.on('close', function() { stdout = new Buffer(stdout, 'binary').toString('utf-8'); stderr = new Buffer(stderr, 'binary').toString('utf-8'); done(); }); }); } function spawnWrapper(params, tmpfiles, callback) { var files = []; var toUnlink = []; if (tmpfiles) { tmpfiles = [].concat(tmpfiles || []); params.forEach(function(value, i) { var fpath; if (value === '--TMPFILE--') { fpath = pathlib.join(tempDir, crypto.randomBytes(20).toString('hex')); files.push({ path: fpath, contents: tmpfiles.shift() }); params[i] = fpath; } }); } var processFiles = function() { var file = files.shift(); if (!file) { return spawnSSL(); } fs.writeFile(file.path, file.contents, function() { toUnlink.push(file.path); processFiles(); }); }; var spawnSSL = function() { spawnOpenSSL(params, function(err, code, stdout, stderr) { toUnlink.forEach(function(filePath) { fs.unlink(filePath); }); callback(err, code, stdout, stderr); }); }; processFiles(); } /** * Spawn an openssl command */ function execOpenSSL(params, searchStr, tmpfiles, callback) { if (!callback && typeof tmpfiles === 'function') { callback = tmpfiles; tmpfiles = false; } spawnWrapper(params, tmpfiles, function(err, code, stdout, stderr) { var start, end; if (err) { return callback(err); } if ((start = stdout.match(new RegExp('\\-+BEGIN ' + searchStr + '\\-+$', 'm')))) { start = start.index; } else { start = -1; } if ((end = stdout.match(new RegExp('^\\-+END ' + searchStr + '\\-+', 'm')))) { end = end.index + (end[0] || '').length; } else { end = -1; } if (start >= 0 && end >= 0) { return callback(null, stdout.substring(start, end)); } else { return callback(new Error(searchStr + ' not found from openssl output:\n---stdout---\n' + stdout + '\n---stderr---\n' + stderr + '\ncode: ' + code)); } }); } /** * Validates the pathBin for the openssl command. * * @param {String} pathBin The path to OpenSSL Bin * @param {Function} callback Callback function with an error object */ function testOpenSSLPath(pathBin, callback) { which(pathBin, function(error) { if (error) { return callback(new Error('Could not find openssl on your system on this path: ' + pathBin)); } callback(); }); }
rishigb/NodeProject_IOTstyle
socketIo/VideoLiveStreamSockets/node_modules/exprestify/node_modules/pem/lib/pem.js
JavaScript
mit
24,288
<?php namespace Neos\Eel\Tests\Unit; /* * This file is part of the Neos.Eel package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Eel\Helper\DateHelper; use Neos\Flow\I18n\Locale; /** * Tests for DateHelper */ class DateHelperTest extends \Neos\Flow\Tests\UnitTestCase { /** * @return array */ public function parseExamples() { $date = \DateTime::createFromFormat('Y-m-d', '2013-07-03'); $dateTime = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-07-03 12:34:56'); return [ 'basic date' => ['2013-07-03', 'Y-m-d', $date], 'date with time' => ['2013-07-03 12:34:56', 'Y-m-d H:i:s', $dateTime] ]; } /** * @test * @dataProvider parseExamples */ public function parseWorks($string, $format, $expected) { $helper = new DateHelper(); $result = $helper->parse($string, $format); self::assertInstanceOf(\DateTime::class, $result); self::assertEqualsWithDelta((float)$expected->format('U'), (float)$result->format('U'), 60, 'Timestamps should match'); } /** * @return array */ public function formatExamples() { $dateTime = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-07-03 12:34:56'); return [ 'DateTime object' => [$dateTime, 'Y-m-d H:i:s', '2013-07-03 12:34:56'], 'timestamp as integer' => [1372856513, 'Y-m-d', '2013-07-03'], 'now' => ['now', 'Y-m-d', date('Y-m-d')], 'interval' => [new \DateInterval('P1D'), '%d days', '1 days'] ]; } /** * @test * @dataProvider formatExamples */ public function formatWorks($dateOrString, $format, $expected) { $helper = new DateHelper(); $result = $helper->format($dateOrString, $format); self::assertSame($expected, $result); } /** * @test */ public function formatCldrThrowsOnEmptyArguments() { $this->expectException(\InvalidArgumentException::class); $helper = new DateHelper(); $helper->formatCldr(null, null); } /** * @test */ public function formatCldrWorksWithEmptyLocale() { $locale = new Locale('en'); $expected = 'whatever-value'; $configurationMock = $this->createMock(\Neos\Flow\I18n\Configuration::class); $configurationMock->expects(self::atLeastOnce())->method('getCurrentLocale')->willReturn($locale); $localizationServiceMock = $this->createMock(\Neos\Flow\I18n\Service::class); $localizationServiceMock->expects(self::atLeastOnce())->method('getConfiguration')->willReturn($configurationMock); $formatMock = $this->createMock(\Neos\Flow\I18n\Formatter\DatetimeFormatter::class); $formatMock->expects(self::atLeastOnce())->method('formatDateTimeWithCustomPattern')->willReturn($expected); $helper = new DateHelper(); $this->inject($helper, 'datetimeFormatter', $formatMock); $this->inject($helper, 'localizationService', $localizationServiceMock); $date = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-07-03 12:34:56'); $format = 'whatever-format'; $helper->formatCldr($date, $format); } /** * @test */ public function formatCldrCallsFormatService() { $date = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-07-03 12:34:56'); $format = 'whatever-format'; $locale = 'en'; $expected = '2013-07-03 12:34:56'; $formatMock = $this->createMock(\Neos\Flow\I18n\Formatter\DatetimeFormatter::class); $formatMock->expects(self::atLeastOnce())->method('formatDateTimeWithCustomPattern'); $helper = new DateHelper(); $this->inject($helper, 'datetimeFormatter', $formatMock); $helper->formatCldr($date, $format, $locale); } /** * @test */ public function nowWorks() { $helper = new DateHelper(); $result = $helper->now(); self::assertInstanceOf(\DateTime::class, $result); self::assertEqualsWithDelta(time(), (integer)$result->format('U'), 1, 'Now should be now'); } /** * @test */ public function createWorks() { $helper = new DateHelper(); $result = $helper->create('yesterday noon'); $expected = new \DateTime('yesterday noon'); self::assertInstanceOf(\DateTime::class, $result); self::assertEqualsWithDelta($expected->getTimestamp(), $result->getTimestamp(), 1, 'Created DateTime object should match expected'); } /** * @test */ public function todayWorks() { $helper = new DateHelper(); $result = $helper->today(); self::assertInstanceOf(\DateTime::class, $result); $today = new \DateTime('today'); self::assertEqualsWithDelta($today->getTimestamp(), $result->getTimestamp(), 1, 'Today should be today'); } /** * @return array */ public function calculationExamples() { $dateTime = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-07-03 12:34:56'); return [ 'add DateTime with DateInterval' => ['add', $dateTime, new \DateInterval('P1D'), '2013-07-04 12:34:56'], 'add DateTime with string' => ['add', $dateTime, 'P1D', '2013-07-04 12:34:56'], 'subtract DateTime with DateInterval' => ['subtract', $dateTime, new \DateInterval('P1D'), '2013-07-02 12:34:56'], 'subtract DateTime with string' => ['subtract', $dateTime, 'P1D', '2013-07-02 12:34:56'], ]; } /** * @test * @dataProvider calculationExamples */ public function calculationWorks($method, $dateTime, $interval, $expected) { $timestamp = $dateTime->getTimestamp(); $helper = new DateHelper(); $result = $helper->$method($dateTime, $interval); self::assertEquals($timestamp, $dateTime->getTimeStamp(), 'DateTime should not be modified'); self::assertEquals($expected, $result->format('Y-m-d H:i:s')); } /** * @test */ public function diffWorks() { $earlierTime = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-07-03 12:34:56'); $futureTime = \DateTime::createFromFormat('Y-m-d H:i:s', '2013-07-10 12:33:56'); $helper = new DateHelper(); $result = $helper->diff($earlierTime, $futureTime); self::assertEquals(6, $result->d); self::assertEquals(23, $result->h); self::assertEquals(59, $result->i); } /** * @test */ public function dateAccessorsWork() { $helper = new DateHelper(); $date = new \DateTime('2013-10-16 14:59:27'); self::assertSame(2013, $helper->year($date)); self::assertSame(10, $helper->month($date)); self::assertSame(16, $helper->dayOfMonth($date)); self::assertSame(14, $helper->hour($date)); self::assertSame(59, $helper->minute($date)); self::assertSame(27, $helper->second($date)); } }
neos/eel
Tests/Unit/Helper/DateHelperTest.php
PHP
mit
7,259
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. import argparse import zipfile from os import getcwd, listdir, makedirs, mkdir, rename from os.path import isdir, isfile, join from shutil import move, rmtree from sys import exit as sys_exit from sys import path path.append("..") from platformio.util import exec_command, get_home_dir def _unzip_generated_file(mbed_dir, output_dir, mcu): filename = join( mbed_dir, "build", "export", "MBED_A1_emblocks_%s.zip" % mcu) variant_dir = join(output_dir, "variant", mcu) if isfile(filename): with zipfile.ZipFile(filename) as zfile: mkdir(variant_dir) zfile.extractall(variant_dir) for f in listdir(join(variant_dir, "MBED_A1")): if not f.lower().startswith("mbed"): continue move(join(variant_dir, "MBED_A1", f), variant_dir) rename(join(variant_dir, "MBED_A1.eix"), join(variant_dir, "%s.eix" % mcu)) rmtree(join(variant_dir, "MBED_A1")) else: print "Warning! Skipped board: %s" % mcu def buildlib(mbed_dir, mcu, lib="mbed"): build_command = [ "python", join(mbed_dir, "workspace_tools", "build.py"), "--mcu", mcu, "-t", "GCC_ARM" ] if lib is not "mbed": build_command.append(lib) build_result = exec_command(build_command, cwd=getcwd()) if build_result['returncode'] != 0: print "* %s doesn't support %s library!" % (mcu, lib) def copylibs(mbed_dir, output_dir): libs = ["dsp", "fat", "net", "rtos", "usb", "usb_host"] libs_dir = join(output_dir, "libs") makedirs(libs_dir) print "Moving generated libraries to framework dir..." for lib in libs: if lib == "net": move(join(mbed_dir, "build", lib, "eth"), libs_dir) continue move(join(mbed_dir, "build", lib), libs_dir) def main(mbed_dir, output_dir): print "Starting..." path.append(mbed_dir) from workspace_tools.export import gccarm if isdir(output_dir): print "Deleting previous framework dir..." rmtree(output_dir) settings_file = join(mbed_dir, "workspace_tools", "private_settings.py") if not isfile(settings_file): with open(settings_file, "w") as f: f.write("GCC_ARM_PATH = '%s'" % join(get_home_dir(), "packages", "toolchain-gccarmnoneeabi", "bin")) makedirs(join(output_dir, "variant")) mbed_libs = ["--rtos", "--dsp", "--fat", "--eth", "--usb", "--usb_host"] for mcu in set(gccarm.GccArm.TARGETS): print "Processing board: %s" % mcu buildlib(mbed_dir, mcu) for lib in mbed_libs: buildlib(mbed_dir, mcu, lib) result = exec_command( ["python", join(mbed_dir, "workspace_tools", "project.py"), "--mcu", mcu, "-i", "emblocks", "-p", "0", "-b"], cwd=getcwd() ) if result['returncode'] != 0: print "Unable to build the project for %s" % mcu continue _unzip_generated_file(mbed_dir, output_dir, mcu) copylibs(mbed_dir, output_dir) with open(join(output_dir, "boards.txt"), "w") as fp: fp.write("\n".join(sorted(listdir(join(output_dir, "variant"))))) print "Complete!" if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--mbed', help="The path to mbed framework") parser.add_argument('--output', help="The path to output directory") args = vars(parser.parse_args()) sys_exit(main(args["mbed"], args["output"]))
mseroczynski/platformio
scripts/mbed_to_package.py
Python
mit
3,667
<?php namespace Concrete\Core\Attribute; use Concrete\Core\Attribute\Key\SearchIndexer\SearchIndexerInterface; interface AttributeKeyInterface { /** * @return int */ public function getAttributeKeyID(); /** * @return string */ public function getAttributeKeyHandle(); /** * @return \Concrete\Core\Entity\Attribute\Type */ public function getAttributeType(); /** * @return bool */ public function isAttributeKeySearchable(); /** * @return SearchIndexerInterface */ public function getSearchIndexer(); /** * @return Controller */ public function getController(); }
jaromirdalecky/concrete5
concrete/src/Attribute/AttributeKeyInterface.php
PHP
mit
678
'''tzinfo timezone information for GMT_minus_0.''' from pytz.tzinfo import StaticTzInfo from pytz.tzinfo import memorized_timedelta as timedelta class GMT_minus_0(StaticTzInfo): '''GMT_minus_0 timezone definition. See datetime.tzinfo for details''' zone = 'GMT_minus_0' _utcoffset = timedelta(seconds=0) _tzname = 'GMT' GMT_minus_0 = GMT_minus_0()
newvem/pytz
pytz/zoneinfo/GMT_minus_0.py
Python
mit
367
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Lock\Tests\Store; use Symfony\Component\Cache\Traits\RedisClusterProxy; use Symfony\Component\Cache\Traits\RedisProxy; use Symfony\Component\Lock\Exception\InvalidArgumentException; use Symfony\Component\Lock\Exception\LockConflictedException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\PersistingStoreInterface; use Symfony\Component\Lock\Store\RedisStore; /** * @author Jérémy Derussé <jeremy@derusse.com> */ abstract class AbstractRedisStoreTest extends AbstractStoreTest { use ExpiringStoreTestTrait; /** * {@inheritdoc} */ protected function getClockDelay() { return 250000; } abstract protected function getRedisConnection(): \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface; /** * {@inheritdoc} */ public function getStore(): PersistingStoreInterface { return new RedisStore($this->getRedisConnection()); } public function testBackwardCompatibility() { $resource = uniqid(__METHOD__, true); $key1 = new Key($resource); $key2 = new Key($resource); $oldStore = new Symfony51Store($this->getRedisConnection()); $newStore = $this->getStore(); $oldStore->save($key1); $this->assertTrue($oldStore->exists($key1)); $this->expectException(LockConflictedException::class); $newStore->save($key2); } } class Symfony51Store { private $redis; public function __construct($redis) { $this->redis = $redis; } public function save(Key $key) { $script = ' if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("PEXPIRE", KEYS[1], ARGV[2]) elseif redis.call("SET", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) then return 1 else return 0 end '; if (!$this->evaluate($script, (string) $key, [$this->getUniqueToken($key), (int) ceil(5 * 1000)])) { throw new LockConflictedException(); } } public function exists(Key $key) { return $this->redis->get((string) $key) === $this->getUniqueToken($key); } private function evaluate(string $script, string $resource, array $args) { if ( $this->redis instanceof \Redis || $this->redis instanceof \RedisCluster || $this->redis instanceof RedisProxy || $this->redis instanceof RedisClusterProxy ) { return $this->redis->eval($script, array_merge([$resource], $args), 1); } if ($this->redis instanceof \RedisArray) { return $this->redis->_instance($this->redis->_target($resource))->eval($script, array_merge([$resource], $args), 1); } if ($this->redis instanceof \Predis\ClientInterface) { return $this->redis->eval(...array_merge([$script, 1, $resource], $args)); } throw new InvalidArgumentException(sprintf('"%s()" expects being initialized with a Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, get_debug_type($this->redis))); } private function getUniqueToken(Key $key): string { if (!$key->hasState(__CLASS__)) { $token = base64_encode(random_bytes(32)); $key->setState(__CLASS__, $token); } return $key->getState(__CLASS__); } }
mpdude/symfony
src/Symfony/Component/Lock/Tests/Store/AbstractRedisStoreTest.php
PHP
mit
3,693
<?php class PSU_Student_Finaid_Application_Factory { public function fetch_by_pidm_aidy_seqno( $pidm, $aidy, $seqno ) { $args = array( 'pidm' => $pidm, 'aidy' => $aidy, 'seqno' => $seqno, ); $where = array( 'rcrapp1_pidm = :pidm', 'rcrapp1_aidy_code = :aidy', 'rcrapp1_seq_no = :seqno', ); $rset = $this->query( $args, $where ); return new PSU_Student_Finaid_Application( $rset ); } public function query( $args, $where = array() ) { $where[] = '1=1'; $where_sql = ' AND ' . implode( ' AND ', $where ); $sql = " SELECT rcrapp4_fath_ssn, rcrapp4_fath_last_name, rcrapp4_fath_first_name_ini, rcrapp4_fath_birth_date, rcrapp4_moth_ssn, rcrapp4_moth_last_name, rcrapp4_moth_first_name_ini, rcrapp4_moth_birth_date FROM rcrapp1 LEFT JOIN rcrapp4 ON rcrapp1_aidy_code = rcrapp4_aidy_code AND rcrapp1_pidm = rcrapp4_pidm AND rcrapp1_infc_code = rcrapp4_infc_code AND rcrapp1_seq_no = rcrapp4_seq_no WHERE rcrapp1_infc_code = 'EDE' $where_sql "; $rset = PSU::db('banner')->GetRow( $sql, $args ); return $rset; } }
jbthibeault/plymouth-webapp
lib/PSU/Student/Finaid/Application/Factory.php
PHP
mit
1,109
<head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Recharge</title> <!-- Load Roboto font --> <link href='http://fonts.googleapis.com/css?family=Roboto:400,300,700&amp;subset=latin,latin-ext' rel='stylesheet' type='text/css'> <!-- Load css styles --> <link rel="stylesheet" type="text/css" href="css/bootstrap.css" /> <link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.css" /> <link rel="stylesheet" type="text/css" href="css/stylemain_tb.css" /> <link rel="stylesheet" type="text/css" href="css/pluton.css" /> <link rel="stylesheet" type="text/css" href="css/style1_payment_portal.css" /> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="css/pluton-ie7.css" /> <![endif]--> <link rel="stylesheet" type="text/css" href="css/jquery.cslider_tb.css" /> <link rel="stylesheet" type="text/css" href="css/jquery.bxslider.css" /> <link rel="stylesheet" type="text/css" href="css/animate.css" /> <!-- Fav and touch icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/apple-touch-icon-72.png"> <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57.png"> <link rel="shortcut icon" href="images/ico/favicon.ico"> </head>
ankushrgv/tollbooth-management-system
tb_management1/laxmi/includes/head_recharge.php
PHP
mit
1,662
<?php return [ 'Names' => [ 'af' => 'Tiếng Afrikaans', 'af_NA' => 'Tiếng Afrikaans (Namibia)', 'af_ZA' => 'Tiếng Afrikaans (Nam Phi)', 'ak' => 'Tiếng Akan', 'ak_GH' => 'Tiếng Akan (Ghana)', 'am' => 'Tiếng Amharic', 'am_ET' => 'Tiếng Amharic (Ethiopia)', 'ar' => 'Tiếng Ả Rập', 'ar_001' => 'Tiếng Ả Rập (Thế giới)', 'ar_AE' => 'Tiếng Ả Rập (Các Tiểu Vương quốc Ả Rập Thống nhất)', 'ar_BH' => 'Tiếng Ả Rập (Bahrain)', 'ar_DJ' => 'Tiếng Ả Rập (Djibouti)', 'ar_DZ' => 'Tiếng Ả Rập (Algeria)', 'ar_EG' => 'Tiếng Ả Rập (Ai Cập)', 'ar_EH' => 'Tiếng Ả Rập (Tây Sahara)', 'ar_ER' => 'Tiếng Ả Rập (Eritrea)', 'ar_IL' => 'Tiếng Ả Rập (Israel)', 'ar_IQ' => 'Tiếng Ả Rập (Iraq)', 'ar_JO' => 'Tiếng Ả Rập (Jordan)', 'ar_KM' => 'Tiếng Ả Rập (Comoros)', 'ar_KW' => 'Tiếng Ả Rập (Kuwait)', 'ar_LB' => 'Tiếng Ả Rập (Li-băng)', 'ar_LY' => 'Tiếng Ả Rập (Libya)', 'ar_MA' => 'Tiếng Ả Rập (Ma-rốc)', 'ar_MR' => 'Tiếng Ả Rập (Mauritania)', 'ar_OM' => 'Tiếng Ả Rập (Oman)', 'ar_PS' => 'Tiếng Ả Rập (Lãnh thổ Palestine)', 'ar_QA' => 'Tiếng Ả Rập (Qatar)', 'ar_SA' => 'Tiếng Ả Rập (Ả Rập Xê-út)', 'ar_SD' => 'Tiếng Ả Rập (Sudan)', 'ar_SO' => 'Tiếng Ả Rập (Somalia)', 'ar_SS' => 'Tiếng Ả Rập (Nam Sudan)', 'ar_SY' => 'Tiếng Ả Rập (Syria)', 'ar_TD' => 'Tiếng Ả Rập (Chad)', 'ar_TN' => 'Tiếng Ả Rập (Tunisia)', 'ar_YE' => 'Tiếng Ả Rập (Yemen)', 'as' => 'Tiếng Assam', 'as_IN' => 'Tiếng Assam (Ấn Độ)', 'az' => 'Tiếng Azerbaijan', 'az_AZ' => 'Tiếng Azerbaijan (Azerbaijan)', 'az_Cyrl' => 'Tiếng Azerbaijan (Chữ Kirin)', 'az_Cyrl_AZ' => 'Tiếng Azerbaijan (Chữ Kirin, Azerbaijan)', 'az_Latn' => 'Tiếng Azerbaijan (Chữ La tinh)', 'az_Latn_AZ' => 'Tiếng Azerbaijan (Chữ La tinh, Azerbaijan)', 'be' => 'Tiếng Belarus', 'be_BY' => 'Tiếng Belarus (Belarus)', 'bg' => 'Tiếng Bulgaria', 'bg_BG' => 'Tiếng Bulgaria (Bulgaria)', 'bm' => 'Tiếng Bambara', 'bm_ML' => 'Tiếng Bambara (Mali)', 'bn' => 'Tiếng Bangla', 'bn_BD' => 'Tiếng Bangla (Bangladesh)', 'bn_IN' => 'Tiếng Bangla (Ấn Độ)', 'bo' => 'Tiếng Tây Tạng', 'bo_CN' => 'Tiếng Tây Tạng (Trung Quốc)', 'bo_IN' => 'Tiếng Tây Tạng (Ấn Độ)', 'br' => 'Tiếng Breton', 'br_FR' => 'Tiếng Breton (Pháp)', 'bs' => 'Tiếng Bosnia', 'bs_BA' => 'Tiếng Bosnia (Bosnia và Herzegovina)', 'bs_Cyrl' => 'Tiếng Bosnia (Chữ Kirin)', 'bs_Cyrl_BA' => 'Tiếng Bosnia (Chữ Kirin, Bosnia và Herzegovina)', 'bs_Latn' => 'Tiếng Bosnia (Chữ La tinh)', 'bs_Latn_BA' => 'Tiếng Bosnia (Chữ La tinh, Bosnia và Herzegovina)', 'ca' => 'Tiếng Catalan', 'ca_AD' => 'Tiếng Catalan (Andorra)', 'ca_ES' => 'Tiếng Catalan (Tây Ban Nha)', 'ca_FR' => 'Tiếng Catalan (Pháp)', 'ca_IT' => 'Tiếng Catalan (Italy)', 'ce' => 'Tiếng Chechen', 'ce_RU' => 'Tiếng Chechen (Nga)', 'cs' => 'Tiếng Séc', 'cs_CZ' => 'Tiếng Séc (Séc)', 'cy' => 'Tiếng Wales', 'cy_GB' => 'Tiếng Wales (Vương quốc Anh)', 'da' => 'Tiếng Đan Mạch', 'da_DK' => 'Tiếng Đan Mạch (Đan Mạch)', 'da_GL' => 'Tiếng Đan Mạch (Greenland)', 'de' => 'Tiếng Đức', 'de_AT' => 'Tiếng Đức (Áo)', 'de_BE' => 'Tiếng Đức (Bỉ)', 'de_CH' => 'Tiếng Đức (Thụy Sĩ)', 'de_DE' => 'Tiếng Đức (Đức)', 'de_IT' => 'Tiếng Đức (Italy)', 'de_LI' => 'Tiếng Đức (Liechtenstein)', 'de_LU' => 'Tiếng Đức (Luxembourg)', 'dz' => 'Tiếng Dzongkha', 'dz_BT' => 'Tiếng Dzongkha (Bhutan)', 'ee' => 'Tiếng Ewe', 'ee_GH' => 'Tiếng Ewe (Ghana)', 'ee_TG' => 'Tiếng Ewe (Togo)', 'el' => 'Tiếng Hy Lạp', 'el_CY' => 'Tiếng Hy Lạp (Síp)', 'el_GR' => 'Tiếng Hy Lạp (Hy Lạp)', 'en' => 'Tiếng Anh', 'en_001' => 'Tiếng Anh (Thế giới)', 'en_150' => 'Tiếng Anh (Châu Âu)', 'en_AE' => 'Tiếng Anh (Các Tiểu Vương quốc Ả Rập Thống nhất)', 'en_AG' => 'Tiếng Anh (Antigua và Barbuda)', 'en_AI' => 'Tiếng Anh (Anguilla)', 'en_AS' => 'Tiếng Anh (Samoa thuộc Mỹ)', 'en_AT' => 'Tiếng Anh (Áo)', 'en_AU' => 'Tiếng Anh (Australia)', 'en_BB' => 'Tiếng Anh (Barbados)', 'en_BE' => 'Tiếng Anh (Bỉ)', 'en_BI' => 'Tiếng Anh (Burundi)', 'en_BM' => 'Tiếng Anh (Bermuda)', 'en_BS' => 'Tiếng Anh (Bahamas)', 'en_BW' => 'Tiếng Anh (Botswana)', 'en_BZ' => 'Tiếng Anh (Belize)', 'en_CA' => 'Tiếng Anh (Canada)', 'en_CC' => 'Tiếng Anh (Quần đảo Cocos [Keeling])', 'en_CH' => 'Tiếng Anh (Thụy Sĩ)', 'en_CK' => 'Tiếng Anh (Quần đảo Cook)', 'en_CM' => 'Tiếng Anh (Cameroon)', 'en_CX' => 'Tiếng Anh (Đảo Giáng Sinh)', 'en_CY' => 'Tiếng Anh (Síp)', 'en_DE' => 'Tiếng Anh (Đức)', 'en_DK' => 'Tiếng Anh (Đan Mạch)', 'en_DM' => 'Tiếng Anh (Dominica)', 'en_ER' => 'Tiếng Anh (Eritrea)', 'en_FI' => 'Tiếng Anh (Phần Lan)', 'en_FJ' => 'Tiếng Anh (Fiji)', 'en_FK' => 'Tiếng Anh (Quần đảo Falkland)', 'en_FM' => 'Tiếng Anh (Micronesia)', 'en_GB' => 'Tiếng Anh (Vương quốc Anh)', 'en_GD' => 'Tiếng Anh (Grenada)', 'en_GG' => 'Tiếng Anh (Guernsey)', 'en_GH' => 'Tiếng Anh (Ghana)', 'en_GI' => 'Tiếng Anh (Gibraltar)', 'en_GM' => 'Tiếng Anh (Gambia)', 'en_GU' => 'Tiếng Anh (Guam)', 'en_GY' => 'Tiếng Anh (Guyana)', 'en_HK' => 'Tiếng Anh (Đặc khu Hành chính Hồng Kông, Trung Quốc)', 'en_IE' => 'Tiếng Anh (Ireland)', 'en_IL' => 'Tiếng Anh (Israel)', 'en_IM' => 'Tiếng Anh (Đảo Man)', 'en_IN' => 'Tiếng Anh (Ấn Độ)', 'en_IO' => 'Tiếng Anh (Lãnh thổ Ấn Độ Dương thuộc Anh)', 'en_JE' => 'Tiếng Anh (Jersey)', 'en_JM' => 'Tiếng Anh (Jamaica)', 'en_KE' => 'Tiếng Anh (Kenya)', 'en_KI' => 'Tiếng Anh (Kiribati)', 'en_KN' => 'Tiếng Anh (St. Kitts và Nevis)', 'en_KY' => 'Tiếng Anh (Quần đảo Cayman)', 'en_LC' => 'Tiếng Anh (St. Lucia)', 'en_LR' => 'Tiếng Anh (Liberia)', 'en_LS' => 'Tiếng Anh (Lesotho)', 'en_MG' => 'Tiếng Anh (Madagascar)', 'en_MH' => 'Tiếng Anh (Quần đảo Marshall)', 'en_MO' => 'Tiếng Anh (Đặc khu Hành chính Macao, Trung Quốc)', 'en_MP' => 'Tiếng Anh (Quần đảo Bắc Mariana)', 'en_MS' => 'Tiếng Anh (Montserrat)', 'en_MT' => 'Tiếng Anh (Malta)', 'en_MU' => 'Tiếng Anh (Mauritius)', 'en_MW' => 'Tiếng Anh (Malawi)', 'en_MY' => 'Tiếng Anh (Malaysia)', 'en_NA' => 'Tiếng Anh (Namibia)', 'en_NF' => 'Tiếng Anh (Đảo Norfolk)', 'en_NG' => 'Tiếng Anh (Nigeria)', 'en_NL' => 'Tiếng Anh (Hà Lan)', 'en_NR' => 'Tiếng Anh (Nauru)', 'en_NU' => 'Tiếng Anh (Niue)', 'en_NZ' => 'Tiếng Anh (New Zealand)', 'en_PG' => 'Tiếng Anh (Papua New Guinea)', 'en_PH' => 'Tiếng Anh (Philippines)', 'en_PK' => 'Tiếng Anh (Pakistan)', 'en_PN' => 'Tiếng Anh (Quần đảo Pitcairn)', 'en_PR' => 'Tiếng Anh (Puerto Rico)', 'en_PW' => 'Tiếng Anh (Palau)', 'en_RW' => 'Tiếng Anh (Rwanda)', 'en_SB' => 'Tiếng Anh (Quần đảo Solomon)', 'en_SC' => 'Tiếng Anh (Seychelles)', 'en_SD' => 'Tiếng Anh (Sudan)', 'en_SE' => 'Tiếng Anh (Thụy Điển)', 'en_SG' => 'Tiếng Anh (Singapore)', 'en_SH' => 'Tiếng Anh (St. Helena)', 'en_SI' => 'Tiếng Anh (Slovenia)', 'en_SL' => 'Tiếng Anh (Sierra Leone)', 'en_SS' => 'Tiếng Anh (Nam Sudan)', 'en_SX' => 'Tiếng Anh (Sint Maarten)', 'en_SZ' => 'Tiếng Anh (Eswatini)', 'en_TC' => 'Tiếng Anh (Quần đảo Turks và Caicos)', 'en_TK' => 'Tiếng Anh (Tokelau)', 'en_TO' => 'Tiếng Anh (Tonga)', 'en_TT' => 'Tiếng Anh (Trinidad và Tobago)', 'en_TV' => 'Tiếng Anh (Tuvalu)', 'en_TZ' => 'Tiếng Anh (Tanzania)', 'en_UG' => 'Tiếng Anh (Uganda)', 'en_UM' => 'Tiếng Anh (Các tiểu đảo xa của Hoa Kỳ)', 'en_US' => 'Tiếng Anh (Hoa Kỳ)', 'en_VC' => 'Tiếng Anh (St. Vincent và Grenadines)', 'en_VG' => 'Tiếng Anh (Quần đảo Virgin thuộc Anh)', 'en_VI' => 'Tiếng Anh (Quần đảo Virgin thuộc Hoa Kỳ)', 'en_VU' => 'Tiếng Anh (Vanuatu)', 'en_WS' => 'Tiếng Anh (Samoa)', 'en_ZA' => 'Tiếng Anh (Nam Phi)', 'en_ZM' => 'Tiếng Anh (Zambia)', 'en_ZW' => 'Tiếng Anh (Zimbabwe)', 'eo' => 'Tiếng Quốc Tế Ngữ', 'eo_001' => 'Tiếng Quốc Tế Ngữ (Thế giới)', 'es' => 'Tiếng Tây Ban Nha', 'es_419' => 'Tiếng Tây Ban Nha (Châu Mỹ La-tinh)', 'es_AR' => 'Tiếng Tây Ban Nha (Argentina)', 'es_BO' => 'Tiếng Tây Ban Nha (Bolivia)', 'es_BR' => 'Tiếng Tây Ban Nha (Brazil)', 'es_BZ' => 'Tiếng Tây Ban Nha (Belize)', 'es_CL' => 'Tiếng Tây Ban Nha (Chile)', 'es_CO' => 'Tiếng Tây Ban Nha (Colombia)', 'es_CR' => 'Tiếng Tây Ban Nha (Costa Rica)', 'es_CU' => 'Tiếng Tây Ban Nha (Cuba)', 'es_DO' => 'Tiếng Tây Ban Nha (Cộng hòa Dominica)', 'es_EC' => 'Tiếng Tây Ban Nha (Ecuador)', 'es_ES' => 'Tiếng Tây Ban Nha (Tây Ban Nha)', 'es_GQ' => 'Tiếng Tây Ban Nha (Guinea Xích Đạo)', 'es_GT' => 'Tiếng Tây Ban Nha (Guatemala)', 'es_HN' => 'Tiếng Tây Ban Nha (Honduras)', 'es_MX' => 'Tiếng Tây Ban Nha (Mexico)', 'es_NI' => 'Tiếng Tây Ban Nha (Nicaragua)', 'es_PA' => 'Tiếng Tây Ban Nha (Panama)', 'es_PE' => 'Tiếng Tây Ban Nha (Peru)', 'es_PH' => 'Tiếng Tây Ban Nha (Philippines)', 'es_PR' => 'Tiếng Tây Ban Nha (Puerto Rico)', 'es_PY' => 'Tiếng Tây Ban Nha (Paraguay)', 'es_SV' => 'Tiếng Tây Ban Nha (El Salvador)', 'es_US' => 'Tiếng Tây Ban Nha (Hoa Kỳ)', 'es_UY' => 'Tiếng Tây Ban Nha (Uruguay)', 'es_VE' => 'Tiếng Tây Ban Nha (Venezuela)', 'et' => 'Tiếng Estonia', 'et_EE' => 'Tiếng Estonia (Estonia)', 'eu' => 'Tiếng Basque', 'eu_ES' => 'Tiếng Basque (Tây Ban Nha)', 'fa' => 'Tiếng Ba Tư', 'fa_AF' => 'Tiếng Ba Tư (Afghanistan)', 'fa_IR' => 'Tiếng Ba Tư (Iran)', 'ff' => 'Tiếng Fulah', 'ff_CM' => 'Tiếng Fulah (Cameroon)', 'ff_GN' => 'Tiếng Fulah (Guinea)', 'ff_Latn' => 'Tiếng Fulah (Chữ La tinh)', 'ff_Latn_BF' => 'Tiếng Fulah (Chữ La tinh, Burkina Faso)', 'ff_Latn_CM' => 'Tiếng Fulah (Chữ La tinh, Cameroon)', 'ff_Latn_GH' => 'Tiếng Fulah (Chữ La tinh, Ghana)', 'ff_Latn_GM' => 'Tiếng Fulah (Chữ La tinh, Gambia)', 'ff_Latn_GN' => 'Tiếng Fulah (Chữ La tinh, Guinea)', 'ff_Latn_GW' => 'Tiếng Fulah (Chữ La tinh, Guinea-Bissau)', 'ff_Latn_LR' => 'Tiếng Fulah (Chữ La tinh, Liberia)', 'ff_Latn_MR' => 'Tiếng Fulah (Chữ La tinh, Mauritania)', 'ff_Latn_NE' => 'Tiếng Fulah (Chữ La tinh, Niger)', 'ff_Latn_NG' => 'Tiếng Fulah (Chữ La tinh, Nigeria)', 'ff_Latn_SL' => 'Tiếng Fulah (Chữ La tinh, Sierra Leone)', 'ff_Latn_SN' => 'Tiếng Fulah (Chữ La tinh, Senegal)', 'ff_MR' => 'Tiếng Fulah (Mauritania)', 'ff_SN' => 'Tiếng Fulah (Senegal)', 'fi' => 'Tiếng Phần Lan', 'fi_FI' => 'Tiếng Phần Lan (Phần Lan)', 'fo' => 'Tiếng Faroe', 'fo_DK' => 'Tiếng Faroe (Đan Mạch)', 'fo_FO' => 'Tiếng Faroe (Quần đảo Faroe)', 'fr' => 'Tiếng Pháp', 'fr_BE' => 'Tiếng Pháp (Bỉ)', 'fr_BF' => 'Tiếng Pháp (Burkina Faso)', 'fr_BI' => 'Tiếng Pháp (Burundi)', 'fr_BJ' => 'Tiếng Pháp (Benin)', 'fr_BL' => 'Tiếng Pháp (St. Barthélemy)', 'fr_CA' => 'Tiếng Pháp (Canada)', 'fr_CD' => 'Tiếng Pháp (Congo - Kinshasa)', 'fr_CF' => 'Tiếng Pháp (Cộng hòa Trung Phi)', 'fr_CG' => 'Tiếng Pháp (Congo - Brazzaville)', 'fr_CH' => 'Tiếng Pháp (Thụy Sĩ)', 'fr_CI' => 'Tiếng Pháp (Côte d’Ivoire)', 'fr_CM' => 'Tiếng Pháp (Cameroon)', 'fr_DJ' => 'Tiếng Pháp (Djibouti)', 'fr_DZ' => 'Tiếng Pháp (Algeria)', 'fr_FR' => 'Tiếng Pháp (Pháp)', 'fr_GA' => 'Tiếng Pháp (Gabon)', 'fr_GF' => 'Tiếng Pháp (Guiana thuộc Pháp)', 'fr_GN' => 'Tiếng Pháp (Guinea)', 'fr_GP' => 'Tiếng Pháp (Guadeloupe)', 'fr_GQ' => 'Tiếng Pháp (Guinea Xích Đạo)', 'fr_HT' => 'Tiếng Pháp (Haiti)', 'fr_KM' => 'Tiếng Pháp (Comoros)', 'fr_LU' => 'Tiếng Pháp (Luxembourg)', 'fr_MA' => 'Tiếng Pháp (Ma-rốc)', 'fr_MC' => 'Tiếng Pháp (Monaco)', 'fr_MF' => 'Tiếng Pháp (St. Martin)', 'fr_MG' => 'Tiếng Pháp (Madagascar)', 'fr_ML' => 'Tiếng Pháp (Mali)', 'fr_MQ' => 'Tiếng Pháp (Martinique)', 'fr_MR' => 'Tiếng Pháp (Mauritania)', 'fr_MU' => 'Tiếng Pháp (Mauritius)', 'fr_NC' => 'Tiếng Pháp (New Caledonia)', 'fr_NE' => 'Tiếng Pháp (Niger)', 'fr_PF' => 'Tiếng Pháp (Polynesia thuộc Pháp)', 'fr_PM' => 'Tiếng Pháp (Saint Pierre và Miquelon)', 'fr_RE' => 'Tiếng Pháp (Réunion)', 'fr_RW' => 'Tiếng Pháp (Rwanda)', 'fr_SC' => 'Tiếng Pháp (Seychelles)', 'fr_SN' => 'Tiếng Pháp (Senegal)', 'fr_SY' => 'Tiếng Pháp (Syria)', 'fr_TD' => 'Tiếng Pháp (Chad)', 'fr_TG' => 'Tiếng Pháp (Togo)', 'fr_TN' => 'Tiếng Pháp (Tunisia)', 'fr_VU' => 'Tiếng Pháp (Vanuatu)', 'fr_WF' => 'Tiếng Pháp (Wallis và Futuna)', 'fr_YT' => 'Tiếng Pháp (Mayotte)', 'fy' => 'Tiếng Frisia', 'fy_NL' => 'Tiếng Frisia (Hà Lan)', 'ga' => 'Tiếng Ireland', 'ga_GB' => 'Tiếng Ireland (Vương quốc Anh)', 'ga_IE' => 'Tiếng Ireland (Ireland)', 'gd' => 'Tiếng Gael Scotland', 'gd_GB' => 'Tiếng Gael Scotland (Vương quốc Anh)', 'gl' => 'Tiếng Galician', 'gl_ES' => 'Tiếng Galician (Tây Ban Nha)', 'gu' => 'Tiếng Gujarati', 'gu_IN' => 'Tiếng Gujarati (Ấn Độ)', 'gv' => 'Tiếng Manx', 'gv_IM' => 'Tiếng Manx (Đảo Man)', 'ha' => 'Tiếng Hausa', 'ha_GH' => 'Tiếng Hausa (Ghana)', 'ha_NE' => 'Tiếng Hausa (Niger)', 'ha_NG' => 'Tiếng Hausa (Nigeria)', 'he' => 'Tiếng Do Thái', 'he_IL' => 'Tiếng Do Thái (Israel)', 'hi' => 'Tiếng Hindi', 'hi_IN' => 'Tiếng Hindi (Ấn Độ)', 'hr' => 'Tiếng Croatia', 'hr_BA' => 'Tiếng Croatia (Bosnia và Herzegovina)', 'hr_HR' => 'Tiếng Croatia (Croatia)', 'hu' => 'Tiếng Hungary', 'hu_HU' => 'Tiếng Hungary (Hungary)', 'hy' => 'Tiếng Armenia', 'hy_AM' => 'Tiếng Armenia (Armenia)', 'ia' => 'Tiếng Khoa Học Quốc Tế', 'ia_001' => 'Tiếng Khoa Học Quốc Tế (Thế giới)', 'id' => 'Tiếng Indonesia', 'id_ID' => 'Tiếng Indonesia (Indonesia)', 'ig' => 'Tiếng Igbo', 'ig_NG' => 'Tiếng Igbo (Nigeria)', 'ii' => 'Tiếng Di Tứ Xuyên', 'ii_CN' => 'Tiếng Di Tứ Xuyên (Trung Quốc)', 'is' => 'Tiếng Iceland', 'is_IS' => 'Tiếng Iceland (Iceland)', 'it' => 'Tiếng Italy', 'it_CH' => 'Tiếng Italy (Thụy Sĩ)', 'it_IT' => 'Tiếng Italy (Italy)', 'it_SM' => 'Tiếng Italy (San Marino)', 'it_VA' => 'Tiếng Italy (Thành Vatican)', 'ja' => 'Tiếng Nhật', 'ja_JP' => 'Tiếng Nhật (Nhật Bản)', 'jv' => 'Tiếng Java', 'jv_ID' => 'Tiếng Java (Indonesia)', 'ka' => 'Tiếng Georgia', 'ka_GE' => 'Tiếng Georgia (Georgia)', 'ki' => 'Tiếng Kikuyu', 'ki_KE' => 'Tiếng Kikuyu (Kenya)', 'kk' => 'Tiếng Kazakh', 'kk_KZ' => 'Tiếng Kazakh (Kazakhstan)', 'kl' => 'Tiếng Kalaallisut', 'kl_GL' => 'Tiếng Kalaallisut (Greenland)', 'km' => 'Tiếng Khmer', 'km_KH' => 'Tiếng Khmer (Campuchia)', 'kn' => 'Tiếng Kannada', 'kn_IN' => 'Tiếng Kannada (Ấn Độ)', 'ko' => 'Tiếng Hàn', 'ko_KP' => 'Tiếng Hàn (Triều Tiên)', 'ko_KR' => 'Tiếng Hàn (Hàn Quốc)', 'ks' => 'Tiếng Kashmir', 'ks_Arab' => 'Tiếng Kashmir (Chữ Ả Rập)', 'ks_Arab_IN' => 'Tiếng Kashmir (Chữ Ả Rập, Ấn Độ)', 'ks_IN' => 'Tiếng Kashmir (Ấn Độ)', 'ku' => 'Tiếng Kurd', 'ku_TR' => 'Tiếng Kurd (Thổ Nhĩ Kỳ)', 'kw' => 'Tiếng Cornwall', 'kw_GB' => 'Tiếng Cornwall (Vương quốc Anh)', 'ky' => 'Tiếng Kyrgyz', 'ky_KG' => 'Tiếng Kyrgyz (Kyrgyzstan)', 'lb' => 'Tiếng Luxembourg', 'lb_LU' => 'Tiếng Luxembourg (Luxembourg)', 'lg' => 'Tiếng Ganda', 'lg_UG' => 'Tiếng Ganda (Uganda)', 'ln' => 'Tiếng Lingala', 'ln_AO' => 'Tiếng Lingala (Angola)', 'ln_CD' => 'Tiếng Lingala (Congo - Kinshasa)', 'ln_CF' => 'Tiếng Lingala (Cộng hòa Trung Phi)', 'ln_CG' => 'Tiếng Lingala (Congo - Brazzaville)', 'lo' => 'Tiếng Lào', 'lo_LA' => 'Tiếng Lào (Lào)', 'lt' => 'Tiếng Litva', 'lt_LT' => 'Tiếng Litva (Litva)', 'lu' => 'Tiếng Luba-Katanga', 'lu_CD' => 'Tiếng Luba-Katanga (Congo - Kinshasa)', 'lv' => 'Tiếng Latvia', 'lv_LV' => 'Tiếng Latvia (Latvia)', 'mg' => 'Tiếng Malagasy', 'mg_MG' => 'Tiếng Malagasy (Madagascar)', 'mi' => 'Tiếng Māori', 'mi_NZ' => 'Tiếng Māori (New Zealand)', 'mk' => 'Tiếng Macedonia', 'mk_MK' => 'Tiếng Macedonia (Bắc Macedonia)', 'ml' => 'Tiếng Malayalam', 'ml_IN' => 'Tiếng Malayalam (Ấn Độ)', 'mn' => 'Tiếng Mông Cổ', 'mn_MN' => 'Tiếng Mông Cổ (Mông Cổ)', 'mr' => 'Tiếng Marathi', 'mr_IN' => 'Tiếng Marathi (Ấn Độ)', 'ms' => 'Tiếng Mã Lai', 'ms_BN' => 'Tiếng Mã Lai (Brunei)', 'ms_ID' => 'Tiếng Mã Lai (Indonesia)', 'ms_MY' => 'Tiếng Mã Lai (Malaysia)', 'ms_SG' => 'Tiếng Mã Lai (Singapore)', 'mt' => 'Tiếng Malta', 'mt_MT' => 'Tiếng Malta (Malta)', 'my' => 'Tiếng Miến Điện', 'my_MM' => 'Tiếng Miến Điện (Myanmar [Miến Điện])', 'nb' => 'Tiếng Na Uy [Bokmål]', 'nb_NO' => 'Tiếng Na Uy [Bokmål] (Na Uy)', 'nb_SJ' => 'Tiếng Na Uy [Bokmål] (Svalbard và Jan Mayen)', 'nd' => 'Tiếng Ndebele Miền Bắc', 'nd_ZW' => 'Tiếng Ndebele Miền Bắc (Zimbabwe)', 'ne' => 'Tiếng Nepal', 'ne_IN' => 'Tiếng Nepal (Ấn Độ)', 'ne_NP' => 'Tiếng Nepal (Nepal)', 'nl' => 'Tiếng Hà Lan', 'nl_AW' => 'Tiếng Hà Lan (Aruba)', 'nl_BE' => 'Tiếng Hà Lan (Bỉ)', 'nl_BQ' => 'Tiếng Hà Lan (Ca-ri-bê Hà Lan)', 'nl_CW' => 'Tiếng Hà Lan (Curaçao)', 'nl_NL' => 'Tiếng Hà Lan (Hà Lan)', 'nl_SR' => 'Tiếng Hà Lan (Suriname)', 'nl_SX' => 'Tiếng Hà Lan (Sint Maarten)', 'nn' => 'Tiếng Na Uy [Nynorsk]', 'nn_NO' => 'Tiếng Na Uy [Nynorsk] (Na Uy)', 'no' => 'Tiếng Na Uy', 'no_NO' => 'Tiếng Na Uy (Na Uy)', 'om' => 'Tiếng Oromo', 'om_ET' => 'Tiếng Oromo (Ethiopia)', 'om_KE' => 'Tiếng Oromo (Kenya)', 'or' => 'Tiếng Odia', 'or_IN' => 'Tiếng Odia (Ấn Độ)', 'os' => 'Tiếng Ossetic', 'os_GE' => 'Tiếng Ossetic (Georgia)', 'os_RU' => 'Tiếng Ossetic (Nga)', 'pa' => 'Tiếng Punjab', 'pa_Arab' => 'Tiếng Punjab (Chữ Ả Rập)', 'pa_Arab_PK' => 'Tiếng Punjab (Chữ Ả Rập, Pakistan)', 'pa_Guru' => 'Tiếng Punjab (Chữ Gurmukhi)', 'pa_Guru_IN' => 'Tiếng Punjab (Chữ Gurmukhi, Ấn Độ)', 'pa_IN' => 'Tiếng Punjab (Ấn Độ)', 'pa_PK' => 'Tiếng Punjab (Pakistan)', 'pl' => 'Tiếng Ba Lan', 'pl_PL' => 'Tiếng Ba Lan (Ba Lan)', 'ps' => 'Tiếng Pashto', 'ps_AF' => 'Tiếng Pashto (Afghanistan)', 'ps_PK' => 'Tiếng Pashto (Pakistan)', 'pt' => 'Tiếng Bồ Đào Nha', 'pt_AO' => 'Tiếng Bồ Đào Nha (Angola)', 'pt_BR' => 'Tiếng Bồ Đào Nha (Brazil)', 'pt_CH' => 'Tiếng Bồ Đào Nha (Thụy Sĩ)', 'pt_CV' => 'Tiếng Bồ Đào Nha (Cape Verde)', 'pt_GQ' => 'Tiếng Bồ Đào Nha (Guinea Xích Đạo)', 'pt_GW' => 'Tiếng Bồ Đào Nha (Guinea-Bissau)', 'pt_LU' => 'Tiếng Bồ Đào Nha (Luxembourg)', 'pt_MO' => 'Tiếng Bồ Đào Nha (Đặc khu Hành chính Macao, Trung Quốc)', 'pt_MZ' => 'Tiếng Bồ Đào Nha (Mozambique)', 'pt_PT' => 'Tiếng Bồ Đào Nha (Bồ Đào Nha)', 'pt_ST' => 'Tiếng Bồ Đào Nha (São Tomé và Príncipe)', 'pt_TL' => 'Tiếng Bồ Đào Nha (Timor-Leste)', 'qu' => 'Tiếng Quechua', 'qu_BO' => 'Tiếng Quechua (Bolivia)', 'qu_EC' => 'Tiếng Quechua (Ecuador)', 'qu_PE' => 'Tiếng Quechua (Peru)', 'rm' => 'Tiếng Romansh', 'rm_CH' => 'Tiếng Romansh (Thụy Sĩ)', 'rn' => 'Tiếng Rundi', 'rn_BI' => 'Tiếng Rundi (Burundi)', 'ro' => 'Tiếng Romania', 'ro_MD' => 'Tiếng Romania (Moldova)', 'ro_RO' => 'Tiếng Romania (Romania)', 'ru' => 'Tiếng Nga', 'ru_BY' => 'Tiếng Nga (Belarus)', 'ru_KG' => 'Tiếng Nga (Kyrgyzstan)', 'ru_KZ' => 'Tiếng Nga (Kazakhstan)', 'ru_MD' => 'Tiếng Nga (Moldova)', 'ru_RU' => 'Tiếng Nga (Nga)', 'ru_UA' => 'Tiếng Nga (Ukraina)', 'rw' => 'Tiếng Kinyarwanda', 'rw_RW' => 'Tiếng Kinyarwanda (Rwanda)', 'sa' => 'Tiếng Phạn', 'sa_IN' => 'Tiếng Phạn (Ấn Độ)', 'sc' => 'Tiếng Sardinia', 'sc_IT' => 'Tiếng Sardinia (Italy)', 'sd' => 'Tiếng Sindhi', 'sd_Arab' => 'Tiếng Sindhi (Chữ Ả Rập)', 'sd_Arab_PK' => 'Tiếng Sindhi (Chữ Ả Rập, Pakistan)', 'sd_Deva' => 'Tiếng Sindhi (Chữ Devanagari)', 'sd_Deva_IN' => 'Tiếng Sindhi (Chữ Devanagari, Ấn Độ)', 'sd_PK' => 'Tiếng Sindhi (Pakistan)', 'se' => 'Tiếng Sami Miền Bắc', 'se_FI' => 'Tiếng Sami Miền Bắc (Phần Lan)', 'se_NO' => 'Tiếng Sami Miền Bắc (Na Uy)', 'se_SE' => 'Tiếng Sami Miền Bắc (Thụy Điển)', 'sg' => 'Tiếng Sango', 'sg_CF' => 'Tiếng Sango (Cộng hòa Trung Phi)', 'sh' => 'Tiếng Serbo-Croatia', 'sh_BA' => 'Tiếng Serbo-Croatia (Bosnia và Herzegovina)', 'si' => 'Tiếng Sinhala', 'si_LK' => 'Tiếng Sinhala (Sri Lanka)', 'sk' => 'Tiếng Slovak', 'sk_SK' => 'Tiếng Slovak (Slovakia)', 'sl' => 'Tiếng Slovenia', 'sl_SI' => 'Tiếng Slovenia (Slovenia)', 'sn' => 'Tiếng Shona', 'sn_ZW' => 'Tiếng Shona (Zimbabwe)', 'so' => 'Tiếng Somali', 'so_DJ' => 'Tiếng Somali (Djibouti)', 'so_ET' => 'Tiếng Somali (Ethiopia)', 'so_KE' => 'Tiếng Somali (Kenya)', 'so_SO' => 'Tiếng Somali (Somalia)', 'sq' => 'Tiếng Albania', 'sq_AL' => 'Tiếng Albania (Albania)', 'sq_MK' => 'Tiếng Albania (Bắc Macedonia)', 'sr' => 'Tiếng Serbia', 'sr_BA' => 'Tiếng Serbia (Bosnia và Herzegovina)', 'sr_Cyrl' => 'Tiếng Serbia (Chữ Kirin)', 'sr_Cyrl_BA' => 'Tiếng Serbia (Chữ Kirin, Bosnia và Herzegovina)', 'sr_Cyrl_ME' => 'Tiếng Serbia (Chữ Kirin, Montenegro)', 'sr_Cyrl_RS' => 'Tiếng Serbia (Chữ Kirin, Serbia)', 'sr_Latn' => 'Tiếng Serbia (Chữ La tinh)', 'sr_Latn_BA' => 'Tiếng Serbia (Chữ La tinh, Bosnia và Herzegovina)', 'sr_Latn_ME' => 'Tiếng Serbia (Chữ La tinh, Montenegro)', 'sr_Latn_RS' => 'Tiếng Serbia (Chữ La tinh, Serbia)', 'sr_ME' => 'Tiếng Serbia (Montenegro)', 'sr_RS' => 'Tiếng Serbia (Serbia)', 'su' => 'Tiếng Sunda', 'su_ID' => 'Tiếng Sunda (Indonesia)', 'su_Latn' => 'Tiếng Sunda (Chữ La tinh)', 'su_Latn_ID' => 'Tiếng Sunda (Chữ La tinh, Indonesia)', 'sv' => 'Tiếng Thụy Điển', 'sv_AX' => 'Tiếng Thụy Điển (Quần đảo Åland)', 'sv_FI' => 'Tiếng Thụy Điển (Phần Lan)', 'sv_SE' => 'Tiếng Thụy Điển (Thụy Điển)', 'sw' => 'Tiếng Swahili', 'sw_CD' => 'Tiếng Swahili (Congo - Kinshasa)', 'sw_KE' => 'Tiếng Swahili (Kenya)', 'sw_TZ' => 'Tiếng Swahili (Tanzania)', 'sw_UG' => 'Tiếng Swahili (Uganda)', 'ta' => 'Tiếng Tamil', 'ta_IN' => 'Tiếng Tamil (Ấn Độ)', 'ta_LK' => 'Tiếng Tamil (Sri Lanka)', 'ta_MY' => 'Tiếng Tamil (Malaysia)', 'ta_SG' => 'Tiếng Tamil (Singapore)', 'te' => 'Tiếng Telugu', 'te_IN' => 'Tiếng Telugu (Ấn Độ)', 'tg' => 'Tiếng Tajik', 'tg_TJ' => 'Tiếng Tajik (Tajikistan)', 'th' => 'Tiếng Thái', 'th_TH' => 'Tiếng Thái (Thái Lan)', 'ti' => 'Tiếng Tigrinya', 'ti_ER' => 'Tiếng Tigrinya (Eritrea)', 'ti_ET' => 'Tiếng Tigrinya (Ethiopia)', 'tk' => 'Tiếng Turkmen', 'tk_TM' => 'Tiếng Turkmen (Turkmenistan)', 'tl' => 'Tiếng Tagalog', 'tl_PH' => 'Tiếng Tagalog (Philippines)', 'to' => 'Tiếng Tonga', 'to_TO' => 'Tiếng Tonga (Tonga)', 'tr' => 'Tiếng Thổ Nhĩ Kỳ', 'tr_CY' => 'Tiếng Thổ Nhĩ Kỳ (Síp)', 'tr_TR' => 'Tiếng Thổ Nhĩ Kỳ (Thổ Nhĩ Kỳ)', 'tt' => 'Tiếng Tatar', 'tt_RU' => 'Tiếng Tatar (Nga)', 'ug' => 'Tiếng Uyghur', 'ug_CN' => 'Tiếng Uyghur (Trung Quốc)', 'uk' => 'Tiếng Ukraina', 'uk_UA' => 'Tiếng Ukraina (Ukraina)', 'ur' => 'Tiếng Urdu', 'ur_IN' => 'Tiếng Urdu (Ấn Độ)', 'ur_PK' => 'Tiếng Urdu (Pakistan)', 'uz' => 'Tiếng Uzbek', 'uz_AF' => 'Tiếng Uzbek (Afghanistan)', 'uz_Arab' => 'Tiếng Uzbek (Chữ Ả Rập)', 'uz_Arab_AF' => 'Tiếng Uzbek (Chữ Ả Rập, Afghanistan)', 'uz_Cyrl' => 'Tiếng Uzbek (Chữ Kirin)', 'uz_Cyrl_UZ' => 'Tiếng Uzbek (Chữ Kirin, Uzbekistan)', 'uz_Latn' => 'Tiếng Uzbek (Chữ La tinh)', 'uz_Latn_UZ' => 'Tiếng Uzbek (Chữ La tinh, Uzbekistan)', 'uz_UZ' => 'Tiếng Uzbek (Uzbekistan)', 'vi' => 'Tiếng Việt', 'vi_VN' => 'Tiếng Việt (Việt Nam)', 'wo' => 'Tiếng Wolof', 'wo_SN' => 'Tiếng Wolof (Senegal)', 'xh' => 'Tiếng Xhosa', 'xh_ZA' => 'Tiếng Xhosa (Nam Phi)', 'yi' => 'Tiếng Yiddish', 'yi_001' => 'Tiếng Yiddish (Thế giới)', 'yo' => 'Tiếng Yoruba', 'yo_BJ' => 'Tiếng Yoruba (Benin)', 'yo_NG' => 'Tiếng Yoruba (Nigeria)', 'zh' => 'Tiếng Trung', 'zh_CN' => 'Tiếng Trung (Trung Quốc)', 'zh_HK' => 'Tiếng Trung (Đặc khu Hành chính Hồng Kông, Trung Quốc)', 'zh_Hans' => 'Tiếng Trung (Giản thể)', 'zh_Hans_CN' => 'Tiếng Trung (Giản thể, Trung Quốc)', 'zh_Hans_HK' => 'Tiếng Trung (Giản thể, Đặc khu Hành chính Hồng Kông, Trung Quốc)', 'zh_Hans_MO' => 'Tiếng Trung (Giản thể, Đặc khu Hành chính Macao, Trung Quốc)', 'zh_Hans_SG' => 'Tiếng Trung (Giản thể, Singapore)', 'zh_Hant' => 'Tiếng Trung (Phồn thể)', 'zh_Hant_HK' => 'Tiếng Trung (Phồn thể, Đặc khu Hành chính Hồng Kông, Trung Quốc)', 'zh_Hant_MO' => 'Tiếng Trung (Phồn thể, Đặc khu Hành chính Macao, Trung Quốc)', 'zh_Hant_TW' => 'Tiếng Trung (Phồn thể, Đài Loan)', 'zh_MO' => 'Tiếng Trung (Đặc khu Hành chính Macao, Trung Quốc)', 'zh_SG' => 'Tiếng Trung (Singapore)', 'zh_TW' => 'Tiếng Trung (Đài Loan)', 'zu' => 'Tiếng Zulu', 'zu_ZA' => 'Tiếng Zulu (Nam Phi)', ], ];
derrabus/symfony
src/Symfony/Component/Intl/Resources/data/locales/vi.php
PHP
mit
30,213
using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Formatting; namespace RefactoringEssentials.CSharp.CodeRefactorings { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert '??' to '?:'")] public class ConvertCoalescingToConditionalExpressionCodeRefactoringProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var span = context.Span; if (!span.IsEmpty) return; var cancellationToken = context.CancellationToken; if (cancellationToken.IsCancellationRequested) return; var root = await document.GetSyntaxRootAsync(cancellationToken); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (model.IsFromGeneratedCode(cancellationToken)) return; var node = root.FindNode(span) as BinaryExpressionSyntax; if (node == null || !node.OperatorToken.IsKind(SyntaxKind.QuestionQuestionToken)) return; context.RegisterRefactoring( CodeActionFactory.Create( span, DiagnosticSeverity.Info, GettextCatalog.GetString("Replace '??' operator with '?:' expression"), t2 => { var left = node.Left; var info = model.GetTypeInfo(left, t2); if (info.ConvertedType.IsNullableType()) left = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, FlipEqualsTargetAndArgumentCodeRefactoringProvider.AddParensIfRequired(left), SyntaxFactory.IdentifierName("Value")); var ternary = SyntaxFactory.ConditionalExpression( SyntaxFactory.BinaryExpression( SyntaxKind.NotEqualsExpression, node.Left, SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression) ), left, node.Right ).WithAdditionalAnnotations(Formatter.Annotation); return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode((SyntaxNode)node, (ExpressionSyntax)ternary))); } ) ); } } }
mrward/RefactoringEssentials
RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertCoalescingToConditionalExpressionCodeRefactoringProvider.cs
C#
mit
2,856
// DOM elements var $source; var $photographer; var $save; var $textColor; var $logo; var $crop; var $logoColor; var $imageLoader; var $imageLink; var $imageLinkButton; var $canvas; var canvas; var $qualityQuestions; var $copyrightHolder; var $dragHelp; var $filename; var $fileinput; var $customFilename; // Constants var IS_MOBILE = Modernizr.touch && Modernizr.mq('screen and max-width(700px)'); var MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif']; // state var scaledImageHeight; var scaledImageWidth; var previewScale = IS_MOBILE ? 0.32 : 0.64; var dy = 0; var dx = 0; var image; var imageFilename = 'image'; var currentCopyright; var credit = 'Belal Khan/Flickr' var shallowImage = false; // JS objects var ctx; var img = new Image(); var logo = new Image(); var onDocumentLoad = function(e) { $source = $('#source'); $photographer = $('#photographer'); $canvas = $('#imageCanvas'); canvas = $canvas[0]; $imageLoader = $('#imageLoader'); $imageLink = $('#imageLink'); $imageLinkButton = $('#imageLinkButton'); ctx = canvas.getContext('2d'); $save = $('.save-btn'); $textColor = $('input[name="textColor"]'); $crop = $('input[name="crop"]'); $logoColor = $('input[name="logoColor"]'); $qualityQuestions = $('.quality-question'); $copyrightHolder = $('.copyright-holder'); $dragHelp = $('.drag-help'); $filename = $('.fileinput-filename'); $fileinput = $('.fileinput'); $customFilename = $('.custom-filename'); $logosWrapper = $('.logos-wrapper'); img.src = defaultImage; img.onload = onImageLoad; logo.src = defaultLogo; logo.onload = renderCanvas; $photographer.on('keyup', renderCanvas); $source.on('keyup', renderCanvas); $imageLoader.on('change', handleImage); $imageLinkButton.on('click', handleImageLink); $save.on('click', onSaveClick); $textColor.on('change', onTextColorChange); $logoColor.on('change', onLogoColorChange); $crop.on('change', onCropChange); $canvas.on('mousedown touchstart', onDrag); $copyrightHolder.on('change', onCopyrightChange); $customFilename.on('click', function(e) { e.stopPropagation(); }) $("body").on("contextmenu", "canvas", function(e) { return false; }); $imageLink.keypress(function(e) { if (e.keyCode == 13) { handleImageLink(); } }); // $imageLink.on('paste', handleImageLink); $(window).on('resize', resizeCanvas); resizeCanvas(); buildForm(); } var resizeCanvas = function() { var scale = $('.canvas-cell').width() / canvasWidth; $canvas.css({ 'webkitTransform': 'scale(' + scale + ')', 'MozTransform': 'scale(' + scale + ')', 'msTransform': 'scale(' + scale + ')', 'OTransform': 'scale(' + scale + ')', 'transform': 'scale(' + scale + ')' }); renderCanvas(); } var buildForm = function() { var copyrightKeys = Object.keys(copyrightOptions); var logoKeys = Object.keys(logos); for (var i = 0; i < copyrightKeys.length; i++) { var key = copyrightKeys[i]; var display = copyrightOptions[key]['display']; $copyrightHolder.append('<option value="' + key + '">' + display + '</option>'); } if (logoKeys.length > 1) { $logosWrapper.append('<div class="btn-group btn-group-justified btn-group-sm logos" data-toggle="buttons"></div>'); var $logos = $('.logos'); for (var j = 0; j < logoKeys.length; j++) { var key = logoKeys[j]; var display = logos[key]['display'] $logos.append('<label class="btn btn-primary"><input type="radio" name="logo" id="' + key + '" value="' + key + '">' + display + '</label>'); disableLogo(); if (key === currentLogo) { $('#' + key).attr('checked', true); $('#' + key).parent('.btn').addClass('active'); } } $logo = $('input[name="logo"]'); $logo.on('change', onLogoChange); } else { $logosWrapper.hide(); } } /* * Draw the image, then the logo, then the text */ var renderCanvas = function() { // canvas is always the same width canvas.width = canvasWidth; // if we're cropping, use the aspect ratio for the height if (currentCrop !== 'original') { canvas.height = canvasWidth / (16/9); } // clear the canvas ctx.clearRect(0,0,canvas.width,canvas.height); // determine height of canvas and scaled image, then draw the image var imageAspect = img.width / img.height; if (currentCrop === 'original') { canvas.height = canvasWidth / imageAspect; scaledImageHeight = canvas.height; ctx.drawImage( img, 0, 0, canvasWidth, scaledImageHeight ); } else { if (img.width / img.height > canvas.width / canvas.height) { shallowImage = true; scaledImageHeight = canvasWidth / imageAspect; scaledImageWidth = canvas.height * (img.width / img.height) ctx.drawImage( img, 0, 0, img.width, img.height, dx, dy, scaledImageWidth, canvas.height ); } else { shallowImage = false; scaledImageHeight = canvasWidth / imageAspect; ctx.drawImage( img, 0, 0, img.width, img.height, dx, dy, canvasWidth, scaledImageHeight ); } } // set alpha channel, draw the logo if (currentLogoColor === 'white') { ctx.globalAlpha = whiteLogoAlpha; } else { ctx.globalAlpha = blackLogoAlpha; } ctx.drawImage( logo, elementPadding, currentLogo === 'npr'? elementPadding : elementPadding - 14, logos[currentLogo]['w'], logos[currentLogo]['h'] ); // reset alpha channel so text is not translucent ctx.globalAlpha = "1"; // draw the text ctx.textBaseline = 'bottom'; ctx.textAlign = 'left'; ctx.fillStyle = currentTextColor; ctx.font = fontWeight + ' ' + fontSize + ' ' + fontFace; if (currentTextColor === 'white') { ctx.shadowColor = fontShadow; ctx.shadowOffsetX = fontShadowOffsetX; ctx.shadowOffsetY = fontShadowOffsetY; ctx.shadowBlur = fontShadowBlur; } if (currentCopyright) { credit = buildCreditString(); } var creditWidth = ctx.measureText(credit); ctx.fillText( credit, canvas.width - (creditWidth.width + elementPadding), canvas.height - elementPadding ); validateForm(); } /* * Build the proper format for the credit based on current copyright */ var buildCreditString = function() { var creditString; var val = $copyrightHolder.val(); if ($photographer.val() !== '') { if (copyrightOptions[val]['source']) { creditString = $photographer.val() + '/' + copyrightOptions[val]['source']; } else { creditString = $photographer.val() + '/' + $source.val(); } } else { if (copyrightOptions[val]['source']) { creditString = copyrightOptions[val]['source']; } else { creditString = $source.val(); } } if (copyrightOptions[val]['photographerRequired']) { if ($photographer.val() !== '') { $photographer.parents('.form-group').removeClass('has-warning'); } else { $photographer.parents('.form-group').addClass('has-warning'); } } if (copyrightOptions[val]['sourceRequired']) { if ($source.val() !== '') { $source.parents('.form-group').removeClass('has-warning'); } else { $source.parents('.form-group').addClass('has-warning'); } } return creditString; } /* * Check to see if any required fields have not been * filled out before enabling saving */ var validateForm = function() { if ($('.has-warning').length === 0 && currentCopyright) { $save.removeAttr('disabled'); $("body").off("contextmenu", "canvas"); } else { $save.attr('disabled', ''); $("body").on("contextmenu", "canvas", function(e) { return false; }); } } /* * Handle dragging the image for crops when applicable */ var onDrag = function(e) { e.preventDefault(); var originY = e.clientY||e.originalEvent.targetTouches[0].clientY; originY = originY/previewScale; var originX = e.clientX||e.originalEvent.targetTouches[0].clientX; originX = originX/previewScale; var startY = dy; var startX = dx; if (currentCrop === 'original') { return; } function update(e) { var dragY = e.clientY||e.originalEvent.targetTouches[0].clientY; dragY = dragY/previewScale; var dragX = e.clientX||e.originalEvent.targetTouches[0].clientX; dragX = dragX/previewScale; if (shallowImage === false) { if (Math.abs(dragY - originY) > 1) { dy = startY - (originY - dragY); // Prevent dragging image below upper bound if (dy > 0) { dy = 0; return; } // Prevent dragging image above lower bound if (dy < canvas.height - scaledImageHeight) { dy = canvas.height - scaledImageHeight; return; } renderCanvas(); } } else { if (Math.abs(dragX - originX) > 1) { dx = startX - (originX - dragX); // Prevent dragging image below left bound if (dx > 0) { dx = 0; return; } // Prevent dragging image above right bound if (dx < canvas.width - scaledImageWidth) { dx = canvas.width - scaledImageWidth; return; } renderCanvas(); } } } // Perform drag sequence: $(document).on('mousemove.drag touchmove', _.debounce(update, 5, true)) .on('mouseup.drag touchend', function(e) { $(document).off('mouseup.drag touchmove mousemove.drag'); update(e); }); } /* * Take an image from file input and load it */ var handleImage = function(e) { var reader = new FileReader(); reader.onload = function(e){ // reset dy value dy = 0; dx = 0; image = e.target.result; imageFilename = $('.fileinput-filename').text().split('.')[0]; img.src = image; $customFilename.text(imageFilename); $customFilename.parents('.form-group').addClass('has-file'); $imageLink.val(''); $imageLink.parents('.form-group').removeClass('has-file'); } reader.readAsDataURL(e.target.files[0]); } /* * Load a remote image */ var handleImageLink = function(e) { var requestStatus = // Test if image URL returns a 200 $.ajax({ url: $imageLink.val(), success: function(data, status, xhr) { var responseType = xhr.getResponseHeader('content-type').toLowerCase(); // if content type is jpeg, gif or png, load the image into the canvas if (MIME_TYPES.indexOf(responseType) >= 0) { // reset dy value dy = 0; dx = 0; $fileinput.fileinput('clear'); $imageLink.parents('.form-group').addClass('has-file').removeClass('has-error'); $imageLink.parents('.input-group').next().text('Click to edit name'); img.src = $imageLink.val(); img.crossOrigin = "anonymous" var filename = $imageLink.val().split('/'); imageFilename = filename[filename.length - 1].split('.')[0]; $imageLink.val(imageFilename); // otherwise, display an error } else { $imageLink.parents('.form-group').addClass('has-error'); $imageLink.parents('.input-group').next().text('Not a valid image URL'); return; } }, error: function(data) { $imageLink.parents('.form-group').addClass('has-error'); $imageLink.parents('.input-group').next().text('Not a valid image URL'); } }); } /* * Set dragging status based on image aspect ratio and render canvas */ var onImageLoad = function(e) { renderCanvas(); onCropChange(); } /* * Load the logo based on radio buttons */ var loadLogo = function() { if (currentLogoColor === 'white') { logo.src = logos[currentLogo]['whitePath']; } else { logo.src = logos[currentLogo]['blackPath']; } disableLogo(); } /* * If image paths not defined for the logo, grey it out */ var disableLogo = function(){ var whiteLogo = logos[currentLogo]['whitePath'] var blackLogo = logos[currentLogo]['blackPath'] if(typeof(whiteLogo) == "undefined"){ $("#whiteLogo").parent().addClass("disabled") }else{ $("#whiteLogo").parent().removeClass("disabled") } if(typeof(blackLogo) == "undefined"){ $("#blackLogo").parent().addClass("disabled") }else{ $("#blackLogo").parent().removeClass("disabled") } } /* * Download the image on save click */ var onSaveClick = function(e) { e.preventDefault(); /// create an "off-screen" anchor tag var link = document.createElement('a'), e; /// the key here is to set the download attribute of the a tag if ($customFilename.text()) { imageFilename = $customFilename.text(); } if ($imageLink.val() !== "") { var filename = $imageLink.val().split('/'); imageFilename = filename[filename.length - 1].split('.')[0]; } link.download = 'waterbug-' + imageFilename + '.png'; /// convert canvas content to data-uri for link. When download /// attribute is set the content pointed to by link will be /// pushed as "download" in HTML5 capable browsers link.href = canvas.toDataURL(); link.target = "_blank"; /// create a "fake" click-event to trigger the download if (document.createEvent) { e = document.createEvent("MouseEvents"); e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); link.dispatchEvent(e); } else if (link.fireEvent) { link.fireEvent("onclick"); } } /* * Handle logo radio button clicks */ var onLogoColorChange = function(e) { currentLogoColor = $(this).val(); loadLogo(); renderCanvas(); } /* * Handle text color radio button clicks */ var onTextColorChange = function(e) { currentTextColor = $(this).val(); renderCanvas(); } /* * Handle logo radio button clicks */ var onLogoChange = function(e) { currentLogo = $(this).val(); loadLogo(); renderCanvas(); } /* * Handle crop radio button clicks */ var onCropChange = function() { currentCrop = $crop.filter(':checked').val(); if (currentCrop !== 'original') { var dragClass = shallowImage ? 'is-draggable shallow' : 'is-draggable'; $canvas.addClass(dragClass); $dragHelp.show(); } else { $canvas.removeClass('is-draggable shallow'); $dragHelp.hide(); } renderCanvas(); } /* * Show the appropriate fields based on the chosen copyright */ var onCopyrightChange = function() { currentCopyright = $copyrightHolder.val(); $photographer.parents('.form-group').removeClass('has-warning'); $source.parents('.form-group').removeClass('has-warning'); if (copyrightOptions[currentCopyright]) { if (copyrightOptions[currentCopyright]['showPhotographer']) { $photographer.parents('.form-group').slideDown(); if (copyrightOptions[currentCopyright]['photographerRequired']) { $photographer.parents('.form-group').addClass('has-warning required'); } else { $photographer.parents('.form-group').removeClass('required') } } else { $photographer.parents('.form-group').slideUp(); } if (copyrightOptions[currentCopyright]['showSource']) { $source.parents('.form-group').slideDown(); if (copyrightOptions[currentCopyright]['sourceRequired']) { $source.parents('.form-group').addClass('has-warning required'); } else { $source.parents('.form-group').removeClass('required') } } else { $source.parents('.form-group').slideUp(); } } else { $photographer.parents('.form-group').slideUp(); $source.parents('.form-group').slideUp(); credit = ''; } // if (currentCopyright === 'npr') { // $photographer.parents('.form-group').removeClass('required').slideDown(); // $source.parents('.form-group').slideUp(); // } else if (currentCopyright === 'freelance') { // $photographer.parents('.form-group').slideDown(); // $source.parents('.form-group').slideUp(); // $photographer.parents('.form-group').addClass('has-warning required'); // } else if (currentCopyright === 'ap' || currentCopyright === 'getty') { // $photographer.parents('.form-group').removeClass('required').slideDown(); // $source.parents('.form-group') // .slideUp() // .removeClass('has-warning required'); // } else if (currentCopyright === 'third-party') { // $photographer.parents('.form-group').removeClass('required').slideDown(); // $source.parents('.form-group').slideDown(); // $source.parents('.form-group').addClass('has-warning required'); // } else { // credit = ''; // $photographer.parents('.form-group').slideUp(); // $source.parents('.form-group') // .slideUp() // .parents('.form-group').removeClass('has-warning required'); // } renderCanvas(); } $(onDocumentLoad);
mcclatchy/lunchbox
www/js/waterbug.js
JavaScript
mit
18,520
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * 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. * * 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. */ #include "native_thread.cpp" #include "nsk_tools.cpp" #include "jni_tools.cpp" #include "jvmti_tools.cpp" #include "agent_tools.cpp" #include "jvmti_FollowRefObjects.cpp" #include "Injector.cpp" #include "JVMTITools.cpp" #include "agent_common.cpp" #include "thrstat003.cpp"
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/jvmti/GetThreadState/thrstat003/libthrstat003.cpp
C++
gpl-2.0
1,327
<?php namespace Drupal\node\Plugin\views\row; use Drupal\Core\Entity\EntityDisplayRepositoryInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\views\Plugin\views\row\RssPluginBase; /** * Plugin which performs a node_view on the resulting object * and formats it as an RSS item. * * @ViewsRow( * id = "node_rss", * title = @Translation("Content"), * help = @Translation("Display the content with standard node view."), * theme = "views_view_row_rss", * register_theme = FALSE, * base = {"node_field_data"}, * display_types = {"feed"} * ) */ class Rss extends RssPluginBase { // Basic properties that let the row style follow relationships. public $base_table = 'node_field_data'; public $base_field = 'nid'; // Stores the nodes loaded with preRender. public $nodes = []; /** * {@inheritdoc} */ protected $entityTypeId = 'node'; /** * The node storage * * @var \Drupal\node\NodeStorageInterface */ protected $nodeStorage; /** * Constructs the Rss object. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin_id for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager * The entity type manager. * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository * The entity display repository. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityDisplayRepositoryInterface $entity_display_repository = NULL) { parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_display_repository); $this->nodeStorage = $entity_type_manager->getStorage('node'); } /** * {@inheritdoc} */ public function buildOptionsForm_summary_options() { $options = parent::buildOptionsForm_summary_options(); $options['title'] = $this->t('Title only'); $options['default'] = $this->t('Use site default RSS settings'); return $options; } public function summaryTitle() { $options = $this->buildOptionsForm_summary_options(); return $options[$this->options['view_mode']]; } public function preRender($values) { $nids = []; foreach ($values as $row) { $nids[] = $row->{$this->field_alias}; } if (!empty($nids)) { $this->nodes = $this->nodeStorage->loadMultiple($nids); } } public function render($row) { global $base_url; $nid = $row->{$this->field_alias}; if (!is_numeric($nid)) { return; } $display_mode = $this->options['view_mode']; if ($display_mode == 'default') { $display_mode = \Drupal::config('system.rss')->get('items.view_mode'); } // Load the specified node: /** @var \Drupal\node\NodeInterface $node */ $node = $this->nodes[$nid]; if (empty($node)) { return; } $node->link = $node->toUrl('canonical', ['absolute' => TRUE])->toString(); $node->rss_namespaces = []; $node->rss_elements = [ [ 'key' => 'pubDate', 'value' => gmdate('r', $node->getCreatedTime()), ], [ 'key' => 'dc:creator', 'value' => $node->getOwner()->getDisplayName(), ], [ 'key' => 'guid', 'value' => $node->id() . ' at ' . $base_url, 'attributes' => ['isPermaLink' => 'false'], ], ]; // The node gets built and modules add to or modify $node->rss_elements // and $node->rss_namespaces. $build_mode = $display_mode; $build = node_view($node, $build_mode); unset($build['#theme']); if (!empty($node->rss_namespaces)) { $this->view->style_plugin->namespaces = array_merge($this->view->style_plugin->namespaces, $node->rss_namespaces); } elseif (function_exists('rdf_get_namespaces')) { // Merge RDF namespaces in the XML namespaces in case they are used // further in the RSS content. $xml_rdf_namespaces = []; foreach (rdf_get_namespaces() as $prefix => $uri) { $xml_rdf_namespaces['xmlns:' . $prefix] = $uri; } $this->view->style_plugin->namespaces += $xml_rdf_namespaces; } $item = new \stdClass(); if ($display_mode != 'title') { // We render node contents. $item->description = $build; } $item->title = $node->label(); $item->link = $node->link; // Provide a reference so that the render call in // template_preprocess_views_view_row_rss() can still access it. $item->elements = &$node->rss_elements; $item->nid = $node->id(); $build = [ '#theme' => $this->themeFunctions(), '#view' => $this->view, '#options' => $this->options, '#row' => $item, ]; return $build; } }
enslyon/ensl
core/modules/node/src/Plugin/views/row/Rss.php
PHP
gpl-2.0
4,982
/* This file is part of the KDE project Copyright (C) 2006-2007 Alfredo Beaumont Sainz <alfredo.beaumont@gmail.com> 2009 Jeremias Epperlein <jeeree@web.de> 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 "TokenElement.h" #include "AttributeManager.h" #include "FormulaCursor.h" #include "Dictionary.h" #include "GlyphElement.h" #include <KoXmlWriter.h> #include <KoXmlReader.h> #include <QPainter> #include <kdebug.h> TokenElement::TokenElement( BasicElement* parent ) : BasicElement( parent ) { m_stretchHorizontally = false; m_stretchVertically = false; } const QList<BasicElement*> TokenElement::childElements() const { // only return the mglyph elements QList<BasicElement*> tmpList; foreach( GlyphElement* tmp, m_glyphs ) tmpList << tmp; return tmpList; } void TokenElement::paint( QPainter& painter, AttributeManager* am ) { // set the painter to background color and paint it painter.setPen( am->colorOf( "mathbackground", this ) ); painter.setBrush( QBrush( painter.pen().color() ) ); painter.drawRect( QRectF( 0.0, 0.0, width(), height() ) ); // set the painter to foreground color and paint the text in the content path QColor color = am->colorOf( "mathcolor", this ); if (!color.isValid()) color = am->colorOf( "color", this ); painter.translate( m_xoffset, baseLine() ); if(m_stretchHorizontally || m_stretchVertically) painter.scale(width() / m_originalSize.width(), height() / m_originalSize.height()); painter.setPen( color ); painter.setBrush( QBrush( color ) ); painter.drawPath( m_contentPath ); } int TokenElement::endPosition() const { return m_rawString.length(); } void TokenElement::layout( const AttributeManager* am ) { m_offsets.erase(m_offsets.begin(),m_offsets.end()); m_offsets << 0.0; // Query the font to use m_font = am->font( this ); QFontMetricsF fm(m_font); // save the token in an empty path m_contentPath = QPainterPath(); /* Current bounding box. Note that the left can be negative, for italics etc */ QRectF boundingrect; if(m_glyphs.isEmpty()) {//optimize for the common case boundingrect = renderToPath(m_rawString, m_contentPath); for (int j = 0; j < m_rawString.length(); ++j) { m_offsets.append(fm.width(m_rawString.left(j+1))); } } else { // replace all the object replacement characters with glyphs // We have to keep track of the bounding box at all times QString chunk; int counter = 0; for( int i = 0; i < m_rawString.length(); i++ ) { if( m_rawString[ i ] != QChar::ObjectReplacementCharacter ) chunk.append( m_rawString[ i ] ); else { m_contentPath.moveTo(boundingrect.right(), 0); QRectF newbox = renderToPath( chunk, m_contentPath ); boundingrect.setRight( boundingrect.right() + newbox.right()); boundingrect.setTop( qMax(boundingrect.top(), newbox.top())); boundingrect.setBottom( qMax(boundingrect.bottom(), newbox.bottom())); qreal glyphoffset = m_offsets.last(); for (int j = 0; j < chunk.length(); ++j) { m_offsets << fm.width(chunk.left(j+1)) + glyphoffset; } m_contentPath.moveTo(boundingrect.right(), 0); newbox = m_glyphs[ counter ]->renderToPath( QString(), m_contentPath ); boundingrect.setRight( boundingrect.right() + newbox.right()); boundingrect.setTop( qMax(boundingrect.top(), newbox.top())); boundingrect.setBottom( qMax(boundingrect.bottom(), newbox.bottom())); m_offsets.append(newbox.width() + m_offsets.last()); counter++; chunk.clear(); } } if( !chunk.isEmpty() ) { m_contentPath.moveTo(boundingrect.right(), 0); QRectF newbox = renderToPath( chunk, m_contentPath ); boundingrect.setRight( boundingrect.right() + newbox.right()); boundingrect.setTop( qMax(boundingrect.top(), newbox.top())); boundingrect.setBottom( qMax(boundingrect.bottom(), newbox.bottom())); // qreal glyphoffset = m_offsets.last(); for (int j = 0; j < chunk.length(); ++j) { m_offsets << fm.width(chunk.left(j+1)) + m_offsets.last(); } } } //FIXME: This is only a temporary solution boundingrect=m_contentPath.boundingRect(); m_offsets.removeLast(); m_offsets.append(m_contentPath.boundingRect().right()); //The left side may be negative, because of italised letters etc. we need to adjust for this when painting //The qMax is just incase. The bounding box left should never be >0 m_xoffset = qMax(-boundingrect.left(), (qreal)0.0); // As the text is added to (0,0) the baseline equals the top edge of the // elements bounding rect, while translating it down the text's baseline moves too setBaseLine( -boundingrect.y() ); // set baseline accordingly setWidth( boundingrect.right() + m_xoffset ); setHeight( boundingrect.height() ); m_originalSize = QSizeF(width(), height()); } bool TokenElement::insertChild( int position, BasicElement* child ) { Q_UNUSED( position) Q_UNUSED( child ) //if( child && child->elementType() == Glyph ) { //m_rawString.insert( QChar( QChar::ObjectReplacementCharacter ) ); // m_glyphs.insert(); // return false; //} else { return false; //} } void TokenElement::insertGlyphs ( int position, QList< GlyphElement* > glyphs ) { for (int i=0; i < glyphs.length(); ++i) { m_glyphs.insert(position+i,glyphs[i]); } } bool TokenElement::insertText ( int position, const QString& text ) { m_rawString.insert (position,text); return true; } QList< GlyphElement* > TokenElement::glyphList ( int position, int length ) { QList<GlyphElement*> tmp; //find out, how many glyphs we have int counter=0; for (int i=position; i<position+length; ++i) { if (m_rawString[ position ] == QChar::ObjectReplacementCharacter) { counter++; } } int start=0; //find out where we should start removing glyphs if (counter>0) { for (int i=0; i<position; ++i) { if (m_rawString[position] == QChar::ObjectReplacementCharacter) { start++; } } } for (int i=start; i<start+counter; ++i) { tmp.append(m_glyphs.at(i)); } return tmp; } int TokenElement::removeText ( int position, int length ) { //find out, how many glyphs we have int counter=0; for (int i=position; i<position+length; ++i) { if (m_rawString[ position ] == QChar::ObjectReplacementCharacter) { counter++; } } int start=0; //find out where we should start removing glyphs if (counter>0) { for (int i=0; i<position; ++i) { if (m_rawString[position] == QChar::ObjectReplacementCharacter) { start++; } } } for (int i=start; i<start+counter; ++i) { m_glyphs.removeAt(i); } m_rawString.remove(position,length); return start; } bool TokenElement::setCursorTo(FormulaCursor& cursor, QPointF point) { int i = 0; cursor.setCurrentElement(this); if (cursorOffset(endPosition())<point.x()) { cursor.setPosition(endPosition()); return true; } //Find the letter we clicked on for( i = 1; i < endPosition(); ++i ) { if (point.x() < cursorOffset(i)) { break; } } //Find out, if we should place the cursor before or after the character if ((point.x()-cursorOffset(i-1))<(cursorOffset(i)-point.x())) { --i; } cursor.setPosition(i); return true; } QLineF TokenElement::cursorLine(int position) const { // inside tokens let the token calculate the cursor x offset qreal tmp = cursorOffset( position ); QPointF top = absoluteBoundingRect().topLeft() + QPointF( tmp, 0 ); QPointF bottom = top + QPointF( 0.0,height() ); return QLineF(top,bottom); } bool TokenElement::acceptCursor( const FormulaCursor& cursor ) { Q_UNUSED( cursor ) return true; } bool TokenElement::moveCursor(FormulaCursor& newcursor, FormulaCursor& oldcursor) { Q_UNUSED( oldcursor ) if ((newcursor.direction()==MoveUp) || (newcursor.direction()==MoveDown) || (newcursor.isHome() && newcursor.direction()==MoveLeft) || (newcursor.isEnd() && newcursor.direction()==MoveRight) ) { return false; } switch( newcursor.direction() ) { case MoveLeft: newcursor+=-1; break; case MoveRight: newcursor+=1; break; default: break; } return true; } qreal TokenElement::cursorOffset( const int position) const { return m_offsets[position]+m_xoffset; } QFont TokenElement::font() const { return m_font; } void TokenElement::setText ( const QString& text ) { removeText(0,m_rawString.length()); insertText(0,text); } const QString& TokenElement::text() { return m_rawString; } bool TokenElement::readMathMLContent( const KoXmlElement& element ) { // iterate over all child elements ( possible embedded glyphs ) and put the text // content in the m_rawString and mark glyph positions with // QChar::ObjectReplacementCharacter GlyphElement* tmpGlyph; KoXmlNode node = element.firstChild(); while( !node.isNull() ) { if( node.isElement() && node.toElement().tagName() == "mglyph" ) { tmpGlyph = new GlyphElement( this ); m_rawString.append( QChar( QChar::ObjectReplacementCharacter ) ); tmpGlyph->readMathML( node.toElement() ); m_glyphs.append(tmpGlyph); } else if( node.isElement() ) return false; /* else if (node.isEntityReference()) { Dictionary dict; m_rawString.append( dict.mapEntity( node.nodeName() ) ); } */ else { m_rawString.append( node.toText().data() ); } node = node.nextSibling(); } m_rawString = m_rawString.simplified(); return true; } void TokenElement::writeMathMLContent( KoXmlWriter* writer, const QString& ns ) const { // split the m_rawString into text content chunks that are divided by glyphs // which are represented as ObjectReplacementCharacter and write each chunk QStringList tmp = m_rawString.split( QChar( QChar::ObjectReplacementCharacter ) ); for ( int i = 0; i < tmp.count(); i++ ) { if( m_rawString.startsWith( QChar( QChar::ObjectReplacementCharacter ) ) ) { m_glyphs[ i ]->writeMathML( writer, ns ); if (i + 1 < tmp.count()) { writer->addTextNode( tmp[ i ] ); } } else { writer->addTextNode( tmp[ i ] ); if (i + 1 < tmp.count()) { m_glyphs[ i ]->writeMathML( writer, ns ); } } } } const QString TokenElement::writeElementContent() const { return m_rawString; }
yxl/emscripten-calligra-mobile
plugins/formulashape/elements/TokenElement.cpp
C++
gpl-2.0
12,060
<?php /** * Customer booking notification */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly ?> <?php do_action( 'woocommerce_email_header', $email_heading ); ?> <?php echo wpautop( wptexturize( $notification_message ) ); ?> <table cellspacing="0" cellpadding="6" style="width: 100%; border: 1px solid #eee;" border="1" bordercolor="#eee"> <tbody> <tr> <th scope="row" style="text-align:left; border: 1px solid #eee;"><?php _e( 'Booked Product', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $booking->get_product()->get_title(); ?></td> </tr> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php _e( 'Booking ID', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $booking->get_id(); ?></td> </tr> <?php if ( $booking->has_resources() && ( $resource = $booking->get_resource() ) ) : ?> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php _e( 'Booking Type', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $resource->post_title; ?></td> </tr> <?php endif; ?> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php _e( 'Booking Start Date', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $booking->get_start_date(); ?></td> </tr> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php _e( 'Booking End Date', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $booking->get_end_date(); ?></td> </tr> <?php if ( $booking->has_persons() ) : ?> <?php foreach ( $booking->get_persons() as $id => $qty ) : if ( 0 === $qty ) { continue; } $person_type = ( 0 < $id ) ? get_the_title( $id ) : __( 'Person(s)', 'woocommerce-bookings' ); ?> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php echo $person_type; ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $qty; ?></td> </tr> <?php endforeach; ?> <?php endif; ?> </tbody> </table> <?php do_action( 'woocommerce_email_footer' ); ?>
snappermorgan/radaralley
wp-content/plugins/woocommerce-bookings/templates/emails/customer-booking-notification.php
PHP
gpl-2.0
2,299
<?php /** * @file * Contains \Drupal\Console\Command\Generate\RouteSubscriber. */ namespace Drupal\Console\Command\Generate; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Drupal\Console\Command\Shared\ModuleTrait; use Drupal\Console\Generator\RouteSubscriberGenerator; use Drupal\Console\Command\Shared\ConfirmationTrait; use Symfony\Component\Console\Command\Command; use Drupal\Console\Core\Style\DrupalStyle; use Drupal\Console\Extension\Manager; use Drupal\Console\Core\Utils\ChainQueue; use Drupal\Console\Core\Command\Shared\CommandTrait; /** * Class RouteSubscriberCommand * * @package Drupal\Console\Command\Generate */ class RouteSubscriberCommand extends Command { use ModuleTrait; use ConfirmationTrait; use CommandTrait; /** * @var Manager */ protected $extensionManager; /** * @var RouteSubscriberGenerator */ protected $generator; /** * @var ChainQueue */ protected $chainQueue; /** * RouteSubscriberCommand constructor. * * @param Manager $extensionManager * @param RouteSubscriberGenerator $generator * @param ChainQueue $chainQueue */ public function __construct( Manager $extensionManager, RouteSubscriberGenerator $generator, ChainQueue $chainQueue ) { $this->extensionManager = $extensionManager; $this->generator = $generator; $this->chainQueue = $chainQueue; parent::__construct(); } /** * {@inheritdoc} */ protected function configure() { $this ->setName('generate:routesubscriber') ->setDescription($this->trans('commands.generate.routesubscriber.description')) ->setHelp($this->trans('commands.generate.routesubscriber.description')) ->addOption( 'module', null, InputOption::VALUE_REQUIRED, $this->trans('commands.common.options.module') ) ->addOption( 'name', null, InputOption::VALUE_REQUIRED, $this->trans('commands.generate.routesubscriber.options.name') ) ->addOption( 'class', null, InputOption::VALUE_REQUIRED, $this->trans('commands.generate.routesubscriber.options.class') ); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output = new DrupalStyle($input, $output); // @see use Drupal\Console\Command\Shared\ConfirmationTrait::confirmGeneration if (!$this->confirmGeneration($output)) { return 1; } $module = $input->getOption('module'); $name = $input->getOption('name'); $class = $input->getOption('class'); $this->generator->generate($module, $name, $class); $this->chainQueue->addCommand('cache:rebuild', ['cache' => 'all']); return 0; } /** * {@inheritdoc} */ protected function interact(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); // --module option $module = $input->getOption('module'); if (!$module) { // @see Drupal\Console\Command\Shared\ModuleTrait::moduleQuestion $module = $this->moduleQuestion($io); $input->setOption('module', $module); } // --name option $name = $input->getOption('name'); if (!$name) { $name = $io->ask( $this->trans('commands.generate.routesubscriber.questions.name'), $module.'.route_subscriber' ); $input->setOption('name', $name); } // --class option $class = $input->getOption('class'); if (!$class) { $class = $io->ask( $this->trans('commands.generate.routesubscriber.questions.class'), 'RouteSubscriber' ); $input->setOption('class', $class); } } protected function createGenerator() { return new RouteSubscriberGenerator(); } }
lian-rr/Ecommerse-Drupal
vendor/drupal/console/src/Command/Generate/RouteSubscriberCommand.php
PHP
gpl-2.0
4,403
#!/usr/bin/python # # Copyright 2010, 2011 wkhtmltopdf authors # # This file is part of wkhtmltopdf. # # wkhtmltopdf is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wkhtmltopdf 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 Lesser General Public License # along with wkhtmltopdf. If not, see <http:#www.gnu.org/licenses/>. from sys import argv, exit import re from datetime import date import os import difflib cdate = re.compile(r"Copyright ([0-9 ,]*) wkhtmltopdf authors") ifdef = re.compile(r"^[\n\r \t]*#ifndef __(.*)__[\t ]*\n#define __(\1)__[\t ]*\n") endif = re.compile(r"#endif.*[\r\n \t]*$") ws = re.compile(r"[ \t]*[\r\n]") branchspace = re.compile(r"([ \t\r\n])(for|if|while|switch|foreach)[\t \r\n]*\(") hangelse = re.compile(r"}[\r\n\t ]*(else)") braceup = re.compile(r"(\)|else)[\r\n\t ]*{") include = re.compile(r"(#include (\"[^\"]*\"|<[^>]*>)\n)+") def includesort(x): return "\n".join(sorted(x.group(0)[:-1].split("\n"))+[""]) changes=False progname="wkhtmltopdf" for path in argv[1:]: if path.split("/")[0] == "include": continue try: data = file(path).read() except: continue mo = cdate.search(data) years = set(mo.group(1).split(", ")) if mo else set() years.add(str(date.today().year)) ext = path.rsplit(".",2)[-1] header = "" cc = "//" if ext in ["hh","h","c","cc","cpp","inl", "inc"]: header += """// -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*- // vi:set ts=4 sts=4 sw=4 noet : // """ elif ext in ["sh"]: header += "#!/bin/bash\n#\n" cc = "#" elif ext in ["py"]: header += "#!/usr/bin/python\n#\n" cc = "#" elif ext in ["pro","pri"]: cc = "#" else: continue header += """// Copyright %(years)s %(name)s authors // // This file is part of %(name)s. // // %(name)s is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // %(name)s 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 Lesser General Public License // along with %(name)s. If not, see <http://www.gnu.org/licenses/>. """%{"years": (", ".join(sorted(list(years)))),"name":progname} if ext in ["c", "h", "inc"]: header = "/*" + header[2:-1] + " */\n\n" cc = " *" hexp = re.compile(r"^/\*([^*]*(\*[^/]))*[^*]*\*/[ \t\n]*"); else: #Strip away generated header hexp = re.compile("^(%s[^\\n]*\\n)*"%(cc)) ndata = hexp.sub("", data,1) ndata = ws.sub("\n", ndata)+"\n" if ext in ["hh","h","inl"]: s=0 e=-1 while ndata[s] in ['\r','\n',' ','\t']: s+=1 while ndata[e] in ['\r','\n',' ','\t']: e-=1 #Strip away generated ifdef if ifdef.search(ndata): ndata = endif.sub("",ifdef.sub("",ndata,1),1) s=0 e=-1 while ndata[s] in ['\r','\n',' ','\t']: s+=1 while ndata[e] in ['\r','\n',' ','\t']: e-=1 ndata=ndata[s:e+1].replace(" ",'\t') if ext in ["hh","h","c","cc","cpp","inl"]: ndata = branchspace.sub(r"\1\2 (",ndata) ndata = hangelse.sub("} else",ndata) ndata = braceup.sub(r"\1 {",ndata) ndata = include.sub(includesort, ndata) if ext in ["hh","h","inl"]: n = os.path.split(path)[-1].replace(".","_").replace(" ","_").upper() ndata = """#ifndef __%s__ #define __%s__ %s #endif %s__%s__%s"""%(n,n,ndata, "//" if ext != "h" else "/*", n, "" if ext != "h" else "*/") ndata = header.replace("//",cc)+ndata+"\n" if ndata != data: for x in difflib.unified_diff(data.split("\n"),ndata.split("\n"), "a/"+path, "b/"+path): print x changes=True file(path, "w").write(ndata) if changes: exit(1)
anouschka42/starktheatreprod
sites/all/libraries/wkhtmltopdf-0.12.0/scripts/sourcefix.py
Python
gpl-2.0
4,292
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\DependencyInjection; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface; /** * Adds services tagged kernel.fragment_renderer as HTTP content rendering strategies. * * @author Fabien Potencier <fabien@symfony.com> */ class FragmentRendererPass implements CompilerPassInterface { private $handlerService; private $rendererTag; /** * @param string $handlerService Service name of the fragment handler in the container * @param string $rendererTag Tag name used for fragments */ public function __construct($handlerService = 'fragment.handler', $rendererTag = 'kernel.fragment_renderer') { $this->handlerService = $handlerService; $this->rendererTag = $rendererTag; } public function process(ContainerBuilder $container) { if (!$container->hasDefinition($this->handlerService)) { return; } $definition = $container->getDefinition($this->handlerService); $renderers = array(); foreach ($container->findTaggedServiceIds($this->rendererTag, true) as $id => $tags) { $def = $container->getDefinition($id); $class = $container->getParameterBag()->resolveValue($def->getClass()); if (!$r = $container->getReflectionClass($class)) { throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); } if (!$r->isSubclassOf(FragmentRendererInterface::class)) { throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, FragmentRendererInterface::class)); } foreach ($tags as $tag) { $renderers[$tag['alias']] = new Reference($id); } } $definition->replaceArgument(0, ServiceLocatorTagPass::register($container, $renderers)); } }
nmacd85/drupal-nicoledawn
vendor/symfony/http-kernel/DependencyInjection/FragmentRendererPass.php
PHP
gpl-2.0
2,526
// license:BSD-3-Clause // copyright-holders:Ville Linde // TMS320C82 Master Processor core execution #include "emu.h" #include "tms32082.h" #define OP_LINK() ((m_ir >> 27) & 0x1f) #define OP_RD() ((m_ir >> 27) & 0x1f) #define OP_RS() ((m_ir >> 22) & 0x1f) #define OP_BASE() ((m_ir >> 22) & 0x1f) #define OP_SIMM15() ((m_ir & 0x4000) ? (0xffffe000 | (m_ir & 0x7fff)) : (m_ir & 0x7fff)) #define OP_UIMM15() (m_ir & 0x7fff) #define OP_BITNUM() ((m_ir >> 27) & 0x1f) #define OP_ROTATE() (m_ir & 0x1f) #define OP_ENDMASK() ((m_ir >> 5) & 0x1f) #define OP_SRC1() (m_ir & 0x1f) #define OP_PD() ((m_ir >> 9) & 0x3) #define OP_P1() ((m_ir >> 5) & 0x3) #define OP_P2() ((m_ir >> 7) & 0x3) #define OP_ACC() ((m_ir >> 15) & 0x2) | ((m_ir >> 11) & 1) #define ROTATE_L(x, r) ((x << r) | (x >> (32-r))) #define ROTATE_R(x, r) ((x >> r) | (x << (32-r))) #define CMP_OVERFLOW32(r, s, d) ((((d) ^ (s)) & ((d) ^ (r)) & 0x80000000) ? 1 : 0) #define CMP_OVERFLOW16(r, s, d) ((((d) ^ (s)) & ((d) ^ (r)) & 0x8000) ? 1 : 0) #define CMP_OVERFLOW8(r, s, d) ((((d) ^ (s)) & ((d) ^ (r)) & 0x80) ? 1 : 0) #define CARRY32(x) (((x) & (((uint64_t)1) << 32)) ? 1 : 0) #define CARRY16(x) (((x) & 0x10000) ? 1 : 0) #define CARRY8(x) (((x) & 0x100) ? 1 : 0) #define SIGN32(x) (((x) & 0x80000000) ? 1 : 0) #define SIGN16(x) (((x) & 0x8000) ? 1 : 0) #define SIGN8(x) (((x) & 0x80) ? 1 : 0) #define SIGN_EXTEND(x, r) ((x) | (((x) & (0x80000000 >> r)) ? ((int32_t)(0x80000000) >> r) : 0)) bool tms32082_mp_device::test_condition(int condition, uint32_t value) { switch (condition) { case 0x00: return false; // never, byte case 0x01: return (int8_t)(value) > 0; // greater than zero, byte case 0x02: return (int8_t)(value) == 0; // equals zero, byte case 0x03: return (int8_t)(value) >= 0; // greater than or equal to zero, byte case 0x04: return (int8_t)(value) < 0; // less than zero, byte case 0x05: return (int8_t)(value) != 0; // not equal to zero, byte case 0x06: return (int8_t)(value) <= 0; // less than or equal to zero, byte case 0x07: return true; // always, byte case 0x08: return false; // never, word case 0x09: return (int16_t)(value) > 0; // greater than zero, word case 0x0a: return (int16_t)(value) == 0; // equals zero, word case 0x0b: return (int16_t)(value) >= 0; // greater than or equal to zero, word case 0x0c: return (int16_t)(value) < 0; // less than zero, word case 0x0d: return (int16_t)(value) != 0; // not equal to zero, word case 0x0e: return (int16_t)(value) <= 0; // less than or equal to zero, word case 0x0f: return true; // always, word case 0x10: return false; // never, dword case 0x11: return (int32_t)(value) > 0; // greater than zero, dword case 0x12: return (int32_t)(value) == 0; // equals zero, dword case 0x13: return (int32_t)(value) >= 0; // greater than or equal to zero, dword case 0x14: return (int32_t)(value) < 0; // less than zero, dword case 0x15: return (int32_t)(value) != 0; // not equal to zero, dword case 0x16: return (int32_t)(value) <= 0; // less than or equal to zero, dword case 0x17: return true; // always, dword default: return false; // reserved } } uint32_t tms32082_mp_device::calculate_cmp(uint32_t src1, uint32_t src2) { uint16_t src1_16 = (uint16_t)(src1); uint8_t src1_8 = (uint8_t)(src1); uint16_t src2_16 = (uint16_t)(src2); uint8_t src2_8 = (uint8_t)(src2); uint64_t res32 = (uint64_t)src1 - (uint64_t)src2; int z32 = (res32 == 0) ? 1 : 0; int n32 = SIGN32(res32); int v32 = CMP_OVERFLOW32(res32, src2, src1); int c32 = CARRY32(res32); uint32_t res16 = (uint32_t)src1_16 - (uint32_t)src2_16; int z16 = (res16 == 0) ? 1 : 0; int n16 = SIGN16(res16); int v16 = CMP_OVERFLOW16(res16, src2_16, src1_16); int c16 = CARRY16(res16); uint16_t res8 = (uint16_t)src1_8 - (uint16_t)src2_8; int z8 = (res8 == 0) ? 1 : 0; int n8 = SIGN8(res8); int v8 = CMP_OVERFLOW8(res8, src2_8, src1_8); int c8 = CARRY8(res8); uint32_t flags = 0; // 32-bits (bits 20-29) flags |= ((~c32) & 1) << 29; // higher than or same (C) flags |= ((c32) & 1) << 28; // lower than (~C) flags |= ((c32|z32) & 1) << 27; // lower than or same (~C|Z) flags |= ((~c32&~z32) & 1) << 26; // higher than (C&~Z) flags |= (((n32&v32)|(~n32&~v32)) & 1) << 25; // greater than or equal (N&V)|(~N&~V) flags |= (((n32&~v32)|(~n32&v32)) & 1) << 24; // less than (N&~V)|(~N&V) flags |= (((n32&~v32)|(~n32&v32)|(z32)) & 1) << 23; // less than or equal (N&~V)|(~N&V)|Z flags |= (((n32&v32&~z32)|(~n32&~v32&~z32)) & 1) << 22; // greater than (N&V&~Z)|(~N&~V&~Z) flags |= ((~z32) & 1) << 21; // not equal (~Z) flags |= ((z32) & 1) << 20; // equal (Z) // 16-bits (bits 10-19) flags |= ((~c16) & 1) << 19; // higher than or same (C) flags |= ((c16) & 1) << 18; // lower than (~C) flags |= ((c16|z16) & 1) << 17; // lower than or same (~C|Z) flags |= ((~c16&~z16) & 1) << 16; // higher than (C&~Z) flags |= (((n16&v16)|(~n16&~v16)) & 1) << 15; // greater than or equal (N&V)|(~N&~V) flags |= (((n16&~v16)|(~n16&v16)) & 1) << 14; // less than (N&~V)|(~N&V) flags |= (((n16&~v16)|(~n16&v16)|(z16)) & 1) << 13; // less than or equal (N&~V)|(~N&V)|Z flags |= (((n16&v16&~z16)|(~n16&~v16&~z16)) & 1) << 12; // greater than (N&V&~Z)|(~N&~V&~Z) flags |= ((~z16) & 1) << 11; // not equal (~Z) flags |= ((z16) & 1) << 10; // equal (Z) // 8-bits (bits 0-9) flags |= ((~c8) & 1) << 9; // higher than or same (C) flags |= ((c8) & 1) << 8; // lower than (~C) flags |= ((c8|z8) & 1) << 7; // lower than or same (~C|Z) flags |= ((~c8&~z8) & 1) << 6; // higher than (C&~Z) flags |= (((n8&v8)|(~n8&~v8)) & 1) << 5; // greater than or equal (N&V)|(~N&~V) flags |= (((n8&~v8)|(~n8&v8)) & 1) << 4; // less than (N&~V)|(~N&V) flags |= (((n8&~v8)|(~n8&v8)|(z8)) & 1) << 3; // less than or equal (N&~V)|(~N&V)|Z flags |= (((n8&v8&~z8)|(~n8&~v8&~z8)) & 1) << 2; // greater than (N&V&~Z)|(~N&~V&~Z) flags |= ((~z8) & 1) << 1; // not equal (~Z) flags |= ((z8) & 1) << 0; // equal (Z) return flags; } void tms32082_mp_device::vector_loadstore() { int rd = OP_RD(); int vector_ls_bits = (((m_ir >> 9) & 0x3) << 1) | ((m_ir >> 6) & 1); switch (vector_ls_bits) { case 0x01: // vst.s { m_program.write_dword(m_outp, m_reg[rd]); m_outp += 4; break; } case 0x03: // vst.d { uint64_t data = m_fpair[rd >> 1]; m_program.write_qword(m_outp, data); m_outp += 8; break; } case 0x04: // vld0.s { m_reg[rd] = m_program.read_dword(m_in0p); m_in0p += 4; break; } case 0x05: // vld1.s { m_reg[rd] = m_program.read_dword(m_in1p); m_in1p += 4; break; } case 0x06: // vld0.d { m_fpair[rd >> 1] = m_program.read_qword(m_in0p); m_in0p += 8; break; } case 0x07: // vld1.d { m_fpair[rd >> 1] = m_program.read_qword(m_in1p); m_in1p += 8; break; } default: fatalerror("vector_loadstore(): ls bits = %02X\n", vector_ls_bits); } } void tms32082_mp_device::execute_short_imm() { switch ((m_ir >> 15) & 0x7f) { case 0x02: // cmnd { uint32_t data = OP_UIMM15(); processor_command(data); break; } case 0x04: // rdcr { int rd = OP_RD(); uint32_t imm = OP_UIMM15(); uint32_t r = read_creg(imm); if (rd) m_reg[rd] = r; break; } case 0x05: // swcr { int rd = OP_RD(); int rs = OP_RS(); uint32_t imm = OP_UIMM15(); uint32_t r = read_creg(imm); if (rd) m_reg[rd] = r; write_creg(imm, m_reg[rs]); break; } case 0x06: // brcr { int cr = OP_UIMM15(); if (cr == 0x0001) { // ignore jump to EIP because of how we emulate the pipeline } else { uint32_t data = read_creg(cr); m_fetchpc = data & ~3; m_ie = (m_ie & ~1) | (data & 1); // global interrupt mask from creg // TODO: user/supervisor latch from creg } break; } case 0x08: // shift.dz { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = OP_ROTATE(); int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = SHIFT_MASK[end ? end : 32]; if (inv) endmask = ~endmask; uint32_t compmask = endmask; // shiftmask == 0xffffffff uint32_t res; if (r) // right { res = ROTATE_R(source, rot) & compmask; } else // left { res = ROTATE_L(source, rot) & compmask; } if (rd) m_reg[rd] = res; break; } case 0x0a: // shift.ds { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = OP_ROTATE(); int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = SHIFT_MASK[end ? end : 32]; if (inv) endmask = ~endmask; uint32_t compmask = endmask; // shiftmask == 0xffffffff uint32_t res; if (r) // right { res = ROTATE_R(source, rot) & compmask; res = SIGN_EXTEND(res, rot); } else // left { res = ROTATE_L(source, rot) & compmask; // sign extend makes no sense to left.. } if (rd) m_reg[rd] = res; break; } case 0x0b: // shift.ez { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = OP_ROTATE(); int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = SHIFT_MASK[end ? end : 32]; if (inv) endmask = ~endmask; int shift = r ? 32-rot : rot; uint32_t shiftmask = SHIFT_MASK[shift ? shift : 32]; uint32_t compmask = endmask & shiftmask; uint32_t res; if (r) // right { res = ROTATE_R(source, rot) & compmask; } else // left { res = ROTATE_L(source, rot) & compmask; } if (rd) m_reg[rd] = res; break; } case 0x0c: // shift.em { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = OP_ROTATE(); int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = SHIFT_MASK[end ? end : 32]; if (inv) endmask = ~endmask; uint32_t shiftmask = SHIFT_MASK[r ? 32-rot : rot]; uint32_t compmask = endmask & shiftmask; uint32_t res; if (r) // right { res = (ROTATE_R(source, rot) & compmask) | (m_reg[rd] & ~compmask); } else // left { res = (ROTATE_L(source, rot) & compmask) | (m_reg[rd] & ~compmask); } if (rd) m_reg[rd] = res; break; } case 0x0d: // shift.es { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = OP_ROTATE(); int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = SHIFT_MASK[end ? end : 32]; if (inv) endmask = ~endmask; int shift = r ? 32-rot : rot; uint32_t shiftmask = SHIFT_MASK[shift ? shift : 32]; uint32_t compmask = endmask & shiftmask; uint32_t res; if (r) // right { res = ROTATE_R(source, rot) & compmask; res = SIGN_EXTEND(res, rot); } else // left { res = ROTATE_L(source, rot) & compmask; // sign extend makes no sense to left.. } if (rd) m_reg[rd] = res; break; } case 0x0e: // shift.iz { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = OP_ROTATE(); int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = SHIFT_MASK[end ? end : 32]; if (inv) endmask = ~endmask; uint32_t shiftmask = SHIFT_MASK[r ? 32-rot : rot]; uint32_t compmask = endmask & ~shiftmask; uint32_t res; if (r) // right { res = ROTATE_R(source, rot) & compmask; } else // left { res = ROTATE_L(source, rot) & compmask; } if (rd) m_reg[rd] = res; break; } case 0x0f: // shift.im { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = OP_ROTATE(); int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = SHIFT_MASK[end ? end : 32]; if (inv) endmask = ~endmask; uint32_t shiftmask = SHIFT_MASK[r ? 32-rot : rot]; uint32_t compmask = endmask & ~shiftmask; uint32_t res; if (r) // right { res = (ROTATE_R(source, rot) & compmask) | (m_reg[rd] & ~compmask); } else // left { res = (ROTATE_L(source, rot) & compmask) | (m_reg[rd] & ~compmask); } if (rd) m_reg[rd] = res; break; } case 0x11: // and { int rd = OP_RD(); int rs = OP_RS(); uint32_t imm = OP_UIMM15(); if (rd) m_reg[rd] = m_reg[rs] & imm; break; } case 0x12: // and.tf { int rd = OP_RD(); int rs = OP_RS(); uint32_t imm = OP_UIMM15(); if (rd) m_reg[rd] = ~m_reg[rs] & imm; break; } case 0x14: // and.ft { int rd = OP_RD(); int rs = OP_RS(); uint32_t imm = OP_UIMM15(); if (rd) m_reg[rd] = m_reg[rs] & ~imm; break; } case 0x17: // or { int rd = OP_RD(); int rs = OP_RS(); uint32_t imm = OP_UIMM15(); if (rd) m_reg[rd] = m_reg[rs] | imm; break; } case 0x1d: // or.ft { int rd = OP_RD(); int rs = OP_RS(); uint32_t imm = OP_UIMM15(); if (rd) m_reg[rd] = m_reg[rs] | ~imm; break; } case 0x24: case 0x20: // ld.b { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; uint32_t data = (uint8_t)m_program.read_byte(address); if (data & 0x80) data |= 0xffffff00; if (rd) m_reg[rd] = data; if (m && base) m_reg[base] = address; break; } case 0x25: case 0x21: // ld.h { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; uint32_t data = (uint16_t)m_program.read_word(address); if (data & 0x8000) data |= 0xffff0000; if (rd) m_reg[rd] = data; if (m && base) m_reg[base] = address; break; } case 0x26: case 0x22: // ld { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; uint32_t data = m_program.read_dword(address); if (rd) m_reg[rd] = data; if (m && base) m_reg[base] = address; break; } case 0x27: case 0x23: // ld.d { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; uint32_t data1 = m_program.read_dword(address); uint32_t data2 = m_program.read_dword(address+4); if (rd) { m_reg[(rd & ~1)+1] = data1; m_reg[(rd & ~1)] = data2; } if (m && base) m_reg[base] = address; break; } case 0x28: case 0x2c: // ld.ub { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; uint32_t data = (uint8_t)(m_program.read_byte(address)); if (rd) m_reg[rd] = data; if (m && base) m_reg[base] = address; break; } case 0x2d: case 0x29: // ld.uh { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; uint32_t data = (uint16_t)(m_program.read_word(address)); if (rd) m_reg[rd] = data; if (m && base) m_reg[base] = address; break; } case 0x34: case 0x30: // st.b { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; m_program.write_byte(address, (uint8_t)(m_reg[rd])); if (m && base) m_reg[base] = address; break; } case 0x35: case 0x31: // st.h { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; m_program.write_word(address, (uint16_t)(m_reg[rd])); if (m && base) m_reg[base] = address; break; } case 0x36: case 0x32: // st { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; m_program.write_dword(address, m_reg[rd]); if (m && base) m_reg[base] = address; break; } case 0x37: case 0x33: // st.d { int rd = OP_RD(); int base = OP_BASE(); int m = m_ir & (1 << 17); int32_t offset = OP_SIMM15(); uint32_t address = m_reg[base] + offset; m_program.write_dword(address+0, m_reg[(rd & ~1) + 1]); m_program.write_dword(address+4, m_reg[rd & ~1]); if (m && base) m_reg[base] = address; break; } case 0x45: // jsr.a { int link = OP_LINK(); int base = OP_BASE(); int32_t offset = OP_SIMM15(); if (link) m_reg[link] = m_fetchpc; m_fetchpc = m_reg[base] + offset; break; } case 0x48: // bbz { int bitnum = OP_BITNUM() ^ 0x1f; int32_t offset = OP_SIMM15(); int rs = OP_RS(); if ((m_reg[rs] & (1 << bitnum)) == 0) { uint32_t address = m_pc + (offset * 4); m_pc = m_fetchpc; delay_slot(); m_fetchpc = address; } break; } case 0x49: // bbz.a { int bitnum = OP_BITNUM() ^ 0x1f; int32_t offset = OP_SIMM15(); int rs = OP_RS(); if ((m_reg[rs] & (1 << bitnum)) == 0) { m_fetchpc = m_pc + (offset * 4); } break; } case 0x4a: // bbo { int bitnum = OP_BITNUM() ^ 0x1f; int32_t offset = OP_SIMM15(); int rs = OP_RS(); if ((m_reg[rs] & (1 << bitnum)) != 0) { uint32_t address = m_pc + (offset * 4); m_pc = m_fetchpc; delay_slot(); m_fetchpc = address; } break; } case 0x4b: // bbo.a { int bitnum = OP_BITNUM() ^ 0x1f; int32_t offset = OP_SIMM15(); int rs = OP_RS(); if ((m_reg[rs] & (1 << bitnum)) != 0) { m_fetchpc = m_pc + (offset * 4); } break; } case 0x4c: // bcnd { int32_t offset = OP_SIMM15(); int code = OP_RD(); int rs = OP_RS(); if (test_condition(code, m_reg[rs])) { uint32_t address = m_pc + (offset * 4); m_pc = m_fetchpc; delay_slot(); m_fetchpc = address; } break; } case 0x4d: // bcnd.a { int32_t offset = OP_SIMM15(); int code = OP_RD(); int rs = OP_RS(); if (test_condition(code, m_reg[rs])) { m_fetchpc = m_pc + (offset * 4); } break; } case 0x50: // cmp { uint32_t src1 = OP_SIMM15(); uint32_t src2 = m_reg[OP_RS()]; int rd = OP_RD(); if (rd) m_reg[rd] = calculate_cmp(src1, src2); break; } case 0x58: // add { int32_t imm = OP_SIMM15(); int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = m_reg[rs] + imm; // TODO: integer overflow exception break; } case 0x59: // addu { int32_t imm = OP_SIMM15(); int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = m_reg[rs] + imm; break; } case 0x5a: // sub { int32_t imm = OP_SIMM15(); int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = imm - m_reg[rs]; // TODO: integer overflow exception break; } case 0x5b: // subu { int32_t imm = OP_SIMM15(); int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = imm - m_reg[rs]; break; } default: fatalerror("execute_short_imm(): %08X: opcode %08X (%02X)", m_pc, m_ir, (m_ir >> 15) & 0x7f); } } void tms32082_mp_device::execute_reg_long_imm() { uint32_t imm32 = 0; int has_imm = (m_ir & (1 << 12)); if (has_imm) imm32 = fetch(); switch ((m_ir >> 12) & 0xff) { case 0x04: // cmnd { uint32_t data = has_imm ? imm32 : m_reg[OP_SRC1()]; processor_command(data); break; } case 0x16: // shift.ez { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = m_reg[OP_ROTATE()]; int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = end ? SHIFT_MASK[end ? end : 32] : m_reg[OP_ROTATE()+1]; if (inv) endmask = ~endmask; int shift = r ? 32-rot : rot; uint32_t shiftmask = SHIFT_MASK[shift ? shift : 32]; uint32_t compmask = endmask & shiftmask; uint32_t res; if (r) // right { res = ROTATE_R(source, rot) & compmask; } else // left { res = ROTATE_L(source, rot) & compmask; } if (rd) m_reg[rd] = res; break; } case 0x1a: // shift.es { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = m_reg[OP_ROTATE()]; int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = end ? SHIFT_MASK[end ? end : 32] : m_reg[OP_ROTATE()+1]; if (inv) endmask = ~endmask; int shift = r ? 32-rot : rot; uint32_t shiftmask = SHIFT_MASK[shift ? shift : 32]; uint32_t compmask = endmask & shiftmask; uint32_t res; if (r) // right { res = ROTATE_R(source, rot) & compmask; res = SIGN_EXTEND(res, rot); } else // left { res = ROTATE_L(source, rot) & compmask; } if (rd) m_reg[rd] = res; break; } case 0x1c: // shift.iz { int r = (m_ir & (1 << 10)); int inv = (m_ir & (1 << 11)); int rot = m_reg[OP_ROTATE()]; int end = OP_ENDMASK(); uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); uint32_t endmask = end ? SHIFT_MASK[end ? end : 32] : m_reg[OP_ROTATE()+1]; if (inv) endmask = ~endmask; int shift = r ? 32-rot : rot; uint32_t shiftmask = SHIFT_MASK[shift ? shift : 32]; uint32_t compmask = endmask & ~shiftmask; uint32_t res; if (r) // right { res = ROTATE_R(source, rot) & compmask; } else // left { res = ROTATE_L(source, rot) & compmask; } if (rd) m_reg[rd] = res; break; } case 0x22: case 0x23: // and { int rd = OP_RD(); int rs = OP_RS(); uint32_t src1 = has_imm ? imm32 : m_reg[OP_SRC1()]; if (rd) m_reg[rd] = src1 & m_reg[rs]; break; } case 0x24: case 0x25: // and.tf { int rd = OP_RD(); int rs = OP_RS(); uint32_t src1 = has_imm ? imm32 : m_reg[OP_SRC1()]; if (rd) m_reg[rd] = src1 & ~(m_reg[rs]); break; } case 0x2c: case 0x2d: // xor { int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = m_reg[rs] ^ (has_imm ? imm32 : m_reg[OP_SRC1()]); break; } case 0x2e: case 0x2f: // or { int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = m_reg[rs] | (has_imm ? imm32 : m_reg[OP_SRC1()]); break; } case 0x3a: case 0x3b: // or.ft { int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = m_reg[rs] | ~(has_imm ? imm32 : m_reg[OP_SRC1()]); break; } case 0x40: case 0x41: case 0x48: case 0x49: // ld.b { int m = m_ir & (1 << 15); int base = OP_BASE(); int rd = OP_RD(); uint32_t address = m_reg[base] + (has_imm ? imm32 : m_reg[OP_SRC1()]); uint32_t r = m_program.read_byte(address); if (r & 0x80) r |= 0xffffff00; if (rd) m_reg[rd] = r; if (m && base) m_reg[base] = address; break; } case 0x42: case 0x4a: case 0x43: case 0x4b: // ld.h { int shift = (m_ir & (1 << 11)) ? 1 : 0; int m = m_ir & (1 << 15); int base = OP_BASE(); int rd = OP_RD(); uint32_t address = m_reg[base] + ((has_imm ? imm32 : m_reg[OP_SRC1()]) << shift); uint32_t r = m_program.read_word(address); if (r & 0x8000) r |= 0xffff0000; if (rd) m_reg[rd] = r; if (m && base) m_reg[base] = address; break; } case 0x4c: case 0x44: case 0x4d: case 0x45: // ld { int shift = (m_ir & (1 << 11)) ? 2 : 0; int m = m_ir & (1 << 15); int base = OP_BASE(); int rd = OP_RD(); uint32_t address = m_reg[base] + ((has_imm ? imm32 : m_reg[OP_SRC1()]) << shift); uint32_t r = m_program.read_dword(address); if (rd) m_reg[rd] = r; if (m && base) m_reg[base] = address; break; } case 0x4e: case 0x4f: case 0x46: case 0x47: // ld.d { int shift = (m_ir & (1 << 11)) ? 3 : 0; int m = m_ir & (1 << 15); int base = OP_BASE(); int rd = OP_RD(); uint32_t address = m_reg[base] + ((has_imm ? imm32 : m_reg[OP_SRC1()]) << shift); uint64_t r = m_program.read_qword(address); if (rd) m_fpair[rd >> 1] = r; if (m && base) m_reg[base] = address; break; } case 0x58: case 0x59: case 0x50: case 0x51: // ld.ub { int m = m_ir & (1 << 15); int base = OP_BASE(); int rd = OP_RD(); uint32_t address = m_reg[base] + (has_imm ? imm32 : m_reg[OP_SRC1()]); uint32_t r = (uint8_t)(m_program.read_byte(address)); if (rd) m_reg[rd] = r; if (m && base) m_reg[base] = address; break; } case 0x5a: case 0x5b: case 0x52: case 0x53: // ld.uh { int shift = (m_ir & (1 << 11)) ? 1 : 0; int m = m_ir & (1 << 15); int base = OP_BASE(); int rd = OP_RD(); uint32_t address = m_reg[base] + ((has_imm ? imm32 : m_reg[OP_SRC1()]) << shift); uint32_t r = (uint16_t)(m_program.read_word(address)); if (rd) m_reg[rd] = r; if (m && base) m_reg[base] = address; break; } case 0x60: case 0x61: case 0x68: case 0x69: // st.b { int m = m_ir & (1 << 15); int base = OP_BASE(); uint32_t address = m_reg[base] + (has_imm ? imm32 : m_reg[OP_SRC1()]); m_program.write_byte(address, (uint8_t)(m_reg[OP_RD()])); if (m && base) m_reg[base] = address; break; } case 0x62: case 0x63: case 0x6a: case 0x6b: // st.h { int shift = (m_ir & (1 << 11)) ? 1 : 0; int m = m_ir & (1 << 15); int base = OP_BASE(); uint32_t address = m_reg[base] + ((has_imm ? imm32 : m_reg[OP_SRC1()]) << shift); m_program.write_word(address, (uint16_t)(m_reg[OP_RD()])); if (m && base) m_reg[base] = address; break; } case 0x6c: case 0x6d: case 0x64: case 0x65: // st { int shift = (m_ir & (1 << 11)) ? 2 : 0; int m = m_ir & (1 << 15); int base = OP_BASE(); uint32_t address = m_reg[base] + ((has_imm ? imm32 : m_reg[OP_SRC1()]) << shift); m_program.write_dword(address, m_reg[OP_RD()]); if (m && base) m_reg[base] = address; break; } case 0x88: case 0x89: // jsr { int link = OP_LINK(); int base = OP_BASE(); if (link) m_reg[link] = m_fetchpc + 4; uint32_t address = m_reg[base] + (has_imm ? imm32 : m_reg[OP_SRC1()]); m_pc = m_fetchpc; delay_slot(); m_fetchpc = address; break; } case 0x8a: case 0x8b: // jsr.a { int link = OP_LINK(); int base = OP_BASE(); if (link) m_reg[link] = m_fetchpc; m_fetchpc = m_reg[base] + (has_imm ? imm32 : m_reg[OP_SRC1()]); break; } case 0xa0: case 0xa1: // cmp { int rd = OP_RD(); uint32_t src1 = has_imm ? imm32 : m_reg[OP_SRC1()]; uint32_t src2 = m_reg[OP_RS()]; if (rd) m_reg[rd] = calculate_cmp(src1, src2); break; } case 0xb2: case 0xb3: // addu { int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = m_reg[rs] + (has_imm ? imm32 : m_reg[OP_SRC1()]); break; } case 0xb4: case 0xb5: // sub { int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = (has_imm ? imm32 : m_reg[OP_SRC1()]) - m_reg[rs]; // TODO: overflow interrupt break; } case 0xb6: case 0xb7: // subu { int rd = OP_RD(); int rs = OP_RS(); if (rd) m_reg[rd] = (has_imm ? imm32 : m_reg[OP_SRC1()]) - m_reg[rs]; break; } case 0xc4: case 0xd4: case 0xc5: case 0xd5: // vmpy { int p1 = m_ir & (1 << 5); int pd = m_ir & (1 << 7); int ls_bit1 = m_ir & (1 << 10); int ls_bit2 = m_ir & (1 << 6); int rd = OP_RS(); int src1 OP_SRC1(); double source = has_imm ? (double)u2f(imm32) : (p1 ? u2d(m_fpair[src1 >> 1]) : (double)u2f(m_reg[src1])); if (rd) { if (pd) { double res = source * u2d(m_fpair[rd >> 1]); m_fpair[rd >> 1] = d2u(res); } else { float res = (float)(source) * u2f(m_reg[rd]); m_reg[rd] = f2u(res); } } // parallel load/store op if (!(ls_bit1 == 0 && ls_bit2 == 0)) { vector_loadstore(); } break; } case 0xc8: case 0xd8: case 0xc9: case 0xd9: // vrnd { int acc = OP_ACC(); int p1 = m_ir & (1 << 5); int pd = (m_ir >> 7) & 3; int ls_bit1 = m_ir & (1 << 10); int ls_bit2 = m_ir & (1 << 6); int rd = OP_RS(); int rs1 = OP_SRC1(); double source = has_imm ? (double)u2f(imm32) : (p1 ? u2d(m_fpair[rs1 >> 1]) : (double)u2f(m_reg[rs1])); if (rd) { // destination register switch (pd) { case 0: m_reg[rd] = f2u((float)source); break; case 1: m_fpair[rd >> 1] = d2u(source); break; case 2: m_reg[rd] = (int32_t)(source); break; case 3: m_reg[rd] = (uint32_t)(source); break; } } else { // destination accumulator if (pd != 1) fatalerror("vrnd pd = %d at %08X\n", pd, m_pc); m_facc[acc] = source; } // parallel load/store op if (!(ls_bit1 == 0 && ls_bit2 == 0)) { vector_loadstore(); } break; } case 0xcc: case 0xdc: case 0xcd: case 0xdd: // vmac { int acc = OP_ACC(); int z = m_ir & (1 << 8); int pd = m_ir & (1 << 9); int ls_bit1 = m_ir & (1 << 10); int ls_bit2 = m_ir & (1 << 6); int rd = OP_RD(); float src1 = u2f(m_reg[OP_SRC1()]); float src2 = u2f(m_reg[OP_RS()]); float res = (src1 * src2) + (z ? 0.0f : m_facc[acc]); // parallel load/store op if (!(ls_bit1 == 0 && ls_bit2 == 0)) { vector_loadstore(); // if the opcode has load/store, dest is always accumulator m_facc[acc] = (double)res; } else { if (rd) { if (pd) m_fpair[rd >> 1] = d2u(res); else m_reg[rd] = f2u((float)res); } else { // write to accumulator m_facc[acc] = (double)res; } } break; } case 0xce: case 0xde: case 0xcf: case 0xdf: // vmsc { int acc = OP_ACC(); int z = m_ir & (1 << 8); int pd = m_ir & (1 << 9); int ls_bit1 = m_ir & (1 << 10); int ls_bit2 = m_ir & (1 << 6); int rd = OP_RD(); float src1 = u2f(m_reg[OP_SRC1()]); float src2 = u2f(m_reg[OP_RS()]); float res = (z ? 0.0f : m_facc[acc]) - (src1 * src2); // parallel load/store op if (!(ls_bit1 == 0 && ls_bit2 == 0)) { vector_loadstore(); // if the opcode has load/store, dest is always accumulator m_facc[acc] = (double)res; } else { if (rd) { if (pd) m_fpair[rd >> 1] = d2u(res); else m_reg[rd] = f2u((float)res); } else { // write to accumulator m_facc[acc] = (double)res; } } break; } case 0xe0: case 0xe1: // fadd { int rd = OP_RD(); int rs = OP_RS(); int src1 = OP_SRC1(); int precision = (m_ir >> 5) & 0x3f; if (rd) // only calculate if destination register is valid { switch (precision) { case 0x00: // SP - SP -> SP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); float s2 = u2f(m_reg[rs]); m_reg[rd] = f2u(s1 + s2); break; } case 0x10: // SP - SP -> DP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); float s2 = u2f(m_reg[rs]); uint64_t res = d2u((double)(s1 + s2)); m_fpair[rd >> 1] = res; break; } case 0x14: // SP - DP -> DP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); double s2 = u2d(m_fpair[rs >> 1]); uint64_t res = d2u((double) s1 + s2); m_fpair[rd >> 1] = res; break; } case 0x11: // DP - SP -> DP { double s1 = u2d(m_fpair[src1 >> 1]); float s2 = u2f(m_reg[rs]); uint64_t res = d2u(s1 + (double) s2); m_fpair[rd >> 1] = res; break; } case 0x15: // DP - DP -> DP { double s1 = u2d(m_fpair[src1 >> 1]); double s2 = u2d(m_fpair[rs >> 1]); uint64_t res = d2u((double)(s1 + s2)); m_fpair[rd >> 1] = res; break; } default: fatalerror("fadd: invalid precision combination %02X\n", precision); } } break; } case 0xe2: case 0xe3: // fsub { int rd = OP_RD(); int rs = OP_RS(); int src1 = OP_SRC1(); int precision = (m_ir >> 5) & 0x3f; if (rd) // only calculate if destination register is valid { switch (precision) { case 0x00: // SP - SP -> SP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); float s2 = u2f(m_reg[rs]); m_reg[rd] = f2u(s1 - s2); break; } case 0x10: // SP - SP -> DP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); float s2 = u2f(m_reg[rs]); uint64_t res = d2u((double)(s1 - s2)); m_fpair[rd >> 1] = res; break; } case 0x14: // SP - DP -> DP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); double s2 = u2d(m_fpair[rs >> 1]); uint64_t res = d2u((double) s1 - s2); m_fpair[rd >> 1] = res; break; } case 0x11: // DP - SP -> DP { double s1 = u2d(m_fpair[src1 >> 1]); float s2 = u2f(m_reg[rs]); uint64_t res = d2u(s1 - (double) s2); m_fpair[rd >> 1] = res; break; } case 0x15: // DP - DP -> DP { double s1 = u2d(m_fpair[src1 >> 1]); double s2 = u2d(m_fpair[rs >> 1]); uint64_t res = d2u((double)(s1 - s2)); m_fpair[rd >> 1] = res; break; } default: fatalerror("fsub: invalid precision combination %02X\n", precision); } } break; } case 0xe4: case 0xe5: // fmpy { int rd = OP_RD(); int rs = OP_RS(); int src1 = OP_SRC1(); int precision = (m_ir >> 5) & 0x3f; if (rd) // only calculate if destination register is valid { switch (precision) { case 0x00: // SP x SP -> SP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); float s2 = u2f(m_reg[rs]); m_reg[rd] = f2u(s1 * s2); break; } case 0x10: // SP x SP -> DP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); float s2 = u2f(m_reg[rs]); uint64_t res = d2u((double)(s1 * s2)); m_fpair[rd >> 1] = res; break; } case 0x14: // SP x DP -> DP { float s1 = u2f(has_imm ? imm32 : m_reg[src1]); double s2 = u2d(m_fpair[rs >> 1]); uint64_t res = d2u((double)s1 * s2); m_fpair[rd >> 1] = res; break; } case 0x11: // DP x SP -> DP { double s1 = u2d(m_fpair[src1 >> 1]); float s2 = u2f(m_reg[rs]); uint64_t res = d2u(s1 * (double) s2); m_fpair[rd >> 1] = res; break; } case 0x15: // DP x DP -> DP { double s1 = u2d(m_fpair[src1 >> 1]); double s2 = u2d(m_fpair[rs >> 1]); uint64_t res = d2u(s1 * s2); m_fpair[rd >> 1] = res; break; } case 0x2a: // I x I -> I { m_reg[rd] = (int32_t)(m_reg[rs]) * (int32_t)(has_imm ? imm32 : m_reg[OP_SRC1()]); break; } case 0x3f: // U x U -> U { m_reg[rd] = (uint32_t)(m_reg[rs]) * (uint32_t)(has_imm ? imm32 : m_reg[OP_SRC1()]); break; } default: fatalerror("fmpy: invalid precision combination %02X\n", precision); } } break; } case 0xe6: case 0xe7: // fdiv { int rd = OP_RD(); int p1 = m_ir & (1 << 5); int p2 = m_ir & (1 << 7); int pd = m_ir & (1 << 9); int rs1 = OP_SRC1(); int rs2 = OP_RS(); if (rd) { double src1 = has_imm ? (double)u2f(imm32) : (p1 ? u2d(m_fpair[rs1 >> 1]) : (double)u2f(m_reg[rs1])); double src2 = p2 ? u2d(m_fpair[rs2 >> 1]) : (double)u2f(m_reg[rs2]); double res; if (src2 != 0.0) res = src1 / src2; else res = 0.0f; if (pd) m_fpair[rd >> 1] = d2u(res); else m_reg[rd] = f2u((float)res); } break; } case 0xe8: case 0xe9: // frnd { //int mode = (m_ir >> 7) & 3; int p1 = (m_ir >> 5) & 3; int pd = (m_ir >> 9) & 3; int src1 = OP_SRC1(); int rd = OP_RD(); double s = 0.0; switch (p1) { case 0: s = has_imm ? (double)(u2f(imm32)) : (double)u2f(m_reg[src1]); break; case 1: s = u2d(m_fpair[src1 >> 1]); break; case 2: s = has_imm ? (double)((int32_t)(imm32)) : (double)(int32_t)(m_reg[src1]); break; case 3: s = has_imm ? (double)((uint32_t)(imm32)) : (double)(uint32_t)(m_reg[src1]); break; } // TODO: round if (rd) { switch (pd) { case 0: m_reg[rd] = f2u((float)(s)); break; case 1: m_fpair[rd >> 1] = d2u(s); break; case 2: m_reg[rd] = (int32_t)(s); break; case 3: m_reg[rd] = (uint32_t)(s); break; } } break; } case 0xea: case 0xeb: // fcmp { int rd = OP_RD(); int p1 = m_ir & (1 << 5); int p2 = m_ir & (1 << 7); int rs1 = OP_SRC1(); int rs2 = OP_RS(); double src1 = has_imm ? (double)(u2f(imm32)) : (p1 ? u2d(m_fpair[rs1 >> 1]) : (double)u2f(m_reg[rs1])); double src2 = p2 ? u2d(m_fpair[rs2 >> 1]) : (double)u2f(m_reg[rs2]); if (rd) { uint32_t flags = 0; flags |= (src1 == src2) ? (1 << 20) : 0; flags |= (src1 != src2) ? (1 << 21) : 0; flags |= (src1 > src2) ? (1 << 22) : 0; flags |= (src1 <= src2) ? (1 << 23) : 0; flags |= (src1 < src2) ? (1 << 24) : 0; flags |= (src1 >= src2) ? (1 << 25) : 0; flags |= (src1 < 0 || src1 > src2) ? (1 << 26) : 0; flags |= (src1 > 0 && src1 < src2) ? (1 << 27) : 0; flags |= (src1 >= 0 && src1 <= src2) ? (1 << 28) : 0; flags |= (src1 <= 0 || src1 >= src2) ? (1 << 29) : 0; // TODO: src1 or src2 unordered // TODO: src1 and src2 ordered m_reg[rd] = flags; } break; } case 0xee: case 0xef: // fsqrt { int rd = OP_RD(); int src1 = OP_SRC1(); int p1 = m_ir & (1 << 5); int pd = m_ir & (1 << 9); double source = has_imm ? (double)u2f(imm32) : (p1 ? u2d(m_fpair[src1 >> 1]) : (double)u2f(m_reg[src1])); if (rd) { double res; if (source >= 0.0f) res = sqrt(source); else res = 0.0; if (pd) m_fpair[rd >> 1] = d2u(res); else m_reg[rd] = f2u((float)res); } break; } case 0xf2: // rmo { uint32_t source = m_reg[OP_RS()]; int rd = OP_RD(); int bit = 32; for (int i=0; i < 32; i++) { if (source & (1 << (31-i))) { bit = i; break; } } if (rd) m_reg[rd] = bit; break; } default: fatalerror("execute_reg_long_imm(): %08X: opcode %08X (%02X)", m_pc, m_ir, (m_ir >> 12) & 0xff); } } void tms32082_mp_device::execute() { switch ((m_ir >> 20) & 3) { case 0: case 1: case 2: execute_short_imm(); break; case 3: execute_reg_long_imm(); break; } }
johnparker007/mame
src/devices/cpu/tms32082/mp_ops.cpp
C++
gpl-2.0
40,621
<?php /* Copyright 2014 Sutherland Boswell (email : sutherland.boswell@gmail.com) 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. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ // Require thumbnail provider class require_once( VIDEO_THUMBNAILS_PATH . '/php/providers/class-video-thumbnails-provider.php' ); class Youku_Thumbnails extends Video_Thumbnails_Provider { // Human-readable name of the video provider public $service_name = 'Youku'; const service_name = 'Youku'; // Slug for the video provider public $service_slug = 'youku'; const service_slug = 'youku'; public static function register_provider( $providers ) { $providers[self::service_slug] = new self; return $providers; } // Regex strings public $regexes = array( '#http://player\.youku\.com/embed/([A-Za-z0-9]+)#', // iFrame '#http://player\.youku\.com/player\.php/sid/([A-Za-z0-9]+)/v\.swf#', // Flash '#http://v\.youku\.com/v_show/id_([A-Za-z0-9]+)\.html#' // Link ); // Thumbnail URL public function get_thumbnail_url( $id ) { $request = "http://v.youku.com/player/getPlayList/VideoIDS/$id/"; $response = wp_remote_get( $request, array( 'sslverify' => false ) ); if( is_wp_error( $response ) ) { $result = $this->construct_info_retrieval_error( $request, $response ); } else { $result = json_decode( $response['body'] ); $result = $result->data[0]->logo; } return $result; } // Test cases public static function get_test_cases() { return array( array( 'markup' => '<iframe height=498 width=510 src="http://player.youku.com/embed/XMzQyMzk5MzQ4" frameborder=0 allowfullscreen></iframe>', 'expected' => 'http://g1.ykimg.com/1100641F464F0FB57407E2053DFCBC802FBBC4-E4C5-7A58-0394-26C366F10493', 'expected_hash' => 'deac7bb89058a8c46ae2350da9d33ba8', 'name' => __( 'iFrame Embed', 'video-thumbnails' ) ), array( 'markup' => '<embed src="http://player.youku.com/player.php/sid/XMzQyMzk5MzQ4/v.swf" quality="high" width="480" height="400" align="middle" allowScriptAccess="sameDomain" allowFullscreen="true" type="application/x-shockwave-flash"></embed>', 'expected' => 'http://g1.ykimg.com/1100641F464F0FB57407E2053DFCBC802FBBC4-E4C5-7A58-0394-26C366F10493', 'expected_hash' => 'deac7bb89058a8c46ae2350da9d33ba8', 'name' => __( 'Flash Embed', 'video-thumbnails' ) ), array( 'markup' => 'http://v.youku.com/v_show/id_XMzQyMzk5MzQ4.html', 'expected' => 'http://g1.ykimg.com/1100641F464F0FB57407E2053DFCBC802FBBC4-E4C5-7A58-0394-26C366F10493', 'expected_hash' => 'deac7bb89058a8c46ae2350da9d33ba8', 'name' => __( 'Video URL', 'video-thumbnails' ) ), ); } } ?>
trocvuong/izzfeed_us
wp-content/plugins/video-thumbnails/php/providers/class-youku-thumbnails.php
PHP
gpl-2.0
3,248
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "EmuFileWrapper.h" #include "filesystem/File.h" #include "threads/SingleLock.h" CEmuFileWrapper g_emuFileWrapper; namespace { constexpr bool isValidFilePtr(FILE* f) { return (f != nullptr); } } CEmuFileWrapper::CEmuFileWrapper() { // since we always use dlls we might just initialize it directly for (int i = 0; i < MAX_EMULATED_FILES; i++) { memset(&m_files[i], 0, sizeof(EmuFileObject)); m_files[i].used = false; m_files[i].fd = -1; } } CEmuFileWrapper::~CEmuFileWrapper() { CleanUp(); } void CEmuFileWrapper::CleanUp() { CSingleLock lock(m_criticalSection); for (int i = 0; i < MAX_EMULATED_FILES; i++) { if (m_files[i].used) { m_files[i].file_xbmc->Close(); delete m_files[i].file_xbmc; if (m_files[i].file_lock) { delete m_files[i].file_lock; m_files[i].file_lock = nullptr; } m_files[i].used = false; m_files[i].fd = -1; } } } EmuFileObject* CEmuFileWrapper::RegisterFileObject(XFILE::CFile* pFile) { EmuFileObject* object = nullptr; CSingleLock lock(m_criticalSection); for (int i = 0; i < MAX_EMULATED_FILES; i++) { if (!m_files[i].used) { // found a free location object = &m_files[i]; object->used = true; object->file_xbmc = pFile; object->fd = (i + FILE_WRAPPER_OFFSET); object->file_lock = new CCriticalSection(); break; } } return object; } void CEmuFileWrapper::UnRegisterFileObjectByDescriptor(int fd) { int i = fd - FILE_WRAPPER_OFFSET; if (! (i >= 0 && i < MAX_EMULATED_FILES)) return; if (!m_files[i].used) return; CSingleLock lock(m_criticalSection); // we assume the emulated function already deleted the CFile object if (m_files[i].file_lock) { delete m_files[i].file_lock; m_files[i].file_lock = nullptr; } m_files[i].used = false; m_files[i].fd = -1; } void CEmuFileWrapper::UnRegisterFileObjectByStream(FILE* stream) { if (isValidFilePtr(stream)) { EmuFileObject* o = reinterpret_cast<EmuFileObject*>(stream); return UnRegisterFileObjectByDescriptor(o->fd); } } void CEmuFileWrapper::LockFileObjectByDescriptor(int fd) { int i = fd - FILE_WRAPPER_OFFSET; if (i >= 0 && i < MAX_EMULATED_FILES) { if (m_files[i].used) { m_files[i].file_lock->lock(); } } } bool CEmuFileWrapper::TryLockFileObjectByDescriptor(int fd) { int i = fd - FILE_WRAPPER_OFFSET; if (i >= 0 && i < MAX_EMULATED_FILES) { if (m_files[i].used) { return m_files[i].file_lock->try_lock(); } } return false; } void CEmuFileWrapper::UnlockFileObjectByDescriptor(int fd) { int i = fd - FILE_WRAPPER_OFFSET; if (i >= 0 && i < MAX_EMULATED_FILES) { if (m_files[i].used) { m_files[i].file_lock->unlock(); } } } EmuFileObject* CEmuFileWrapper::GetFileObjectByDescriptor(int fd) { int i = fd - FILE_WRAPPER_OFFSET; if (i >= 0 && i < MAX_EMULATED_FILES) { if (m_files[i].used) { return &m_files[i]; } } return nullptr; } EmuFileObject* CEmuFileWrapper::GetFileObjectByStream(FILE* stream) { if (isValidFilePtr(stream)) { EmuFileObject* o = reinterpret_cast<EmuFileObject*>(stream); return GetFileObjectByDescriptor(o->fd); } return nullptr; } XFILE::CFile* CEmuFileWrapper::GetFileXbmcByDescriptor(int fd) { auto object = GetFileObjectByDescriptor(fd); if (object != nullptr && object->used) { return object->file_xbmc; } return nullptr; } XFILE::CFile* CEmuFileWrapper::GetFileXbmcByStream(FILE* stream) { if (isValidFilePtr(stream)) { EmuFileObject* object = reinterpret_cast<EmuFileObject*>(stream); if (object != nullptr && object->used) { return object->file_xbmc; } } return nullptr; } int CEmuFileWrapper::GetDescriptorByStream(FILE* stream) { if (isValidFilePtr(stream)) { EmuFileObject* obj = reinterpret_cast<EmuFileObject*>(stream); int i = obj->fd - FILE_WRAPPER_OFFSET; if (i >= 0 && i < MAX_EMULATED_FILES) { return i + FILE_WRAPPER_OFFSET; } } return -1; } FILE* CEmuFileWrapper::GetStreamByDescriptor(int fd) { auto object = GetFileObjectByDescriptor(fd); if (object != nullptr && object->used) { return reinterpret_cast<FILE*>(object); } return nullptr; } bool CEmuFileWrapper::StreamIsEmulatedFile(FILE* stream) { if (isValidFilePtr(stream)) { EmuFileObject* obj = reinterpret_cast<EmuFileObject*>(stream); return DescriptorIsEmulatedFile(obj->fd); } return false; }
notspiff/xbmc
xbmc/cores/DllLoader/exports/util/EmuFileWrapper.cpp
C++
gpl-2.0
5,290
/** * @license @product.name@ JS v@product.version@ (@product.date@) * * Money Flow Index indicator for Highstock * * (c) 2010-2019 Grzegorz Blachliński * * License: www.highcharts.com/license */ 'use strict'; import '../../indicators/mfi.src.js';
blue-eyed-devil/testCMS
externals/highcharts/es-modules/masters/indicators/mfi.src.js
JavaScript
gpl-3.0
258
// { dg-options "-std=gnu++14" } // { dg-do compile } // Copyright (C) 2015-2016 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, 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 General Public License for more details. // You should have received a moved_to of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <experimental/memory> using std::experimental::observer_ptr; struct nontrivial {nontrivial() {}}; struct other {}; struct base {}; struct derived : base {}; static_assert(!std::is_trivially_constructible< observer_ptr<nontrivial>>::value, ""); static_assert(std::is_trivially_copyable< observer_ptr<nontrivial>>::value, ""); static_assert(std::is_trivially_destructible< observer_ptr<nontrivial>>::value, ""); static_assert(std::is_constructible< observer_ptr<nontrivial>, nontrivial*>::value, ""); static_assert(std::is_constructible<observer_ptr<base>, base*>::value, ""); static_assert(std::is_constructible<observer_ptr<base>, derived*>::value, ""); static_assert(!std::is_constructible<observer_ptr<base>, other*>::value, ""); static_assert(std::is_constructible< observer_ptr<base>, observer_ptr<base>>::value, ""); static_assert(std::is_constructible< observer_ptr<base>, observer_ptr<derived>>::value, ""); static_assert(!std::is_constructible< observer_ptr<base>, observer_ptr<other>>::value, ""); static_assert(!std::is_assignable< observer_ptr<nontrivial>, nontrivial*>::value, ""); static_assert(std::is_assignable< observer_ptr<nontrivial>, observer_ptr<nontrivial>>::value, ""); static_assert(std::is_assignable<observer_ptr<base>, observer_ptr<base>>::value, ""); static_assert(std::is_assignable<observer_ptr<base>, observer_ptr<derived>>::value, ""); static_assert(!std::is_assignable< observer_ptr<base>, observer_ptr<other>>::value, ""); static_assert(std::is_assignable<observer_ptr<const int>, observer_ptr<int>>::value, ""); static_assert(!std::is_assignable<observer_ptr<int>, observer_ptr<const int>>::value, "");
selmentdev/selment-toolchain
source/gcc-latest/libstdc++-v3/testsuite/experimental/memory/observer_ptr/requirements.cc
C++
gpl-3.0
2,725
package nomad import ( "fmt" "time" "github.com/armon/go-metrics" "github.com/hashicorp/nomad/nomad/structs" ) // Periodic endpoint is used for periodic job interactions type Periodic struct { srv *Server } // Force is used to force a new instance of a periodic job func (p *Periodic) Force(args *structs.PeriodicForceRequest, reply *structs.PeriodicForceResponse) error { if done, err := p.srv.forward("Periodic.Force", args, args, reply); done { return err } defer metrics.MeasureSince([]string{"nomad", "periodic", "force"}, time.Now()) // Validate the arguments if args.JobID == "" { return fmt.Errorf("missing job ID for evaluation") } // Lookup the job snap, err := p.srv.fsm.State().Snapshot() if err != nil { return err } job, err := snap.JobByID(args.JobID) if err != nil { return err } if job == nil { return fmt.Errorf("job not found") } if !job.IsPeriodic() { return fmt.Errorf("can't force launch non-periodic job") } // Force run the job. eval, err := p.srv.periodicDispatcher.ForceRun(job.ID) if err != nil { return fmt.Errorf("force launch for job %q failed: %v", job.ID, err) } reply.EvalID = eval.ID reply.EvalCreateIndex = eval.CreateIndex reply.Index = eval.CreateIndex return nil }
mkuzmin/terraform
vendor/github.com/hashicorp/nomad/nomad/periodic_endpoint.go
GO
mpl-2.0
1,256
<?php /** *@package plugins.inletArmada */ class InletArmadaPlugin extends KalturaPlugin implements IKalturaObjectLoader, IKalturaEnumerator { const PLUGIN_NAME = 'inletArmada'; public static function getPluginName() { return self::PLUGIN_NAME; } /** * @param string $baseClass * @param string $enumValue * @param array $constructorArgs * @return object */ public static function loadObject($baseClass, $enumValue, array $constructorArgs = null) { if($baseClass == 'KOperationEngine' && $enumValue == KalturaConversionEngineType::INLET_ARMADA) { if(!isset($constructorArgs['params']) || !isset($constructorArgs['outFilePath'])) return null; return new KOperationEngineInletArmada("", $constructorArgs['outFilePath']); } if($baseClass == 'KDLOperatorBase' && $enumValue == self::getApiValue(InletArmadaConversionEngineType::INLET_ARMADA)) { return new KDLOperatorInletArmada($enumValue); } return null; } /** * @param string $baseClass * @param string $enumValue * @return string */ public static function getObjectClass($baseClass, $enumValue) { if($baseClass == 'KOperationEngine' && $enumValue == self::getApiValue(InletArmadaConversionEngineType::INLET_ARMADA)) return 'KOperationEngineInletArmada'; if($baseClass == 'KDLOperatorBase' && $enumValue == self::getConversionEngineCoreValue(InletArmadaConversionEngineType::INLET_ARMADA)) return 'KDLOperatorInletArmada'; return null; } /** * @return array<string> list of enum classes names that extend the base enum name */ public static function getEnums($baseEnumName = null) { if(is_null($baseEnumName)) return array('InletArmadaConversionEngineType'); if($baseEnumName == 'conversionEngineType') return array('InletArmadaConversionEngineType'); return array(); } /** * @return int id of dynamic enum in the DB. */ public static function getConversionEngineCoreValue($valueName) { $value = self::getPluginName() . IKalturaEnumerator::PLUGIN_VALUE_DELIMITER . $valueName; return kPluginableEnumsManager::apiToCore('conversionEngineType', $value); } /** * @return string external API value of dynamic enum. */ public static function getApiValue($valueName) { return self::getPluginName() . IKalturaEnumerator::PLUGIN_VALUE_DELIMITER . $valueName; } }
ratliff/server
plugins/transcoding/inlet_armada/InletArmadaPlugin.php
PHP
agpl-3.0
2,348
require 'spec_helper' describe Spree::Admin::OverviewController do include AuthenticationWorkflow context "loading overview" do let(:user) { create_enterprise_user(enterprise_limit: 2) } before do controller.stub spree_current_user: user end context "when user owns only one enterprise" do let!(:enterprise) { create(:distributor_enterprise, owner: user) } context "when the referer is not an admin page" do before { @request.env['HTTP_REFERER'] = 'http://test.com/some_other_path' } context "and the enterprise has sells='unspecified'" do before do enterprise.update_attribute(:sells, "unspecified") end it "redirects to the welcome page for the enterprise" do spree_get :index response.should redirect_to welcome_admin_enterprise_path(enterprise) end end context "and the enterprise does not have sells='unspecified'" do it "renders the single enterprise dashboard" do spree_get :index response.should render_template "single_enterprise_dashboard" end end end context "when the refer is an admin page" do before { @request.env['HTTP_REFERER'] = 'http://test.com/admin' } it "renders the single enterprise dashboard" do spree_get :index response.should render_template "single_enterprise_dashboard" end end end context "when user owns multiple enterprises" do let!(:enterprise1) { create(:distributor_enterprise, owner: user) } let!(:enterprise2) { create(:distributor_enterprise, owner: user) } context "when the referer is not an admin page" do before { @request.env['HTTP_REFERER'] = 'http://test.com/some_other_path' } context "and at least one owned enterprise has sells='unspecified'" do before do enterprise1.update_attribute(:sells, "unspecified") end it "redirects to the enterprises index" do spree_get :index response.should redirect_to admin_enterprises_path end end context "and no owned enterprises have sells='unspecified'" do it "renders the multiple enterprise dashboard" do spree_get :index response.should render_template "multi_enterprise_dashboard" end end end context "when the refer is an admin page" do before { @request.env['HTTP_REFERER'] = 'http://test.com/admin' } it "renders the multiple enterprise dashboard" do spree_get :index response.should render_template "multi_enterprise_dashboard" end end end end end
levent/openfoodnetwork
spec/controllers/spree/admin/overview_controller_spec.rb
Ruby
agpl-3.0
2,772
<?php return array( /* |-------------------------------------------------------------------------- | Pagination Language Lines |-------------------------------------------------------------------------- | | The following language lines are used by the paginator library to build | the simple pagination links. You are free to change them to anything | you want to customize your views to better match your application. | */ 'previous' => '&laquo; Nakaraan', 'next' => 'Susunod &raquo;', );
ixmid/snipe-it
resources/lang/fil/pagination.php
PHP
agpl-3.0
547
//////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com . puppycrawl .tools. checkstyle.checks.whitespace.nowhitespacebefore; /** * Class for testing whitespace issues. * error missing author tag **/ class InputNoWhitespaceBeforeDefault { /** ignore assignment **/ private int mVar1=1; /** ignore assignment **/ private int mVar2 =1; /** Should be ok **/ private int mVar3 = 1; /** method **/ void method1() { final int a = 1; int b= 1; // Ignore 1 b=1; // Ignore 1 b+=1; // Ignore 1 b -=- 1 + (+ b); // Ignore 2 b = b ++ + b --; // Ignore 1 b = ++ b - -- b; // Ignore 1 } /** method **/ void method2() { synchronized(this) { } try{ } catch(RuntimeException e){ } } /** skip blank lines between comment and code, should be ok **/ private int mVar4 = 1; /** test WS after void return */ private void fastExit() { boolean complicatedStuffNeeded = true; if( !complicatedStuffNeeded ) { return; // should not complain about missing WS after return } else { // do complicated stuff } } /** test WS after non void return @return 2 */ private int nonVoid() { if ( true ) { return(2); // should complain about missing WS after return } else { return 2; // this is ok } } /** test casts **/ private void testCasts() { Object o = (Object) new Object(); // ok o = (Object)o; // error o = ( Object ) o; // ok o = (Object) o; // ok } /** test questions **/ private void testQuestions() { boolean b = (1 == 2)?true:false; b = (1==2) ? false : true; } /** star test **/ private void starTest() { int x = 2 *3* 4; } /** boolean test **/ private void boolTest() { boolean a = true; boolean x = ! a; int z = ~1 + ~ 2; } /** division test **/ private void divTest() { int a = 4 % 2; int b = 4% 2; int c = 4 %2; int d = 4%2; int e = 4 / 2; int f = 4/ 2; int g = 4 /2; int h = 4/2; } /** @return dot test **/ private java .lang. String dotTest() { Object o = new java.lang.Object(); o. toString(); o .toString(); o . toString(); return o.toString(); } /** assert statement test */ public void assertTest() { // OK assert true; // OK assert true : "Whups"; // evil colons, should be OK assert "OK".equals(null) ? false : true : "Whups"; // missing WS around assert assert(true); // missing WS around colon assert true:"Whups"; } /** another check */ void donBradman(Runnable aRun) { donBradman(new Runnable() { public void run() { } }); final Runnable r = new Runnable() { public void run() { } }; } /** rfe 521323, detect whitespace before ';' */ void rfe521323() { doStuff() ; // ^ whitespace for (int i = 0 ; i < 5; i++) { // ^ whitespace } } /** bug 806243 (NoWhitespaceBeforeCheck error for anonymous inner class) */ private int i ; // ^ whitespace private int i1, i2, i3 ; // ^ whitespace private int i4, i5, i6; /** bug 806243 (NoWhitespaceBeforeCheck error for anonymous inner class) */ void bug806243() { Object o = new InputNoWhitespaceBeforeDefault() { private int j ; // ^ whitespace }; } void doStuff() { } } /** * Bug 806242 (NoWhitespaceBeforeCheck error with an interface). * @author o_sukhodolsky * @version 1.0 */ interface IFoo_NoWhitespaceBeforeDefault { void foo() ; // ^ whitespace } /** * Avoid Whitespace errors in for loop. * @author lkuehne * @version 1.0 */ class SpecialCasesInForLoop_NoWhitespaceBeforeDefault { void forIterator() { // avoid conflict between WhiteSpaceAfter ';' and ParenPad(nospace) for (int i = 0; i++ < 5;) { // ^ no whitespace } // bug 895072 // avoid confilct between ParenPad(space) and NoWhiteSpace before ';' int i = 0; for ( ; i < 5; i++ ) { // ^ whitespace } for (int anInt : getSomeInts()) { //Should be ignored } } int[] getSomeInts() { int i = (int) ( 2 / 3 ); return null; } public void myMethod() { new Thread() { public void run() { } }.start(); } public void foo(java.util.List<? extends String[]> bar, Comparable<? super Object[]> baz) { } public void mySuperMethod() { Runnable[] runs = new Runnable[] {new Runnable() { public void run() { } }, new Runnable() { public void run() { } }}; runs[0] . run() ; } public void testNullSemi() { return ; } public void register(Object obj) { } public void doSomething(String args[]) { register(boolean[].class); register( args ); } public void parentheses() { testNullSemi ( ) ; } public static void testNoWhitespaceBeforeEllipses(String ... args) { } }
AkshitaKukreja30/checkstyle
src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespacebefore/InputNoWhitespaceBeforeDefault.java
Java
lgpl-2.1
5,995
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric.ws; import org.sonar.api.server.ws.WebService; public class MetricsWs implements WebService { public static final String ENDPOINT = "api/metrics"; private final MetricsWsAction[] actions; public MetricsWs(MetricsWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(ENDPOINT); controller.setDescription("Metrics management"); controller.setSince("2.6"); for (MetricsWsAction action : actions) { action.define(controller); } controller.done(); } }
abbeyj/sonarqube
server/sonar-server/src/main/java/org/sonar/server/metric/ws/MetricsWs.java
Java
lgpl-3.0
1,515
require_dependency 'user_query' class UsersController < ApplicationController def index if params[:followed_by] || params[:followers_of] if params[:followed_by] users = User.find(params[:followed_by]).following elsif params[:followers_of] users = User.find(params[:followers_of]).followers end users = users.page(params[:page]).per(20) UserQuery.load_is_followed(users, current_user) render json: users, meta: { cursor: 1 + (params[:page] || 1).to_i } elsif params[:to_follow] render json: User.where(to_follow: true), each_serializer: UserSerializer else ### OLD CODE PATH BELOW. Used only by the recommendations page. authenticate_user! status = { recommendations_up_to_date: current_user.recommendations_up_to_date } respond_to do |format| format.html { redirect_to '/' } format.json { render json: status } end end end def show user = User.find(params[:id]) # Redirect to canonical path if request.path != user_path(user) return redirect_to user_path(user), status: :moved_permanently end if user_signed_in? && current_user == user # Clear notifications if the current user is viewing his/her feed. # TODO: This needs to be moved elsewhere. Notification.where(user: user, notification_type: 'profile_comment', seen: false).update_all seen: true end respond_with_ember user end ember_action(:ember) { User.find(params[:user_id]) } def follow authenticate_user! user = User.find(params[:user_id]) if user != current_user if user.followers.include? current_user user.followers.destroy current_user action_type = 'unfollowed' else if current_user.following_count < 10_000 user.followers.push current_user action_type = 'followed' else flash[:message] = "Wow! You're following 10,000 people?! You should \ unfollow a few people that no longer interest you \ before following any others." action_type = nil end end if action_type Substory.from_action( user_id: current_user.id, action_type: action_type, followed_id: user.id ) end end respond_to do |format| format.html { redirect_to :back } format.json { render json: true } end end def update_avatar authenticate_user! user = User.find(params[:user_id]) if user == current_user user.avatar = params[:avatar] || params[:user][:avatar] user.save! respond_to do |format| format.html { redirect_to :back } format.json { render json: user, serializer: CurrentUserSerializer } end else error! 403 end end def disconnect_facebook authenticate_user! current_user.update_attributes(facebook_id: nil) redirect_to :back end def redirect_short_url @user = User.find_by_name params[:username] fail ActionController::RoutingError, 'Not Found' if @user.nil? redirect_to @user end def comment authenticate_user! # Create the story. @user = User.find(params[:user_id]) Action.broadcast( action_type: 'created_profile_comment', user: @user, poster: current_user, comment: params[:comment] ) respond_to do |format| format.html { redirect_to :back } format.json { render json: true } end end def update authenticate_user! user = User.find(params[:id]) changes = params[:current_user] || params[:user] return error!(401, 'Wrong user') unless current_user == user # Finagling things into place changes[:cover_image] = changes[:cover_image_url] if changes[:cover_image_url] =~ /^data:/ changes[:password] = changes[:new_password] if changes[:new_password].present? changes[:name] = changes[:new_username] if changes[:new_username].present? changes[:star_rating] = (changes[:rating_type] == 'advanced') %i(new_password new_username rating_type cover_image_url).each do |key| changes.delete(key) end changes = changes.permit(:about, :location, :website, :name, :waifu_char_id, :sfw_filter, :waifu, :bio, :email, :cover_image, :waifu_or_husbando, :title_language_preference, :password, :star_rating) # Convert to hash so that we ignore disallowed attributes user.assign_attributes(changes.to_h) if user.save render json: user else return error!(user.errors, 400) end end def to_follow fixed_user_list = %w( Gigguk Holden JeanP Arkada HappiLeeErin DoctorDazza Yokurama dexbonus DEMOLITION_D ) @users = User.where(name: fixed_user_list) render json: @users, each_serializer: UserSerializer end end
jcoady9/hummingbird
app/controllers/users_controller.rb
Ruby
apache-2.0
5,020
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Insights.Models; namespace Microsoft.Azure.Commands.Insights.OutputClasses { /// <summary> /// Wraps around a list of Dimension objects to display them with indentation /// </summary> public class PSLocalizableString : LocalizableString { /// <summary> /// Initializes a new instance of the PSLocalizableString class /// </summary> /// <param name="localizableString">The input LocalizableString object</param> public PSLocalizableString(LocalizableString localizableString) { if (localizableString != null) { this.LocalizedValue = localizableString.LocalizedValue; this.Value = localizableString.Value; } } /// <summary> /// A string representation of the list LocalizableString objects including indentation /// </summary> /// <returns>A string representation of the LocalizableString object including indentation</returns> public override string ToString() { return this.ToString(indentationTabs: 1); } } }
zhencui/azure-powershell
src/ResourceManager/Insights/Commands.Insights/OutputClasses/PSLocalizableString.cs
C#
apache-2.0
1,909
//>>built define("dgrid/extensions/nls/zh-cn/columnHider",{popupLabel:"\u663e\u793a\u6216\u9690\u85cf\u5217"});
aconyteds/Esri-Ozone-Map-Widget
vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dgrid/extensions/nls/zh-cn/columnHider.js
JavaScript
apache-2.0
111