question
stringclasses 1
value | context
stringlengths 4.2k
104k
| answers
listlengths 1
1
| length
int32 399
10k
| dataset
stringclasses 1
value | language
stringclasses 3
values | all_classes
null | _id
stringlengths 48
48
| _row_id
int64 0
499
| context_cheatsheet
stringlengths 4.19k
104k
| prompt_cheatsheet
stringclasses 1
value | answer_prefix
stringclasses 1
value | task
stringclasses 1
value | max_new_tokens
int64 84
84
| cheatsheet
stringlengths 620
12k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Please complete the code given below.
using System;
using System.Collections;
using System.Collections.Generic;
using Server.Commands;
using Server.Engines.PartySystem;
using Server.Factions;
using Server.Gumps;
using Server.Items;
using Server.Mobiles;
using Server.Network;
using Server.Spells;
using Server.Spells.Bushido;
using Server.Spells.Chivalry;
using Server.Spells.Necromancy;
using Server.Spells.Ninjitsu;
using Server.Spells.Seventh;
using Server.Spells.Spellweaving;
namespace Server.Engines.ConPVP
{
public delegate void CountdownCallback( int count );
public class DuelContext
{
private Mobile m_Initiator;
private ArrayList m_Participants;
private Ruleset m_Ruleset;
private Arena m_Arena;
private bool m_Registered = true;
private bool m_Finished, m_Started;
private bool m_ReadyWait;
private int m_ReadyCount;
private bool m_Rematch;
public bool Rematch{ get{ return m_Rematch; } }
public bool ReadyWait{ get{ return m_ReadyWait; } }
public int ReadyCount{ get{ return m_ReadyCount; } }
public bool Registered{ get{ return m_Registered; } }
public bool Finished{ get{ return m_Finished; } }
public bool Started{ get{ return m_Started; } }
public Mobile Initiator{ get{ return m_Initiator; } }
public ArrayList Participants{ get{ return m_Participants; } }
public Ruleset Ruleset{ get{ return m_Ruleset; } }
public Arena Arena{ get{ return m_Arena; } }
private bool CantDoAnything( Mobile mob )
{
if ( m_EventGame != null )
return m_EventGame.CantDoAnything( mob );
else
return false;
}
public static bool IsFreeConsume( Mobile mob )
{
PlayerMobile pm = mob as PlayerMobile;
if ( pm == null || pm.DuelContext == null || pm.DuelContext.m_EventGame == null )
return false;
return pm.DuelContext.m_EventGame.FreeConsume;
}
public void DelayBounce( TimeSpan ts, Mobile mob, Container corpse )
{
Timer.DelayCall( ts, new TimerStateCallback( DelayBounce_Callback ), new object[]{ mob, corpse } );
}
public static bool AllowSpecialMove( Mobile from, string name, SpecialMove move )
{
PlayerMobile pm = from as PlayerMobile;
if( pm == null )
return true;
DuelContext dc = pm.DuelContext;
return (dc == null || dc.InstAllowSpecialMove( from, name, move ));
}
public bool InstAllowSpecialMove( Mobile from, string name, SpecialMove move )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( CantDoAnything( from ) )
return false;
string title = null;
if( move is NinjaMove )
title = "Bushido";
else if( move is SamuraiMove )
title = "Ninjitsu";
if ( title == null || name == null || m_Ruleset.GetOption( title, name ) )
return true;
from.SendMessage( "The dueling ruleset prevents you from using this move." );
return false;
}
public bool AllowSpellCast( Mobile from, Spell spell )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( CantDoAnything( from ) )
return false;
if ( spell is Server.Spells.Fourth.RecallSpell )
from.SendMessage( "You may not cast this spell." );
string title = null, option = null;
if( spell is ArcanistSpell )
{
title = "Spellweaving";
option = spell.Name;
}
else if ( spell is PaladinSpell )
{
title = "Chivalry";
option = spell.Name;
}
else if ( spell is NecromancerSpell )
{
title = "Necromancy";
option = spell.Name;
}
else if ( spell is NinjaSpell )
{
title = "Ninjitsu";
option = spell.Name;
}
else if ( spell is SamuraiSpell )
{
title = "Bushido";
option = spell.Name;
}
else if( spell is MagerySpell )
{
switch( ((MagerySpell)spell).Circle )
{
case SpellCircle.First: title = "1st Circle"; break;
case SpellCircle.Second: title = "2nd Circle"; break;
case SpellCircle.Third: title = "3rd Circle"; break;
case SpellCircle.Fourth: title = "4th Circle"; break;
case SpellCircle.Fifth: title = "5th Circle"; break;
case SpellCircle.Sixth: title = "6th Circle"; break;
case SpellCircle.Seventh: title = "7th Circle"; break;
case SpellCircle.Eighth: title = "8th Circle"; break;
}
option = spell.Name;
}
else
{
title = "Other Spell";
option = spell.Name;
}
if ( title == null || option == null || m_Ruleset.GetOption( title, option ) )
return true;
from.SendMessage( "The dueling ruleset prevents you from casting this spell." );
return false;
}
public bool AllowItemEquip( Mobile from, Item item )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( item is Dagger || CheckItemEquip( from, item ) )
return true;
from.SendMessage( "The dueling ruleset prevents you from equiping this item." );
return false;
}
public static bool AllowSpecialAbility( Mobile from, string name, bool message )
{
PlayerMobile pm = from as PlayerMobile;
if ( pm == null )
return true;
DuelContext dc = pm.DuelContext;
return ( dc == null || dc.InstAllowSpecialAbility( from, name, message ) );
}
public bool InstAllowSpecialAbility( Mobile from, string name, bool message )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( CantDoAnything( from ) )
return false;
if ( m_Ruleset.GetOption( "Combat Abilities", name ) )
return true;
if ( message )
from.SendMessage( "The dueling ruleset prevents you from using this combat ability." );
return false;
}
public bool CheckItemEquip( Mobile from, Item item )
{
if ( item is Fists )
{
if ( !m_Ruleset.GetOption( "Weapons", "Wrestling" ) )
return false;
}
else if ( item is BaseArmor )
{
BaseArmor armor = (BaseArmor)item;
if ( armor.ProtectionLevel > ArmorProtectionLevel.Regular && !m_Ruleset.GetOption( "Armor", "Magical" ) )
return false;
if ( !Core.AOS && armor.Resource != armor.DefaultResource && !m_Ruleset.GetOption( "Armor", "Colored" ) )
return false;
if ( armor is BaseShield && !m_Ruleset.GetOption( "Armor", "Shields" ) )
return false;
}
else if ( item is BaseWeapon )
{
BaseWeapon weapon = (BaseWeapon)item;
if ( (weapon.DamageLevel > WeaponDamageLevel.Regular || weapon.AccuracyLevel > WeaponAccuracyLevel.Regular) && !m_Ruleset.GetOption( "Weapons", "Magical" ) )
return false;
if ( !Core.AOS && weapon.Resource != CraftResource.Iron && weapon.Resource != CraftResource.None && !m_Ruleset.GetOption( "Weapons", "Runics" ) )
return false;
if ( weapon is BaseRanged && !m_Ruleset.GetOption( "Weapons", "Ranged" ) )
return false;
if ( !(weapon is BaseRanged) && !m_Ruleset.GetOption( "Weapons", "Melee" ) )
return false;
if ( weapon.PoisonCharges > 0 && weapon.Poison != null && !m_Ruleset.GetOption( "Weapons", "Poisoned" ) )
return false;
if ( weapon is BaseWand && !m_Ruleset.GetOption( "Items", "Wands" ) )
return false;
}
return true;
}
public bool AllowSkillUse( Mobile from, SkillName skill )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( CantDoAnything( from ) )
return false;
int id = (int)skill;
if ( id >= 0 && id < SkillInfo.Table.Length )
{
if ( m_Ruleset.GetOption( "Skills", SkillInfo.Table[id].Name ) )
return true;
}
from.SendMessage( "The dueling ruleset prevents you from using this skill." );
return false;
}
public bool AllowItemUse( Mobile from, Item item )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( !(item is BaseRefreshPotion) )
{
if ( CantDoAnything( from ) )
return false;
}
string title = null, option = null;
if ( item is BasePotion )
{
title = "Potions";
if ( item is BaseAgilityPotion )
option = "Agility";
else if ( item is BaseCurePotion )
option = "Cure";
else if ( item is BaseHealPotion )
option = "Heal";
else if ( item is NightSightPotion )
option = "Nightsight";
else if ( item is BasePoisonPotion )
option = "Poison";
else if ( item is BaseStrengthPotion )
option = "Strength";
else if ( item is BaseExplosionPotion )
option = "Explosion";
else if ( item is BaseRefreshPotion )
option = "Refresh";
}
else if ( item is Bandage )
{
title = "Items";
option = "Bandages";
}
else if ( item is TrapableContainer )
{
if ( ((TrapableContainer)item).TrapType != TrapType.None )
{
title = "Items";
option = "Trapped Containers";
}
}
else if ( item is Bola )
{
title = "Items";
option = "Bolas";
}
else if ( item is OrangePetals )
{
title = "Items";
option = "Orange Petals";
}
else if ( item is EtherealMount || item.Layer == Layer.Mount )
{
title = "Items";
option = "Mounts";
}
else if ( item is LeatherNinjaBelt )
{
title = "Items";
option = "Shurikens";
}
else if ( item is Fukiya )
{
title = "Items";
option = "Fukiya Darts";
}
else if ( item is FireHorn )
{
title = "Items";
option = "Fire Horns";
}
else if ( item is BaseWand )
{
title = "Items";
option = "Wands";
}
if ( title != null && option != null && m_StartedBeginCountdown && !m_Started )
{
from.SendMessage( "You may not use this item before the duel begins." );
return false;
}
else if ( item is BasePotion && !(item is BaseExplosionPotion) && !(item is BaseRefreshPotion) && IsSuddenDeath )
{
from.SendMessage( 0x22, "You may not drink potions in sudden death." );
return false;
}
else if ( item is Bandage && IsSuddenDeath )
{
from.SendMessage( 0x22, "You may not use bandages in sudden death." );
return false;
}
if ( title == null || option == null || m_Ruleset.GetOption( title, option ) )
return true;
from.SendMessage( "The dueling ruleset prevents you from using this item." );
return false;
}
private void DelayBounce_Callback( object state )
{
object[] states = (object[])state;
Mobile mob = (Mobile) states[0];
Container corpse = (Container) states[1];
RemoveAggressions( mob );
SendOutside( mob );
Refresh( mob, corpse );
Debuff( mob );
CancelSpell( mob );
mob.Frozen = false;
}
public void OnMapChanged( Mobile mob )
{
OnLocationChanged( mob );
}
public void OnLocationChanged( Mobile mob )
{
if ( !m_Registered || !m_StartedBeginCountdown || m_Finished )
return;
Arena arena = m_Arena;
if ( arena == null )
return;
if ( mob.Map == arena.Facet && arena.Bounds.Contains( mob.Location ) )
return;
DuelPlayer pl = Find( mob );
if ( pl == null || pl.Eliminated )
return;
if ( mob.Map == Map.Internal ) {
// they've logged out
if ( mob.LogoutMap == arena.Facet && arena.Bounds.Contains( mob.LogoutLocation ) ) {
// they logged out inside the arena.. set them to eject on login
mob.LogoutLocation = arena.Outside;
}
}
pl.Eliminated = true;
mob.LocalOverheadMessage( MessageType.Regular, 0x22, false, "You have forfeited your position in the duel." );
mob.NonlocalOverheadMessage( MessageType.Regular, 0x22, false, String.Format( "{0} has forfeited by leaving the dueling arena.", mob.Name ) );
Participant winner = CheckCompletion();
if ( winner != null )
Finish( winner );
}
private bool m_Yielding;
public void OnDeath( Mobile mob, Container corpse )
{
if ( !m_Registered || !m_Started )
return;
DuelPlayer pl = Find( mob );
if ( pl != null && !pl.Eliminated )
{
if ( m_EventGame != null && !m_EventGame.OnDeath( mob, corpse ) )
return;
pl.Eliminated = true;
if ( mob.Poison != null )
mob.Poison = null;
Requip( mob, corpse );
DelayBounce( TimeSpan.FromSeconds( 4.0 ), mob, corpse );
Participant winner = CheckCompletion();
if ( winner != null )
{
Finish( winner );
}
else if ( !m_Yielding )
{
mob.LocalOverheadMessage( MessageType.Regular, 0x22, false, "You have been defeated." );
mob.NonlocalOverheadMessage( MessageType.Regular, 0x22, false, String.Format( "{0} has been defeated.", mob.Name ) );
}
}
}
public bool CheckFull()
{
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
if ( p.HasOpenSlot )
return false;
}
return true;
}
public void Requip( Mobile from, Container cont )
{
Corpse corpse = cont as Corpse;
if ( corpse == null )
return;
List<Item> items = new List<Item>( corpse.Items );
bool gathered = false;
bool didntFit = false;
Container pack = from.Backpack;
for ( int i = 0; !didntFit && i < items.Count; ++i )
{
Item item = items[i];
Point3D loc = item.Location;
if ( (item.Layer == Layer.Hair || item.Layer == Layer.FacialHair) || !item.Movable )
continue;
if ( pack != null )
{
pack.DropItem( item );
gathered = true;
}
else
{
didntFit = true;
}
}
corpse.Carved = true;
if ( corpse.ItemID == 0x2006 )
{
corpse.ProcessDelta();
corpse.SendRemovePacket();
corpse.ItemID = Utility.Random( 0xECA, 9 ); // bone graphic
corpse.Hue = 0;
corpse.ProcessDelta();
Mobile killer = from.FindMostRecentDamager( false );
if ( killer != null && killer.Player )
killer.AddToBackpack( new Head( m_Tournament == null ? HeadType.Duel : HeadType.Tournament, from.Name ) );
}
from.PlaySound( 0x3E3 );
if ( gathered && !didntFit )
from.SendLocalizedMessage( 1062471 ); // You quickly gather all of your belongings.
else if ( gathered && didntFit )
from.SendLocalizedMessage( 1062472 ); // You gather some of your belongings. The rest remain on the corpse.
}
public void Refresh( Mobile mob, Container cont )
{
if ( !mob.Alive )
{
mob.Resurrect();
DeathRobe robe = mob.FindItemOnLayer( Layer.OuterTorso ) as DeathRobe;
if ( robe != null )
robe.Delete();
if ( cont is Corpse )
{
Corpse corpse = (Corpse) cont;
for ( int i = 0; i < corpse.EquipItems.Count; ++i )
{
Item item = corpse.EquipItems[i];
if ( item.Movable && item.Layer != Layer.Hair && item.Layer != Layer.FacialHair && item.IsChildOf( mob.Backpack ) )
mob.EquipItem( item );
}
}
}
mob.Hits = mob.HitsMax;
mob.Stam = mob.StamMax;
mob.Mana = mob.ManaMax;
mob.Poison = null;
}
public void SendOutside( Mobile mob )
{
if ( m_Arena == null )
return;
mob.Combatant = null;
mob.MoveToWorld( m_Arena.Outside, m_Arena.Facet );
}
private Point3D m_GatePoint;
private Map m_GateFacet;
public void Finish( Participant winner )
{
if ( m_Finished )
return;
EndAutoTie();
StopSDTimers();
m_Finished = true;
for ( int i = 0; i < winner.Players.Length; ++i )
{
DuelPlayer pl = winner.Players[i];
if ( pl != null && !pl.Eliminated )
DelayBounce( TimeSpan.FromSeconds( 8.0 ), pl.Mobile, null );
}
winner.Broadcast( 0x59, null, winner.Players.Length == 1 ? "{0} has won the duel." : "{0} and {1} team have won the duel.", winner.Players.Length == 1 ? "You have won the duel." : "Your team has won the duel." );
if ( m_Tournament != null && winner.TournyPart != null )
{
m_Match.Winner = winner.TournyPart;
winner.TournyPart.WonMatch( m_Match );
m_Tournament.HandleWon( m_Arena, m_Match, winner.TournyPart );
}
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant loser = (Participant)m_Participants[i];
if ( loser != winner )
{
loser.Broadcast( 0x22, null, loser.Players.Length == 1 ? "{0} has lost the duel." : "{0} and {1} team have lost the duel.", loser.Players.Length == 1 ? "You have lost the duel." : "Your team has lost the duel." );
if ( m_Tournament != null && loser.TournyPart != null )
loser.TournyPart.LostMatch( m_Match );
}
for ( int j = 0; j < loser.Players.Length; ++j )
{
if ( loser.Players[j] != null )
{
RemoveAggressions( loser.Players[j].Mobile );
loser.Players[j].Mobile.Delta( MobileDelta.Noto );
loser.Players[j].Mobile.CloseGump( typeof( BeginGump ) );
if ( m_Tournament != null )
loser.Players[j].Mobile.SendEverything();
}
}
}
if ( IsOneVsOne )
{
DuelPlayer dp1 = ((Participant)m_Participants[0]).Players[0];
DuelPlayer dp2 = ((Participant)m_Participants[1]).Players[0];
if ( dp1 != null && dp2 != null )
{
Award( dp1.Mobile, dp2.Mobile, dp1.Participant == winner );
Award( dp2.Mobile, dp1.Mobile, dp2.Participant == winner );
}
}
if ( m_EventGame != null )
m_EventGame.OnStop();
Timer.DelayCall( TimeSpan.FromSeconds( 9.0 ), new TimerCallback( UnregisterRematch ) );
}
public void Award( Mobile us, Mobile them, bool won )
{
Ladder ladder = ( m_Arena == null ? Ladder.Instance : m_Arena.AcquireLadder() );
if ( ladder == null )
return;
LadderEntry ourEntry = ladder.Find( us );
LadderEntry theirEntry = ladder.Find( them );
if ( ourEntry == null || theirEntry == null )
return;
int xpGain = Ladder.GetExperienceGain( ourEntry, theirEntry, won );
if ( xpGain == 0 )
return;
if ( m_Tournament != null )
xpGain *= ( xpGain > 0 ? 5 : 2 );
if ( won )
++ourEntry.Wins;
else
++ourEntry.Losses;
int oldLevel = Ladder.GetLevel( ourEntry.Experience );
ourEntry.Experience += xpGain;
if ( ourEntry.Experience < 0 )
ourEntry.Experience = 0;
ladder.UpdateEntry( ourEntry );
int newLevel = Ladder.GetLevel( ourEntry.Experience );
if ( newLevel > oldLevel )
us.SendMessage( 0x59, "You have achieved level {0}!", newLevel );
else if ( newLevel < oldLevel )
us.SendMessage( 0x22, "You have lost a level. You are now at {0}.", newLevel );
}
public void UnregisterRematch()
{
Unregister(true);
}
public void Unregister()
{
Unregister(false);
}
public void Unregister( bool queryRematch )
{
DestroyWall();
if ( !m_Registered )
return;
m_Registered = false;
if ( m_Arena != null )
m_Arena.Evict();
StopSDTimers();
Type[] types = new Type[]{ typeof( BeginGump ), typeof( DuelContextGump ), typeof( ParticipantGump ), typeof( PickRulesetGump ), typeof( ReadyGump ), typeof( ReadyUpGump ), typeof( RulesetGump ) };
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = (DuelPlayer)p.Players[j];
if ( pl == null )
continue;
if ( pl.Mobile is PlayerMobile )
((PlayerMobile)pl.Mobile).DuelPlayer = null;
for ( int k = 0; k < types.Length; ++k )
pl.Mobile.CloseGump( types[k] );
}
}
if ( queryRematch && m_Tournament == null )
QueryRematch();
}
public void QueryRematch()
{
DuelContext dc = new DuelContext( m_Initiator, m_Ruleset.Layout, false );
dc.m_Ruleset = m_Ruleset;
dc.m_Rematch = true;
dc.m_Participants.Clear();
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant oldPart = (Participant)m_Participants[i];
Participant newPart = new Participant( dc, oldPart.Players.Length );
for ( int j = 0; j < oldPart.Players.Length; ++j )
{
DuelPlayer oldPlayer = oldPart.Players[j];
if ( oldPlayer != null )
newPart.Players[j] = new DuelPlayer( oldPlayer.Mobile, newPart );
}
dc.m_Participants.Add( newPart );
}
dc.CloseAllGumps();
dc.SendReadyUpGump();
}
public DuelPlayer Find( Mobile mob )
{
if ( mob is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)mob;
if ( pm.DuelContext == this )
return pm.DuelPlayer;
return null;
}
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
DuelPlayer pl = p.Find( mob );
if ( pl != null )
return pl;
}
return null;
}
public bool IsAlly( Mobile m1, Mobile m2 )
{
DuelPlayer pl1 = Find( m1 );
DuelPlayer pl2 = Find( m2 );
return ( pl1 != null && pl2 != null && pl1.Participant == pl2.Participant );
}
public Participant CheckCompletion()
{
Participant winner = null;
bool hasWinner = false;
int eliminated = 0;
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
if ( p.Eliminated )
{
++eliminated;
if ( eliminated == (m_Participants.Count - 1) )
hasWinner = true;
}
else
{
winner = p;
}
}
if ( hasWinner )
return winner == null ? (Participant) m_Participants[0] : winner;
return null;
}
private Timer m_Countdown;
public void StartCountdown( int count, CountdownCallback cb )
{
cb(count);
m_Countdown=Timer.DelayCall( TimeSpan.FromSeconds( 1.0 ), TimeSpan.FromSeconds( 1.0 ), count, new TimerStateCallback( Countdown_Callback ), new object[]{ count-1, cb } );
}
public void StopCountdown()
{
if ( m_Countdown != null )
m_Countdown.Stop();
m_Countdown = null;
}
private void Countdown_Callback( object state )
{
object[] states = (object[])state;
int count = (int)states[0];
CountdownCallback cb = (CountdownCallback)states[1];
if ( count==0 )
{
if ( m_Countdown != null )
m_Countdown.Stop();
m_Countdown=null;
}
cb( count );
states[0] = count - 1;
}
private Timer m_AutoTieTimer;
private bool m_Tied;
public bool Tied{ get{ return m_Tied; } }
private bool m_IsSuddenDeath;
public bool IsSuddenDeath{ get{ return m_IsSuddenDeath; } set{ m_IsSuddenDeath = value; } }
private Timer m_SDWarnTimer, m_SDActivateTimer;
public void StopSDTimers()
{
if ( m_SDWarnTimer != null )
m_SDWarnTimer.Stop();
m_SDWarnTimer = null;
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = null;
}
public void StartSuddenDeath( TimeSpan timeUntilActive )
{
if ( m_SDWarnTimer != null )
m_SDWarnTimer.Stop();
m_SDWarnTimer = Timer.DelayCall( TimeSpan.FromMinutes( timeUntilActive.TotalMinutes * 0.9 ), new TimerCallback( WarnSuddenDeath ) );
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = Timer.DelayCall( timeUntilActive, new TimerCallback( ActivateSuddenDeath ) );
}
public void WarnSuddenDeath()
{
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl == null || pl.Eliminated )
continue;
pl.Mobile.SendSound( 0x1E1 );
pl.Mobile.SendMessage( 0x22, "Warning! Warning! Warning!" );
pl.Mobile.SendMessage( 0x22, "Sudden death will be active soon!" );
}
}
if ( m_Tournament != null )
m_Tournament.Alert( m_Arena, "Sudden death will be active soon!" );
if ( m_SDWarnTimer != null )
m_SDWarnTimer.Stop();
m_SDWarnTimer = null;
}
public static bool CheckSuddenDeath( Mobile mob )
{
if ( mob is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)mob;
if ( pm.DuelPlayer != null && !pm.DuelPlayer.Eliminated && pm.DuelContext != null && pm.DuelContext.IsSuddenDeath )
return true;
}
return false;
}
public void ActivateSuddenDeath()
{
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl == null || pl.Eliminated )
continue;
pl.Mobile.SendSound( 0x1E1 );
pl.Mobile.SendMessage( 0x22, "Warning! Warning! Warning!" );
pl.Mobile.SendMessage( 0x22, "Sudden death has ACTIVATED. You are now unable to perform any beneficial actions." );
}
}
if ( m_Tournament != null )
m_Tournament.Alert( m_Arena, "Sudden death has been activated!" );
m_IsSuddenDeath = true;
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = null;
}
public void BeginAutoTie()
{
if ( m_AutoTieTimer != null )
m_AutoTieTimer.Stop();
TimeSpan ts = ( m_Tournament == null || m_Tournament.TournyType == TournyType.Standard )
? AutoTieDelay
: TimeSpan.FromMinutes( 90.0 );
m_AutoTieTimer = Timer.DelayCall( ts, new TimerCallback( InvokeAutoTie ) );
}
public void EndAutoTie()
{
if ( m_AutoTieTimer != null )
m_AutoTieTimer.Stop();
m_AutoTieTimer = null;
}
public void InvokeAutoTie()
{
m_AutoTieTimer = null;
if ( !m_Started || m_Finished )
return;
m_Tied = true;
m_Finished = true;
StopSDTimers();
ArrayList remaining = new ArrayList();
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
if ( p.Eliminated )
{
p.Broadcast( 0x22, null, p.Players.Length == 1 ? "{0} has lost the duel." : "{0} and {1} team have lost the duel.", p.Players.Length == 1 ? "You have lost the duel." : "Your team has lost the duel." );
}
else
{
p.Broadcast( 0x59, null, p.Players.Length == 1 ? "{0} has tied the duel due to time expiration." : "{0} and {1} team have tied the duel due to time expiration.", p.Players.Length == 1 ? "You have tied the duel due to time expiration." : "Your team has tied the duel due to time expiration." );
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl != null && !pl.Eliminated )
DelayBounce( TimeSpan.FromSeconds( 8.0 ), pl.Mobile, null );
}
if ( p.TournyPart != null )
remaining.Add( p.TournyPart );
}
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl != null )
{
pl.Mobile.Delta( MobileDelta.Noto );
pl.Mobile.SendEverything();
}
}
}
if ( m_Tournament != null )
m_Tournament.HandleTie( m_Arena, m_Match, remaining );
Timer.DelayCall( TimeSpan.FromSeconds( 10.0 ), new TimerCallback( Unregister ) );
}
public bool IsOneVsOne
{
get
{
if ( m_Participants.Count != 2 )
return false;
if ( ((Participant)m_Participants[0]).Players.Length != 1 )
return false;
if ( ((Participant)m_Participants[1]).Players.Length != 1 )
return false;
return true;
}
}
public static void Initialize()
{
EventSink.Speech += new SpeechEventHandler( EventSink_Speech );
EventSink.Login += new LoginEventHandler( EventSink_Login );
CommandSystem.Register( "vli", AccessLevel.GameMaster, new CommandEventHandler( vli_oc ) );
}
private static void vli_oc( CommandEventArgs e )
{
e.Mobile.BeginTarget( -1, false, Targeting.TargetFlags.None, new TargetCallback( vli_ot ) );
}
private static void vli_ot( Mobile from, object obj )
{
if ( obj is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)obj;
Ladder ladder = Ladder.Instance;
if ( ladder == null )
return;
LadderEntry entry = ladder.Find( pm );
if ( entry != null )
from.SendGump( new PropertiesGump( from, entry ) );
}
}
private static TimeSpan CombatDelay = TimeSpan.FromSeconds( 30.0 );
private static TimeSpan AutoTieDelay = TimeSpan.FromMinutes( 15.0 );
public static bool CheckCombat( Mobile m )
{
for ( int i = 0; i < m.Aggressed.Count; ++i )
{
AggressorInfo info = m.Aggressed[i];
if ( info.Defender.Player && (DateTime.UtcNow - info.LastCombatTime) < CombatDelay )
return true;
}
for ( int i = 0; i < m.Aggressors.Count; ++i )
{
AggressorInfo info = m.Aggressors[i];
if ( info.Attacker.Player && (DateTime.UtcNow - info.LastCombatTime) < CombatDelay )
return true;
}
return false;
}
private static void EventSink_Login( LoginEventArgs e )
{
PlayerMobile pm = e.Mobile as PlayerMobile;
if ( pm == null )
return;
DuelContext dc = pm.DuelContext;
if ( dc == null )
return;
if ( dc.ReadyWait && pm.DuelPlayer.Ready && !dc.Started && !dc.StartedBeginCountdown && !dc.Finished )
{
if ( dc.m_Tournament == null )
pm.SendGump( new ReadyGump( pm, dc, dc.m_ReadyCount ) );
}
else if ( dc.ReadyWait && !dc.StartedBeginCountdown && !dc.Started && !dc.Finished )
{
if ( dc.m_Tournament == null )
pm.SendGump( new ReadyUpGump( pm, dc ) );
}
else if ( dc.Initiator == pm && !dc.ReadyWait && !dc.StartedBeginCountdown && !dc.Started && !dc.Finished )
pm.SendGump( new DuelContextGump( pm, dc ) );
}
private static void ViewLadder_OnTarget( Mobile from, object obj, object state )
{
if ( obj is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)obj;
Ladder ladder = (Ladder)state;
LadderEntry entry = ladder.Find( pm );
if ( entry == null )
return; // sanity
string text = String.Format( "{{0}} are ranked {0} at level {1}.", LadderGump.Rank( entry.Index + 1 ), Ladder.GetLevel( entry.Experience ) );
pm.PrivateOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( text, from==pm?"You":"They" ), from.NetState );
}
else if ( obj is Mobile )
{
Mobile mob = (Mobile)obj;
if ( mob.Body.IsHuman )
mob.PrivateOverheadMessage( MessageType.Regular, mob.SpeechHue, false, "I'm not a duelist, and quite frankly, I resent the implication.", from.NetState );
else
mob.PrivateOverheadMessage( MessageType.Regular, 0x3B2, true, "It's probably better than you.", from.NetState );
}
else
{
from.SendMessage( "That's not a player." );
}
}
private static void EventSink_Speech( SpeechEventArgs e )
{
if ( e.Handled )
return;
PlayerMobile pm = e.Mobile as PlayerMobile;
if ( pm == null )
return;
if ( Insensitive.Contains( e.Speech, "i wish to duel" ) )
{
if ( !pm.CheckAlive() )
{
}
else if ( pm.Region.IsPartOf( typeof( Regions.Jail ) ) )
{
}
else if ( CheckCombat( pm ) )
{
e.Mobile.SendMessage( 0x22, "You have recently been in combat with another player and must wait before starting a duel." );
}
else if ( pm.DuelContext != null )
{
if ( pm.DuelContext.Initiator == pm )
e.Mobile.SendMessage( 0x22, "You have already started a duel." );
else
e.Mobile.SendMessage( 0x22, "You have already been challenged in a duel." );
}
else if ( TournamentController.IsActive )
{
e.Mobile.SendMessage( 0x22, "You may not start a duel while a tournament is active." );
}
else
{
pm.SendGump( new DuelContextGump( pm, new DuelContext( pm, RulesetLayout.Root ) ) );
e.Handled = true;
}
}
else if ( Insensitive.Equals( e.Speech, "change arena preferences" ) )
{
if ( !pm.CheckAlive() )
{
}
else
{
Preferences prefs = Preferences.Instance;
if ( prefs != null )
{
e.Mobile.CloseGump( typeof( PreferencesGump ) );
e.Mobile.SendGump( new PreferencesGump( e.Mobile, prefs ) );
}
}
}
else if ( Insensitive.Equals( e.Speech, "showladder" ) )
{
e.Blocked=true;
if ( !pm.CheckAlive() )
{
}
else
{
Ladder instance = Ladder.Instance;
if ( instance == null )
{
//pm.SendMessage( "Ladder not yet initialized." );
}
else
{
LadderEntry entry = instance.Find( pm );
if ( entry == null )
return; // sanity
string text = String.Format( "{{0}} {{1}} ranked {0} at level {1}.", LadderGump.Rank( entry.Index + 1 ), Ladder.GetLevel( entry.Experience ) );
pm.LocalOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( text, "You", "are" ) );
pm.NonlocalOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( text, pm.Name, "is" ) );
//pm.PublicOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( "Level {0} with {1} win{2} and {3} loss{4}.", Ladder.GetLevel( entry.Experience ), entry.Wins, entry.Wins==1?"":"s", entry.Losses, entry.Losses==1?"":"es" ) );
//pm.PublicOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( "Level {0} with {1} win{2} and {3} loss{4}.", Ladder.GetLevel( entry.Experience ), entry.Wins, entry.Wins==1?"":"s", entry.Losses, entry.Losses==1?"":"es" ) );
}
}
}
else if ( Insensitive.Equals( e.Speech, "viewladder" ) )
{
e.Blocked=true;
if ( !pm.CheckAlive() )
{
}
else
{
Ladder instance = Ladder.Instance;
if ( instance == null )
{
//pm.SendMessage( "Ladder not yet initialized." );
}
else
{
pm.SendMessage( "Target a player to view their ranking and level." );
pm.BeginTarget( 16, false, Targeting.TargetFlags.None, new TargetStateCallback( ViewLadder_OnTarget ), instance );
}
}
}
else if ( Insensitive.Contains( e.Speech, "i yield" ) )
{
if ( !pm.CheckAlive() )
{
}
else if ( pm.DuelContext == null )
{
}
else if ( pm.DuelContext.Finished )
{
e.Mobile.SendMessage( 0x22, "The duel is already finished." );
}
else if ( !pm.DuelContext.Started )
{
DuelContext dc = pm.DuelContext;
Mobile init = dc.Initiator;
if ( pm.DuelContext.StartedBeginCountdown )
{
e.Mobile.SendMessage( 0x22, "The duel has not yet started." );
}
else
{
DuelPlayer pl = pm.DuelContext.Find( pm );
if ( pl == null )
return;
Participant p = pl.Participant;
if ( !pm.DuelContext.ReadyWait ) // still setting stuff up
{
p.Broadcast( 0x22, null, "{0} has yielded.", "You have yielded." );
if ( init == pm )
{
dc.Unregister();
}
else
{
p.Nullify( pl );
pm.DuelPlayer=null;
NetState ns = init.NetState;
if ( ns != null )
{
foreach ( Gump g in ns.Gumps )
{
if ( g is ParticipantGump )
{
ParticipantGump pg = (ParticipantGump)g;
if ( pg.Participant == p )
{
init.SendGump( new ParticipantGump( init, dc, p ) );
break;
}
}
else if ( g is DuelContextGump )
{
DuelContextGump dcg = (DuelContextGump)g;
if ( dcg.Context == dc )
{
init.SendGump( new DuelContextGump( init, dc ) );
break;
}
}
}
}
}
}
else if ( !pm.DuelContext.StartedReadyCountdown ) // at ready stage
{
p.Broadcast( 0x22, null, "{0} has yielded.", "You have yielded." );
dc.m_Yielding=true;
dc.RejectReady( pm, null );
dc.m_Yielding=false;
if ( init == pm )
{
dc.Unregister();
}
else if ( dc.m_Registered )
{
p.Nullify( pl );
pm.DuelPlayer=null;
NetState ns = init.NetState;
if ( ns != null )
{
bool send=true;
foreach ( Gump g in ns.Gumps )
{
if ( g is ParticipantGump )
{
ParticipantGump pg = (ParticipantGump)g;
if ( pg.Participant == p )
{
init.SendGump( new ParticipantGump( init, dc, p ) );
send=false;
break;
}
}
else if ( g is DuelContextGump )
{
DuelContextGump dcg = (DuelContextGump)g;
if ( dcg.Context == dc )
{
init.SendGump( new DuelContextGump( init, dc ) );
send=false;
break;
}
}
}
if ( send )
init.SendGump( new DuelContextGump( init, dc ) );
}
}
}
else
{
if ( pm.DuelContext.m_Countdown != null )
pm.DuelContext.m_Countdown.Stop();
pm.DuelContext.m_Countdown= null;
pm.DuelContext.m_StartedReadyCountdown=false;
p.Broadcast( 0x22, null, "{0} has yielded.", "You have yielded." );
dc.m_Yielding=true;
dc.RejectReady( pm, null );
dc.m_Yielding=false;
if ( init == pm )
{
dc.Unregister();
}
else if ( dc.m_Registered )
{
p.Nullify( pl );
pm.DuelPlayer=null;
NetState ns = init.NetState;
if ( ns != null )
{
bool send=true;
foreach ( Gump g in ns.Gumps )
{
if ( g is ParticipantGump )
{
ParticipantGump pg = (ParticipantGump)g;
if ( pg.Participant == p )
{
init.SendGump( new ParticipantGump( init, dc, p ) );
send=false;
break;
}
}
else if ( g is DuelContextGump )
{
DuelContextGump dcg = (DuelContextGump)g;
if ( dcg.Context == dc )
{
init.SendGump( new DuelContextGump( init, dc ) );
send=false;
break;
}
}
}
if ( send )
init.SendGump( new DuelContextGump( init, dc ) );
}
}
}
}
}
else
{
DuelPlayer pl = pm.DuelContext.Find( pm );
if ( pl != null )
{
if ( pm.DuelContext.IsOneVsOne )
{
e.Mobile.SendMessage( 0x22, "You may not yield a 1 on 1 match." );
}
else if ( pl.Eliminated )
{
e.Mobile.SendMessage( 0x22, "You have already been eliminated." );
}
else
{
pm.LocalOverheadMessage( MessageType.Regular, 0x22, false, "You have yielded." );
pm.NonlocalOverheadMessage( MessageType.Regular, 0x22, false, String.Format( "{0} has yielded.", pm.Name ) );
pm.DuelContext.m_Yielding=true;
pm.Kill();
pm.DuelContext.m_Yielding=false;
if ( pm.Alive ) // invul, ...
{
pl.Eliminated = true;
pm.DuelContext.RemoveAggressions( pm );
pm.DuelContext.SendOutside( pm );
pm.DuelContext.Refresh( pm, null );
Debuff( pm );
CancelSpell( pm );
pm.Frozen = false;
Participant winner = pm.DuelContext.CheckCompletion();
if ( winner != null )
pm.DuelContext.Finish( winner );
}
}
}
else
{
e.Mobile.SendMessage( 0x22, "BUG: Unable to find duel context." );
}
}
}
}
public DuelContext( Mobile initiator, RulesetLayout layout ) : this( initiator, layout, true )
{
}
public DuelContext( Mobile initiator, RulesetLayout layout, bool addNew )
{
m_Initiator = initiator;
m_Participants = new ArrayList();
m_Ruleset = new Ruleset( layout );
m_Ruleset.ApplyDefault( layout.Defaults[0] );
if ( addNew )
{
m_Participants.Add( new Participant( this, 1 ) );
m_Participants.Add( new Participant( this, 1 ) );
((Participant)m_Participants[0]).Add( initiator );
}
}
public void CloseAllGumps()
{
Type[] types = new Type[]{ typeof( DuelContextGump ), typeof( ParticipantGump ), typeof( RulesetGump ) };
int[] defs = new int[]{ -1, -1, -1 };
for ( int i = 0; i < m_Participants.Count; ++i )
{
|
[
"\t\t\t\tParticipant p = (Participant)m_Participants[i];"
] | 5,243
|
lcc
|
csharp
| null |
28ce5cf5e0beeb47248c6cba20ae17fa71d60d402770d464
| 0
|
Your task is code completion.
using System;
using System.Collections;
using System.Collections.Generic;
using Server.Commands;
using Server.Engines.PartySystem;
using Server.Factions;
using Server.Gumps;
using Server.Items;
using Server.Mobiles;
using Server.Network;
using Server.Spells;
using Server.Spells.Bushido;
using Server.Spells.Chivalry;
using Server.Spells.Necromancy;
using Server.Spells.Ninjitsu;
using Server.Spells.Seventh;
using Server.Spells.Spellweaving;
namespace Server.Engines.ConPVP
{
public delegate void CountdownCallback( int count );
public class DuelContext
{
private Mobile m_Initiator;
private ArrayList m_Participants;
private Ruleset m_Ruleset;
private Arena m_Arena;
private bool m_Registered = true;
private bool m_Finished, m_Started;
private bool m_ReadyWait;
private int m_ReadyCount;
private bool m_Rematch;
public bool Rematch{ get{ return m_Rematch; } }
public bool ReadyWait{ get{ return m_ReadyWait; } }
public int ReadyCount{ get{ return m_ReadyCount; } }
public bool Registered{ get{ return m_Registered; } }
public bool Finished{ get{ return m_Finished; } }
public bool Started{ get{ return m_Started; } }
public Mobile Initiator{ get{ return m_Initiator; } }
public ArrayList Participants{ get{ return m_Participants; } }
public Ruleset Ruleset{ get{ return m_Ruleset; } }
public Arena Arena{ get{ return m_Arena; } }
private bool CantDoAnything( Mobile mob )
{
if ( m_EventGame != null )
return m_EventGame.CantDoAnything( mob );
else
return false;
}
public static bool IsFreeConsume( Mobile mob )
{
PlayerMobile pm = mob as PlayerMobile;
if ( pm == null || pm.DuelContext == null || pm.DuelContext.m_EventGame == null )
return false;
return pm.DuelContext.m_EventGame.FreeConsume;
}
public void DelayBounce( TimeSpan ts, Mobile mob, Container corpse )
{
Timer.DelayCall( ts, new TimerStateCallback( DelayBounce_Callback ), new object[]{ mob, corpse } );
}
public static bool AllowSpecialMove( Mobile from, string name, SpecialMove move )
{
PlayerMobile pm = from as PlayerMobile;
if( pm == null )
return true;
DuelContext dc = pm.DuelContext;
return (dc == null || dc.InstAllowSpecialMove( from, name, move ));
}
public bool InstAllowSpecialMove( Mobile from, string name, SpecialMove move )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( CantDoAnything( from ) )
return false;
string title = null;
if( move is NinjaMove )
title = "Bushido";
else if( move is SamuraiMove )
title = "Ninjitsu";
if ( title == null || name == null || m_Ruleset.GetOption( title, name ) )
return true;
from.SendMessage( "The dueling ruleset prevents you from using this move." );
return false;
}
public bool AllowSpellCast( Mobile from, Spell spell )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( CantDoAnything( from ) )
return false;
if ( spell is Server.Spells.Fourth.RecallSpell )
from.SendMessage( "You may not cast this spell." );
string title = null, option = null;
if( spell is ArcanistSpell )
{
title = "Spellweaving";
option = spell.Name;
}
else if ( spell is PaladinSpell )
{
title = "Chivalry";
option = spell.Name;
}
else if ( spell is NecromancerSpell )
{
title = "Necromancy";
option = spell.Name;
}
else if ( spell is NinjaSpell )
{
title = "Ninjitsu";
option = spell.Name;
}
else if ( spell is SamuraiSpell )
{
title = "Bushido";
option = spell.Name;
}
else if( spell is MagerySpell )
{
switch( ((MagerySpell)spell).Circle )
{
case SpellCircle.First: title = "1st Circle"; break;
case SpellCircle.Second: title = "2nd Circle"; break;
case SpellCircle.Third: title = "3rd Circle"; break;
case SpellCircle.Fourth: title = "4th Circle"; break;
case SpellCircle.Fifth: title = "5th Circle"; break;
case SpellCircle.Sixth: title = "6th Circle"; break;
case SpellCircle.Seventh: title = "7th Circle"; break;
case SpellCircle.Eighth: title = "8th Circle"; break;
}
option = spell.Name;
}
else
{
title = "Other Spell";
option = spell.Name;
}
if ( title == null || option == null || m_Ruleset.GetOption( title, option ) )
return true;
from.SendMessage( "The dueling ruleset prevents you from casting this spell." );
return false;
}
public bool AllowItemEquip( Mobile from, Item item )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( item is Dagger || CheckItemEquip( from, item ) )
return true;
from.SendMessage( "The dueling ruleset prevents you from equiping this item." );
return false;
}
public static bool AllowSpecialAbility( Mobile from, string name, bool message )
{
PlayerMobile pm = from as PlayerMobile;
if ( pm == null )
return true;
DuelContext dc = pm.DuelContext;
return ( dc == null || dc.InstAllowSpecialAbility( from, name, message ) );
}
public bool InstAllowSpecialAbility( Mobile from, string name, bool message )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( CantDoAnything( from ) )
return false;
if ( m_Ruleset.GetOption( "Combat Abilities", name ) )
return true;
if ( message )
from.SendMessage( "The dueling ruleset prevents you from using this combat ability." );
return false;
}
public bool CheckItemEquip( Mobile from, Item item )
{
if ( item is Fists )
{
if ( !m_Ruleset.GetOption( "Weapons", "Wrestling" ) )
return false;
}
else if ( item is BaseArmor )
{
BaseArmor armor = (BaseArmor)item;
if ( armor.ProtectionLevel > ArmorProtectionLevel.Regular && !m_Ruleset.GetOption( "Armor", "Magical" ) )
return false;
if ( !Core.AOS && armor.Resource != armor.DefaultResource && !m_Ruleset.GetOption( "Armor", "Colored" ) )
return false;
if ( armor is BaseShield && !m_Ruleset.GetOption( "Armor", "Shields" ) )
return false;
}
else if ( item is BaseWeapon )
{
BaseWeapon weapon = (BaseWeapon)item;
if ( (weapon.DamageLevel > WeaponDamageLevel.Regular || weapon.AccuracyLevel > WeaponAccuracyLevel.Regular) && !m_Ruleset.GetOption( "Weapons", "Magical" ) )
return false;
if ( !Core.AOS && weapon.Resource != CraftResource.Iron && weapon.Resource != CraftResource.None && !m_Ruleset.GetOption( "Weapons", "Runics" ) )
return false;
if ( weapon is BaseRanged && !m_Ruleset.GetOption( "Weapons", "Ranged" ) )
return false;
if ( !(weapon is BaseRanged) && !m_Ruleset.GetOption( "Weapons", "Melee" ) )
return false;
if ( weapon.PoisonCharges > 0 && weapon.Poison != null && !m_Ruleset.GetOption( "Weapons", "Poisoned" ) )
return false;
if ( weapon is BaseWand && !m_Ruleset.GetOption( "Items", "Wands" ) )
return false;
}
return true;
}
public bool AllowSkillUse( Mobile from, SkillName skill )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( CantDoAnything( from ) )
return false;
int id = (int)skill;
if ( id >= 0 && id < SkillInfo.Table.Length )
{
if ( m_Ruleset.GetOption( "Skills", SkillInfo.Table[id].Name ) )
return true;
}
from.SendMessage( "The dueling ruleset prevents you from using this skill." );
return false;
}
public bool AllowItemUse( Mobile from, Item item )
{
if ( !m_StartedBeginCountdown )
return true;
DuelPlayer pl = Find( from );
if ( pl == null || pl.Eliminated )
return true;
if ( !(item is BaseRefreshPotion) )
{
if ( CantDoAnything( from ) )
return false;
}
string title = null, option = null;
if ( item is BasePotion )
{
title = "Potions";
if ( item is BaseAgilityPotion )
option = "Agility";
else if ( item is BaseCurePotion )
option = "Cure";
else if ( item is BaseHealPotion )
option = "Heal";
else if ( item is NightSightPotion )
option = "Nightsight";
else if ( item is BasePoisonPotion )
option = "Poison";
else if ( item is BaseStrengthPotion )
option = "Strength";
else if ( item is BaseExplosionPotion )
option = "Explosion";
else if ( item is BaseRefreshPotion )
option = "Refresh";
}
else if ( item is Bandage )
{
title = "Items";
option = "Bandages";
}
else if ( item is TrapableContainer )
{
if ( ((TrapableContainer)item).TrapType != TrapType.None )
{
title = "Items";
option = "Trapped Containers";
}
}
else if ( item is Bola )
{
title = "Items";
option = "Bolas";
}
else if ( item is OrangePetals )
{
title = "Items";
option = "Orange Petals";
}
else if ( item is EtherealMount || item.Layer == Layer.Mount )
{
title = "Items";
option = "Mounts";
}
else if ( item is LeatherNinjaBelt )
{
title = "Items";
option = "Shurikens";
}
else if ( item is Fukiya )
{
title = "Items";
option = "Fukiya Darts";
}
else if ( item is FireHorn )
{
title = "Items";
option = "Fire Horns";
}
else if ( item is BaseWand )
{
title = "Items";
option = "Wands";
}
if ( title != null && option != null && m_StartedBeginCountdown && !m_Started )
{
from.SendMessage( "You may not use this item before the duel begins." );
return false;
}
else if ( item is BasePotion && !(item is BaseExplosionPotion) && !(item is BaseRefreshPotion) && IsSuddenDeath )
{
from.SendMessage( 0x22, "You may not drink potions in sudden death." );
return false;
}
else if ( item is Bandage && IsSuddenDeath )
{
from.SendMessage( 0x22, "You may not use bandages in sudden death." );
return false;
}
if ( title == null || option == null || m_Ruleset.GetOption( title, option ) )
return true;
from.SendMessage( "The dueling ruleset prevents you from using this item." );
return false;
}
private void DelayBounce_Callback( object state )
{
object[] states = (object[])state;
Mobile mob = (Mobile) states[0];
Container corpse = (Container) states[1];
RemoveAggressions( mob );
SendOutside( mob );
Refresh( mob, corpse );
Debuff( mob );
CancelSpell( mob );
mob.Frozen = false;
}
public void OnMapChanged( Mobile mob )
{
OnLocationChanged( mob );
}
public void OnLocationChanged( Mobile mob )
{
if ( !m_Registered || !m_StartedBeginCountdown || m_Finished )
return;
Arena arena = m_Arena;
if ( arena == null )
return;
if ( mob.Map == arena.Facet && arena.Bounds.Contains( mob.Location ) )
return;
DuelPlayer pl = Find( mob );
if ( pl == null || pl.Eliminated )
return;
if ( mob.Map == Map.Internal ) {
// they've logged out
if ( mob.LogoutMap == arena.Facet && arena.Bounds.Contains( mob.LogoutLocation ) ) {
// they logged out inside the arena.. set them to eject on login
mob.LogoutLocation = arena.Outside;
}
}
pl.Eliminated = true;
mob.LocalOverheadMessage( MessageType.Regular, 0x22, false, "You have forfeited your position in the duel." );
mob.NonlocalOverheadMessage( MessageType.Regular, 0x22, false, String.Format( "{0} has forfeited by leaving the dueling arena.", mob.Name ) );
Participant winner = CheckCompletion();
if ( winner != null )
Finish( winner );
}
private bool m_Yielding;
public void OnDeath( Mobile mob, Container corpse )
{
if ( !m_Registered || !m_Started )
return;
DuelPlayer pl = Find( mob );
if ( pl != null && !pl.Eliminated )
{
if ( m_EventGame != null && !m_EventGame.OnDeath( mob, corpse ) )
return;
pl.Eliminated = true;
if ( mob.Poison != null )
mob.Poison = null;
Requip( mob, corpse );
DelayBounce( TimeSpan.FromSeconds( 4.0 ), mob, corpse );
Participant winner = CheckCompletion();
if ( winner != null )
{
Finish( winner );
}
else if ( !m_Yielding )
{
mob.LocalOverheadMessage( MessageType.Regular, 0x22, false, "You have been defeated." );
mob.NonlocalOverheadMessage( MessageType.Regular, 0x22, false, String.Format( "{0} has been defeated.", mob.Name ) );
}
}
}
public bool CheckFull()
{
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
if ( p.HasOpenSlot )
return false;
}
return true;
}
public void Requip( Mobile from, Container cont )
{
Corpse corpse = cont as Corpse;
if ( corpse == null )
return;
List<Item> items = new List<Item>( corpse.Items );
bool gathered = false;
bool didntFit = false;
Container pack = from.Backpack;
for ( int i = 0; !didntFit && i < items.Count; ++i )
{
Item item = items[i];
Point3D loc = item.Location;
if ( (item.Layer == Layer.Hair || item.Layer == Layer.FacialHair) || !item.Movable )
continue;
if ( pack != null )
{
pack.DropItem( item );
gathered = true;
}
else
{
didntFit = true;
}
}
corpse.Carved = true;
if ( corpse.ItemID == 0x2006 )
{
corpse.ProcessDelta();
corpse.SendRemovePacket();
corpse.ItemID = Utility.Random( 0xECA, 9 ); // bone graphic
corpse.Hue = 0;
corpse.ProcessDelta();
Mobile killer = from.FindMostRecentDamager( false );
if ( killer != null && killer.Player )
killer.AddToBackpack( new Head( m_Tournament == null ? HeadType.Duel : HeadType.Tournament, from.Name ) );
}
from.PlaySound( 0x3E3 );
if ( gathered && !didntFit )
from.SendLocalizedMessage( 1062471 ); // You quickly gather all of your belongings.
else if ( gathered && didntFit )
from.SendLocalizedMessage( 1062472 ); // You gather some of your belongings. The rest remain on the corpse.
}
public void Refresh( Mobile mob, Container cont )
{
if ( !mob.Alive )
{
mob.Resurrect();
DeathRobe robe = mob.FindItemOnLayer( Layer.OuterTorso ) as DeathRobe;
if ( robe != null )
robe.Delete();
if ( cont is Corpse )
{
Corpse corpse = (Corpse) cont;
for ( int i = 0; i < corpse.EquipItems.Count; ++i )
{
Item item = corpse.EquipItems[i];
if ( item.Movable && item.Layer != Layer.Hair && item.Layer != Layer.FacialHair && item.IsChildOf( mob.Backpack ) )
mob.EquipItem( item );
}
}
}
mob.Hits = mob.HitsMax;
mob.Stam = mob.StamMax;
mob.Mana = mob.ManaMax;
mob.Poison = null;
}
public void SendOutside( Mobile mob )
{
if ( m_Arena == null )
return;
mob.Combatant = null;
mob.MoveToWorld( m_Arena.Outside, m_Arena.Facet );
}
private Point3D m_GatePoint;
private Map m_GateFacet;
public void Finish( Participant winner )
{
if ( m_Finished )
return;
EndAutoTie();
StopSDTimers();
m_Finished = true;
for ( int i = 0; i < winner.Players.Length; ++i )
{
DuelPlayer pl = winner.Players[i];
if ( pl != null && !pl.Eliminated )
DelayBounce( TimeSpan.FromSeconds( 8.0 ), pl.Mobile, null );
}
winner.Broadcast( 0x59, null, winner.Players.Length == 1 ? "{0} has won the duel." : "{0} and {1} team have won the duel.", winner.Players.Length == 1 ? "You have won the duel." : "Your team has won the duel." );
if ( m_Tournament != null && winner.TournyPart != null )
{
m_Match.Winner = winner.TournyPart;
winner.TournyPart.WonMatch( m_Match );
m_Tournament.HandleWon( m_Arena, m_Match, winner.TournyPart );
}
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant loser = (Participant)m_Participants[i];
if ( loser != winner )
{
loser.Broadcast( 0x22, null, loser.Players.Length == 1 ? "{0} has lost the duel." : "{0} and {1} team have lost the duel.", loser.Players.Length == 1 ? "You have lost the duel." : "Your team has lost the duel." );
if ( m_Tournament != null && loser.TournyPart != null )
loser.TournyPart.LostMatch( m_Match );
}
for ( int j = 0; j < loser.Players.Length; ++j )
{
if ( loser.Players[j] != null )
{
RemoveAggressions( loser.Players[j].Mobile );
loser.Players[j].Mobile.Delta( MobileDelta.Noto );
loser.Players[j].Mobile.CloseGump( typeof( BeginGump ) );
if ( m_Tournament != null )
loser.Players[j].Mobile.SendEverything();
}
}
}
if ( IsOneVsOne )
{
DuelPlayer dp1 = ((Participant)m_Participants[0]).Players[0];
DuelPlayer dp2 = ((Participant)m_Participants[1]).Players[0];
if ( dp1 != null && dp2 != null )
{
Award( dp1.Mobile, dp2.Mobile, dp1.Participant == winner );
Award( dp2.Mobile, dp1.Mobile, dp2.Participant == winner );
}
}
if ( m_EventGame != null )
m_EventGame.OnStop();
Timer.DelayCall( TimeSpan.FromSeconds( 9.0 ), new TimerCallback( UnregisterRematch ) );
}
public void Award( Mobile us, Mobile them, bool won )
{
Ladder ladder = ( m_Arena == null ? Ladder.Instance : m_Arena.AcquireLadder() );
if ( ladder == null )
return;
LadderEntry ourEntry = ladder.Find( us );
LadderEntry theirEntry = ladder.Find( them );
if ( ourEntry == null || theirEntry == null )
return;
int xpGain = Ladder.GetExperienceGain( ourEntry, theirEntry, won );
if ( xpGain == 0 )
return;
if ( m_Tournament != null )
xpGain *= ( xpGain > 0 ? 5 : 2 );
if ( won )
++ourEntry.Wins;
else
++ourEntry.Losses;
int oldLevel = Ladder.GetLevel( ourEntry.Experience );
ourEntry.Experience += xpGain;
if ( ourEntry.Experience < 0 )
ourEntry.Experience = 0;
ladder.UpdateEntry( ourEntry );
int newLevel = Ladder.GetLevel( ourEntry.Experience );
if ( newLevel > oldLevel )
us.SendMessage( 0x59, "You have achieved level {0}!", newLevel );
else if ( newLevel < oldLevel )
us.SendMessage( 0x22, "You have lost a level. You are now at {0}.", newLevel );
}
public void UnregisterRematch()
{
Unregister(true);
}
public void Unregister()
{
Unregister(false);
}
public void Unregister( bool queryRematch )
{
DestroyWall();
if ( !m_Registered )
return;
m_Registered = false;
if ( m_Arena != null )
m_Arena.Evict();
StopSDTimers();
Type[] types = new Type[]{ typeof( BeginGump ), typeof( DuelContextGump ), typeof( ParticipantGump ), typeof( PickRulesetGump ), typeof( ReadyGump ), typeof( ReadyUpGump ), typeof( RulesetGump ) };
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = (DuelPlayer)p.Players[j];
if ( pl == null )
continue;
if ( pl.Mobile is PlayerMobile )
((PlayerMobile)pl.Mobile).DuelPlayer = null;
for ( int k = 0; k < types.Length; ++k )
pl.Mobile.CloseGump( types[k] );
}
}
if ( queryRematch && m_Tournament == null )
QueryRematch();
}
public void QueryRematch()
{
DuelContext dc = new DuelContext( m_Initiator, m_Ruleset.Layout, false );
dc.m_Ruleset = m_Ruleset;
dc.m_Rematch = true;
dc.m_Participants.Clear();
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant oldPart = (Participant)m_Participants[i];
Participant newPart = new Participant( dc, oldPart.Players.Length );
for ( int j = 0; j < oldPart.Players.Length; ++j )
{
DuelPlayer oldPlayer = oldPart.Players[j];
if ( oldPlayer != null )
newPart.Players[j] = new DuelPlayer( oldPlayer.Mobile, newPart );
}
dc.m_Participants.Add( newPart );
}
dc.CloseAllGumps();
dc.SendReadyUpGump();
}
public DuelPlayer Find( Mobile mob )
{
if ( mob is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)mob;
if ( pm.DuelContext == this )
return pm.DuelPlayer;
return null;
}
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
DuelPlayer pl = p.Find( mob );
if ( pl != null )
return pl;
}
return null;
}
public bool IsAlly( Mobile m1, Mobile m2 )
{
DuelPlayer pl1 = Find( m1 );
DuelPlayer pl2 = Find( m2 );
return ( pl1 != null && pl2 != null && pl1.Participant == pl2.Participant );
}
public Participant CheckCompletion()
{
Participant winner = null;
bool hasWinner = false;
int eliminated = 0;
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
if ( p.Eliminated )
{
++eliminated;
if ( eliminated == (m_Participants.Count - 1) )
hasWinner = true;
}
else
{
winner = p;
}
}
if ( hasWinner )
return winner == null ? (Participant) m_Participants[0] : winner;
return null;
}
private Timer m_Countdown;
public void StartCountdown( int count, CountdownCallback cb )
{
cb(count);
m_Countdown=Timer.DelayCall( TimeSpan.FromSeconds( 1.0 ), TimeSpan.FromSeconds( 1.0 ), count, new TimerStateCallback( Countdown_Callback ), new object[]{ count-1, cb } );
}
public void StopCountdown()
{
if ( m_Countdown != null )
m_Countdown.Stop();
m_Countdown = null;
}
private void Countdown_Callback( object state )
{
object[] states = (object[])state;
int count = (int)states[0];
CountdownCallback cb = (CountdownCallback)states[1];
if ( count==0 )
{
if ( m_Countdown != null )
m_Countdown.Stop();
m_Countdown=null;
}
cb( count );
states[0] = count - 1;
}
private Timer m_AutoTieTimer;
private bool m_Tied;
public bool Tied{ get{ return m_Tied; } }
private bool m_IsSuddenDeath;
public bool IsSuddenDeath{ get{ return m_IsSuddenDeath; } set{ m_IsSuddenDeath = value; } }
private Timer m_SDWarnTimer, m_SDActivateTimer;
public void StopSDTimers()
{
if ( m_SDWarnTimer != null )
m_SDWarnTimer.Stop();
m_SDWarnTimer = null;
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = null;
}
public void StartSuddenDeath( TimeSpan timeUntilActive )
{
if ( m_SDWarnTimer != null )
m_SDWarnTimer.Stop();
m_SDWarnTimer = Timer.DelayCall( TimeSpan.FromMinutes( timeUntilActive.TotalMinutes * 0.9 ), new TimerCallback( WarnSuddenDeath ) );
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = Timer.DelayCall( timeUntilActive, new TimerCallback( ActivateSuddenDeath ) );
}
public void WarnSuddenDeath()
{
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl == null || pl.Eliminated )
continue;
pl.Mobile.SendSound( 0x1E1 );
pl.Mobile.SendMessage( 0x22, "Warning! Warning! Warning!" );
pl.Mobile.SendMessage( 0x22, "Sudden death will be active soon!" );
}
}
if ( m_Tournament != null )
m_Tournament.Alert( m_Arena, "Sudden death will be active soon!" );
if ( m_SDWarnTimer != null )
m_SDWarnTimer.Stop();
m_SDWarnTimer = null;
}
public static bool CheckSuddenDeath( Mobile mob )
{
if ( mob is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)mob;
if ( pm.DuelPlayer != null && !pm.DuelPlayer.Eliminated && pm.DuelContext != null && pm.DuelContext.IsSuddenDeath )
return true;
}
return false;
}
public void ActivateSuddenDeath()
{
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl == null || pl.Eliminated )
continue;
pl.Mobile.SendSound( 0x1E1 );
pl.Mobile.SendMessage( 0x22, "Warning! Warning! Warning!" );
pl.Mobile.SendMessage( 0x22, "Sudden death has ACTIVATED. You are now unable to perform any beneficial actions." );
}
}
if ( m_Tournament != null )
m_Tournament.Alert( m_Arena, "Sudden death has been activated!" );
m_IsSuddenDeath = true;
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = null;
}
public void BeginAutoTie()
{
if ( m_AutoTieTimer != null )
m_AutoTieTimer.Stop();
TimeSpan ts = ( m_Tournament == null || m_Tournament.TournyType == TournyType.Standard )
? AutoTieDelay
: TimeSpan.FromMinutes( 90.0 );
m_AutoTieTimer = Timer.DelayCall( ts, new TimerCallback( InvokeAutoTie ) );
}
public void EndAutoTie()
{
if ( m_AutoTieTimer != null )
m_AutoTieTimer.Stop();
m_AutoTieTimer = null;
}
public void InvokeAutoTie()
{
m_AutoTieTimer = null;
if ( !m_Started || m_Finished )
return;
m_Tied = true;
m_Finished = true;
StopSDTimers();
ArrayList remaining = new ArrayList();
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
if ( p.Eliminated )
{
p.Broadcast( 0x22, null, p.Players.Length == 1 ? "{0} has lost the duel." : "{0} and {1} team have lost the duel.", p.Players.Length == 1 ? "You have lost the duel." : "Your team has lost the duel." );
}
else
{
p.Broadcast( 0x59, null, p.Players.Length == 1 ? "{0} has tied the duel due to time expiration." : "{0} and {1} team have tied the duel due to time expiration.", p.Players.Length == 1 ? "You have tied the duel due to time expiration." : "Your team has tied the duel due to time expiration." );
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl != null && !pl.Eliminated )
DelayBounce( TimeSpan.FromSeconds( 8.0 ), pl.Mobile, null );
}
if ( p.TournyPart != null )
remaining.Add( p.TournyPart );
}
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl != null )
{
pl.Mobile.Delta( MobileDelta.Noto );
pl.Mobile.SendEverything();
}
}
}
if ( m_Tournament != null )
m_Tournament.HandleTie( m_Arena, m_Match, remaining );
Timer.DelayCall( TimeSpan.FromSeconds( 10.0 ), new TimerCallback( Unregister ) );
}
public bool IsOneVsOne
{
get
{
if ( m_Participants.Count != 2 )
return false;
if ( ((Participant)m_Participants[0]).Players.Length != 1 )
return false;
if ( ((Participant)m_Participants[1]).Players.Length != 1 )
return false;
return true;
}
}
public static void Initialize()
{
EventSink.Speech += new SpeechEventHandler( EventSink_Speech );
EventSink.Login += new LoginEventHandler( EventSink_Login );
CommandSystem.Register( "vli", AccessLevel.GameMaster, new CommandEventHandler( vli_oc ) );
}
private static void vli_oc( CommandEventArgs e )
{
e.Mobile.BeginTarget( -1, false, Targeting.TargetFlags.None, new TargetCallback( vli_ot ) );
}
private static void vli_ot( Mobile from, object obj )
{
if ( obj is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)obj;
Ladder ladder = Ladder.Instance;
if ( ladder == null )
return;
LadderEntry entry = ladder.Find( pm );
if ( entry != null )
from.SendGump( new PropertiesGump( from, entry ) );
}
}
private static TimeSpan CombatDelay = TimeSpan.FromSeconds( 30.0 );
private static TimeSpan AutoTieDelay = TimeSpan.FromMinutes( 15.0 );
public static bool CheckCombat( Mobile m )
{
for ( int i = 0; i < m.Aggressed.Count; ++i )
{
AggressorInfo info = m.Aggressed[i];
if ( info.Defender.Player && (DateTime.UtcNow - info.LastCombatTime) < CombatDelay )
return true;
}
for ( int i = 0; i < m.Aggressors.Count; ++i )
{
AggressorInfo info = m.Aggressors[i];
if ( info.Attacker.Player && (DateTime.UtcNow - info.LastCombatTime) < CombatDelay )
return true;
}
return false;
}
private static void EventSink_Login( LoginEventArgs e )
{
PlayerMobile pm = e.Mobile as PlayerMobile;
if ( pm == null )
return;
DuelContext dc = pm.DuelContext;
if ( dc == null )
return;
if ( dc.ReadyWait && pm.DuelPlayer.Ready && !dc.Started && !dc.StartedBeginCountdown && !dc.Finished )
{
if ( dc.m_Tournament == null )
pm.SendGump( new ReadyGump( pm, dc, dc.m_ReadyCount ) );
}
else if ( dc.ReadyWait && !dc.StartedBeginCountdown && !dc.Started && !dc.Finished )
{
if ( dc.m_Tournament == null )
pm.SendGump( new ReadyUpGump( pm, dc ) );
}
else if ( dc.Initiator == pm && !dc.ReadyWait && !dc.StartedBeginCountdown && !dc.Started && !dc.Finished )
pm.SendGump( new DuelContextGump( pm, dc ) );
}
private static void ViewLadder_OnTarget( Mobile from, object obj, object state )
{
if ( obj is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)obj;
Ladder ladder = (Ladder)state;
LadderEntry entry = ladder.Find( pm );
if ( entry == null )
return; // sanity
string text = String.Format( "{{0}} are ranked {0} at level {1}.", LadderGump.Rank( entry.Index + 1 ), Ladder.GetLevel( entry.Experience ) );
pm.PrivateOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( text, from==pm?"You":"They" ), from.NetState );
}
else if ( obj is Mobile )
{
Mobile mob = (Mobile)obj;
if ( mob.Body.IsHuman )
mob.PrivateOverheadMessage( MessageType.Regular, mob.SpeechHue, false, "I'm not a duelist, and quite frankly, I resent the implication.", from.NetState );
else
mob.PrivateOverheadMessage( MessageType.Regular, 0x3B2, true, "It's probably better than you.", from.NetState );
}
else
{
from.SendMessage( "That's not a player." );
}
}
private static void EventSink_Speech( SpeechEventArgs e )
{
if ( e.Handled )
return;
PlayerMobile pm = e.Mobile as PlayerMobile;
if ( pm == null )
return;
if ( Insensitive.Contains( e.Speech, "i wish to duel" ) )
{
if ( !pm.CheckAlive() )
{
}
else if ( pm.Region.IsPartOf( typeof( Regions.Jail ) ) )
{
}
else if ( CheckCombat( pm ) )
{
e.Mobile.SendMessage( 0x22, "You have recently been in combat with another player and must wait before starting a duel." );
}
else if ( pm.DuelContext != null )
{
if ( pm.DuelContext.Initiator == pm )
e.Mobile.SendMessage( 0x22, "You have already started a duel." );
else
e.Mobile.SendMessage( 0x22, "You have already been challenged in a duel." );
}
else if ( TournamentController.IsActive )
{
e.Mobile.SendMessage( 0x22, "You may not start a duel while a tournament is active." );
}
else
{
pm.SendGump( new DuelContextGump( pm, new DuelContext( pm, RulesetLayout.Root ) ) );
e.Handled = true;
}
}
else if ( Insensitive.Equals( e.Speech, "change arena preferences" ) )
{
if ( !pm.CheckAlive() )
{
}
else
{
Preferences prefs = Preferences.Instance;
if ( prefs != null )
{
e.Mobile.CloseGump( typeof( PreferencesGump ) );
e.Mobile.SendGump( new PreferencesGump( e.Mobile, prefs ) );
}
}
}
else if ( Insensitive.Equals( e.Speech, "showladder" ) )
{
e.Blocked=true;
if ( !pm.CheckAlive() )
{
}
else
{
Ladder instance = Ladder.Instance;
if ( instance == null )
{
//pm.SendMessage( "Ladder not yet initialized." );
}
else
{
LadderEntry entry = instance.Find( pm );
if ( entry == null )
return; // sanity
string text = String.Format( "{{0}} {{1}} ranked {0} at level {1}.", LadderGump.Rank( entry.Index + 1 ), Ladder.GetLevel( entry.Experience ) );
pm.LocalOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( text, "You", "are" ) );
pm.NonlocalOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( text, pm.Name, "is" ) );
//pm.PublicOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( "Level {0} with {1} win{2} and {3} loss{4}.", Ladder.GetLevel( entry.Experience ), entry.Wins, entry.Wins==1?"":"s", entry.Losses, entry.Losses==1?"":"es" ) );
//pm.PublicOverheadMessage( MessageType.Regular, pm.SpeechHue, true, String.Format( "Level {0} with {1} win{2} and {3} loss{4}.", Ladder.GetLevel( entry.Experience ), entry.Wins, entry.Wins==1?"":"s", entry.Losses, entry.Losses==1?"":"es" ) );
}
}
}
else if ( Insensitive.Equals( e.Speech, "viewladder" ) )
{
e.Blocked=true;
if ( !pm.CheckAlive() )
{
}
else
{
Ladder instance = Ladder.Instance;
if ( instance == null )
{
//pm.SendMessage( "Ladder not yet initialized." );
}
else
{
pm.SendMessage( "Target a player to view their ranking and level." );
pm.BeginTarget( 16, false, Targeting.TargetFlags.None, new TargetStateCallback( ViewLadder_OnTarget ), instance );
}
}
}
else if ( Insensitive.Contains( e.Speech, "i yield" ) )
{
if ( !pm.CheckAlive() )
{
}
else if ( pm.DuelContext == null )
{
}
else if ( pm.DuelContext.Finished )
{
e.Mobile.SendMessage( 0x22, "The duel is already finished." );
}
else if ( !pm.DuelContext.Started )
{
DuelContext dc = pm.DuelContext;
Mobile init = dc.Initiator;
if ( pm.DuelContext.StartedBeginCountdown )
{
e.Mobile.SendMessage( 0x22, "The duel has not yet started." );
}
else
{
DuelPlayer pl = pm.DuelContext.Find( pm );
if ( pl == null )
return;
Participant p = pl.Participant;
if ( !pm.DuelContext.ReadyWait ) // still setting stuff up
{
p.Broadcast( 0x22, null, "{0} has yielded.", "You have yielded." );
if ( init == pm )
{
dc.Unregister();
}
else
{
p.Nullify( pl );
pm.DuelPlayer=null;
NetState ns = init.NetState;
if ( ns != null )
{
foreach ( Gump g in ns.Gumps )
{
if ( g is ParticipantGump )
{
ParticipantGump pg = (ParticipantGump)g;
if ( pg.Participant == p )
{
init.SendGump( new ParticipantGump( init, dc, p ) );
break;
}
}
else if ( g is DuelContextGump )
{
DuelContextGump dcg = (DuelContextGump)g;
if ( dcg.Context == dc )
{
init.SendGump( new DuelContextGump( init, dc ) );
break;
}
}
}
}
}
}
else if ( !pm.DuelContext.StartedReadyCountdown ) // at ready stage
{
p.Broadcast( 0x22, null, "{0} has yielded.", "You have yielded." );
dc.m_Yielding=true;
dc.RejectReady( pm, null );
dc.m_Yielding=false;
if ( init == pm )
{
dc.Unregister();
}
else if ( dc.m_Registered )
{
p.Nullify( pl );
pm.DuelPlayer=null;
NetState ns = init.NetState;
if ( ns != null )
{
bool send=true;
foreach ( Gump g in ns.Gumps )
{
if ( g is ParticipantGump )
{
ParticipantGump pg = (ParticipantGump)g;
if ( pg.Participant == p )
{
init.SendGump( new ParticipantGump( init, dc, p ) );
send=false;
break;
}
}
else if ( g is DuelContextGump )
{
DuelContextGump dcg = (DuelContextGump)g;
if ( dcg.Context == dc )
{
init.SendGump( new DuelContextGump( init, dc ) );
send=false;
break;
}
}
}
if ( send )
init.SendGump( new DuelContextGump( init, dc ) );
}
}
}
else
{
if ( pm.DuelContext.m_Countdown != null )
pm.DuelContext.m_Countdown.Stop();
pm.DuelContext.m_Countdown= null;
pm.DuelContext.m_StartedReadyCountdown=false;
p.Broadcast( 0x22, null, "{0} has yielded.", "You have yielded." );
dc.m_Yielding=true;
dc.RejectReady( pm, null );
dc.m_Yielding=false;
if ( init == pm )
{
dc.Unregister();
}
else if ( dc.m_Registered )
{
p.Nullify( pl );
pm.DuelPlayer=null;
NetState ns = init.NetState;
if ( ns != null )
{
bool send=true;
foreach ( Gump g in ns.Gumps )
{
if ( g is ParticipantGump )
{
ParticipantGump pg = (ParticipantGump)g;
if ( pg.Participant == p )
{
init.SendGump( new ParticipantGump( init, dc, p ) );
send=false;
break;
}
}
else if ( g is DuelContextGump )
{
DuelContextGump dcg = (DuelContextGump)g;
if ( dcg.Context == dc )
{
init.SendGump( new DuelContextGump( init, dc ) );
send=false;
break;
}
}
}
if ( send )
init.SendGump( new DuelContextGump( init, dc ) );
}
}
}
}
}
else
{
DuelPlayer pl = pm.DuelContext.Find( pm );
if ( pl != null )
{
if ( pm.DuelContext.IsOneVsOne )
{
e.Mobile.SendMessage( 0x22, "You may not yield a 1 on 1 match." );
}
else if ( pl.Eliminated )
{
e.Mobile.SendMessage( 0x22, "You have already been eliminated." );
}
else
{
pm.LocalOverheadMessage( MessageType.Regular, 0x22, false, "You have yielded." );
pm.NonlocalOverheadMessage( MessageType.Regular, 0x22, false, String.Format( "{0} has yielded.", pm.Name ) );
pm.DuelContext.m_Yielding=true;
pm.Kill();
pm.DuelContext.m_Yielding=false;
if ( pm.Alive ) // invul, ...
{
pl.Eliminated = true;
pm.DuelContext.RemoveAggressions( pm );
pm.DuelContext.SendOutside( pm );
pm.DuelContext.Refresh( pm, null );
Debuff( pm );
CancelSpell( pm );
pm.Frozen = false;
Participant winner = pm.DuelContext.CheckCompletion();
if ( winner != null )
pm.DuelContext.Finish( winner );
}
}
}
else
{
e.Mobile.SendMessage( 0x22, "BUG: Unable to find duel context." );
}
}
}
}
public DuelContext( Mobile initiator, RulesetLayout layout ) : this( initiator, layout, true )
{
}
public DuelContext( Mobile initiator, RulesetLayout layout, bool addNew )
{
m_Initiator = initiator;
m_Participants = new ArrayList();
m_Ruleset = new Ruleset( layout );
m_Ruleset.ApplyDefault( layout.Defaults[0] );
if ( addNew )
{
m_Participants.Add( new Participant( this, 1 ) );
m_Participants.Add( new Participant( this, 1 ) );
((Participant)m_Participants[0]).Add( initiator );
}
}
public void CloseAllGumps()
{
Type[] types = new Type[]{ typeof( DuelContextGump ), typeof( ParticipantGump ), typeof( RulesetGump ) };
int[] defs = new int[]{ -1, -1, -1 };
for ( int i = 0; i < m_Participants.Count; ++i )
{
|
Before solving the code completion task, imagine you are a student memorizing this material according to the task that you will have to perform. Ensure you preserve all critical details to solve the task and create a cheat sheet covering the entire context. Once you have done that, I will prompt you to solve the code completion task.
Since your task is code completion, write a cheat sheet that is tailored to help you write the correct next line(s) of code. Highlight or list the specific lines or variables in the context that are most relevant for this task.
For example:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class Example {
private int count;
public void increment() {
count++;
}
public int getCount() {
Cheatsheet (for next line):
- We are in getCount(), which should return the current value of count.
- count is a private integer field.
- Convention: Getter methods return the corresponding field.
- [Relevant lines: declaration of count, method header]
Next line will likely be: return count;
|
Next line of code:
|
lcc
| 84
|
Cheat sheet for the given context:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class DuelContext {
// ... (many lines of code)
public void Award( Mobile us, Mobile them, bool won )
{
// ... (many lines of code)
LadderEntry ourEntry = ladder.Find( us );
LadderEntry theirEntry = ladder.Find( them );
if ( ourEntry == null || theirEntry == null )
return;
int xpGain = Ladder.GetExperienceGain( ourEntry, theirEntry, won );
if ( xpGain == 0 )
return;
if ( m_Tournament != null )
xpGain *= ( xpGain > 0 ? 5 : 2 );
if ( won )
++ourEntry.Wins;
else
++ourEntry.Losses;
int oldLevel = Ladder.GetLevel( ourEntry.Experience );
ourEntry.Experience += xpGain;
if ( ourEntry.Experience < 0 )
ourEntry.Experience = 0;
ladder.UpdateEntry( ourEntry );
int newLevel = Ladder.GetLevel( ourEntry.Experience );
if ( newLevel > oldLevel )
us.SendMessage( 0x59, "You have achieved level {0}!", newLevel );
else if ( newLevel < oldLevel )
us.SendMessage( 0x22, "You have lost a level. You are now at {0}.", newLevel );
// ... (many lines of code)
}
public void Unregister( bool queryRematch )
{
// ... (many lines of code)
if ( m_Tournament != null )
m_Tournament.Alert( m_Arena, "Sudden death has been activated!" );
m_IsSuddenDeath = true;
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = null;
}
public void StartSuddenDeath( TimeSpan timeUntilActive )
{
// ... (many lines of code)
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = Timer.DelayCall( timeUntilActive, new TimerCallback( ActivateSuddenDeath ) );
}
public void ActivateSuddenDeath()
{
// ... (many lines of code)
m_IsSuddenDeath = true;
if ( m_SDActivateTimer != null )
m_SDActivateTimer.Stop();
m_SDActivateTimer = null;
}
public void BeginAutoTie()
{
// ... (many lines of code)
m_AutoTieTimer = Timer.DelayCall( ts, new TimerCallback( InvokeAutoTie ) );
}
public void InvokeAutoTie()
{
// ... (many lines of code)
m_AutoTieTimer = null;
if ( !m_Started || m_Finished )
return;
m_Tied = true;
m_Finished = true;
StopSDTimers();
ArrayList remaining = new ArrayList();
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
if ( p.Eliminated )
{
p.Broadcast( 0x22, null, p.Players.Length == 1 ? "{0} has lost the duel." : "{0} and {1} team have lost the duel.", p.Players.Length == 1 ? "You have lost the duel." : "Your team has lost the duel." );
}
else
{
p.Broadcast( 0x59, null, p.Players.Length == 1 ? "{0} has tied the duel due to time expiration." : "{0} and {1} team have tied the duel due to time expiration.", p.Players.Length == 1 ? "You have tied the duel due to time expiration." : "Your team has tied the duel due to time expiration." );
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl != null && !pl.Eliminated )
DelayBounce( TimeSpan.FromSeconds( 8.0 ), pl.Mobile, null );
}
if ( p.TournyPart != null )
remaining.Add( p.TournyPart );
}
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl != null )
{
pl.Mobile.Delta( MobileDelta.Noto );
pl.Mobile.SendEverything();
}
}
}
if ( m_Tournament != null )
m_Tournament.HandleTie( m_Arena, m_Match, remaining );
Timer.DelayCall( TimeSpan.FromSeconds( 10.0 ), new TimerCallback( Unregister ) );
}
public bool IsOneVsOne
{
get
{
if ( m_Participants.Count != 2 )
return false;
if ( ((Participant)m_Participants[0]).Players.Length != 1 )
return false;
if ( ((Participant)m_Participants[1]).Players.Length != 1 )
return false;
return true;
}
}
public static void Initialize()
{
EventSink.Speech += new SpeechEventHandler( EventSink_Speech );
EventSink.Login += new LoginEventHandler( EventSink_Login );
CommandSystem.Register( "vli", AccessLevel.GameMaster, new CommandEventHandler( vli_oc ) );
}
private static void vli_oc( CommandEventArgs e )
{
e.Mobile.BeginTarget( -1, false, Targeting.TargetFlags.None, new TargetCallback( vli_ot ) );
}
private static void vli_ot( Mobile from, object obj )
{
if ( obj is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)obj;
Ladder ladder = (Ladder)state;
LadderEntry entry = ladder.Find( pm );
if ( entry != null )
from.SendGump( new PropertiesGump( from, entry ) );
}
else if ( obj is Mobile )
{
Mobile mob = (Mobile)obj;
if ( mob.Body.IsHuman )
mob.PrivateOverheadMessage( MessageType.Regular, mob.SpeechHue, false, "I'm not a duelist, and quite frankly, I resent the implication.", from.NetState );
else
mob.PrivateOverheadMessage( MessageType.Regular, 0x3B2, true, "It's probably better than you.", from.NetState );
}
else
{
from.SendMessage( "That's not a player." );
}
}
private static void EventSink_Login( LoginEventArgs e )
{
PlayerMobile pm = e.Mobile as PlayerMobile;
if ( pm == null )
return;
if ( pm.DuelContext != null )
{
if ( pm.DuelContext.Initiator == pm )
pm.SendGump( new DuelContextGump( pm, pm.DuelContext ) );
}
else
{
pm.SendGump( new DuelContextGump( pm, new DuelContext( pm, RulesetLayout.Root ) ) );
}
}
private static void EventSink_Speech( SpeechEventArgs e )
{
// ... (many lines of code)
if ( Insensitive.Contains( e.Speech, "i wish to duel" ) )
{
// ... (many lines of code)
}
else if ( Insensitive.Equals( e.Speech, "viewladder" ) )
{
e.Blocked=true;
if ( !pm.CheckAlive() )
{
}
else
{
Ladder instance = Ladder.Instance;
if ( instance == null )
{
//pm.SendMessage( "Ladder not yet initialized." );
}
else
{
pm.SendMessage( "Target a player to view their ranking and level." );
pm.BeginTarget( 16, false, Targeting.TargetFlags.None, new TargetStateCallback( ViewLadder_OnTarget ), instance );
}
}
}
else if ( Insensitive.Contains( e.Speech, "i yield" ) )
{
// ... (many lines of code)
}
}
public DuelContext( Mobile initiator, RulesetLayout layout ) : this( initiator, layout, true )
{
}
public DuelContext( Mobile initiator, RulesetLayout layout, bool addNew )
{
m_Initiator = initiator;
m_Participants = new ArrayList();
m_Ruleset = new Ruleset( layout );
m_Ruleset.ApplyDefault( layout.Defaults[0] );
if ( addNew )
{
m_Participants.Add( new Participant( this, 1 ) );
m_Participants.Add( new Participant( this, 1 ) );
((Participant)m_Participants[0]).Add( initiator );
}
}
public void CloseAllGumps()
{
Type[] types = new Type[]{ typeof( DuelContextGump ), typeof( ParticipantGump ), typeof( RulesetGump ) };
int[] defs = new int[]{ -1, -1, -1 };
for ( int i = 0; i < m_Participants.Count; ++i )
{
Participant p = (Participant)m_Participants[i];
for ( int j = 0; j < p.Players.Length; ++j )
{
DuelPlayer pl = p.Players[j];
if ( pl != null )
{
pl.Mobile.CloseGump( typeof(
|
|
Please complete the code given below.
import networkx as nx
import pickle
from Queue import PriorityQueue
import copy
import random
import string
import sys
class MultiDiGraph_EdgeKey(nx.MultiDiGraph):
"""
MultiDiGraph which assigns unique keys to every edge.
Adds a dictionary edge_index which maps edge keys to (u, v, data) tuples.
This is not a complete implementation. For Edmonds algorithm, we only use
add_node and add_edge, so that is all that is implemented here. During
additions, any specified keys are ignored---this means that you also
cannot update edge attributes through add_node and add_edge.
"""
def __init__(self, data=None, **attr):
cls = super(MultiDiGraph_EdgeKey, self)
cls.__init__(data=data, **attr)
self._cls = cls
self.edge_index = {}
def remove_node(self, n):
keys = set([])
for keydict in self.pred[n].values():
keys.update(keydict)
for keydict in self.succ[n].values():
keys.update(keydict)
for key in keys:
del self.edge_index[key]
self._cls.remove_node(n)
def remove_nodes_from(self, nbunch):
for n in nbunch:
self.remove_node(n)
def add_edge(self, u, v, key, attr_dict=None, **attr):
"""
Key is now required.
"""
if key in self.edge_index:
uu, vv, _ = self.edge_index[key]
if (u != uu) or (v != vv):
raise Exception("Key {0!r} is already in use.".format(key))
self._cls.add_edge(u, v, key=key, attr_dict=attr_dict, **attr)
self.edge_index[key] = (u, v, self.succ[u][v][key])
def add_edges_from(self, ebunch, attr_dict=None, **attr):
for edge in ebunch:
self.add_edge(*edge)
def remove_edge_with_key(self, key):
try:
u, v, _ = self.edge_index[key]
# print ('***',u,v,key)
except KeyError:
raise KeyError('Invalid edge key {0!r}'.format(key))
else:
del self.edge_index[key]
# print ('***** self.edge_index',self.edge_index)
self._cls.remove_edge(u, v, key)
def remove_edges_from(self, ebunch):
raise NotImplementedError
def random_string(L=15, seed=None):
random.seed(seed)
return ''.join([random.choice(string.ascii_letters) for n in range(L)])
class Camerini():
def __init__(self, graph, Y=nx.DiGraph(), Z=nx.DiGraph(), attr='weight'):
self.original_graph = graph
self.attr = attr
self._init(Y=Y, Z=Z)
self.template = random_string()
def _init(self, graph=None, Y=nx.DiGraph(), Z=nx.DiGraph()):
self.graph = MultiDiGraph_EdgeKey()
if graph is None:
graph = self.original_graph
for key, (u, v, data) in enumerate(graph.edges(data=True)):
if (u,v) not in Z.edges():
self.graph.add_edge(u,v,key,data.copy())
for Y_edge in Y.edges(data=True):
for (u,v) in self.graph.in_edges([Y_edge[1]]):
if u != Y_edge[0]:
self.graph.remove_edge(u,v)
def best_incoming_edge(self, node, graph):
max_weight = float('-inf')
e = None
# print ('Graph',graph.edges())
for u,v,key,data in graph.in_edges([node], data=True, keys=True):
# print ('edge',u,v,data)
if max_weight <= data[self.attr]:
max_weight = data[self.attr]
e = (u,v,key,data)
return e
def collapse_cycle(self, graph, cycle, B, new_node):
for node in cycle:
for u,v,key,data in graph.out_edges([node], data=True, keys=True):
graph.remove_edge_with_key(key)
if v not in cycle:
dd = data.copy()
graph.add_edge(new_node,v,key,**dd)
for u,v,key,data in graph.in_edges([node], data=True, keys=True):
if u in cycle:
# it will be delete later
continue
graph.remove_edge_with_key(key)
dd = data.copy()
dd_eh = list(B.in_edges([node], data=True))[0][2]
dd[self.attr] = dd[self.attr] - dd_eh[self.attr]
graph.add_edge(u, new_node, key, **dd)
for node in cycle:
B.remove_node(node)
return graph, B
def add_b_to_branching(self, exposed_nodes, order, M, supernodes, B):
v = exposed_nodes.pop(0)
order.append(v)
b = self.best_incoming_edge(v, M)
if b is None:
if v in supernodes:
supernodes.remove(v)
return exposed_nodes, order, M, supernodes, B, None
b_u, b_v, b_key, b_data = b
data = {self.attr: b_data[self.attr], 'origin': b_data['origin']}
B.add_edge(b_u, b_v, **data)
return exposed_nodes, order, M, supernodes, B, b
def contracting_phase(self, B, n, supernodes, exposed_nodes, M, C, root):
cycles = list(nx.simple_cycles(B))
if len(cycles) > 0:
u = 'v_'+str(n)
supernodes.append(str(u))
exposed_nodes.append(u)
for node in cycles[0]:
C[str(node)] = str(u)
M, B = self.collapse_cycle(M, cycles[0], B, u)
for node in B.nodes():
if B.in_edges([node]) == []:
if B.out_edges([node]) == []:
B.remove_node(node)
if node != root and node not in exposed_nodes:
exposed_nodes.append(node)
n += 1
return B, n, supernodes, exposed_nodes, M, C
def best(self, root):
M = self.graph
for u,v,key,data in M.edges(data=True, keys=True):
data['origin'] = (u,v,key,{self.attr: data[self.attr]})
n = 0
B = nx.DiGraph()
# C contains for every node its parent node, so it will be easy to find the path in the collapsing phase
# from an isolated root v_1 to v_k
nodes = M.nodes()
if len(nodes) == 1:
A = nx.DiGraph()
A.add_node(nodes[0])
C = {str(node): None for node in nodes}
del C[str(root)]
exposed_nodes = [node for node in nodes]
exposed_nodes.remove(root)
supernodes = []
beta = {}
order = []
# collapsing phase
while len(exposed_nodes) > 0:
exposed_nodes, order, M, supernodes, B, b = self.add_b_to_branching(exposed_nodes, order, M, supernodes, B)
if b is None:
continue
b_u, b_v, b_key, b_data = b
beta[b_v] = (b_u, b_v, b_key, b_data)
B, n, supernodes, exposed_nodes, M, C = self.contracting_phase(B, n, supernodes, exposed_nodes, M, C, root)
# expanding phase
while len(supernodes) > 0:
v_1 = supernodes.pop()
origin_edge_v_1 = beta[v_1][3]['origin']
v_k = origin_edge_v_1[1]
beta[v_k] = beta[v_1]
v_i = str(C[str(v_k)])
while v_i != v_1:
supernodes.remove(v_i)
v_i = C.pop(v_i)
A = nx.DiGraph()
for k, edge in beta.items():
if k in nodes:
u,v,key,data = edge[3]['origin']
A.add_edge(u,v,**data.copy())
return A
def get_priority_queue_for_incoming_node(self, graph, v, b):
Q = PriorityQueue()
for u,v,key,data in graph.in_edges([v], data=True, keys=True):
if key == b[2]:
continue
Q.put((-data[self.attr], (u,v,key,data)))
return Q
def seek(self, b, A, graph):
v = b[1]
Q = self.get_priority_queue_for_incoming_node(graph, v, b)
while not Q.empty():
f = Q.get()
try:
# v = T(b) is an ancestor of O(f)=f[1][1]?
v_origin = b[3]['origin'][1]
f_origin = f[1][3]['origin'][0]
nx.shortest_path(A, v_origin, f_origin)
except nx.exception.NetworkXNoPath:
return f[1]
return None
def next(self, A, Y, Z, graph=None, root='R'):
d = float('inf')
edge = None
if graph is not None:
self._init(graph)
M = self.graph
for u,v,key,data in M.edges(data=True, keys=True):
data['origin'] = (u,v,key,{self.attr: data[self.attr]})
n = 0
B = nx.DiGraph()
nodes = M.nodes()
C = {str(node): None for node in nodes}
exposed_nodes = [node for node in nodes]
if 'R' in exposed_nodes:
exposed_nodes.remove('R')
order = []
supernodes = []
while len(exposed_nodes) > 0:
exposed_nodes, order, M, supernodes, B, b = self.add_b_to_branching(exposed_nodes, order, M, supernodes, B)
if b is None:
continue
b_u, b_v, b_key, b_data = b
origin_u, origin_v = b_data['origin'][:2]
if (origin_u, origin_v) in A.edges():
if (origin_u, origin_v) not in Y.edges():
f = self.seek(b, A, M)
if f is not None:
f_u, f_v, f_key, f_data = f
if b_data[self.attr] - f_data[self.attr] < d:
edge = b
d = b_data[self.attr] - f_data[self.attr]
B, n, supernodes, exposed_nodes, M, C = self.contracting_phase(B, n, supernodes, exposed_nodes, M, C, root)
return edge[3]['origin'], d
def ranking(self, k, graph=None, Y=nx.DiGraph(), Z=nx.DiGraph(), mode='branching', root='R'):
if graph is not None:
self._init(graph, Y, Z)
if root == 'R' and mode == 'branching':
best = self.best_branching
elif root == 'R' and mode == 'arborescence_no_rooted':
best = self.best_arborescence_no_rooted
else:
best = self.best_arborescence_rooted
graph = self.graph.copy()
A = best(root)
roots = self.find_roots(A)
if 'R' in roots:
roots.remove('R')
print ('roots for ranking',roots)
self._init(graph)
e, d = self.next(A, Y, Z)
P = PriorityQueue()
w = self.get_graph_score(A) - d if d != float('inf') else float('inf')
P.put( (-w, e, A, Y, Z) )
solutions = [A]
for j in range(1,k+1):
w, e, A, Y, Z = P.get()
w = -w
roots.extend([root for root in self.find_roots(A) if root not in roots])
if 'R' in roots:
roots.remove('R')
if w == float('-inf'):
return solutions
e_u, e_v, e_key, data = e
Y_ = Y.copy()
Y_.add_edge(e_u, e_v, **data.copy())
Z_ = Z.copy()
|
[
"\t\t\tZ_.add_edge(e_u, e_v, **data.copy())"
] | 1,069
|
lcc
|
python
| null |
ca807f49d7c6f84dcae3df694bde685aa7f75a02e9d4f574
| 1
|
Your task is code completion.
import networkx as nx
import pickle
from Queue import PriorityQueue
import copy
import random
import string
import sys
class MultiDiGraph_EdgeKey(nx.MultiDiGraph):
"""
MultiDiGraph which assigns unique keys to every edge.
Adds a dictionary edge_index which maps edge keys to (u, v, data) tuples.
This is not a complete implementation. For Edmonds algorithm, we only use
add_node and add_edge, so that is all that is implemented here. During
additions, any specified keys are ignored---this means that you also
cannot update edge attributes through add_node and add_edge.
"""
def __init__(self, data=None, **attr):
cls = super(MultiDiGraph_EdgeKey, self)
cls.__init__(data=data, **attr)
self._cls = cls
self.edge_index = {}
def remove_node(self, n):
keys = set([])
for keydict in self.pred[n].values():
keys.update(keydict)
for keydict in self.succ[n].values():
keys.update(keydict)
for key in keys:
del self.edge_index[key]
self._cls.remove_node(n)
def remove_nodes_from(self, nbunch):
for n in nbunch:
self.remove_node(n)
def add_edge(self, u, v, key, attr_dict=None, **attr):
"""
Key is now required.
"""
if key in self.edge_index:
uu, vv, _ = self.edge_index[key]
if (u != uu) or (v != vv):
raise Exception("Key {0!r} is already in use.".format(key))
self._cls.add_edge(u, v, key=key, attr_dict=attr_dict, **attr)
self.edge_index[key] = (u, v, self.succ[u][v][key])
def add_edges_from(self, ebunch, attr_dict=None, **attr):
for edge in ebunch:
self.add_edge(*edge)
def remove_edge_with_key(self, key):
try:
u, v, _ = self.edge_index[key]
# print ('***',u,v,key)
except KeyError:
raise KeyError('Invalid edge key {0!r}'.format(key))
else:
del self.edge_index[key]
# print ('***** self.edge_index',self.edge_index)
self._cls.remove_edge(u, v, key)
def remove_edges_from(self, ebunch):
raise NotImplementedError
def random_string(L=15, seed=None):
random.seed(seed)
return ''.join([random.choice(string.ascii_letters) for n in range(L)])
class Camerini():
def __init__(self, graph, Y=nx.DiGraph(), Z=nx.DiGraph(), attr='weight'):
self.original_graph = graph
self.attr = attr
self._init(Y=Y, Z=Z)
self.template = random_string()
def _init(self, graph=None, Y=nx.DiGraph(), Z=nx.DiGraph()):
self.graph = MultiDiGraph_EdgeKey()
if graph is None:
graph = self.original_graph
for key, (u, v, data) in enumerate(graph.edges(data=True)):
if (u,v) not in Z.edges():
self.graph.add_edge(u,v,key,data.copy())
for Y_edge in Y.edges(data=True):
for (u,v) in self.graph.in_edges([Y_edge[1]]):
if u != Y_edge[0]:
self.graph.remove_edge(u,v)
def best_incoming_edge(self, node, graph):
max_weight = float('-inf')
e = None
# print ('Graph',graph.edges())
for u,v,key,data in graph.in_edges([node], data=True, keys=True):
# print ('edge',u,v,data)
if max_weight <= data[self.attr]:
max_weight = data[self.attr]
e = (u,v,key,data)
return e
def collapse_cycle(self, graph, cycle, B, new_node):
for node in cycle:
for u,v,key,data in graph.out_edges([node], data=True, keys=True):
graph.remove_edge_with_key(key)
if v not in cycle:
dd = data.copy()
graph.add_edge(new_node,v,key,**dd)
for u,v,key,data in graph.in_edges([node], data=True, keys=True):
if u in cycle:
# it will be delete later
continue
graph.remove_edge_with_key(key)
dd = data.copy()
dd_eh = list(B.in_edges([node], data=True))[0][2]
dd[self.attr] = dd[self.attr] - dd_eh[self.attr]
graph.add_edge(u, new_node, key, **dd)
for node in cycle:
B.remove_node(node)
return graph, B
def add_b_to_branching(self, exposed_nodes, order, M, supernodes, B):
v = exposed_nodes.pop(0)
order.append(v)
b = self.best_incoming_edge(v, M)
if b is None:
if v in supernodes:
supernodes.remove(v)
return exposed_nodes, order, M, supernodes, B, None
b_u, b_v, b_key, b_data = b
data = {self.attr: b_data[self.attr], 'origin': b_data['origin']}
B.add_edge(b_u, b_v, **data)
return exposed_nodes, order, M, supernodes, B, b
def contracting_phase(self, B, n, supernodes, exposed_nodes, M, C, root):
cycles = list(nx.simple_cycles(B))
if len(cycles) > 0:
u = 'v_'+str(n)
supernodes.append(str(u))
exposed_nodes.append(u)
for node in cycles[0]:
C[str(node)] = str(u)
M, B = self.collapse_cycle(M, cycles[0], B, u)
for node in B.nodes():
if B.in_edges([node]) == []:
if B.out_edges([node]) == []:
B.remove_node(node)
if node != root and node not in exposed_nodes:
exposed_nodes.append(node)
n += 1
return B, n, supernodes, exposed_nodes, M, C
def best(self, root):
M = self.graph
for u,v,key,data in M.edges(data=True, keys=True):
data['origin'] = (u,v,key,{self.attr: data[self.attr]})
n = 0
B = nx.DiGraph()
# C contains for every node its parent node, so it will be easy to find the path in the collapsing phase
# from an isolated root v_1 to v_k
nodes = M.nodes()
if len(nodes) == 1:
A = nx.DiGraph()
A.add_node(nodes[0])
C = {str(node): None for node in nodes}
del C[str(root)]
exposed_nodes = [node for node in nodes]
exposed_nodes.remove(root)
supernodes = []
beta = {}
order = []
# collapsing phase
while len(exposed_nodes) > 0:
exposed_nodes, order, M, supernodes, B, b = self.add_b_to_branching(exposed_nodes, order, M, supernodes, B)
if b is None:
continue
b_u, b_v, b_key, b_data = b
beta[b_v] = (b_u, b_v, b_key, b_data)
B, n, supernodes, exposed_nodes, M, C = self.contracting_phase(B, n, supernodes, exposed_nodes, M, C, root)
# expanding phase
while len(supernodes) > 0:
v_1 = supernodes.pop()
origin_edge_v_1 = beta[v_1][3]['origin']
v_k = origin_edge_v_1[1]
beta[v_k] = beta[v_1]
v_i = str(C[str(v_k)])
while v_i != v_1:
supernodes.remove(v_i)
v_i = C.pop(v_i)
A = nx.DiGraph()
for k, edge in beta.items():
if k in nodes:
u,v,key,data = edge[3]['origin']
A.add_edge(u,v,**data.copy())
return A
def get_priority_queue_for_incoming_node(self, graph, v, b):
Q = PriorityQueue()
for u,v,key,data in graph.in_edges([v], data=True, keys=True):
if key == b[2]:
continue
Q.put((-data[self.attr], (u,v,key,data)))
return Q
def seek(self, b, A, graph):
v = b[1]
Q = self.get_priority_queue_for_incoming_node(graph, v, b)
while not Q.empty():
f = Q.get()
try:
# v = T(b) is an ancestor of O(f)=f[1][1]?
v_origin = b[3]['origin'][1]
f_origin = f[1][3]['origin'][0]
nx.shortest_path(A, v_origin, f_origin)
except nx.exception.NetworkXNoPath:
return f[1]
return None
def next(self, A, Y, Z, graph=None, root='R'):
d = float('inf')
edge = None
if graph is not None:
self._init(graph)
M = self.graph
for u,v,key,data in M.edges(data=True, keys=True):
data['origin'] = (u,v,key,{self.attr: data[self.attr]})
n = 0
B = nx.DiGraph()
nodes = M.nodes()
C = {str(node): None for node in nodes}
exposed_nodes = [node for node in nodes]
if 'R' in exposed_nodes:
exposed_nodes.remove('R')
order = []
supernodes = []
while len(exposed_nodes) > 0:
exposed_nodes, order, M, supernodes, B, b = self.add_b_to_branching(exposed_nodes, order, M, supernodes, B)
if b is None:
continue
b_u, b_v, b_key, b_data = b
origin_u, origin_v = b_data['origin'][:2]
if (origin_u, origin_v) in A.edges():
if (origin_u, origin_v) not in Y.edges():
f = self.seek(b, A, M)
if f is not None:
f_u, f_v, f_key, f_data = f
if b_data[self.attr] - f_data[self.attr] < d:
edge = b
d = b_data[self.attr] - f_data[self.attr]
B, n, supernodes, exposed_nodes, M, C = self.contracting_phase(B, n, supernodes, exposed_nodes, M, C, root)
return edge[3]['origin'], d
def ranking(self, k, graph=None, Y=nx.DiGraph(), Z=nx.DiGraph(), mode='branching', root='R'):
if graph is not None:
self._init(graph, Y, Z)
if root == 'R' and mode == 'branching':
best = self.best_branching
elif root == 'R' and mode == 'arborescence_no_rooted':
best = self.best_arborescence_no_rooted
else:
best = self.best_arborescence_rooted
graph = self.graph.copy()
A = best(root)
roots = self.find_roots(A)
if 'R' in roots:
roots.remove('R')
print ('roots for ranking',roots)
self._init(graph)
e, d = self.next(A, Y, Z)
P = PriorityQueue()
w = self.get_graph_score(A) - d if d != float('inf') else float('inf')
P.put( (-w, e, A, Y, Z) )
solutions = [A]
for j in range(1,k+1):
w, e, A, Y, Z = P.get()
w = -w
roots.extend([root for root in self.find_roots(A) if root not in roots])
if 'R' in roots:
roots.remove('R')
if w == float('-inf'):
return solutions
e_u, e_v, e_key, data = e
Y_ = Y.copy()
Y_.add_edge(e_u, e_v, **data.copy())
Z_ = Z.copy()
|
Before solving the code completion task, imagine you are a student memorizing this material according to the task that you will have to perform. Ensure you preserve all critical details to solve the task and create a cheat sheet covering the entire context. Once you have done that, I will prompt you to solve the code completion task.
Since your task is code completion, write a cheat sheet that is tailored to help you write the correct next line(s) of code. Highlight or list the specific lines or variables in the context that are most relevant for this task.
For example:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class Example {
private int count;
public void increment() {
count++;
}
public int getCount() {
Cheatsheet (for next line):
- We are in getCount(), which should return the current value of count.
- count is a private integer field.
- Convention: Getter methods return the corresponding field.
- [Relevant lines: declaration of count, method header]
Next line will likely be: return count;
|
Next line of code:
|
lcc
| 84
|
Cheat sheet for the given code:
**Context:**
[Previous code... ~10,000 lines omitted for brevity]
def ranking(self, k, graph=None, Y=nx.DiGraph(), Z=nx.DiGraph(), mode='branching', root='R'):
if graph is not None:
self._init(graph, Y, Z)
if root == 'R' and mode == 'branching':
best = self.best_branching
elif root == 'R' and mode == 'arborescence_no_rooted':
best = self.best_arborescence_no_rooted
else:
best = self.best_arborescence_rooted
graph = self.graph.copy()
A = best(root)
roots = self.find_roots(A)
if 'R' in roots:
roots.remove('R')
print ('roots for ranking',roots)
self._init(graph)
e, d = self.next(A, Y, Z)
P = PriorityQueue()
w = self.get_graph_score(A) - d if d != float('inf') else float('inf')
P.put( (-w, e, A, Y, Z) )
solutions = [A]
for j in range(1,k+1):
w, e, A, Y, Z = P.get()
w = -w
roots.extend([root for root in self.find_roots(A) if root not in roots])
if 'R' in roots:
roots.remove('R')
if w == float('-inf'):
return solutions
e_u, e_v, e_key, data = e
Y_ = Y.copy()
Y_.add_edge(e_u, e_v, **data.copy())
Z_ = Z.copy()
**Cheat sheet:**
- We are in the for loop of the ranking method, which is iterating from 1 to k.
- The current iteration is j, and we need to get the next solution from the priority queue P.
- The current solution is stored in A, Y, and Z.
- We need to update the priority queue P with the next solution.
- The next solution is obtained by removing the top element from P.
- The top element is a tuple containing the negative weight w, the edge e, the graph A, the graph Y, and the graph Z.
- We need to unpack this tuple and update the variables accordingly.
- The weight w is negated to make it positive, as it's a priority queue.
- The edge e is stored in e_u, e_v, e_key, and data.
- The graphs A, Y, and Z are updated by copying the current values.
- The new graphs Y_ and Z_ are created by adding the edge e to Y and Z, respectively.
**Relevant lines:**
- `for j in range(1,k+1):`
- `w, e, A, Y, Z = P.get()`
- `P.put( (-w, e, A, Y, Z) )`
- `e_u, e_v, e_key, data = e`
- `Y_ = Y.copy()`
- `Z_ = Z.copy()`
**Next line:**
- We need to update the priority queue P with the new solution.
- The new solution is obtained by negating the weight w and keeping the same edge e, graph A, graph Y, and graph Z.
- The new solution is stored in the priority queue P.
The next line of code should be:
```python
P.put( (-w, e, A, Y_, Z_) )
```
|
|
Please complete the code given below.
#! /usr/bin/env python
# Last Change: Sun Dec 14 07:00 PM 2008 J
"""Test for the sndfile class."""
from os.path import join, dirname
import os
import sys
from numpy.testing import TestCase, assert_array_equal, dec
import numpy as np
from audiolab import Sndfile, Format, available_encodings, available_file_formats
from testcommon import open_tmp_file, close_tmp_file, TEST_DATA_DIR
_DTYPE_TO_ENC = {np.float64 : 'float64', np.float32: 'float32',
np.int32: 'pcm32', np.int16: 'pcm16'}
# XXX: there is a lot to refactor here
class TestSndfile(TestCase):
def test_basic_io(self):
""" Check open, close and basic read/write"""
# dirty !
ofilename = join(TEST_DATA_DIR, 'test.wav')
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
nbuff = 22050
# Open the test file for reading
a = Sndfile(ofilename, 'r')
nframes = a.nframes
# Open the copy file for writing
format = Format('wav', 'pcm16')
b = Sndfile(fd, 'w', format, a.channels, a.samplerate)
# Copy the data
for i in range(nframes / nbuff):
tmpa = a.read_frames(nbuff)
assert tmpa.dtype == np.float
b.write_frames(tmpa)
nrem = nframes % nbuff
tmpa = a.read_frames(nrem)
assert tmpa.dtype == np.float
b.write_frames(tmpa)
a.close()
b.close()
finally:
close_tmp_file(rfd, cfilename)
@dec.skipif(sys.platform=='win32',
"Not testing opening by fd because does not work on win32")
def test_basic_io_fd(self):
""" Check open from fd works"""
ofilename = join(TEST_DATA_DIR, 'test.wav')
fd = os.open(ofilename, os.O_RDONLY)
hdl = Sndfile(fd, 'r')
hdl.close()
def test_raw(self):
rawname = join(TEST_DATA_DIR, 'test.raw')
format = Format('raw', 'pcm16', 'little')
a = Sndfile(rawname, 'r', format, 1, 11025)
assert a.nframes == 11290
a.close()
def test_float64(self):
"""Check float64 write/read works"""
self._test_read_write(np.float64)
def test_float32(self):
"""Check float32 write/read works"""
self._test_read_write(np.float32)
def test_int32(self):
"""Check 32 bits pcm write/read works"""
self._test_read_write(np.int32)
def test_int16(self):
"""Check 16 bits pcm write/read works"""
self._test_read_write(np.int16)
def _test_read_write(self, dtype):
# dirty !
ofilename = join(TEST_DATA_DIR, 'test.wav')
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
nbuff = 22050
# Open the test file for reading
a = Sndfile(ofilename, 'r')
nframes = a.nframes
# Open the copy file for writing
format = Format('wav', _DTYPE_TO_ENC[dtype])
b = Sndfile(fd, 'w', format, a.channels, a.samplerate)
# Copy the data in the wav file
for i in range(nframes / nbuff):
tmpa = a.read_frames(nbuff, dtype=dtype)
assert tmpa.dtype == dtype
b.write_frames(tmpa)
nrem = nframes % nbuff
tmpa = a.read_frames(nrem)
b.write_frames(tmpa)
a.close()
b.close()
# Now, reopen both files in for reading, and check data are
# the same
a = Sndfile(ofilename, 'r')
b = Sndfile(cfilename, 'r')
for i in range(nframes / nbuff):
tmpa = a.read_frames(nbuff, dtype=dtype)
tmpb = b.read_frames(nbuff, dtype=dtype)
assert_array_equal(tmpa, tmpb)
a.close()
b.close()
finally:
close_tmp_file(rfd, cfilename)
#def test_supported_features(self):
# for i in available_file_formats():
# print "Available encodings for format %s are : " % i
# for j in available_encodings(i):
# print '\t%s' % j
def test_short_io(self):
self._test_int_io(np.short)
def test_int32_io(self):
self._test_int_io(np.int32)
def _test_int_io(self, dt):
# TODO: check if neg or pos value is the highest in abs
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
# Use almost full possible range possible for the given data-type
nb = 2 ** (8 * np.dtype(dt).itemsize - 3)
fs = 22050
nbuff = fs
a = np.random.random_integers(-nb, nb, nbuff)
a = a.astype(dt)
# Open the file for writing
format = Format('wav', _DTYPE_TO_ENC[dt])
b = Sndfile(fd, 'w', format, 1, fs)
b.write_frames(a)
b.close()
b = Sndfile(cfilename, 'r')
read_a = b.read_frames(nbuff, dtype=dt)
b.close()
assert_array_equal(a, read_a)
finally:
close_tmp_file(rfd, cfilename)
def test_mismatch(self):
"""Check for bad arguments."""
# This test open a file for writing, but with bad args (channels and
# nframes inverted)
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
# Open the file for writing
format = Format('wav', 'pcm16')
try:
b = Sndfile(fd, 'w', format, channels=22000, samplerate=1)
raise AssertionError("Try to open a file with more than 256 "\
"channels, this should not succeed !")
except ValueError, e:
pass
finally:
close_tmp_file(rfd, cfilename)
def test_bigframes(self):
""" Try to seek really far."""
rawname = join(TEST_DATA_DIR, 'test.wav')
a = Sndfile(rawname, 'r')
try:
try:
a.seek(2 ** 60)
raise Exception, \
"Seek really succeded ! This should not happen"
except IOError, e:
pass
finally:
a.close()
def test_float_frames(self):
""" Check nframes can be a float"""
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
# Open the file for writing
format = Format('wav', 'pcm16')
a = Sndfile(fd, 'rw', format, channels=1, samplerate=22050)
tmp = np.random.random_integers(-100, 100, 1000)
tmp = tmp.astype(np.short)
a.write_frames(tmp)
a.seek(0)
a.sync()
ctmp = a.read_frames(1e2, dtype=np.short)
a.close()
finally:
close_tmp_file(rfd, cfilename)
def test_nofile(self):
""" Check the failure when opening a non existing file."""
try:
f = Sndfile("floupi.wav", "r")
raise AssertionError("call to non existing file should not succeed")
except IOError:
pass
except Exception, e:
raise AssertionError("opening non existing file should raise" \
" a IOError exception, got %s instead" %
e.__class__)
class TestSeek(TestCase):
def test_simple(self):
ofilename = join(TEST_DATA_DIR, 'test.wav')
# Open the test file for reading
a = Sndfile(ofilename, 'r')
nframes = a.nframes
buffsize = 1024
buffsize = min(nframes, buffsize)
# First, read some frames, go back, and compare buffers
buff = a.read_frames(buffsize)
a.seek(0)
buff2 = a.read_frames(buffsize)
assert_array_equal(buff, buff2)
a.close()
# Now, read some frames, go back, and compare buffers
# (check whence == 1 == SEEK_CUR)
a = Sndfile(ofilename, 'r')
a.read_frames(buffsize)
buff = a.read_frames(buffsize)
a.seek(-buffsize, 1)
buff2 = a.read_frames(buffsize)
assert_array_equal(buff, buff2)
a.close()
# Now, read some frames, go back, and compare buffers
# (check whence == 2 == SEEK_END)
a = Sndfile(ofilename, 'r')
buff = a.read_frames(nframes)
a.seek(-buffsize, 2)
buff2 = a.read_frames(buffsize)
assert_array_equal(buff[-buffsize:], buff2)
def test_rw(self):
"""Test read/write pointers for seek."""
ofilename = join(TEST_DATA_DIR, 'test.wav')
|
[
" rfd, fd, cfilename = open_tmp_file('rwseektest.wav')"
] | 844
|
lcc
|
python
| null |
04429037d9380b6e9c3f7b2070992a5af10745895025113c
| 2
|
Your task is code completion.
#! /usr/bin/env python
# Last Change: Sun Dec 14 07:00 PM 2008 J
"""Test for the sndfile class."""
from os.path import join, dirname
import os
import sys
from numpy.testing import TestCase, assert_array_equal, dec
import numpy as np
from audiolab import Sndfile, Format, available_encodings, available_file_formats
from testcommon import open_tmp_file, close_tmp_file, TEST_DATA_DIR
_DTYPE_TO_ENC = {np.float64 : 'float64', np.float32: 'float32',
np.int32: 'pcm32', np.int16: 'pcm16'}
# XXX: there is a lot to refactor here
class TestSndfile(TestCase):
def test_basic_io(self):
""" Check open, close and basic read/write"""
# dirty !
ofilename = join(TEST_DATA_DIR, 'test.wav')
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
nbuff = 22050
# Open the test file for reading
a = Sndfile(ofilename, 'r')
nframes = a.nframes
# Open the copy file for writing
format = Format('wav', 'pcm16')
b = Sndfile(fd, 'w', format, a.channels, a.samplerate)
# Copy the data
for i in range(nframes / nbuff):
tmpa = a.read_frames(nbuff)
assert tmpa.dtype == np.float
b.write_frames(tmpa)
nrem = nframes % nbuff
tmpa = a.read_frames(nrem)
assert tmpa.dtype == np.float
b.write_frames(tmpa)
a.close()
b.close()
finally:
close_tmp_file(rfd, cfilename)
@dec.skipif(sys.platform=='win32',
"Not testing opening by fd because does not work on win32")
def test_basic_io_fd(self):
""" Check open from fd works"""
ofilename = join(TEST_DATA_DIR, 'test.wav')
fd = os.open(ofilename, os.O_RDONLY)
hdl = Sndfile(fd, 'r')
hdl.close()
def test_raw(self):
rawname = join(TEST_DATA_DIR, 'test.raw')
format = Format('raw', 'pcm16', 'little')
a = Sndfile(rawname, 'r', format, 1, 11025)
assert a.nframes == 11290
a.close()
def test_float64(self):
"""Check float64 write/read works"""
self._test_read_write(np.float64)
def test_float32(self):
"""Check float32 write/read works"""
self._test_read_write(np.float32)
def test_int32(self):
"""Check 32 bits pcm write/read works"""
self._test_read_write(np.int32)
def test_int16(self):
"""Check 16 bits pcm write/read works"""
self._test_read_write(np.int16)
def _test_read_write(self, dtype):
# dirty !
ofilename = join(TEST_DATA_DIR, 'test.wav')
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
nbuff = 22050
# Open the test file for reading
a = Sndfile(ofilename, 'r')
nframes = a.nframes
# Open the copy file for writing
format = Format('wav', _DTYPE_TO_ENC[dtype])
b = Sndfile(fd, 'w', format, a.channels, a.samplerate)
# Copy the data in the wav file
for i in range(nframes / nbuff):
tmpa = a.read_frames(nbuff, dtype=dtype)
assert tmpa.dtype == dtype
b.write_frames(tmpa)
nrem = nframes % nbuff
tmpa = a.read_frames(nrem)
b.write_frames(tmpa)
a.close()
b.close()
# Now, reopen both files in for reading, and check data are
# the same
a = Sndfile(ofilename, 'r')
b = Sndfile(cfilename, 'r')
for i in range(nframes / nbuff):
tmpa = a.read_frames(nbuff, dtype=dtype)
tmpb = b.read_frames(nbuff, dtype=dtype)
assert_array_equal(tmpa, tmpb)
a.close()
b.close()
finally:
close_tmp_file(rfd, cfilename)
#def test_supported_features(self):
# for i in available_file_formats():
# print "Available encodings for format %s are : " % i
# for j in available_encodings(i):
# print '\t%s' % j
def test_short_io(self):
self._test_int_io(np.short)
def test_int32_io(self):
self._test_int_io(np.int32)
def _test_int_io(self, dt):
# TODO: check if neg or pos value is the highest in abs
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
# Use almost full possible range possible for the given data-type
nb = 2 ** (8 * np.dtype(dt).itemsize - 3)
fs = 22050
nbuff = fs
a = np.random.random_integers(-nb, nb, nbuff)
a = a.astype(dt)
# Open the file for writing
format = Format('wav', _DTYPE_TO_ENC[dt])
b = Sndfile(fd, 'w', format, 1, fs)
b.write_frames(a)
b.close()
b = Sndfile(cfilename, 'r')
read_a = b.read_frames(nbuff, dtype=dt)
b.close()
assert_array_equal(a, read_a)
finally:
close_tmp_file(rfd, cfilename)
def test_mismatch(self):
"""Check for bad arguments."""
# This test open a file for writing, but with bad args (channels and
# nframes inverted)
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
# Open the file for writing
format = Format('wav', 'pcm16')
try:
b = Sndfile(fd, 'w', format, channels=22000, samplerate=1)
raise AssertionError("Try to open a file with more than 256 "\
"channels, this should not succeed !")
except ValueError, e:
pass
finally:
close_tmp_file(rfd, cfilename)
def test_bigframes(self):
""" Try to seek really far."""
rawname = join(TEST_DATA_DIR, 'test.wav')
a = Sndfile(rawname, 'r')
try:
try:
a.seek(2 ** 60)
raise Exception, \
"Seek really succeded ! This should not happen"
except IOError, e:
pass
finally:
a.close()
def test_float_frames(self):
""" Check nframes can be a float"""
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
# Open the file for writing
format = Format('wav', 'pcm16')
a = Sndfile(fd, 'rw', format, channels=1, samplerate=22050)
tmp = np.random.random_integers(-100, 100, 1000)
tmp = tmp.astype(np.short)
a.write_frames(tmp)
a.seek(0)
a.sync()
ctmp = a.read_frames(1e2, dtype=np.short)
a.close()
finally:
close_tmp_file(rfd, cfilename)
def test_nofile(self):
""" Check the failure when opening a non existing file."""
try:
f = Sndfile("floupi.wav", "r")
raise AssertionError("call to non existing file should not succeed")
except IOError:
pass
except Exception, e:
raise AssertionError("opening non existing file should raise" \
" a IOError exception, got %s instead" %
e.__class__)
class TestSeek(TestCase):
def test_simple(self):
ofilename = join(TEST_DATA_DIR, 'test.wav')
# Open the test file for reading
a = Sndfile(ofilename, 'r')
nframes = a.nframes
buffsize = 1024
buffsize = min(nframes, buffsize)
# First, read some frames, go back, and compare buffers
buff = a.read_frames(buffsize)
a.seek(0)
buff2 = a.read_frames(buffsize)
assert_array_equal(buff, buff2)
a.close()
# Now, read some frames, go back, and compare buffers
# (check whence == 1 == SEEK_CUR)
a = Sndfile(ofilename, 'r')
a.read_frames(buffsize)
buff = a.read_frames(buffsize)
a.seek(-buffsize, 1)
buff2 = a.read_frames(buffsize)
assert_array_equal(buff, buff2)
a.close()
# Now, read some frames, go back, and compare buffers
# (check whence == 2 == SEEK_END)
a = Sndfile(ofilename, 'r')
buff = a.read_frames(nframes)
a.seek(-buffsize, 2)
buff2 = a.read_frames(buffsize)
assert_array_equal(buff[-buffsize:], buff2)
def test_rw(self):
"""Test read/write pointers for seek."""
ofilename = join(TEST_DATA_DIR, 'test.wav')
|
Before solving the code completion task, imagine you are a student memorizing this material according to the task that you will have to perform. Ensure you preserve all critical details to solve the task and create a cheat sheet covering the entire context. Once you have done that, I will prompt you to solve the code completion task.
Since your task is code completion, write a cheat sheet that is tailored to help you write the correct next line(s) of code. Highlight or list the specific lines or variables in the context that are most relevant for this task.
For example:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class Example {
private int count;
public void increment() {
count++;
}
public int getCount() {
Cheatsheet (for next line):
- We are in getCount(), which should return the current value of count.
- count is a private integer field.
- Convention: Getter methods return the corresponding field.
- [Relevant lines: declaration of count, method header]
Next line will likely be: return count;
|
Next line of code:
|
lcc
| 84
|
Cheat sheet for the given code completion task:
Context:
[Previous code... ~10,000 lines omitted for brevity]
def test_float_frames(self):
""" Check nframes can be a float"""
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
# Open the file for writing
format = Format('wav', 'pcm16')
a = Sndfile(fd, 'rw', format, channels=1, samplerate=22050)
tmp = np.random.random_integers(-100, 100, 1000)
tmp = tmp.astype(np.short)
a.write_frames(tmp)
a.seek(0)
a.sync()
ctmp = a.read_frames(1e2, dtype=np.short)
a.close()
finally:
close_tmp_file(rfd, cfilename)
Cheatsheet (for next line):
- We are in the finally block of the test_float_frames method.
- The task is to close the file descriptor rfd.
- The close_tmp_file function takes two arguments: the file descriptor and the file name.
- [Relevant lines: open_tmp_file call, close_tmp_file call]
Next line will likely be: close_tmp_file(rfd, cfilename)
|
|
Please complete the code given below.
#!/usr/bin/env python
from apps.webdriver_testing.pages.site_pages import UnisubsPage
from urlparse import urlsplit
class VideoPage(UnisubsPage):
"""
Video Page contains the common elements in the video page.
"""
_URL = "videos/%s/info/" # %s is the unique onsite video id
_VIDEO_TITLE = ".main-title a"
_SPEAKER_NAME = "div.content div div > h4"
_LOCATION = "div.content div div h4:nth-child(2)"
_DESCRIPTION = "div#description"
_EMBEDDED_VIDEO = "div.unisubs-widget div.unisubs-videoTab-container"
_SUBTITLE_MENU = "a.unisubs-subtitleMeLink span.unisubs-tabTextchoose"
_LIKE_FACEBOOK = "li.unisubs-facebook-like button"
_POST_FACEBOOK = "a.facebook"
_POST_TWITTER = "a.twittter"
_EMAIL_FRIENDS = "a.email"
_FOLLOW = "button.follow-button"
#FOLLOW CONFIRMATION
_UNFOLLOW_ALL = 'input#unfollow-all-languages-button'
_SUBTITLES_OK = 'input#popup_ok'
_EMBED_HELP = "div.unisubs-share h3 a.embed_options_link"
_EMBED_CODE = ("div#embed-modal.modal div.modal-body form fieldset "
"textarea")
#TOP TABS
_URLS_TAB = 'href="?tab=urls"]'
_VIDEO_TAB = 'a[href="?tab=video"]'
_COMMENTS_TAB = 'a[href="?tab=comments"]'
_ACTIVITY_TAB = 'a[href="?tab=activity"]'
_ADD_SUBTITLES = "a.add_subtitles"
#VIDEO SIDE SECTION
_INFO = "ul#video-menu.left_nav li:nth-child(1) > a"
_ADD_TRANSLATION = "li.contribute a#add_translation"
_UPLOAD_SUBTITLES = "a#upload-subtitles-link"
#SUBTITLES_SIDE_SECTION
_SUB_LANGUAGES = "ul#subtitles-menu li"
_STATUS_TAGS = "span.tags"
#TEAM_SIDE_SECTION
_ADD_TO_TEAM_PULLDOWN = ("ul#moderation-menu.left_nav li div.sort_button "
"div.arrow")
_TEAM_LINK = ("ul#moderation-menu.left_nav li div.sort_button ul li "
"a[href*='%s']")
#ADMIN_SIDE_SECTION
_DEBUG_INFO = ""
_EDIT = ""
#UPLOAD SUBTITLES DIALOG
_SELECT_LANGUAGE = 'select#id_language_code'
_TRANSLATE_FROM = 'select#id_from_language_code'
_PRIMARY_AUDIO = 'select#id_primary_audio_language_code'
_SUBTITLES_FILE = 'input#subtitles-file-field'
_IS_COMPLETE = 'input#updload-subtitles-form-is_complete' #checked default
_UPLOAD_SUBMIT = 'form#upload-subtitles-form button.green_button'
_FEEDBACK_MESSAGE = 'p.feedback-message'
_CLOSE = 'div#upload_subs-div a.close'
UPLOAD_SUCCESS_TEXT = ('Thank you for uploading. It may take a minute or '
'so for your subtitles to appear.')
#TAB FIELDS
_COMMENTS_BOX = 'textarea#id_comment_form_content'
_ACTIVITY_LIST = 'ul.activity li p'
def open_video_page(self, video_id):
self.open_page(self._URL % video_id)
def open_video_activity(self, video_id):
self.open_video_page(video_id)
self.click_by_css(self._ACTIVITY_TAB)
def video_title(self):
return self.get_text_by_css(self._VIDEO_TITLE)
def add_translation(self):
self.click_by_css(self._ADD_TRANSLATION)
def upload_subtitles(self,
sub_lang,
sub_file,
audio_lang = None,
translated_from = None,
is_complete = True):
#Open the dialog
self.wait_for_element_visible(self._UPLOAD_SUBTITLES)
self.click_by_css(self._UPLOAD_SUBTITLES)
#Choose the language
self.wait_for_element_visible(self._SELECT_LANGUAGE)
self.select_option_by_text(self._SELECT_LANGUAGE, sub_lang)
#Set the audio language
if audio_lang:
self.select_option_by_text(self._PRIMARY_AUDIO, audio_lang)
#Set the translation_from field
if translated_from:
self.select_option_by_text(self._TRANSLATE_FROM, translated_from)
#Input the subtitle file
self.type_by_css(self._SUBTITLES_FILE, sub_file)
#Set complete
if not is_complete:
self.click_by_css(self._IS_COMPLETE)
#Start the upload
self.wait_for_element_present(self._UPLOAD_SUBMIT)
self.click_by_css(self._UPLOAD_SUBMIT)
#Get the the response message
self.wait_for_element_present(self._FEEDBACK_MESSAGE, wait_time=20)
message_text = self.get_text_by_css(self._FEEDBACK_MESSAGE)
#Close the dialog
self.click_by_css(self._CLOSE)
self.wait_for_element_not_visible(self._CLOSE)
return message_text
def open_info_page(self):
self.click_by_css(self._INFO)
def add_video_to_team(self, team_name):
self.click_by_css(self._ADD_TO_TEAM_PULLDOWN)
self.click_by_css(self._TEAM_LINK % team_name)
def video_id(self):
page_url = self.browser.current_url
url_parts = urlsplit(page_url).path
urlfrag = url_parts.split('/')[3]
return urlfrag
def description_text(self):
return self.get_text_by_css(self._DESCRIPTION)
def speaker_name(self):
return self.get_text_by_css(self._SPEAKER_NAME)
def location(self):
return self.get_text_by_css(self._LOCATION)
def video_embed_present(self):
if self.is_element_present(self._EMBEDDED_VIDEO):
return True
def add_subtitles(self):
self.click_by_css(self._ADD_SUBTITLES)
def team_slug(self, slug):
"""Return true if the team stub is linked on the video page.
"""
team_link = "a[href*='/teams/%s/']" % slug
if self.is_element_present(team_link):
return True
def feature_video(self):
self.click_link_text('Feature video')
def unfeature_video(self):
self.click_link_text('Unfeature video')
def displays_subtitle_me(self):
return self.is_element_visible(self._SUBTITLE_MENU)
def click_subtitle_me(self):
self.click_by_css(self._SUBTITLE_MENU)
def displays_add_subtitles(self):
return self.is_element_visible(self._ADD_SUBTITLES)
def displays_add_translation(self):
return self.is_element_visible(self._ADD_TRANSLATION)
def displays_upload_subtitles(self):
return self.is_element_visible(self._UPLOAD_SUBTITLES)
def follow_text(self):
return self.get_text_by_css(self._FOLLOW)
def toggle_follow(self, lang=False):
self.click_by_css(self._FOLLOW)
if lang:
self.click_by_css(self._SUBTITLES_OK)
else:
self.click_by_css(self._UNFOLLOW_ALL)
def subtitle_languages(self):
langs = []
els = self.get_elements_list(self._SUB_LANGUAGES + " a")
for el in els:
langs.append(el.text)
return langs
def language_status(self, language):
els = self.get_elements_list(self._SUB_LANGUAGES)
for el in els:
e = el.find_element_by_css_selector("a")
self.logger.info(e.text)
|
[
" if e.text == language:"
] | 462
|
lcc
|
python
| null |
9bc1f81e1a4c4b44da11ffc093a0c9fecbe5f99e4eff3aa5
| 3
|
Your task is code completion.
#!/usr/bin/env python
from apps.webdriver_testing.pages.site_pages import UnisubsPage
from urlparse import urlsplit
class VideoPage(UnisubsPage):
"""
Video Page contains the common elements in the video page.
"""
_URL = "videos/%s/info/" # %s is the unique onsite video id
_VIDEO_TITLE = ".main-title a"
_SPEAKER_NAME = "div.content div div > h4"
_LOCATION = "div.content div div h4:nth-child(2)"
_DESCRIPTION = "div#description"
_EMBEDDED_VIDEO = "div.unisubs-widget div.unisubs-videoTab-container"
_SUBTITLE_MENU = "a.unisubs-subtitleMeLink span.unisubs-tabTextchoose"
_LIKE_FACEBOOK = "li.unisubs-facebook-like button"
_POST_FACEBOOK = "a.facebook"
_POST_TWITTER = "a.twittter"
_EMAIL_FRIENDS = "a.email"
_FOLLOW = "button.follow-button"
#FOLLOW CONFIRMATION
_UNFOLLOW_ALL = 'input#unfollow-all-languages-button'
_SUBTITLES_OK = 'input#popup_ok'
_EMBED_HELP = "div.unisubs-share h3 a.embed_options_link"
_EMBED_CODE = ("div#embed-modal.modal div.modal-body form fieldset "
"textarea")
#TOP TABS
_URLS_TAB = 'href="?tab=urls"]'
_VIDEO_TAB = 'a[href="?tab=video"]'
_COMMENTS_TAB = 'a[href="?tab=comments"]'
_ACTIVITY_TAB = 'a[href="?tab=activity"]'
_ADD_SUBTITLES = "a.add_subtitles"
#VIDEO SIDE SECTION
_INFO = "ul#video-menu.left_nav li:nth-child(1) > a"
_ADD_TRANSLATION = "li.contribute a#add_translation"
_UPLOAD_SUBTITLES = "a#upload-subtitles-link"
#SUBTITLES_SIDE_SECTION
_SUB_LANGUAGES = "ul#subtitles-menu li"
_STATUS_TAGS = "span.tags"
#TEAM_SIDE_SECTION
_ADD_TO_TEAM_PULLDOWN = ("ul#moderation-menu.left_nav li div.sort_button "
"div.arrow")
_TEAM_LINK = ("ul#moderation-menu.left_nav li div.sort_button ul li "
"a[href*='%s']")
#ADMIN_SIDE_SECTION
_DEBUG_INFO = ""
_EDIT = ""
#UPLOAD SUBTITLES DIALOG
_SELECT_LANGUAGE = 'select#id_language_code'
_TRANSLATE_FROM = 'select#id_from_language_code'
_PRIMARY_AUDIO = 'select#id_primary_audio_language_code'
_SUBTITLES_FILE = 'input#subtitles-file-field'
_IS_COMPLETE = 'input#updload-subtitles-form-is_complete' #checked default
_UPLOAD_SUBMIT = 'form#upload-subtitles-form button.green_button'
_FEEDBACK_MESSAGE = 'p.feedback-message'
_CLOSE = 'div#upload_subs-div a.close'
UPLOAD_SUCCESS_TEXT = ('Thank you for uploading. It may take a minute or '
'so for your subtitles to appear.')
#TAB FIELDS
_COMMENTS_BOX = 'textarea#id_comment_form_content'
_ACTIVITY_LIST = 'ul.activity li p'
def open_video_page(self, video_id):
self.open_page(self._URL % video_id)
def open_video_activity(self, video_id):
self.open_video_page(video_id)
self.click_by_css(self._ACTIVITY_TAB)
def video_title(self):
return self.get_text_by_css(self._VIDEO_TITLE)
def add_translation(self):
self.click_by_css(self._ADD_TRANSLATION)
def upload_subtitles(self,
sub_lang,
sub_file,
audio_lang = None,
translated_from = None,
is_complete = True):
#Open the dialog
self.wait_for_element_visible(self._UPLOAD_SUBTITLES)
self.click_by_css(self._UPLOAD_SUBTITLES)
#Choose the language
self.wait_for_element_visible(self._SELECT_LANGUAGE)
self.select_option_by_text(self._SELECT_LANGUAGE, sub_lang)
#Set the audio language
if audio_lang:
self.select_option_by_text(self._PRIMARY_AUDIO, audio_lang)
#Set the translation_from field
if translated_from:
self.select_option_by_text(self._TRANSLATE_FROM, translated_from)
#Input the subtitle file
self.type_by_css(self._SUBTITLES_FILE, sub_file)
#Set complete
if not is_complete:
self.click_by_css(self._IS_COMPLETE)
#Start the upload
self.wait_for_element_present(self._UPLOAD_SUBMIT)
self.click_by_css(self._UPLOAD_SUBMIT)
#Get the the response message
self.wait_for_element_present(self._FEEDBACK_MESSAGE, wait_time=20)
message_text = self.get_text_by_css(self._FEEDBACK_MESSAGE)
#Close the dialog
self.click_by_css(self._CLOSE)
self.wait_for_element_not_visible(self._CLOSE)
return message_text
def open_info_page(self):
self.click_by_css(self._INFO)
def add_video_to_team(self, team_name):
self.click_by_css(self._ADD_TO_TEAM_PULLDOWN)
self.click_by_css(self._TEAM_LINK % team_name)
def video_id(self):
page_url = self.browser.current_url
url_parts = urlsplit(page_url).path
urlfrag = url_parts.split('/')[3]
return urlfrag
def description_text(self):
return self.get_text_by_css(self._DESCRIPTION)
def speaker_name(self):
return self.get_text_by_css(self._SPEAKER_NAME)
def location(self):
return self.get_text_by_css(self._LOCATION)
def video_embed_present(self):
if self.is_element_present(self._EMBEDDED_VIDEO):
return True
def add_subtitles(self):
self.click_by_css(self._ADD_SUBTITLES)
def team_slug(self, slug):
"""Return true if the team stub is linked on the video page.
"""
team_link = "a[href*='/teams/%s/']" % slug
if self.is_element_present(team_link):
return True
def feature_video(self):
self.click_link_text('Feature video')
def unfeature_video(self):
self.click_link_text('Unfeature video')
def displays_subtitle_me(self):
return self.is_element_visible(self._SUBTITLE_MENU)
def click_subtitle_me(self):
self.click_by_css(self._SUBTITLE_MENU)
def displays_add_subtitles(self):
return self.is_element_visible(self._ADD_SUBTITLES)
def displays_add_translation(self):
return self.is_element_visible(self._ADD_TRANSLATION)
def displays_upload_subtitles(self):
return self.is_element_visible(self._UPLOAD_SUBTITLES)
def follow_text(self):
return self.get_text_by_css(self._FOLLOW)
def toggle_follow(self, lang=False):
self.click_by_css(self._FOLLOW)
if lang:
self.click_by_css(self._SUBTITLES_OK)
else:
self.click_by_css(self._UNFOLLOW_ALL)
def subtitle_languages(self):
langs = []
els = self.get_elements_list(self._SUB_LANGUAGES + " a")
for el in els:
langs.append(el.text)
return langs
def language_status(self, language):
els = self.get_elements_list(self._SUB_LANGUAGES)
for el in els:
e = el.find_element_by_css_selector("a")
self.logger.info(e.text)
|
Before solving the code completion task, imagine you are a student memorizing this material according to the task that you will have to perform. Ensure you preserve all critical details to solve the task and create a cheat sheet covering the entire context. Once you have done that, I will prompt you to solve the code completion task.
Since your task is code completion, write a cheat sheet that is tailored to help you write the correct next line(s) of code. Highlight or list the specific lines or variables in the context that are most relevant for this task.
For example:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class Example {
private int count;
public void increment() {
count++;
}
public int getCount() {
Cheatsheet (for next line):
- We are in getCount(), which should return the current value of count.
- count is a private integer field.
- Convention: Getter methods return the corresponding field.
- [Relevant lines: declaration of count, method header]
Next line will likely be: return count;
|
Next line of code:
|
lcc
| 84
|
Cheat sheet for the given code:
Context:
[Previous code... ~10,000 lines omitted for brevity]
class VideoPage(UnisubsPage):
# ... (many lines of code)
def __init__(self):
# ... (many lines of code)
def upload_subtitles(self,
sub_lang,
sub_file,
audio_lang = None,
translated_from = None,
is_complete = True):
# ... (many lines of code)
def open_video_page(self, video_id):
self.open_page(self._URL % video_id)
def open_video_activity(self, video_id):
self.open_video_page(video_id)
self.click_by_css(self._ACTIVITY_TAB)
def video_title(self):
return self.get_text_by_css(self._VIDEO_TITLE)
def add_translation(self):
self.click_by_css(self._ADD_TRANSLATION)
def upload_subtitles(self,
sub_lang,
sub_file,
audio_lang = None,
translated_from = None,
is_complete = True):
# ... (many lines of code)
def open_info_page(self):
self.click_by_css(self._INFO)
def add_video_to_team(self, team_name):
self.click_by_css(self._ADD_TO_TEAM_PULLDOWN)
self.click_by_css(self._TEAM_LINK % team_name)
def video_id(self):
page_url = self.browser.current_url
url_parts = urlsplit(page_url).path
urlfrag = url_parts.split('/')[3]
return urlfrag
def description_text(self):
return self.get_text_by_css(self._DESCRIPTION)
def speaker_name(self):
return self.get_text_by_css(self._SPEAKER_NAME)
def location(self):
return self.get_text_by_css(self._LOCATION)
def video_embed_present(self):
if self.is_element_present(self._EMBEDDED_VIDEO):
return True
def add_subtitles(self):
self.click_by_css(self._ADD_SUBTITLES)
def team_slug(self, slug):
"""Return true if the team stub is linked on the video page.
"""
team_link = "a[href*='/teams/%s/']" % slug
if self.is_element_present(team_link):
return True
def feature_video(self):
self.click_link_text('Feature video')
def unfeature_video(self):
self.click_link_text('Unfeature video')
def displays_subtitle_me(self):
return self.is_element_visible(self._SUBTITLE_MENU)
def click_subtitle_me(self):
self.click_by_css(self._SUBTITLE_MENU)
def displays_add_subtitles(self):
return self.is_element_visible(self._ADD_SUBTITLES)
def displays_add_translation(self):
return self.is_element_visible(self._ADD_TRANSLATION)
def displays_upload_subtitles(self):
return self.is_element_visible(self._UPLOAD_SUBTITLES)
def follow_text(self):
return self.get_text_by_css(self._FOLLOW)
def toggle_follow(self, lang=False):
self.click_by_css(self._FOLLOW)
if lang:
self.click_by_css(self._SUBTITLES_OK)
else:
self.click_by_css(self._UNFOLLOW_ALL)
def subtitle_languages(self):
langs = []
els = self.get_elements_list(self._SUB_LANGUAGES + " a")
for el in els:
langs.append(el.text)
return langs
def language_status(self, language):
els = self.get_elements_list(self._SUB_LANGUAGES)
for el in els:
e = el.find_element_by_css_selector("a")
self.logger.info(e.text)
Cheatsheet (for next line):
- We are in a method that seems to be related to video information.
- The method is likely to return a specific piece of information about the video.
- The method name is `video_id`, which suggests it returns the ID of the video.
- The method uses `urlsplit` to parse the current URL and extract the video ID.
- The method is part of the `VideoPage` class, which suggests it's related to video pages.
- Relevant lines: `video_id(self)`, `page_url = self.browser.current_url`, `url_parts = urlsplit(page_url).path`, `urlfrag = url_parts.split('/')[3]`
Next line will likely be: `return urlfrag;`
|
|
Please complete the code given below.
/*
* $Header: it.geosolutions.geobatch.wmc.WMCStream,v. 0.1 03/dic/2009 01:55:21 created by Fabiani $
* $Revision: 0.1 $
* $Date: 03/dic/2009 01:55:21 $
*
* ====================================================================
*
* Copyright (C) 2007-2008 GeoSolutions S.A.S.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.
*
* ====================================================================
*
* This software consists of voluntary contributions made by developers
* of GeoSolutions. For more information on GeoSolutions, please see
* <http://www.geo-solutions.it/>.
*
*/
package it.geosolutions.geobatch.wmc;
import it.geosolutions.geobatch.wmc.model.GeneralWMCConfiguration;
import it.geosolutions.geobatch.wmc.model.OLBaseClass;
import it.geosolutions.geobatch.wmc.model.OLDimension;
import it.geosolutions.geobatch.wmc.model.OLExtent;
import it.geosolutions.geobatch.wmc.model.OLStyleColorRamps;
import it.geosolutions.geobatch.wmc.model.OLStyleValue;
import it.geosolutions.geobatch.wmc.model.ViewContext;
import it.geosolutions.geobatch.wmc.model.WMCBoundingBox;
import it.geosolutions.geobatch.wmc.model.WMCExtension;
import it.geosolutions.geobatch.wmc.model.WMCFormat;
import it.geosolutions.geobatch.wmc.model.WMCLayer;
import it.geosolutions.geobatch.wmc.model.WMCOnlineResource;
import it.geosolutions.geobatch.wmc.model.WMCSLD;
import it.geosolutions.geobatch.wmc.model.WMCServer;
import it.geosolutions.geobatch.wmc.model.WMCStyle;
import it.geosolutions.geobatch.wmc.model.WMCWindow;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* @author Fabiani
*
*/
public class WMCStream {
private XStream xstream = new XStream(new DomDriver("UTF-8"));
/**
*
*/
public WMCStream() {
// WMC ViewContext
xstream.alias("ViewContext", ViewContext.class);
xstream.useAttributeFor(ViewContext.class, "xmlns");
xstream.useAttributeFor(ViewContext.class, "xlink");
xstream.useAttributeFor(ViewContext.class, "id");
xstream.useAttributeFor(ViewContext.class, "version");
xstream.aliasField("xmlns:xlink", ViewContext.class, "xlink");
xstream.aliasField("General", ViewContext.class, "general");
xstream.aliasField("LayerList", ViewContext.class, "layerList");
// WMC ViewContext::General
xstream.aliasField("Window", GeneralWMCConfiguration.class, "window");
xstream.aliasField("Title", GeneralWMCConfiguration.class, "title");
xstream.aliasField("Abstract", GeneralWMCConfiguration.class, "_abstract");
// WMC ViewContext::General::Window
xstream.useAttributeFor(WMCWindow.class, "height");
xstream.useAttributeFor(WMCWindow.class, "width");
xstream.aliasField("BoundingBox", WMCWindow.class, "bbox");
// WMC ViewContext::General::Window::BoundingBox
xstream.useAttributeFor(WMCBoundingBox.class, "srs");
xstream.useAttributeFor(WMCBoundingBox.class, "maxx");
xstream.useAttributeFor(WMCBoundingBox.class, "maxy");
xstream.useAttributeFor(WMCBoundingBox.class, "minx");
xstream.useAttributeFor(WMCBoundingBox.class, "miny");
xstream.aliasField("SRS", WMCBoundingBox.class, "srs");
// WMC ViewContext::LayerList::Layer
xstream.alias("Layer", WMCLayer.class);
xstream.useAttributeFor(WMCLayer.class, "queryable");
xstream.useAttributeFor(WMCLayer.class, "hidden");
xstream.aliasField("SRS", WMCLayer.class, "srs");
xstream.aliasField("Name", WMCLayer.class, "name");
xstream.aliasField("Title", WMCLayer.class, "title");
xstream.aliasField("Server", WMCLayer.class, "server");
xstream.aliasField("FormatList", WMCLayer.class, "formatList");
xstream.aliasField("StyleList", WMCLayer.class, "styleList");
xstream.aliasField("Extension", WMCLayer.class, "extension");
// WMC ViewContext::LayerList::Layer::Server
xstream.useAttributeFor(WMCServer.class, "service");
xstream.useAttributeFor(WMCServer.class, "version");
xstream.useAttributeFor(WMCServer.class, "title");
xstream.aliasField("OnlineResource", WMCServer.class, "onlineResource");
// WMC ViewContext::LayerList::Layer::Server::OnlineResource
xstream.useAttributeFor(WMCOnlineResource.class, "xlink_type");
xstream.useAttributeFor(WMCOnlineResource.class, "xlink_href");
xstream.aliasField("xlink:type", WMCOnlineResource.class, "xlink_type");
xstream.aliasField("xlink:href", WMCOnlineResource.class, "xlink_href");
// WMC ViewContext::LayerList::Layer::FormatList::Format
xstream.alias("Format", WMCFormat.class);
xstream.registerConverter(new Converter() {
public boolean canConvert(Class clazz) {
return WMCFormat.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
WMCFormat format = (WMCFormat) value;
writer.addAttribute("current", format.getCurrent());
if (format.getContent() != null)
writer.setValue(format.getContent());
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
WMCFormat format = new WMCFormat("1", reader.getValue());
return format;
}
});
// WMC ViewContext::LayerList::Layer::FormatList::Style
xstream.alias("Style", WMCStyle.class);
xstream.useAttributeFor(WMCStyle.class, "current");
xstream.aliasField("SLD", WMCStyle.class, "sld");
xstream.aliasField("OnlineResource", WMCSLD.class, "onlineResource");
// WMC ViewContext::LayerList::Layer::Extension
xstream.alias("Extension", WMCExtension.class);
// WMC ViewContext::LayerList::Layer::Extension::OL
xstream.aliasField("ol:id", WMCExtension.class, "id");
xstream.aliasField("ol:transparent", WMCExtension.class, "transparent");
xstream.aliasField("ol:isBaseLayer", WMCExtension.class, "isBaseLayer");
xstream.aliasField("ol:opacity", WMCExtension.class, "opacity");
xstream.aliasField("ol:displayInLayerSwitcher", WMCExtension.class, "displayInLayerSwitcher");
xstream.aliasField("ol:singleTile", WMCExtension.class, "singleTile");
xstream.aliasField("ol:numZoomLevels", WMCExtension.class, "numZoomLevels");
xstream.aliasField("ol:units", WMCExtension.class, "units");
xstream.aliasField("ol:maxExtent", WMCExtension.class, "maxExtent");
xstream.aliasField("ol:dimension", WMCExtension.class, "time");
xstream.aliasField("ol:dimension", WMCExtension.class, "elevation");
xstream.aliasField("ol:mainLayer", WMCExtension.class, "mainLayer");
xstream.aliasField("ol:styleClassNumber", WMCExtension.class, "styleClassNumber");
xstream.aliasField("ol:styleColorRamps", WMCExtension.class, "styleColorRamps");
xstream.aliasField("ol:styleMaxValue", WMCExtension.class, "styleMaxValue");
xstream.aliasField("ol:styleMinValue", WMCExtension.class, "styleMinValue");
xstream.aliasField("ol:styleRestService", WMCExtension.class, "styleRestService");
xstream.aliasField("ol:styleLegendService", WMCExtension.class, "styleLegendService");
xstream.useAttributeFor(OLStyleColorRamps.class, "defaultRamp");
xstream.aliasField("default", OLStyleColorRamps.class, "defaultRamp");
xstream.registerConverter(new Converter() {
public boolean canConvert(Class clazz) {
return OLBaseClass.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
OLBaseClass ol = (OLBaseClass) value;
writer.addAttribute("xmlns:ol", ol.getXmlns_ol());
if (value instanceof OLExtent) {
OLExtent extent = (OLExtent) value;
writer.addAttribute("minx", extent.getMinx());
writer.addAttribute("miny", extent.getMiny());
writer.addAttribute("maxx", extent.getMaxx());
writer.addAttribute("maxy", extent.getMaxy());
}
if (value instanceof OLDimension) {
OLDimension dimension = (OLDimension) value;
writer.addAttribute("name", dimension.getName());
writer.addAttribute("default", dimension.getDefaultValue());
}
if (value instanceof OLStyleValue) {
|
[
"\t\t\t\t\tOLStyleValue styleValue = (OLStyleValue) value;"
] | 570
|
lcc
|
java
| null |
a5da7e173afd5ba71e0185228a1df77238c2949ba3ea2935
| 4
|
Your task is code completion.
/*
* $Header: it.geosolutions.geobatch.wmc.WMCStream,v. 0.1 03/dic/2009 01:55:21 created by Fabiani $
* $Revision: 0.1 $
* $Date: 03/dic/2009 01:55:21 $
*
* ====================================================================
*
* Copyright (C) 2007-2008 GeoSolutions S.A.S.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.
*
* ====================================================================
*
* This software consists of voluntary contributions made by developers
* of GeoSolutions. For more information on GeoSolutions, please see
* <http://www.geo-solutions.it/>.
*
*/
package it.geosolutions.geobatch.wmc;
import it.geosolutions.geobatch.wmc.model.GeneralWMCConfiguration;
import it.geosolutions.geobatch.wmc.model.OLBaseClass;
import it.geosolutions.geobatch.wmc.model.OLDimension;
import it.geosolutions.geobatch.wmc.model.OLExtent;
import it.geosolutions.geobatch.wmc.model.OLStyleColorRamps;
import it.geosolutions.geobatch.wmc.model.OLStyleValue;
import it.geosolutions.geobatch.wmc.model.ViewContext;
import it.geosolutions.geobatch.wmc.model.WMCBoundingBox;
import it.geosolutions.geobatch.wmc.model.WMCExtension;
import it.geosolutions.geobatch.wmc.model.WMCFormat;
import it.geosolutions.geobatch.wmc.model.WMCLayer;
import it.geosolutions.geobatch.wmc.model.WMCOnlineResource;
import it.geosolutions.geobatch.wmc.model.WMCSLD;
import it.geosolutions.geobatch.wmc.model.WMCServer;
import it.geosolutions.geobatch.wmc.model.WMCStyle;
import it.geosolutions.geobatch.wmc.model.WMCWindow;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* @author Fabiani
*
*/
public class WMCStream {
private XStream xstream = new XStream(new DomDriver("UTF-8"));
/**
*
*/
public WMCStream() {
// WMC ViewContext
xstream.alias("ViewContext", ViewContext.class);
xstream.useAttributeFor(ViewContext.class, "xmlns");
xstream.useAttributeFor(ViewContext.class, "xlink");
xstream.useAttributeFor(ViewContext.class, "id");
xstream.useAttributeFor(ViewContext.class, "version");
xstream.aliasField("xmlns:xlink", ViewContext.class, "xlink");
xstream.aliasField("General", ViewContext.class, "general");
xstream.aliasField("LayerList", ViewContext.class, "layerList");
// WMC ViewContext::General
xstream.aliasField("Window", GeneralWMCConfiguration.class, "window");
xstream.aliasField("Title", GeneralWMCConfiguration.class, "title");
xstream.aliasField("Abstract", GeneralWMCConfiguration.class, "_abstract");
// WMC ViewContext::General::Window
xstream.useAttributeFor(WMCWindow.class, "height");
xstream.useAttributeFor(WMCWindow.class, "width");
xstream.aliasField("BoundingBox", WMCWindow.class, "bbox");
// WMC ViewContext::General::Window::BoundingBox
xstream.useAttributeFor(WMCBoundingBox.class, "srs");
xstream.useAttributeFor(WMCBoundingBox.class, "maxx");
xstream.useAttributeFor(WMCBoundingBox.class, "maxy");
xstream.useAttributeFor(WMCBoundingBox.class, "minx");
xstream.useAttributeFor(WMCBoundingBox.class, "miny");
xstream.aliasField("SRS", WMCBoundingBox.class, "srs");
// WMC ViewContext::LayerList::Layer
xstream.alias("Layer", WMCLayer.class);
xstream.useAttributeFor(WMCLayer.class, "queryable");
xstream.useAttributeFor(WMCLayer.class, "hidden");
xstream.aliasField("SRS", WMCLayer.class, "srs");
xstream.aliasField("Name", WMCLayer.class, "name");
xstream.aliasField("Title", WMCLayer.class, "title");
xstream.aliasField("Server", WMCLayer.class, "server");
xstream.aliasField("FormatList", WMCLayer.class, "formatList");
xstream.aliasField("StyleList", WMCLayer.class, "styleList");
xstream.aliasField("Extension", WMCLayer.class, "extension");
// WMC ViewContext::LayerList::Layer::Server
xstream.useAttributeFor(WMCServer.class, "service");
xstream.useAttributeFor(WMCServer.class, "version");
xstream.useAttributeFor(WMCServer.class, "title");
xstream.aliasField("OnlineResource", WMCServer.class, "onlineResource");
// WMC ViewContext::LayerList::Layer::Server::OnlineResource
xstream.useAttributeFor(WMCOnlineResource.class, "xlink_type");
xstream.useAttributeFor(WMCOnlineResource.class, "xlink_href");
xstream.aliasField("xlink:type", WMCOnlineResource.class, "xlink_type");
xstream.aliasField("xlink:href", WMCOnlineResource.class, "xlink_href");
// WMC ViewContext::LayerList::Layer::FormatList::Format
xstream.alias("Format", WMCFormat.class);
xstream.registerConverter(new Converter() {
public boolean canConvert(Class clazz) {
return WMCFormat.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
WMCFormat format = (WMCFormat) value;
writer.addAttribute("current", format.getCurrent());
if (format.getContent() != null)
writer.setValue(format.getContent());
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
WMCFormat format = new WMCFormat("1", reader.getValue());
return format;
}
});
// WMC ViewContext::LayerList::Layer::FormatList::Style
xstream.alias("Style", WMCStyle.class);
xstream.useAttributeFor(WMCStyle.class, "current");
xstream.aliasField("SLD", WMCStyle.class, "sld");
xstream.aliasField("OnlineResource", WMCSLD.class, "onlineResource");
// WMC ViewContext::LayerList::Layer::Extension
xstream.alias("Extension", WMCExtension.class);
// WMC ViewContext::LayerList::Layer::Extension::OL
xstream.aliasField("ol:id", WMCExtension.class, "id");
xstream.aliasField("ol:transparent", WMCExtension.class, "transparent");
xstream.aliasField("ol:isBaseLayer", WMCExtension.class, "isBaseLayer");
xstream.aliasField("ol:opacity", WMCExtension.class, "opacity");
xstream.aliasField("ol:displayInLayerSwitcher", WMCExtension.class, "displayInLayerSwitcher");
xstream.aliasField("ol:singleTile", WMCExtension.class, "singleTile");
xstream.aliasField("ol:numZoomLevels", WMCExtension.class, "numZoomLevels");
xstream.aliasField("ol:units", WMCExtension.class, "units");
xstream.aliasField("ol:maxExtent", WMCExtension.class, "maxExtent");
xstream.aliasField("ol:dimension", WMCExtension.class, "time");
xstream.aliasField("ol:dimension", WMCExtension.class, "elevation");
xstream.aliasField("ol:mainLayer", WMCExtension.class, "mainLayer");
xstream.aliasField("ol:styleClassNumber", WMCExtension.class, "styleClassNumber");
xstream.aliasField("ol:styleColorRamps", WMCExtension.class, "styleColorRamps");
xstream.aliasField("ol:styleMaxValue", WMCExtension.class, "styleMaxValue");
xstream.aliasField("ol:styleMinValue", WMCExtension.class, "styleMinValue");
xstream.aliasField("ol:styleRestService", WMCExtension.class, "styleRestService");
xstream.aliasField("ol:styleLegendService", WMCExtension.class, "styleLegendService");
xstream.useAttributeFor(OLStyleColorRamps.class, "defaultRamp");
xstream.aliasField("default", OLStyleColorRamps.class, "defaultRamp");
xstream.registerConverter(new Converter() {
public boolean canConvert(Class clazz) {
return OLBaseClass.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
OLBaseClass ol = (OLBaseClass) value;
writer.addAttribute("xmlns:ol", ol.getXmlns_ol());
if (value instanceof OLExtent) {
OLExtent extent = (OLExtent) value;
writer.addAttribute("minx", extent.getMinx());
writer.addAttribute("miny", extent.getMiny());
writer.addAttribute("maxx", extent.getMaxx());
writer.addAttribute("maxy", extent.getMaxy());
}
if (value instanceof OLDimension) {
OLDimension dimension = (OLDimension) value;
writer.addAttribute("name", dimension.getName());
writer.addAttribute("default", dimension.getDefaultValue());
}
if (value instanceof OLStyleValue) {
|
Before solving the code completion task, imagine you are a student memorizing this material according to the task that you will have to perform. Ensure you preserve all critical details to solve the task and create a cheat sheet covering the entire context. Once you have done that, I will prompt you to solve the code completion task.
Since your task is code completion, write a cheat sheet that is tailored to help you write the correct next line(s) of code. Highlight or list the specific lines or variables in the context that are most relevant for this task.
For example:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class Example {
private int count;
public void increment() {
count++;
}
public int getCount() {
Cheatsheet (for next line):
- We are in getCount(), which should return the current value of count.
- count is a private integer field.
- Convention: Getter methods return the corresponding field.
- [Relevant lines: declaration of count, method header]
Next line will likely be: return count;
|
Next line of code:
|
lcc
| 84
|
Cheat sheet for the code completion task:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class WMCStream {
private XStream xstream = new XStream(new DomDriver("UTF-8"));
// ...
xstream.registerConverter(new Converter() {
public boolean canConvert(Class clazz) {
return OLBaseClass.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
OLBaseClass ol = (OLBaseClass) value;
// ...
if (value instanceof OLStyleValue) {
OLStyleValue styleValue = (OLStyleValue) value;
// ...
writer.addAttribute("default", styleValue.getDefault());
writer.addAttribute("value", styleValue.getValue());
writer.addAttribute("units", styleValue.getUnits());
writer.addAttribute("label", styleValue.getLabel());
writer.addAttribute("description", styleValue.getDescription());
// ...
}
// ...
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
OLBaseClass ol = new OLBaseClass();
// ...
return ol;
}
});
// ...
Cheatsheet (for next line):
- We are in the unmarshal method of the Converter class.
- The method is supposed to create an instance of OLBaseClass.
- The method is supposed to read the attributes from the HierarchicalStreamReader.
- The method is supposed to return the created OLBaseClass instance.
- Relevant lines: declaration of OLBaseClass, marshal method, unmarshal method.
Next line will likely be: OLBaseClass ol = new OLBaseClass();
|
|
"Please complete the code given below. \n#!/usr/bin/env python\nimport sys\n#begin dependent modules(...TRUNCATED)
|
[
" longest = max(self.answers)"
] | 1,229
|
lcc
|
python
| null |
3bd5a501fc0327fd7bcda8389c7d11b3a821c9b5ce5a93cc
| 5
| "Your task is code completion.\n#!/usr/bin/env python\nimport sys\n#begin dependent modules\n#sys.pa(...TRUNCATED)
| "Before solving the code completion task, imagine you are a student memorizing this material accordi(...TRUNCATED)
|
Next line of code:
|
lcc
| 84
| "Cheat sheet for the given code completion task:\n\nContext:\n[Previous code... ~10,000 lines omitte(...TRUNCATED)
|
|
"Please complete the code given below. \n/**************************************\n*Script Name: Staf(...TRUNCATED)
|
[
" mob.Target = new SR_NewRuneTarget(RuneAcc);"
] | 907
|
lcc
|
csharp
| null |
227b063979c62ee1de7436be168450b5a7712a7a637fa6d4
| 6
| "Your task is code completion.\n/**************************************\n*Script Name: Staff Runeboo(...TRUNCATED)
| "Before solving the code completion task, imagine you are a student memorizing this material accordi(...TRUNCATED)
|
Next line of code:
|
lcc
| 84
| "Cheat sheet for the given code completion task:\n\nContext:\n[Previous code... ~10,000 lines omitte(...TRUNCATED)
|
|
"Please complete the code given below. \n/*\n * Copyright (c) 1996, 2012, Oracle and/or its affiliat(...TRUNCATED)
|
[
" for (int i = 0; i < chain.length; i++)"
] | 1,820
|
lcc
|
java
| null |
f652398c3e8be338b4a7873ba6fecc5a686204d99a1a8d10
| 7
| "Your task is code completion.\n/*\n * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All r(...TRUNCATED)
| "Before solving the code completion task, imagine you are a student memorizing this material accordi(...TRUNCATED)
|
Next line of code:
|
lcc
| 84
| "Cheat sheet for the code completion task:\n\nContext:\n[Previous code... ~10,000 lines omitted for (...TRUNCATED)
|
|
"Please complete the code given below. \n/*\n * jPOS Project [http://jpos.org]\n * Copyright (C) 200(...TRUNCATED)
|
[
" sp = new JESpace(name, path);"
] | 1,096
|
lcc
|
java
| null |
01b11dc980d93775ce16fd5e630cf5619f66f281ee12947b
| 8
| "Your task is code completion.\n/*\n * jPOS Project [http://jpos.org]\n * Copyright (C) 2000-2015 Al(...TRUNCATED)
| "Before solving the code completion task, imagine you are a student memorizing this material accordi(...TRUNCATED)
|
Next line of code:
|
lcc
| 84
| "Cheat sheet for the given code:\n\nContext:\n[Previous code... ~10,000 lines omitted for brevity]\n(...TRUNCATED)
|
|
"Please complete the code given below. \n/*\n * Pixel Dungeon\n * Copyright (C) 2012-2015 Oleg Dolya(...TRUNCATED)
|
[
"\t\t\t\t\tpos = btnEnergizeAll.bottom();"
] | 567
|
lcc
|
java
| null |
64d5f26d486a85e85284229e8d254f996cfafd844cd321c5
| 9
| "Your task is code completion.\n/*\n * Pixel Dungeon\n * Copyright (C) 2012-2015 Oleg Dolya\n *\n * (...TRUNCATED)
| "Before solving the code completion task, imagine you are a student memorizing this material accordi(...TRUNCATED)
|
Next line of code:
|
lcc
| 84
| "Cheat sheet for the given code:\n\nContext:\n[Previous code... ~10,000 lines omitted for brevity]\n(...TRUNCATED)
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 12