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.
#!/usr/bin/env python
import sys
#begin dependent modules
#sys.path.insert(0, "../")
import yobot_interfaces
import yobotproto
from client_support import YCAccount, SimpleNotice
from gui import gui_util
from gui.gui_util import signal_connect, ConnectionWidget
#end
import triviadb
import PyQt4
from PyQt4.QtGui import (QComboBox, QMainWindow, QStandardItemModel, QStandardItem,
QIcon, QPixmap, QImage, QPainter, QDialog, QMessageBox,
QApplication, QFont, QTextEdit, QColorDialog, QPalette,
QListWidget, QListWidgetItem, QStyledItemDelegate,
QStyleOptionViewItem, QRegion, QWidget, QBrush, QStyle,
QPushButton, QStyleOption, QMenu, QAction, QCursor,
QLineEdit, QFileDialog, QErrorMessage,
QFontDialog, QColor, QDockWidget, QSizePolicy,
QStackedWidget,
QGridLayout, QLayout, QFrame,
)
from PyQt4.QtCore import (QPoint, QSize, QModelIndex, Qt, QObject, SIGNAL, QVariant,
QAbstractItemModel, QRect, QRectF, QPointF, QT_VERSION)
from debuglog import log_debug, log_info, log_err, log_crit, log_warn
import sqlite3.dbapi2 as sqlite3
import pickle
import lxml.html
import re
from time import time
from collections import defaultdict
import random
from gui.html_fmt import point_to_html
import os.path
import yobotops
from cgi import escape as html_escape
import datetime
import gui_new
#trivia types
TYPE_ANAGRAMS, TYPE_TRIVIA, TYPE_BOTH = range(1, 4)
TRIVIA_ROOT = "/home/mordy/src/purple/py/triviabot"
article_start_re = re.compile("^(the|a) ")
def get_categories_list(dbname):
dbconn = sqlite3.connect(dbname)
ret = []
for r in dbconn.cursor().execute("select distinct category from questions"):
ret.append(r[0])
return ret
def scramble_word(word):
return "".join(random.sample(word, len(word)))
class _BlackHole(str):
def __init__(self, *args, **kwargs):
pass
def __getattr__(self, name):
return _BlackHole()
def __setattr__(self, name, value):
pass
def __call__(self, *args, **kwargs):
pass
def __bool__(self):
return False
def __str__(self):
return ""
class TriviaGui(gui_new.TGui):
def __init__(self, parent=None):
gui_new.TGui.__init__(self, parent)
self.widgets = self
w = self.widgets
self.model = yobot_interfaces.component_registry.get_component("account-model")
self.client_ops = yobot_interfaces.component_registry.get_component("client-operations")
assert self.client_ops
def _handle_connect(username, password, improto, **proxy_params):
self.client_ops.connect(username, password, improto, **proxy_params)
def offset_pos_fn():
return QPoint(0, self.menubar.height())
self.connwidget = gui_util.OverlayConnectionWidget(offset_pos_fn, _handle_connect, self)
signal_connect(w.actionConnect, SIGNAL("toggled(bool)"), self.connwidget.setVisible)
signal_connect(self.connwidget.widgets.conn_close, SIGNAL("clicked()"),
lambda: w.actionConnect.setChecked(False))
if not self.model:
w.actionConnect.setChecked(True)
self.model = gui_util.AccountModel(None)
self.menubar.show()
else:
self.connwidget.hide()
#notification widgets:
qdw = QFrame(self)
if QT_VERSION >= 0x040600:
from PyQt4.QtGui import QGraphicsDropShadowEffect
self.notification_shadow = QGraphicsDropShadowEffect(qdw)
self.notification_shadow.setBlurRadius(10.0)
qdw.setGraphicsEffect(self.notification_shadow)
qdw.setFrameShadow(qdw.Raised)
qdw.setFrameShape(qdw.StyledPanel)
qdw.setAutoFillBackground(True)
qsw = QStackedWidget(qdw)
qdw.setLayout(QGridLayout())
qdw.layout().setSizeConstraint(QLayout.SetMinimumSize)
qdw.layout().addWidget(qsw)
self._notification_dlg = qdw
self.qdw = qdw
self.qsw = qsw
self.notifications = gui_util.NotificationBox(qdw, qsw, noTitleBar=False)
#self.qdw.show()
#resize/show events
def _force_bottom(event, superclass_fn):
log_err("")
superclass_fn(self.qdw, event)
self.qdw.move(0, self.height()-self.qdw.height())
self.qdw.resizeEvent = lambda e: _force_bottom(e, QWidget.resizeEvent)
self.qdw.showEvent = lambda e: _force_bottom(e, QWidget.showEvent)
#set up account menu
w.account.setModel(self.model)
for a in ("start", "stop", "pause", "next"):
gui_util.signal_connect(getattr(w, a), SIGNAL("clicked()"),
lambda cls=self, a=a: getattr(cls, a + "_requested")())
getattr(w, a).setEnabled(False)
w.start.setEnabled(True)
self.anagrams_prefix_blacklist = set()
self.anagrams_suffix_blacklist = set()
#listWidgetItems
def _add_nfix(typestr):
txt = getattr(w, typestr + "_input").text()
if not txt:
return
txt = str(txt)
st = getattr(self, "anagrams_" + typestr + "_blacklist")
target = getattr(w, typestr + "_list")
if not txt in st:
target.addItem(txt)
st.add(txt)
getattr(w, typestr + "_input").clear()
def _remove_nfix(typestr):
target = getattr(w, typestr + "_list")
st = getattr(self, "anagrams_" + typestr + "_blacklist")
item = target.currentItem()
if item:
txt = str(item.text())
assert txt in st
target.takeItem(target.row(item))
st.remove(txt)
else:
log_warn("item is None")
for nfix in ("suffix", "prefix"):
signal_connect(getattr(w, nfix + "_add"), SIGNAL("clicked()"),
lambda typestr=nfix: _add_nfix(typestr))
signal_connect(getattr(w, nfix + "_del"), SIGNAL("clicked()"),
lambda typestr=nfix: _remove_nfix(typestr))
#hide the extended options
w.questions_categories_params.hide()
w.suffix_prefix_options.hide()
self.resize(self.minimumSizeHint())
#connect signals for enabling the start button
signal_connect(w.account, SIGNAL("currentIndexChanged(int)"), self._enable_start)
signal_connect(w.room, SIGNAL("activated(int)"), self._enable_start)
signal_connect(w.room, SIGNAL("editTextchanged(QString)"), self._enable_start)
signal_connect(w.questions_database, SIGNAL("textChanged(QString)"), self.questions_dbfile_changed)
signal_connect(w.questions_database, SIGNAL("textChanged(QString)"), self._validate_questions_db)
signal_connect(w.anagrams_database, SIGNAL("textChanged(QString)"), self._validate_anagrams_db)
signal_connect(w.questions_database, SIGNAL("textChanged(QString)"), self._enable_start)
signal_connect(w.anagrams_database, SIGNAL("textChanged(QString)"), self._enable_start)
#category list for questions:
self.selected_questions_categories = set()
def _unselect(lwitem):
row = w.selected_categories.row(lwitem)
self.selected_questions_categories.remove(str(lwitem.text()))
self.widgets.selected_categories.takeItem(row)
def _select(lwitem):
category = str(lwitem.text())
if not category in self.selected_questions_categories:
log_debug("Adding", category)
self.selected_questions_categories.add(category)
w.selected_categories.addItem(category)
signal_connect(w.questions_categories, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), _select)
signal_connect(w.selected_categories, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), _unselect)
self.anagrams_db_is_valid = False
self.questions_db_is_valid = False
#profile stuff..
signal_connect(w.actionLoad, SIGNAL("activated()"), lambda: self.profile_handler(load=True))
signal_connect(w.actionSave, SIGNAL("activated()"), lambda: self.profile_handler(save=True))
signal_connect(w.actionSave_As, SIGNAL("activated()"), lambda: self.profile_handler(save_as=True))
self.current_profile_name = ""
w.suffix_prefix_options.sizeHint = lambda: QSize(1,1)
w.questions_categories_params.sizeHint = lambda: QSize(1,1)
self.show()
def _validate_anagrams_db(self, db):
dbconn = None
db = str(db)
try:
assert os.path.exists(db)
dbconn = sqlite3.connect(db)
cursor = dbconn.cursor()
cursor.execute("select word from words limit 1").fetchone()[0]
self.anagrams_db_is_valid = True
except Exception, e:
log_err(e)
self.anagrams_db_is_valid = False
QErrorMessage(self).showMessage("Anagrams database is invalid: " + str(e))
finally:
if dbconn:
dbconn.close()
def _validate_questions_db(self, db):
dbconn = None
db = str(db)
try:
assert os.path.exists(db)
dbconn = sqlite3.connect(db)
cursor = dbconn.cursor()
cursor.execute("select id, frequency, question, answer, alt_answers from questions limit 1").fetchone()[0]
self.questions_db_is_valid = True
except Exception, e:
log_err(e)
self.questions_db_is_valid = False
QErrorMessage(self).showMessage("Questions database is invalid: " + str(e))
finally:
if dbconn:
dbconn.close()
def _dbs_are_valid(self):
type = str(self.widgets.questions_type.currentText()).lower()
if type == "mix" and not ( self.anagrams_db_is_valid and self.questions_db_is_valid):
return False
elif type == "anagrams" and not self.anagrams_db_is_valid:
return False
elif type == "trivia" and not self.questions_db_is_valid:
return False
return True
def _enable_start(self, *args):
w = self.widgets
if w.account.currentText() and w.room.currentText() and self._dbs_are_valid():
w.start.setEnabled(True)
else:
w.start.setEnabled(False)
#some hooks
def questions_dbfile_changed(self, dbname):
self.widgets.questions_categories.clear()
try:
l = get_categories_list(str(dbname))
except Exception, e:
log_err(e)
return
for s in l:
if s:
self.widgets.questions_categories.addItem(str(s))
@staticmethod
def create_profile_mappings():
#make a tuple.
#format: (cast_fn, get_fn, set_fn)
d = {}
#integers
for a in ("post_interval", "answer_timeout", "percent_anagrams", "percent_trivia",
"amount", "anagrams_letters_min", "anagrams_letters_max"):
d[a] = ("int", "value", "setValue")
#strings
for a in ("anagrams_database", "questions_database"):
d[a] = ("str", "text", "setText")
#booleans
for a in ("updatedb_bool", "anagrams_caps_hint", "questions_blacklist",
"questions_use_categories", "anagrams_use_nfixes"):
d[a] = ("bool", "isChecked", "setChecked")
#room combobox
d["room"] = ("str", "currentText", "addItem")
return d
#for accounts, we need to do some special handling because they are
#referenced by index
def save_profile(self, profile_name):
try:
f = open(profile_name, "w")
f.write("#Yobot Trivia Profile Settings automatically generated on %s\n" %
str(datetime.datetime.now()))
f.write("#Configuration is case-sensitive. Use 'True' and 'False' for boolean values\n")
f.write("#this file is parsed directly using python's eval\n")
d = TriviaGui.create_profile_mappings()
for k, v in d.items():
#k is the attribute
field = getattr(self.widgets, k)
cast, getter, setter = v
value = getattr(field, getter)() if getter else field
if cast == "str":
value = str(value)
#if not value and cast == "bool":
# value = int(value)
if not value and cast == "str":
value = ""
f.write(k + "=" + repr(value) + "\n")
#for account..
acct_index = self.widgets.account.currentIndex()
acct_index = self.model.index(acct_index)
account = acct_index.internalPointer()
if account:
f.write("account_username=" + account.user + "\n")
f.write("account_improto=" + yobotops.imprototostr(account.improto) + "\n")
#for complex types
for c in ("anagrams_suffix_blacklist", "anagrams_prefix_blacklist",
"selected_questions_categories"):
log_info(getattr(self, c))
f.write(c + "=" + repr(getattr(self, c)) + "\n")
#for font and color:
if self.font:
f.write("font=" + self.font.toString() + "\n")
if self.color:
f.write("color=" + self.color.name() + "\n")
#for type, just write the current type
f.write("questions_type=" + self.widgets.questions_type.currentText() + "\n")
#for the blacklists/whitelists..
f.close()
return True
except Exception, e:
QErrorMessage(self).showMessage(str(e))
return False
def load_profile(self, profile_name):
d = TriviaGui.create_profile_mappings()
try:
f = open(profile_name, "r")
for l in f.readlines():
if l.strip()[0] in ("#", ";"):
continue
k, v = [s.strip() for s in l.split("=")]
dkey = d.get(k, None)
if not dkey:
#complex handling
if k in ("anagrams_prefix_blacklist", "anagrams_suffix_blacklist"):
tmp = k.split("_")[1]
getattr(self, k).clear()
getattr(self, k).update([str(s) for s in eval(v)])
getattr(self.widgets, tmp + "_list").clear()
getattr(self.widgets, tmp + "_list").addItems(list(getattr(self, k)))
elif k == "selected_questions_categories":
getattr(self, k).clear()
getattr(self, k).update(eval(v))
getattr(self.widgets, "selected_categories").clear()
getattr(self.widgets, "selected_categories").addItems(list(getattr(self, k)))
elif k == "font":
self.font = QFont()
self.font.fromString(v)
self._gen_font_stylesheet()
self._update_fmtstr()
elif k == "color":
self.color = QColor(v)
self._gen_font_stylesheet()
self._update_fmtstr()
else:
log_warn("unknown key", k)
continue
cast, getter, setter = dkey
field = getattr(self.widgets, k)
#getattr(field, setter)(eval(cast)(v))
getattr(field, setter)(eval(v))
f.close()
return True
except Exception, e:
QErrorMessage(self).showMessage(str(e))
return False
def profile_handler(self, load=False, save=False, save_as=False):
if load:
profile = QFileDialog.getOpenFileName(self, "Select Profile", TRIVIA_ROOT)
if profile and self.load_profile(profile):
self.current_profile_name = profile
elif save:
if self.current_profile_name:
self.save_profile(self.current_profile_name)
elif save_as:
profile = QFileDialog.getSaveFileName(self, "Save Profile", TRIVIA_ROOT)
if profile:
self.save_profile(profile)
def start_requested(self):
log_err("implement me")
def stop_requested(self):
log_err("implement me")
def pause_requested(self):
log_err("implement me")
def next_requested(self):
log_err("implement me")
def got_notification(self, notification_object):
self.notifications.addItem(notification_object)
self._notification_dlg.show()
def del_notification(self, notification_object):
self.notifications.delItem(notification_object)
class _QAData(object):
def __init__(self):
self.question = None
self.answers = []
self.id = -1
self.category = None
self.type = None
def ask_string(self):
pass
def hint_string(self):
pass
def is_correct(self, answer):
for a in self.answers:
if a.lower() in answer.lower():
return True
return False
class _QuestionData(_QAData):
def ask_string(self):
return "Category %s: %s" % (self.category, self.question)
def hint_string(self):
ret = ""
|
[
" longest = max(self.answers)"
] | 1,229
|
lcc
|
python
| null |
3bd5a501fc0327fd7bcda8389c7d11b3a821c9b5ce5a93cc
| 5
|
Your task is code completion.
#!/usr/bin/env python
import sys
#begin dependent modules
#sys.path.insert(0, "../")
import yobot_interfaces
import yobotproto
from client_support import YCAccount, SimpleNotice
from gui import gui_util
from gui.gui_util import signal_connect, ConnectionWidget
#end
import triviadb
import PyQt4
from PyQt4.QtGui import (QComboBox, QMainWindow, QStandardItemModel, QStandardItem,
QIcon, QPixmap, QImage, QPainter, QDialog, QMessageBox,
QApplication, QFont, QTextEdit, QColorDialog, QPalette,
QListWidget, QListWidgetItem, QStyledItemDelegate,
QStyleOptionViewItem, QRegion, QWidget, QBrush, QStyle,
QPushButton, QStyleOption, QMenu, QAction, QCursor,
QLineEdit, QFileDialog, QErrorMessage,
QFontDialog, QColor, QDockWidget, QSizePolicy,
QStackedWidget,
QGridLayout, QLayout, QFrame,
)
from PyQt4.QtCore import (QPoint, QSize, QModelIndex, Qt, QObject, SIGNAL, QVariant,
QAbstractItemModel, QRect, QRectF, QPointF, QT_VERSION)
from debuglog import log_debug, log_info, log_err, log_crit, log_warn
import sqlite3.dbapi2 as sqlite3
import pickle
import lxml.html
import re
from time import time
from collections import defaultdict
import random
from gui.html_fmt import point_to_html
import os.path
import yobotops
from cgi import escape as html_escape
import datetime
import gui_new
#trivia types
TYPE_ANAGRAMS, TYPE_TRIVIA, TYPE_BOTH = range(1, 4)
TRIVIA_ROOT = "/home/mordy/src/purple/py/triviabot"
article_start_re = re.compile("^(the|a) ")
def get_categories_list(dbname):
dbconn = sqlite3.connect(dbname)
ret = []
for r in dbconn.cursor().execute("select distinct category from questions"):
ret.append(r[0])
return ret
def scramble_word(word):
return "".join(random.sample(word, len(word)))
class _BlackHole(str):
def __init__(self, *args, **kwargs):
pass
def __getattr__(self, name):
return _BlackHole()
def __setattr__(self, name, value):
pass
def __call__(self, *args, **kwargs):
pass
def __bool__(self):
return False
def __str__(self):
return ""
class TriviaGui(gui_new.TGui):
def __init__(self, parent=None):
gui_new.TGui.__init__(self, parent)
self.widgets = self
w = self.widgets
self.model = yobot_interfaces.component_registry.get_component("account-model")
self.client_ops = yobot_interfaces.component_registry.get_component("client-operations")
assert self.client_ops
def _handle_connect(username, password, improto, **proxy_params):
self.client_ops.connect(username, password, improto, **proxy_params)
def offset_pos_fn():
return QPoint(0, self.menubar.height())
self.connwidget = gui_util.OverlayConnectionWidget(offset_pos_fn, _handle_connect, self)
signal_connect(w.actionConnect, SIGNAL("toggled(bool)"), self.connwidget.setVisible)
signal_connect(self.connwidget.widgets.conn_close, SIGNAL("clicked()"),
lambda: w.actionConnect.setChecked(False))
if not self.model:
w.actionConnect.setChecked(True)
self.model = gui_util.AccountModel(None)
self.menubar.show()
else:
self.connwidget.hide()
#notification widgets:
qdw = QFrame(self)
if QT_VERSION >= 0x040600:
from PyQt4.QtGui import QGraphicsDropShadowEffect
self.notification_shadow = QGraphicsDropShadowEffect(qdw)
self.notification_shadow.setBlurRadius(10.0)
qdw.setGraphicsEffect(self.notification_shadow)
qdw.setFrameShadow(qdw.Raised)
qdw.setFrameShape(qdw.StyledPanel)
qdw.setAutoFillBackground(True)
qsw = QStackedWidget(qdw)
qdw.setLayout(QGridLayout())
qdw.layout().setSizeConstraint(QLayout.SetMinimumSize)
qdw.layout().addWidget(qsw)
self._notification_dlg = qdw
self.qdw = qdw
self.qsw = qsw
self.notifications = gui_util.NotificationBox(qdw, qsw, noTitleBar=False)
#self.qdw.show()
#resize/show events
def _force_bottom(event, superclass_fn):
log_err("")
superclass_fn(self.qdw, event)
self.qdw.move(0, self.height()-self.qdw.height())
self.qdw.resizeEvent = lambda e: _force_bottom(e, QWidget.resizeEvent)
self.qdw.showEvent = lambda e: _force_bottom(e, QWidget.showEvent)
#set up account menu
w.account.setModel(self.model)
for a in ("start", "stop", "pause", "next"):
gui_util.signal_connect(getattr(w, a), SIGNAL("clicked()"),
lambda cls=self, a=a: getattr(cls, a + "_requested")())
getattr(w, a).setEnabled(False)
w.start.setEnabled(True)
self.anagrams_prefix_blacklist = set()
self.anagrams_suffix_blacklist = set()
#listWidgetItems
def _add_nfix(typestr):
txt = getattr(w, typestr + "_input").text()
if not txt:
return
txt = str(txt)
st = getattr(self, "anagrams_" + typestr + "_blacklist")
target = getattr(w, typestr + "_list")
if not txt in st:
target.addItem(txt)
st.add(txt)
getattr(w, typestr + "_input").clear()
def _remove_nfix(typestr):
target = getattr(w, typestr + "_list")
st = getattr(self, "anagrams_" + typestr + "_blacklist")
item = target.currentItem()
if item:
txt = str(item.text())
assert txt in st
target.takeItem(target.row(item))
st.remove(txt)
else:
log_warn("item is None")
for nfix in ("suffix", "prefix"):
signal_connect(getattr(w, nfix + "_add"), SIGNAL("clicked()"),
lambda typestr=nfix: _add_nfix(typestr))
signal_connect(getattr(w, nfix + "_del"), SIGNAL("clicked()"),
lambda typestr=nfix: _remove_nfix(typestr))
#hide the extended options
w.questions_categories_params.hide()
w.suffix_prefix_options.hide()
self.resize(self.minimumSizeHint())
#connect signals for enabling the start button
signal_connect(w.account, SIGNAL("currentIndexChanged(int)"), self._enable_start)
signal_connect(w.room, SIGNAL("activated(int)"), self._enable_start)
signal_connect(w.room, SIGNAL("editTextchanged(QString)"), self._enable_start)
signal_connect(w.questions_database, SIGNAL("textChanged(QString)"), self.questions_dbfile_changed)
signal_connect(w.questions_database, SIGNAL("textChanged(QString)"), self._validate_questions_db)
signal_connect(w.anagrams_database, SIGNAL("textChanged(QString)"), self._validate_anagrams_db)
signal_connect(w.questions_database, SIGNAL("textChanged(QString)"), self._enable_start)
signal_connect(w.anagrams_database, SIGNAL("textChanged(QString)"), self._enable_start)
#category list for questions:
self.selected_questions_categories = set()
def _unselect(lwitem):
row = w.selected_categories.row(lwitem)
self.selected_questions_categories.remove(str(lwitem.text()))
self.widgets.selected_categories.takeItem(row)
def _select(lwitem):
category = str(lwitem.text())
if not category in self.selected_questions_categories:
log_debug("Adding", category)
self.selected_questions_categories.add(category)
w.selected_categories.addItem(category)
signal_connect(w.questions_categories, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), _select)
signal_connect(w.selected_categories, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), _unselect)
self.anagrams_db_is_valid = False
self.questions_db_is_valid = False
#profile stuff..
signal_connect(w.actionLoad, SIGNAL("activated()"), lambda: self.profile_handler(load=True))
signal_connect(w.actionSave, SIGNAL("activated()"), lambda: self.profile_handler(save=True))
signal_connect(w.actionSave_As, SIGNAL("activated()"), lambda: self.profile_handler(save_as=True))
self.current_profile_name = ""
w.suffix_prefix_options.sizeHint = lambda: QSize(1,1)
w.questions_categories_params.sizeHint = lambda: QSize(1,1)
self.show()
def _validate_anagrams_db(self, db):
dbconn = None
db = str(db)
try:
assert os.path.exists(db)
dbconn = sqlite3.connect(db)
cursor = dbconn.cursor()
cursor.execute("select word from words limit 1").fetchone()[0]
self.anagrams_db_is_valid = True
except Exception, e:
log_err(e)
self.anagrams_db_is_valid = False
QErrorMessage(self).showMessage("Anagrams database is invalid: " + str(e))
finally:
if dbconn:
dbconn.close()
def _validate_questions_db(self, db):
dbconn = None
db = str(db)
try:
assert os.path.exists(db)
dbconn = sqlite3.connect(db)
cursor = dbconn.cursor()
cursor.execute("select id, frequency, question, answer, alt_answers from questions limit 1").fetchone()[0]
self.questions_db_is_valid = True
except Exception, e:
log_err(e)
self.questions_db_is_valid = False
QErrorMessage(self).showMessage("Questions database is invalid: " + str(e))
finally:
if dbconn:
dbconn.close()
def _dbs_are_valid(self):
type = str(self.widgets.questions_type.currentText()).lower()
if type == "mix" and not ( self.anagrams_db_is_valid and self.questions_db_is_valid):
return False
elif type == "anagrams" and not self.anagrams_db_is_valid:
return False
elif type == "trivia" and not self.questions_db_is_valid:
return False
return True
def _enable_start(self, *args):
w = self.widgets
if w.account.currentText() and w.room.currentText() and self._dbs_are_valid():
w.start.setEnabled(True)
else:
w.start.setEnabled(False)
#some hooks
def questions_dbfile_changed(self, dbname):
self.widgets.questions_categories.clear()
try:
l = get_categories_list(str(dbname))
except Exception, e:
log_err(e)
return
for s in l:
if s:
self.widgets.questions_categories.addItem(str(s))
@staticmethod
def create_profile_mappings():
#make a tuple.
#format: (cast_fn, get_fn, set_fn)
d = {}
#integers
for a in ("post_interval", "answer_timeout", "percent_anagrams", "percent_trivia",
"amount", "anagrams_letters_min", "anagrams_letters_max"):
d[a] = ("int", "value", "setValue")
#strings
for a in ("anagrams_database", "questions_database"):
d[a] = ("str", "text", "setText")
#booleans
for a in ("updatedb_bool", "anagrams_caps_hint", "questions_blacklist",
"questions_use_categories", "anagrams_use_nfixes"):
d[a] = ("bool", "isChecked", "setChecked")
#room combobox
d["room"] = ("str", "currentText", "addItem")
return d
#for accounts, we need to do some special handling because they are
#referenced by index
def save_profile(self, profile_name):
try:
f = open(profile_name, "w")
f.write("#Yobot Trivia Profile Settings automatically generated on %s\n" %
str(datetime.datetime.now()))
f.write("#Configuration is case-sensitive. Use 'True' and 'False' for boolean values\n")
f.write("#this file is parsed directly using python's eval\n")
d = TriviaGui.create_profile_mappings()
for k, v in d.items():
#k is the attribute
field = getattr(self.widgets, k)
cast, getter, setter = v
value = getattr(field, getter)() if getter else field
if cast == "str":
value = str(value)
#if not value and cast == "bool":
# value = int(value)
if not value and cast == "str":
value = ""
f.write(k + "=" + repr(value) + "\n")
#for account..
acct_index = self.widgets.account.currentIndex()
acct_index = self.model.index(acct_index)
account = acct_index.internalPointer()
if account:
f.write("account_username=" + account.user + "\n")
f.write("account_improto=" + yobotops.imprototostr(account.improto) + "\n")
#for complex types
for c in ("anagrams_suffix_blacklist", "anagrams_prefix_blacklist",
"selected_questions_categories"):
log_info(getattr(self, c))
f.write(c + "=" + repr(getattr(self, c)) + "\n")
#for font and color:
if self.font:
f.write("font=" + self.font.toString() + "\n")
if self.color:
f.write("color=" + self.color.name() + "\n")
#for type, just write the current type
f.write("questions_type=" + self.widgets.questions_type.currentText() + "\n")
#for the blacklists/whitelists..
f.close()
return True
except Exception, e:
QErrorMessage(self).showMessage(str(e))
return False
def load_profile(self, profile_name):
d = TriviaGui.create_profile_mappings()
try:
f = open(profile_name, "r")
for l in f.readlines():
if l.strip()[0] in ("#", ";"):
continue
k, v = [s.strip() for s in l.split("=")]
dkey = d.get(k, None)
if not dkey:
#complex handling
if k in ("anagrams_prefix_blacklist", "anagrams_suffix_blacklist"):
tmp = k.split("_")[1]
getattr(self, k).clear()
getattr(self, k).update([str(s) for s in eval(v)])
getattr(self.widgets, tmp + "_list").clear()
getattr(self.widgets, tmp + "_list").addItems(list(getattr(self, k)))
elif k == "selected_questions_categories":
getattr(self, k).clear()
getattr(self, k).update(eval(v))
getattr(self.widgets, "selected_categories").clear()
getattr(self.widgets, "selected_categories").addItems(list(getattr(self, k)))
elif k == "font":
self.font = QFont()
self.font.fromString(v)
self._gen_font_stylesheet()
self._update_fmtstr()
elif k == "color":
self.color = QColor(v)
self._gen_font_stylesheet()
self._update_fmtstr()
else:
log_warn("unknown key", k)
continue
cast, getter, setter = dkey
field = getattr(self.widgets, k)
#getattr(field, setter)(eval(cast)(v))
getattr(field, setter)(eval(v))
f.close()
return True
except Exception, e:
QErrorMessage(self).showMessage(str(e))
return False
def profile_handler(self, load=False, save=False, save_as=False):
if load:
profile = QFileDialog.getOpenFileName(self, "Select Profile", TRIVIA_ROOT)
if profile and self.load_profile(profile):
self.current_profile_name = profile
elif save:
if self.current_profile_name:
self.save_profile(self.current_profile_name)
elif save_as:
profile = QFileDialog.getSaveFileName(self, "Save Profile", TRIVIA_ROOT)
if profile:
self.save_profile(profile)
def start_requested(self):
log_err("implement me")
def stop_requested(self):
log_err("implement me")
def pause_requested(self):
log_err("implement me")
def next_requested(self):
log_err("implement me")
def got_notification(self, notification_object):
self.notifications.addItem(notification_object)
self._notification_dlg.show()
def del_notification(self, notification_object):
self.notifications.delItem(notification_object)
class _QAData(object):
def __init__(self):
self.question = None
self.answers = []
self.id = -1
self.category = None
self.type = None
def ask_string(self):
pass
def hint_string(self):
pass
def is_correct(self, answer):
for a in self.answers:
if a.lower() in answer.lower():
return True
return False
class _QuestionData(_QAData):
def ask_string(self):
return "Category %s: %s" % (self.category, self.question)
def hint_string(self):
ret = ""
|
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 start_requested(self):
log_err("implement me")
def stop_requested(self):
log_err("implement me")
def pause_requested(self):
log_err("implement me")
def next_requested(self):
log_err("implement me")
Cheatsheet (for next line):
- We are in the start_requested() method, which is a hook for starting the trivia game.
- The method is currently logging an error message, but it should be implemented to start the game.
- The method is part of the TriviaGui class, which has access to various attributes and methods related to the game.
- The method is likely to interact with the client-operations component to start the game.
- Relevant lines: start_requested() method header, client_ops attribute.
Based on this information, the next line of code is likely to be related to starting the game using the client-operations component.
|
|
Please complete the code given below.
/**************************************
*Script Name: Staff Runebook *
*Author: Joeku *
*For use with RunUO 2.0 RC2 *
*Client Tested with: 6.0.9.2 *
*Version: 1.10 *
*Initial Release: 11/25/07 *
*Revision Date: 02/04/09 *
**************************************/
using System;
using System.Collections.Generic;
using Server;
using Server.Gumps;
using Server.Items;
using Server.Network;
namespace Joeku.SR
{
public class SR_Gump : Gump
{
public SR_RuneAccount RuneAcc { get; set; }
public SR_Gump(Mobile m, SR_RuneAccount runeAcc)
: base(0, 27)
{
RuneAcc = runeAcc;
int count = 0;
if (RuneAcc.ChildRune == null)
count = RuneAcc.Count;
else
count = RuneAcc.ChildRune.Count;
int RunebooksH = 0,
RunebooksW = 0;
int tier = -1;
if (RuneAcc.ChildRune != null)
tier = RuneAcc.ChildRune.Tier;
if (tier > -1)
{
if (tier == 0)
{
RunebooksH = 42;
RunebooksW = 278;
}
else
{
RunebooksH = 37 + 42;
RunebooksW = 278 + (tier * 5);
}
}
int RunesH = 10 * 2;
if (count > 10)
count = 10;
if (count > 0)
RunesH += (count * 22);
if (count > 1)
RunesH += ((count - 1) * 5);
DisplayHeader();
int labelHue = m != null && m.NetState != null && m.NetState.IsEnhancedClient ? 2101 : 2100;
if (tier > -1)
DisplayRunebooks(42, RunebooksH, RunebooksW, tier, labelHue);
DisplayAddNew(42 + RunebooksH + RunesH, labelHue);
DisplayRunes(42 + RunebooksH, RunesH, labelHue);
}
public static void Send(Mobile mob, SR_RuneAccount runeAcc)
{
mob.CloseGump(typeof(SR_Gump));
mob.SendGump(new SR_Gump(mob, runeAcc));
}
public void DisplayHeader()
{
AddPage(0);
AddBackground(0, 0, 210, 42, 9270);
AddImageTiled(10, 10, 190, 22, 2624);
AddAlphaRegion(10, 10, 190, 22);
AddHtml(0, 11, 210, 20, "<CENTER><BASEFONT COLOR=#FFFFFF><BIG>Joeku's Staff Runebook</CENTER>", false, false);
}
public void DisplayRunebooks(int y, int h, int w, int tiers, int labelHue)
{
AddBackground(0, y, w, h, 9270);
AddImageTiled(10, y + 10, w - 20, h - 20, 2624);
AddAlphaRegion(10, y + 10, w - 20, h - 20);
for (int i = tiers, j = 1; i > 0; i--, j++)
{
AddBackground(j * 5, y + 37, ((i - 1) * 5) + 278, 42, 9270);
if (i == 1)
{
AddImageTiled((j * 5) + 10, y + 47, ((i - 1) * 5) + 258, 22, 2624);
AddAlphaRegion((j * 5) + 10, y + 47, ((i - 1) * 5) + 258, 22);
}
}
SR_Rune rune = RuneAcc.Runes[RuneAcc.PageIndex];
AddItem(SR_Utilities.ItemOffsetX(rune), y + SR_Utilities.ItemOffsetY(rune) + 12, SR_Utilities.RunebookID, SR_Utilities.ItemHue(rune));
AddLabelCropped(35, y + 12, w - 108, 20, labelHue, rune.Name);
AddButton(w - 70, y + 10, 4014, 4016, 5, GumpButtonType.Reply, 0);
AddButton(w - 40, y + 10, 4017, 4019, 4, GumpButtonType.Reply, 0);
if (tiers > 0)
{
rune = RuneAcc.ChildRune;
AddItem(SR_Utilities.ItemOffsetX(rune) + tiers * 5, y + SR_Utilities.ItemOffsetY(rune) + 12 + 37, SR_Utilities.RunebookID, SR_Utilities.ItemHue(rune));
AddLabelCropped(35 + tiers * 5, y + 12 + 37, 170, 20, labelHue, rune.Name);
AddButton(w - 70, y + 10 + 37, 4014, 4016, 7, GumpButtonType.Reply, 0);
AddButton(w - 40, y + 10 + 37, 4017, 4019, 6, GumpButtonType.Reply, 0);
}
// AddButton(238, 30 + bgY + 10, 4011, 4013, 0, GumpButtonType.Reply, 0);
}
public void DisplayAddNew(int y, int labelHue)
{
AddBackground(0, y, 278, 42, 9270);
AddImageTiled(10, y + 10, 258, 22, 2624);
AddAlphaRegion(10, y + 10, 258, 22);
AddLabel(15, y + 10, labelHue, @"New Rune");
AddButton(80, y + 10, 4011, 4013, 1, GumpButtonType.Reply, 0);
AddButton(110, y + 10, 4029, 4031, 2, GumpButtonType.Reply, 0);
AddLabel(150, y + 10, labelHue, @"New Runebook");
AddButton(238, y + 10, 4011, 4013, 3, GumpButtonType.Reply, 0);
}
public void DisplayRunes(int y, int h, int labelHue)
{
AddBackground(0, y, 430/*400*/, h, 9270);
AddImageTiled(10, y + 10, 410, h - 20, 2624);
AddAlphaRegion(10, y + 10, 410, h - 20);
List<SR_Rune> runes = null;
int count, runebooks;
if (RuneAcc.ChildRune == null)
{
runes = RuneAcc.Runes;
count = RuneAcc.Count;
runebooks = RuneAcc.RunebookCount;
}
else
{
runes = RuneAcc.ChildRune.Runes;
count = RuneAcc.ChildRune.Count;
runebooks = RuneAcc.ChildRune.RunebookCount;
}
AddPage(1);
int pages = (int)Math.Ceiling((double)count / 9.0), temp = 0;
for (int i = 0, loc = 0, page = 1; i < count; i++, loc++)
{
temp = 10 + y + (22 + 5) * loc;
AddItem(SR_Utilities.ItemOffsetX(runes[i]), 2 + SR_Utilities.ItemOffsetY(runes[i]) + temp, runes[i].IsRunebook ? SR_Utilities.RunebookID : SR_Utilities.RuneID, SR_Utilities.ItemHue(runes[i]));
if (runes[i].IsRunebook)
AddLabelCropped(35, 2 + temp, 175, 20, labelHue, String.Format("{0}. {1}", i + 1, runes[i].Name));
else
{
AddLabelCropped(35, 2 + temp, 175, 20, labelHue, String.Format("{0}. {1} ({2})", i + 1 - runebooks, runes[i].Name, runes[i].TargetMap.ToString()));
AddLabelCropped(215, 2 + temp, 110, 20, labelHue, runes[i].TargetLoc.ToString());
AddButton(360, temp, 4008, 4010, i + 30010, GumpButtonType.Reply, 0);
}
AddButton(330 + (runes[i].IsRunebook ? 30 : 0), temp, 4005, 4007, i + 10, GumpButtonType.Reply, 0);
//AddButton(340, 40 + ((22+5)*i), 4026, 4028, 0, GumpButtonType.Reply, 0);
//AddImage(340, 40 + ((22+5)*i), 4026, 1000);
AddButton(390, temp, 4017, 4019, i + 60010, GumpButtonType.Reply, 0); // delete
if (pages > 1 && ((loc == 8 && i < count - 1) || i == count - 1))
{
temp = 10 + y + (22 + 5) * 9;
// (430(bg) - 20 (buffer) - 70 (txt/buffer) - 60(buttons)) / 2 = 140
if (page > 1)
AddButton(140, temp, 4014, 4016, 0, GumpButtonType.Page, page - 1);
else
AddImage(140, temp, 4014, 1000);
AddHtml(170, 2 + temp, 90, 20, String.Format("<BASEFONT COLOR=#FFFFFF><CENTER>Page {0}/{1}", page, pages), false, false);
if (page < pages)
AddButton(260, temp, 4005, 4007, 0, GumpButtonType.Page, page + 1);
else
AddImage(260, temp, 4005, 1000);
page++;
AddPage(page);
loc = -1;
}
}
}
public override void OnResponse(NetState sender, RelayInfo info)
{
int button = info.ButtonID;
Mobile mob = sender.Mobile;
switch( button )
{
case 0:
break;
case 1:
mob.SendMessage("Enter a description:");
mob.Prompt = new SR_NewRunePrompt(RuneAcc, mob.Location, mob.Map);
Send(mob, SR_Utilities.FetchInfo(mob.Account));
break;
case 2:
mob.SendMessage("Target a location to mark:");
|
[
" mob.Target = new SR_NewRuneTarget(RuneAcc);"
] | 907
|
lcc
|
csharp
| null |
227b063979c62ee1de7436be168450b5a7712a7a637fa6d4
| 6
|
Your task is code completion.
/**************************************
*Script Name: Staff Runebook *
*Author: Joeku *
*For use with RunUO 2.0 RC2 *
*Client Tested with: 6.0.9.2 *
*Version: 1.10 *
*Initial Release: 11/25/07 *
*Revision Date: 02/04/09 *
**************************************/
using System;
using System.Collections.Generic;
using Server;
using Server.Gumps;
using Server.Items;
using Server.Network;
namespace Joeku.SR
{
public class SR_Gump : Gump
{
public SR_RuneAccount RuneAcc { get; set; }
public SR_Gump(Mobile m, SR_RuneAccount runeAcc)
: base(0, 27)
{
RuneAcc = runeAcc;
int count = 0;
if (RuneAcc.ChildRune == null)
count = RuneAcc.Count;
else
count = RuneAcc.ChildRune.Count;
int RunebooksH = 0,
RunebooksW = 0;
int tier = -1;
if (RuneAcc.ChildRune != null)
tier = RuneAcc.ChildRune.Tier;
if (tier > -1)
{
if (tier == 0)
{
RunebooksH = 42;
RunebooksW = 278;
}
else
{
RunebooksH = 37 + 42;
RunebooksW = 278 + (tier * 5);
}
}
int RunesH = 10 * 2;
if (count > 10)
count = 10;
if (count > 0)
RunesH += (count * 22);
if (count > 1)
RunesH += ((count - 1) * 5);
DisplayHeader();
int labelHue = m != null && m.NetState != null && m.NetState.IsEnhancedClient ? 2101 : 2100;
if (tier > -1)
DisplayRunebooks(42, RunebooksH, RunebooksW, tier, labelHue);
DisplayAddNew(42 + RunebooksH + RunesH, labelHue);
DisplayRunes(42 + RunebooksH, RunesH, labelHue);
}
public static void Send(Mobile mob, SR_RuneAccount runeAcc)
{
mob.CloseGump(typeof(SR_Gump));
mob.SendGump(new SR_Gump(mob, runeAcc));
}
public void DisplayHeader()
{
AddPage(0);
AddBackground(0, 0, 210, 42, 9270);
AddImageTiled(10, 10, 190, 22, 2624);
AddAlphaRegion(10, 10, 190, 22);
AddHtml(0, 11, 210, 20, "<CENTER><BASEFONT COLOR=#FFFFFF><BIG>Joeku's Staff Runebook</CENTER>", false, false);
}
public void DisplayRunebooks(int y, int h, int w, int tiers, int labelHue)
{
AddBackground(0, y, w, h, 9270);
AddImageTiled(10, y + 10, w - 20, h - 20, 2624);
AddAlphaRegion(10, y + 10, w - 20, h - 20);
for (int i = tiers, j = 1; i > 0; i--, j++)
{
AddBackground(j * 5, y + 37, ((i - 1) * 5) + 278, 42, 9270);
if (i == 1)
{
AddImageTiled((j * 5) + 10, y + 47, ((i - 1) * 5) + 258, 22, 2624);
AddAlphaRegion((j * 5) + 10, y + 47, ((i - 1) * 5) + 258, 22);
}
}
SR_Rune rune = RuneAcc.Runes[RuneAcc.PageIndex];
AddItem(SR_Utilities.ItemOffsetX(rune), y + SR_Utilities.ItemOffsetY(rune) + 12, SR_Utilities.RunebookID, SR_Utilities.ItemHue(rune));
AddLabelCropped(35, y + 12, w - 108, 20, labelHue, rune.Name);
AddButton(w - 70, y + 10, 4014, 4016, 5, GumpButtonType.Reply, 0);
AddButton(w - 40, y + 10, 4017, 4019, 4, GumpButtonType.Reply, 0);
if (tiers > 0)
{
rune = RuneAcc.ChildRune;
AddItem(SR_Utilities.ItemOffsetX(rune) + tiers * 5, y + SR_Utilities.ItemOffsetY(rune) + 12 + 37, SR_Utilities.RunebookID, SR_Utilities.ItemHue(rune));
AddLabelCropped(35 + tiers * 5, y + 12 + 37, 170, 20, labelHue, rune.Name);
AddButton(w - 70, y + 10 + 37, 4014, 4016, 7, GumpButtonType.Reply, 0);
AddButton(w - 40, y + 10 + 37, 4017, 4019, 6, GumpButtonType.Reply, 0);
}
// AddButton(238, 30 + bgY + 10, 4011, 4013, 0, GumpButtonType.Reply, 0);
}
public void DisplayAddNew(int y, int labelHue)
{
AddBackground(0, y, 278, 42, 9270);
AddImageTiled(10, y + 10, 258, 22, 2624);
AddAlphaRegion(10, y + 10, 258, 22);
AddLabel(15, y + 10, labelHue, @"New Rune");
AddButton(80, y + 10, 4011, 4013, 1, GumpButtonType.Reply, 0);
AddButton(110, y + 10, 4029, 4031, 2, GumpButtonType.Reply, 0);
AddLabel(150, y + 10, labelHue, @"New Runebook");
AddButton(238, y + 10, 4011, 4013, 3, GumpButtonType.Reply, 0);
}
public void DisplayRunes(int y, int h, int labelHue)
{
AddBackground(0, y, 430/*400*/, h, 9270);
AddImageTiled(10, y + 10, 410, h - 20, 2624);
AddAlphaRegion(10, y + 10, 410, h - 20);
List<SR_Rune> runes = null;
int count, runebooks;
if (RuneAcc.ChildRune == null)
{
runes = RuneAcc.Runes;
count = RuneAcc.Count;
runebooks = RuneAcc.RunebookCount;
}
else
{
runes = RuneAcc.ChildRune.Runes;
count = RuneAcc.ChildRune.Count;
runebooks = RuneAcc.ChildRune.RunebookCount;
}
AddPage(1);
int pages = (int)Math.Ceiling((double)count / 9.0), temp = 0;
for (int i = 0, loc = 0, page = 1; i < count; i++, loc++)
{
temp = 10 + y + (22 + 5) * loc;
AddItem(SR_Utilities.ItemOffsetX(runes[i]), 2 + SR_Utilities.ItemOffsetY(runes[i]) + temp, runes[i].IsRunebook ? SR_Utilities.RunebookID : SR_Utilities.RuneID, SR_Utilities.ItemHue(runes[i]));
if (runes[i].IsRunebook)
AddLabelCropped(35, 2 + temp, 175, 20, labelHue, String.Format("{0}. {1}", i + 1, runes[i].Name));
else
{
AddLabelCropped(35, 2 + temp, 175, 20, labelHue, String.Format("{0}. {1} ({2})", i + 1 - runebooks, runes[i].Name, runes[i].TargetMap.ToString()));
AddLabelCropped(215, 2 + temp, 110, 20, labelHue, runes[i].TargetLoc.ToString());
AddButton(360, temp, 4008, 4010, i + 30010, GumpButtonType.Reply, 0);
}
AddButton(330 + (runes[i].IsRunebook ? 30 : 0), temp, 4005, 4007, i + 10, GumpButtonType.Reply, 0);
//AddButton(340, 40 + ((22+5)*i), 4026, 4028, 0, GumpButtonType.Reply, 0);
//AddImage(340, 40 + ((22+5)*i), 4026, 1000);
AddButton(390, temp, 4017, 4019, i + 60010, GumpButtonType.Reply, 0); // delete
if (pages > 1 && ((loc == 8 && i < count - 1) || i == count - 1))
{
temp = 10 + y + (22 + 5) * 9;
// (430(bg) - 20 (buffer) - 70 (txt/buffer) - 60(buttons)) / 2 = 140
if (page > 1)
AddButton(140, temp, 4014, 4016, 0, GumpButtonType.Page, page - 1);
else
AddImage(140, temp, 4014, 1000);
AddHtml(170, 2 + temp, 90, 20, String.Format("<BASEFONT COLOR=#FFFFFF><CENTER>Page {0}/{1}", page, pages), false, false);
if (page < pages)
AddButton(260, temp, 4005, 4007, 0, GumpButtonType.Page, page + 1);
else
AddImage(260, temp, 4005, 1000);
page++;
AddPage(page);
loc = -1;
}
}
}
public override void OnResponse(NetState sender, RelayInfo info)
{
int button = info.ButtonID;
Mobile mob = sender.Mobile;
switch( button )
{
case 0:
break;
case 1:
mob.SendMessage("Enter a description:");
mob.Prompt = new SR_NewRunePrompt(RuneAcc, mob.Location, mob.Map);
Send(mob, SR_Utilities.FetchInfo(mob.Account));
break;
case 2:
mob.SendMessage("Target a location to mark:");
|
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]
public class SR_Gump : Gump
{
public override void OnResponse(NetState sender, RelayInfo info)
{
int button = info.ButtonID;
Mobile mob = sender.Mobile;
switch( button )
{
case 0:
break;
case 1:
mob.SendMessage("Enter a description:");
mob.Prompt = new SR_NewRunePrompt(RuneAcc, mob.Location, mob.Map);
Send(mob, SR_Utilities.FetchInfo(mob.Account));
break;
case 2:
mob.SendMessage("Target a location to mark:");
// [Current line]
// [Previous code... ~10,000 lines omitted for brevity]
Cheatsheet (for next line):
- We are in the case 2 block, which handles the button click event.
- mob.SendMessage() is used to send a message to the mobile.
- mob.Prompt is set in the case 1 block.
- SR_Utilities.FetchInfo() is used to fetch information.
- mob.Account is used to get the account of the mobile.
- [Relevant lines: case 1 block, mob.SendMessage(), mob.Prompt, SR_Utilities.FetchInfo(), mob.Account]
Next line will likely be:
mob.SendMessage("Target a location to mark:");
|
|
Please complete the code given below.
/*
* Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.ssl;
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.lang.reflect.*;
import javax.security.auth.x500.X500Principal;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.DHPublicKeySpec;
import javax.net.ssl.*;
import sun.security.internal.spec.TlsPrfParameterSpec;
import sun.security.ssl.CipherSuite.*;
import static sun.security.ssl.CipherSuite.PRF.*;
import sun.security.util.KeyUtil;
/**
* Many data structures are involved in the handshake messages. These
* classes are used as structures, with public data members. They are
* not visible outside the SSL package.
*
* Handshake messages all have a common header format, and they are all
* encoded in a "handshake data" SSL record substream. The base class
* here (HandshakeMessage) provides a common framework and records the
* SSL record type of the particular handshake message.
*
* This file contains subclasses for all the basic handshake messages.
* All handshake messages know how to encode and decode themselves on
* SSL streams; this facilitates using the same code on SSL client and
* server sides, although they don't send and receive the same messages.
*
* Messages also know how to print themselves, which is quite handy
* for debugging. They always identify their type, and can optionally
* dump all of their content.
*
* @author David Brownell
*/
public abstract class HandshakeMessage {
HandshakeMessage() { }
// enum HandshakeType:
static final byte ht_hello_request = 0;
static final byte ht_client_hello = 1;
static final byte ht_server_hello = 2;
static final byte ht_certificate = 11;
static final byte ht_server_key_exchange = 12;
static final byte ht_certificate_request = 13;
static final byte ht_server_hello_done = 14;
static final byte ht_certificate_verify = 15;
static final byte ht_client_key_exchange = 16;
static final byte ht_finished = 20;
/* Class and subclass dynamic debugging support */
public static final Debug debug = Debug.getInstance("ssl");
/**
* Utility method to convert a BigInteger to a byte array in unsigned
* format as needed in the handshake messages. BigInteger uses
* 2's complement format, i.e. it prepends an extra zero if the MSB
* is set. We remove that.
*/
static byte[] toByteArray(BigInteger bi) {
byte[] b = bi.toByteArray();
if ((b.length > 1) && (b[0] == 0)) {
int n = b.length - 1;
byte[] newarray = new byte[n];
System.arraycopy(b, 1, newarray, 0, n);
b = newarray;
}
return b;
}
/*
* SSL 3.0 MAC padding constants.
* Also used by CertificateVerify and Finished during the handshake.
*/
static final byte[] MD5_pad1 = genPad(0x36, 48);
static final byte[] MD5_pad2 = genPad(0x5c, 48);
static final byte[] SHA_pad1 = genPad(0x36, 40);
static final byte[] SHA_pad2 = genPad(0x5c, 40);
private static byte[] genPad(int b, int count) {
byte[] padding = new byte[count];
Arrays.fill(padding, (byte)b);
return padding;
}
/*
* Write a handshake message on the (handshake) output stream.
* This is just a four byte header followed by the data.
*
* NOTE that huge messages -- notably, ones with huge cert
* chains -- are handled correctly.
*/
final void write(HandshakeOutStream s) throws IOException {
int len = messageLength();
if (len >= Record.OVERFLOW_OF_INT24) {
throw new SSLException("Handshake message too big"
+ ", type = " + messageType() + ", len = " + len);
}
s.write(messageType());
s.putInt24(len);
send(s);
}
/*
* Subclasses implement these methods so those kinds of
* messages can be emitted. Base class delegates to subclass.
*/
abstract int messageType();
abstract int messageLength();
abstract void send(HandshakeOutStream s) throws IOException;
/*
* Write a descriptive message on the output stream; for debugging.
*/
abstract void print(PrintStream p) throws IOException;
//
// NOTE: the rest of these classes are nested within this one, and are
// imported by other classes in this package. There are a few other
// handshake message classes, not neatly nested here because of current
// licensing requirement for native (RSA) methods. They belong here,
// but those native methods complicate things a lot!
//
/*
* HelloRequest ... SERVER --> CLIENT
*
* Server can ask the client to initiate a new handshake, e.g. to change
* session parameters after a connection has been (re)established.
*/
static final class HelloRequest extends HandshakeMessage {
@Override
int messageType() { return ht_hello_request; }
HelloRequest() { }
HelloRequest(HandshakeInStream in) throws IOException
{
// nothing in this message
}
@Override
int messageLength() { return 0; }
@Override
void send(HandshakeOutStream out) throws IOException
{
// nothing in this messaage
}
@Override
void print(PrintStream out) throws IOException
{
out.println("*** HelloRequest (empty)");
}
}
/*
* ClientHello ... CLIENT --> SERVER
*
* Client initiates handshake by telling server what it wants, and what it
* can support (prioritized by what's first in the ciphe suite list).
*
* By RFC2246:7.4.1.2 it's explicitly anticipated that this message
* will have more data added at the end ... e.g. what CAs the client trusts.
* Until we know how to parse it, we will just read what we know
* about, and let our caller handle the jumps over unknown data.
*/
static final class ClientHello extends HandshakeMessage {
ProtocolVersion protocolVersion;
RandomCookie clnt_random;
SessionId sessionId;
private CipherSuiteList cipherSuites;
byte[] compression_methods;
HelloExtensions extensions = new HelloExtensions();
private final static byte[] NULL_COMPRESSION = new byte[] {0};
ClientHello(SecureRandom generator, ProtocolVersion protocolVersion,
SessionId sessionId, CipherSuiteList cipherSuites) {
this.protocolVersion = protocolVersion;
this.sessionId = sessionId;
this.cipherSuites = cipherSuites;
if (cipherSuites.containsEC()) {
extensions.add(SupportedEllipticCurvesExtension.DEFAULT);
extensions.add(SupportedEllipticPointFormatsExtension.DEFAULT);
}
clnt_random = new RandomCookie(generator);
compression_methods = NULL_COMPRESSION;
}
ClientHello(HandshakeInStream s, int messageLength) throws IOException {
protocolVersion = ProtocolVersion.valueOf(s.getInt8(), s.getInt8());
clnt_random = new RandomCookie(s);
sessionId = new SessionId(s.getBytes8());
cipherSuites = new CipherSuiteList(s);
compression_methods = s.getBytes8();
if (messageLength() != messageLength) {
extensions = new HelloExtensions(s);
}
}
CipherSuiteList getCipherSuites() {
return cipherSuites;
}
// add renegotiation_info extension
void addRenegotiationInfoExtension(byte[] clientVerifyData) {
HelloExtension renegotiationInfo = new RenegotiationInfoExtension(
clientVerifyData, new byte[0]);
extensions.add(renegotiationInfo);
}
// add server_name extension
void addSNIExtension(List<SNIServerName> serverNames) {
try {
extensions.add(new ServerNameExtension(serverNames));
} catch (IOException ioe) {
// ignore the exception and return
}
}
// add signature_algorithm extension
void addSignatureAlgorithmsExtension(
Collection<SignatureAndHashAlgorithm> algorithms) {
HelloExtension signatureAlgorithm =
new SignatureAlgorithmsExtension(algorithms);
extensions.add(signatureAlgorithm);
}
@Override
int messageType() { return ht_client_hello; }
@Override
int messageLength() {
/*
* Add fixed size parts of each field...
* version + random + session + cipher + compress
*/
return (2 + 32 + 1 + 2 + 1
+ sessionId.length() /* ... + variable parts */
+ (cipherSuites.size() * 2)
+ compression_methods.length)
+ extensions.length();
}
@Override
void send(HandshakeOutStream s) throws IOException {
s.putInt8(protocolVersion.major);
s.putInt8(protocolVersion.minor);
clnt_random.send(s);
s.putBytes8(sessionId.getId());
cipherSuites.send(s);
s.putBytes8(compression_methods);
extensions.send(s);
}
@Override
void print(PrintStream s) throws IOException {
s.println("*** ClientHello, " + protocolVersion);
if (debug != null && Debug.isOn("verbose")) {
s.print("RandomCookie: ");
clnt_random.print(s);
s.print("Session ID: ");
s.println(sessionId);
s.println("Cipher Suites: " + cipherSuites);
Debug.println(s, "Compression Methods", compression_methods);
extensions.print(s);
s.println("***");
}
}
}
/*
* ServerHello ... SERVER --> CLIENT
*
* Server chooses protocol options from among those it supports and the
* client supports. Then it sends the basic session descriptive parameters
* back to the client.
*/
static final
class ServerHello extends HandshakeMessage
{
@Override
int messageType() { return ht_server_hello; }
ProtocolVersion protocolVersion;
RandomCookie svr_random;
SessionId sessionId;
CipherSuite cipherSuite;
byte compression_method;
HelloExtensions extensions = new HelloExtensions();
ServerHello() {
// empty
}
ServerHello(HandshakeInStream input, int messageLength)
throws IOException {
protocolVersion = ProtocolVersion.valueOf(input.getInt8(),
input.getInt8());
svr_random = new RandomCookie(input);
sessionId = new SessionId(input.getBytes8());
cipherSuite = CipherSuite.valueOf(input.getInt8(), input.getInt8());
compression_method = (byte)input.getInt8();
if (messageLength() != messageLength) {
extensions = new HelloExtensions(input);
}
}
@Override
int messageLength()
{
// almost fixed size, except session ID and extensions:
// major + minor = 2
// random = 32
// session ID len field = 1
// cipher suite + compression = 3
// extensions: if present, 2 + length of extensions
return 38 + sessionId.length() + extensions.length();
}
@Override
void send(HandshakeOutStream s) throws IOException
{
s.putInt8(protocolVersion.major);
s.putInt8(protocolVersion.minor);
svr_random.send(s);
s.putBytes8(sessionId.getId());
s.putInt8(cipherSuite.id >> 8);
s.putInt8(cipherSuite.id & 0xff);
s.putInt8(compression_method);
extensions.send(s);
}
@Override
void print(PrintStream s) throws IOException
{
s.println("*** ServerHello, " + protocolVersion);
if (debug != null && Debug.isOn("verbose")) {
s.print("RandomCookie: ");
svr_random.print(s);
s.print("Session ID: ");
s.println(sessionId);
s.println("Cipher Suite: " + cipherSuite);
s.println("Compression Method: " + compression_method);
extensions.print(s);
s.println("***");
}
}
}
/*
* CertificateMsg ... send by both CLIENT and SERVER
*
* Each end of a connection may need to pass its certificate chain to
* the other end. Such chains are intended to validate an identity with
* reference to some certifying authority. Examples include companies
* like Verisign, or financial institutions. There's some control over
* the certifying authorities which are sent.
*
* NOTE: that these messages might be huge, taking many handshake records.
* Up to 2^48 bytes of certificate may be sent, in records of at most 2^14
* bytes each ... up to 2^32 records sent on the output stream.
*/
static final
class CertificateMsg extends HandshakeMessage
{
@Override
int messageType() { return ht_certificate; }
private X509Certificate[] chain;
private List<byte[]> encodedChain;
private int messageLength;
CertificateMsg(X509Certificate[] certs) {
chain = certs;
}
CertificateMsg(HandshakeInStream input) throws IOException {
int chainLen = input.getInt24();
List<Certificate> v = new ArrayList<>(4);
CertificateFactory cf = null;
while (chainLen > 0) {
byte[] cert = input.getBytes24();
chainLen -= (3 + cert.length);
try {
if (cf == null) {
cf = CertificateFactory.getInstance("X.509");
}
v.add(cf.generateCertificate(new ByteArrayInputStream(cert)));
} catch (CertificateException e) {
throw (SSLProtocolException)new SSLProtocolException(
e.getMessage()).initCause(e);
}
}
chain = v.toArray(new X509Certificate[v.size()]);
}
@Override
int messageLength() {
if (encodedChain == null) {
messageLength = 3;
encodedChain = new ArrayList<byte[]>(chain.length);
try {
for (X509Certificate cert : chain) {
byte[] b = cert.getEncoded();
encodedChain.add(b);
messageLength += b.length + 3;
}
} catch (CertificateEncodingException e) {
encodedChain = null;
throw new RuntimeException("Could not encode certificates", e);
}
}
return messageLength;
}
@Override
void send(HandshakeOutStream s) throws IOException {
s.putInt24(messageLength() - 3);
for (byte[] b : encodedChain) {
s.putBytes24(b);
}
}
@Override
void print(PrintStream s) throws IOException {
s.println("*** Certificate chain");
if (debug != null && Debug.isOn("verbose")) {
|
[
" for (int i = 0; i < chain.length; i++)"
] | 1,820
|
lcc
|
java
| null |
f652398c3e8be338b4a7873ba6fecc5a686204d99a1a8d10
| 7
|
Your task is code completion.
/*
* Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.ssl;
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.lang.reflect.*;
import javax.security.auth.x500.X500Principal;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.DHPublicKeySpec;
import javax.net.ssl.*;
import sun.security.internal.spec.TlsPrfParameterSpec;
import sun.security.ssl.CipherSuite.*;
import static sun.security.ssl.CipherSuite.PRF.*;
import sun.security.util.KeyUtil;
/**
* Many data structures are involved in the handshake messages. These
* classes are used as structures, with public data members. They are
* not visible outside the SSL package.
*
* Handshake messages all have a common header format, and they are all
* encoded in a "handshake data" SSL record substream. The base class
* here (HandshakeMessage) provides a common framework and records the
* SSL record type of the particular handshake message.
*
* This file contains subclasses for all the basic handshake messages.
* All handshake messages know how to encode and decode themselves on
* SSL streams; this facilitates using the same code on SSL client and
* server sides, although they don't send and receive the same messages.
*
* Messages also know how to print themselves, which is quite handy
* for debugging. They always identify their type, and can optionally
* dump all of their content.
*
* @author David Brownell
*/
public abstract class HandshakeMessage {
HandshakeMessage() { }
// enum HandshakeType:
static final byte ht_hello_request = 0;
static final byte ht_client_hello = 1;
static final byte ht_server_hello = 2;
static final byte ht_certificate = 11;
static final byte ht_server_key_exchange = 12;
static final byte ht_certificate_request = 13;
static final byte ht_server_hello_done = 14;
static final byte ht_certificate_verify = 15;
static final byte ht_client_key_exchange = 16;
static final byte ht_finished = 20;
/* Class and subclass dynamic debugging support */
public static final Debug debug = Debug.getInstance("ssl");
/**
* Utility method to convert a BigInteger to a byte array in unsigned
* format as needed in the handshake messages. BigInteger uses
* 2's complement format, i.e. it prepends an extra zero if the MSB
* is set. We remove that.
*/
static byte[] toByteArray(BigInteger bi) {
byte[] b = bi.toByteArray();
if ((b.length > 1) && (b[0] == 0)) {
int n = b.length - 1;
byte[] newarray = new byte[n];
System.arraycopy(b, 1, newarray, 0, n);
b = newarray;
}
return b;
}
/*
* SSL 3.0 MAC padding constants.
* Also used by CertificateVerify and Finished during the handshake.
*/
static final byte[] MD5_pad1 = genPad(0x36, 48);
static final byte[] MD5_pad2 = genPad(0x5c, 48);
static final byte[] SHA_pad1 = genPad(0x36, 40);
static final byte[] SHA_pad2 = genPad(0x5c, 40);
private static byte[] genPad(int b, int count) {
byte[] padding = new byte[count];
Arrays.fill(padding, (byte)b);
return padding;
}
/*
* Write a handshake message on the (handshake) output stream.
* This is just a four byte header followed by the data.
*
* NOTE that huge messages -- notably, ones with huge cert
* chains -- are handled correctly.
*/
final void write(HandshakeOutStream s) throws IOException {
int len = messageLength();
if (len >= Record.OVERFLOW_OF_INT24) {
throw new SSLException("Handshake message too big"
+ ", type = " + messageType() + ", len = " + len);
}
s.write(messageType());
s.putInt24(len);
send(s);
}
/*
* Subclasses implement these methods so those kinds of
* messages can be emitted. Base class delegates to subclass.
*/
abstract int messageType();
abstract int messageLength();
abstract void send(HandshakeOutStream s) throws IOException;
/*
* Write a descriptive message on the output stream; for debugging.
*/
abstract void print(PrintStream p) throws IOException;
//
// NOTE: the rest of these classes are nested within this one, and are
// imported by other classes in this package. There are a few other
// handshake message classes, not neatly nested here because of current
// licensing requirement for native (RSA) methods. They belong here,
// but those native methods complicate things a lot!
//
/*
* HelloRequest ... SERVER --> CLIENT
*
* Server can ask the client to initiate a new handshake, e.g. to change
* session parameters after a connection has been (re)established.
*/
static final class HelloRequest extends HandshakeMessage {
@Override
int messageType() { return ht_hello_request; }
HelloRequest() { }
HelloRequest(HandshakeInStream in) throws IOException
{
// nothing in this message
}
@Override
int messageLength() { return 0; }
@Override
void send(HandshakeOutStream out) throws IOException
{
// nothing in this messaage
}
@Override
void print(PrintStream out) throws IOException
{
out.println("*** HelloRequest (empty)");
}
}
/*
* ClientHello ... CLIENT --> SERVER
*
* Client initiates handshake by telling server what it wants, and what it
* can support (prioritized by what's first in the ciphe suite list).
*
* By RFC2246:7.4.1.2 it's explicitly anticipated that this message
* will have more data added at the end ... e.g. what CAs the client trusts.
* Until we know how to parse it, we will just read what we know
* about, and let our caller handle the jumps over unknown data.
*/
static final class ClientHello extends HandshakeMessage {
ProtocolVersion protocolVersion;
RandomCookie clnt_random;
SessionId sessionId;
private CipherSuiteList cipherSuites;
byte[] compression_methods;
HelloExtensions extensions = new HelloExtensions();
private final static byte[] NULL_COMPRESSION = new byte[] {0};
ClientHello(SecureRandom generator, ProtocolVersion protocolVersion,
SessionId sessionId, CipherSuiteList cipherSuites) {
this.protocolVersion = protocolVersion;
this.sessionId = sessionId;
this.cipherSuites = cipherSuites;
if (cipherSuites.containsEC()) {
extensions.add(SupportedEllipticCurvesExtension.DEFAULT);
extensions.add(SupportedEllipticPointFormatsExtension.DEFAULT);
}
clnt_random = new RandomCookie(generator);
compression_methods = NULL_COMPRESSION;
}
ClientHello(HandshakeInStream s, int messageLength) throws IOException {
protocolVersion = ProtocolVersion.valueOf(s.getInt8(), s.getInt8());
clnt_random = new RandomCookie(s);
sessionId = new SessionId(s.getBytes8());
cipherSuites = new CipherSuiteList(s);
compression_methods = s.getBytes8();
if (messageLength() != messageLength) {
extensions = new HelloExtensions(s);
}
}
CipherSuiteList getCipherSuites() {
return cipherSuites;
}
// add renegotiation_info extension
void addRenegotiationInfoExtension(byte[] clientVerifyData) {
HelloExtension renegotiationInfo = new RenegotiationInfoExtension(
clientVerifyData, new byte[0]);
extensions.add(renegotiationInfo);
}
// add server_name extension
void addSNIExtension(List<SNIServerName> serverNames) {
try {
extensions.add(new ServerNameExtension(serverNames));
} catch (IOException ioe) {
// ignore the exception and return
}
}
// add signature_algorithm extension
void addSignatureAlgorithmsExtension(
Collection<SignatureAndHashAlgorithm> algorithms) {
HelloExtension signatureAlgorithm =
new SignatureAlgorithmsExtension(algorithms);
extensions.add(signatureAlgorithm);
}
@Override
int messageType() { return ht_client_hello; }
@Override
int messageLength() {
/*
* Add fixed size parts of each field...
* version + random + session + cipher + compress
*/
return (2 + 32 + 1 + 2 + 1
+ sessionId.length() /* ... + variable parts */
+ (cipherSuites.size() * 2)
+ compression_methods.length)
+ extensions.length();
}
@Override
void send(HandshakeOutStream s) throws IOException {
s.putInt8(protocolVersion.major);
s.putInt8(protocolVersion.minor);
clnt_random.send(s);
s.putBytes8(sessionId.getId());
cipherSuites.send(s);
s.putBytes8(compression_methods);
extensions.send(s);
}
@Override
void print(PrintStream s) throws IOException {
s.println("*** ClientHello, " + protocolVersion);
if (debug != null && Debug.isOn("verbose")) {
s.print("RandomCookie: ");
clnt_random.print(s);
s.print("Session ID: ");
s.println(sessionId);
s.println("Cipher Suites: " + cipherSuites);
Debug.println(s, "Compression Methods", compression_methods);
extensions.print(s);
s.println("***");
}
}
}
/*
* ServerHello ... SERVER --> CLIENT
*
* Server chooses protocol options from among those it supports and the
* client supports. Then it sends the basic session descriptive parameters
* back to the client.
*/
static final
class ServerHello extends HandshakeMessage
{
@Override
int messageType() { return ht_server_hello; }
ProtocolVersion protocolVersion;
RandomCookie svr_random;
SessionId sessionId;
CipherSuite cipherSuite;
byte compression_method;
HelloExtensions extensions = new HelloExtensions();
ServerHello() {
// empty
}
ServerHello(HandshakeInStream input, int messageLength)
throws IOException {
protocolVersion = ProtocolVersion.valueOf(input.getInt8(),
input.getInt8());
svr_random = new RandomCookie(input);
sessionId = new SessionId(input.getBytes8());
cipherSuite = CipherSuite.valueOf(input.getInt8(), input.getInt8());
compression_method = (byte)input.getInt8();
if (messageLength() != messageLength) {
extensions = new HelloExtensions(input);
}
}
@Override
int messageLength()
{
// almost fixed size, except session ID and extensions:
// major + minor = 2
// random = 32
// session ID len field = 1
// cipher suite + compression = 3
// extensions: if present, 2 + length of extensions
return 38 + sessionId.length() + extensions.length();
}
@Override
void send(HandshakeOutStream s) throws IOException
{
s.putInt8(protocolVersion.major);
s.putInt8(protocolVersion.minor);
svr_random.send(s);
s.putBytes8(sessionId.getId());
s.putInt8(cipherSuite.id >> 8);
s.putInt8(cipherSuite.id & 0xff);
s.putInt8(compression_method);
extensions.send(s);
}
@Override
void print(PrintStream s) throws IOException
{
s.println("*** ServerHello, " + protocolVersion);
if (debug != null && Debug.isOn("verbose")) {
s.print("RandomCookie: ");
svr_random.print(s);
s.print("Session ID: ");
s.println(sessionId);
s.println("Cipher Suite: " + cipherSuite);
s.println("Compression Method: " + compression_method);
extensions.print(s);
s.println("***");
}
}
}
/*
* CertificateMsg ... send by both CLIENT and SERVER
*
* Each end of a connection may need to pass its certificate chain to
* the other end. Such chains are intended to validate an identity with
* reference to some certifying authority. Examples include companies
* like Verisign, or financial institutions. There's some control over
* the certifying authorities which are sent.
*
* NOTE: that these messages might be huge, taking many handshake records.
* Up to 2^48 bytes of certificate may be sent, in records of at most 2^14
* bytes each ... up to 2^32 records sent on the output stream.
*/
static final
class CertificateMsg extends HandshakeMessage
{
@Override
int messageType() { return ht_certificate; }
private X509Certificate[] chain;
private List<byte[]> encodedChain;
private int messageLength;
CertificateMsg(X509Certificate[] certs) {
chain = certs;
}
CertificateMsg(HandshakeInStream input) throws IOException {
int chainLen = input.getInt24();
List<Certificate> v = new ArrayList<>(4);
CertificateFactory cf = null;
while (chainLen > 0) {
byte[] cert = input.getBytes24();
chainLen -= (3 + cert.length);
try {
if (cf == null) {
cf = CertificateFactory.getInstance("X.509");
}
v.add(cf.generateCertificate(new ByteArrayInputStream(cert)));
} catch (CertificateException e) {
throw (SSLProtocolException)new SSLProtocolException(
e.getMessage()).initCause(e);
}
}
chain = v.toArray(new X509Certificate[v.size()]);
}
@Override
int messageLength() {
if (encodedChain == null) {
messageLength = 3;
encodedChain = new ArrayList<byte[]>(chain.length);
try {
for (X509Certificate cert : chain) {
byte[] b = cert.getEncoded();
encodedChain.add(b);
messageLength += b.length + 3;
}
} catch (CertificateEncodingException e) {
encodedChain = null;
throw new RuntimeException("Could not encode certificates", e);
}
}
return messageLength;
}
@Override
void send(HandshakeOutStream s) throws IOException {
s.putInt24(messageLength() - 3);
for (byte[] b : encodedChain) {
s.putBytes24(b);
}
}
@Override
void print(PrintStream s) throws IOException {
s.println("*** Certificate chain");
if (debug != null && Debug.isOn("verbose")) {
|
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 abstract class HandshakeMessage {
// ...
abstract int messageType();
abstract int messageLength();
abstract void send(HandshakeOutStream s) throws IOException;
// ...
}
static final class CertificateMsg extends HandshakeMessage {
// ...
@Override
int messageType() { return ht_certificate; }
// ...
@Override
int messageLength() {
if (encodedChain == null) {
messageLength = 3;
encodedChain = new ArrayList<byte[]>(chain.length);
try {
for (X509Certificate cert : chain) {
byte[] b = cert.getEncoded();
encodedChain.add(b);
messageLength += b.length + 3;
}
} catch (CertificateEncodingException e) {
encodedChain = null;
throw new RuntimeException("Could not encode certificates", e);
}
}
return messageLength;
}
// ...
@Override
void send(HandshakeOutStream s) throws IOException {
s.putInt24(messageLength() - 3);
for (byte[] b : encodedChain) {
s.putBytes24(b);
}
}
// ...
}
Cheatsheet (for next line):
- We are in the CertificateMsg class, which extends HandshakeMessage.
- The send() method is being implemented for CertificateMsg.
- The method is supposed to write the handshake message on the HandshakeOutStream.
- The message length is calculated in the messageLength() method.
- The message is written in chunks of 24 bytes (putInt24() and putBytes24()).
- The message length is written first, followed by the message data.
- The message data is stored in the encodedChain list.
- The encodedChain list contains byte arrays, which are written using putBytes24().
- The message length is calculated in the messageLength() method, which is called in the send() method.
Next line will likely be: s.putBytes24(encodedChain.get(i));
|
|
Please complete the code given below.
/*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2015 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.space;
import java.io.*;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import com.sleepycat.je.*;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.Persistent;
import com.sleepycat.persist.model.PrimaryKey;
import com.sleepycat.persist.model.SecondaryKey;
import com.sleepycat.persist.model.Relationship;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import org.jpos.util.Log;
import org.jpos.util.Loggeable;
/**
* BerkeleyDB Jave Edition based persistent space implementation
*
* @author Alejandro Revilla
* @since 1.6.5
*/
@SuppressWarnings("unchecked")
public class JESpace<K,V> extends Log implements LocalSpace<K,V>, Loggeable, Runnable {
Environment dbe = null;
EntityStore store = null;
PrimaryIndex<Long, Ref> pIndex = null;
PrimaryIndex<Long,GCRef> gcpIndex = null;
SecondaryIndex<String,Long, Ref> sIndex = null;
SecondaryIndex<Long,Long,GCRef> gcsIndex = null;
Semaphore gcSem = new Semaphore(1);
LocalSpace<Object,SpaceListener> sl;
private static final long NRD_RESOLUTION = 500L;
public static final long GC_DELAY = 60*1000L;
private Future gcTask;
static final Map<String,Space> spaceRegistrar =
new HashMap<String,Space> ();
public JESpace(String name, String path) throws SpaceError {
super();
try {
EnvironmentConfig envConfig = new EnvironmentConfig();
StoreConfig storeConfig = new StoreConfig();
envConfig.setAllowCreate (true);
envConfig.setTransactional(true);
// envConfig.setTxnTimeout(5L, TimeUnit.MINUTES);
envConfig.setLockTimeout(5, TimeUnit.SECONDS);
storeConfig.setAllowCreate (true);
storeConfig.setTransactional (true);
File dir = new File(path);
dir.mkdirs();
dbe = new Environment (dir, envConfig);
store = new EntityStore (dbe, name, storeConfig);
pIndex = store.getPrimaryIndex (Long.class, Ref.class);
gcpIndex = store.getPrimaryIndex (Long.class, GCRef.class);
sIndex = store.getSecondaryIndex (pIndex, String.class, "key");
gcsIndex = store.getSecondaryIndex (gcpIndex, Long.class, "expires");
gcTask = SpaceFactory.getGCExecutor().scheduleAtFixedRate(this, GC_DELAY, GC_DELAY, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new SpaceError (e);
}
}
public void out (K key, V value) {
out (key, value, 0L);
}
public void out (K key, V value, long timeout) {
Transaction txn = null;
try {
txn = dbe.beginTransaction (null, null);
Ref ref = new Ref(key.toString(), value, timeout);
pIndex.put (ref);
if (timeout > 0L)
gcpIndex.putNoReturn (
new GCRef (ref.getId(), ref.getExpiration())
);
txn.commit();
txn = null;
synchronized (this) {
notifyAll ();
}
if (sl != null)
notifyListeners(key, value);
} catch (Exception e) {
throw new SpaceError (e);
} finally {
if (txn != null)
abort (txn);
}
}
public void push (K key, V value, long timeout) {
Transaction txn = null;
try {
txn = dbe.beginTransaction (null, null);
Ref ref = new Ref(key.toString(), value, timeout);
pIndex.put (ref);
pIndex.delete (ref.getId());
ref.reverseId();
pIndex.put (ref);
txn.commit();
txn = null;
synchronized (this) {
notifyAll ();
}
if (sl != null)
notifyListeners(key, value);
} catch (Exception e) {
throw new SpaceError (e);
} finally {
if (txn != null)
abort (txn);
}
}
public void push (K key, V value) {
push (key, value, 0L);
}
@SuppressWarnings("unchecked")
public V rdp (Object key) {
try {
return (V) getObject (key, false);
} catch (DatabaseException e) {
throw new SpaceError (e);
}
}
@SuppressWarnings("unchecked")
public synchronized V in (Object key) {
Object obj;
while ((obj = inp (key)) == null) {
try {
this.wait ();
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
@SuppressWarnings("unchecked")
public synchronized V in (Object key, long timeout) {
Object obj;
long now = System.currentTimeMillis();
long end = now + timeout;
while ((obj = inp (key)) == null &&
(now = System.currentTimeMillis()) < end)
{
try {
this.wait (end - now);
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
@SuppressWarnings("unchecked")
public synchronized V rd (Object key) {
Object obj;
while ((obj = rdp (key)) == null) {
try {
this.wait ();
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
@SuppressWarnings("unchecked")
public synchronized V rd (Object key, long timeout) {
Object obj;
long now = System.currentTimeMillis();
long end = now + timeout;
while ((obj = rdp (key)) == null &&
(now = System.currentTimeMillis()) < end)
{
try {
this.wait (end - now);
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
public synchronized void nrd (Object key) {
while (rdp (key) != null) {
try {
this.wait (NRD_RESOLUTION);
} catch (InterruptedException ignored) { }
}
}
public synchronized V nrd (Object key, long timeout) {
Object obj;
long now = System.currentTimeMillis();
long end = now + timeout;
while ((obj = rdp (key)) != null &&
(now = System.currentTimeMillis()) < end)
{
try {
this.wait (Math.min(NRD_RESOLUTION, end - now));
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
@SuppressWarnings("unchecked")
public V inp (Object key) {
try {
return (V) getObject (key, true);
} catch (DatabaseException e) {
throw new SpaceError (e);
}
}
public boolean existAny (Object[] keys) {
for (Object key : keys) {
if (rdp(key) != null) {
return true;
}
}
return false;
}
public boolean existAny (Object[] keys, long timeout) {
long now = System.currentTimeMillis();
long end = now + timeout;
while ((now = System.currentTimeMillis()) < end) {
if (existAny (keys))
return true;
synchronized (this) {
try {
wait (end - now);
} catch (InterruptedException ignored) { }
}
}
return false;
}
public synchronized void put (K key, V value, long timeout) {
while (inp (key) != null)
;
out (key, value, timeout);
}
public synchronized void put (K key, V value) {
while (inp (key) != null)
;
out (key, value);
}
public void gc () throws DatabaseException {
Transaction txn = null;
EntityCursor<GCRef> cursor = null;
try {
if (!gcSem.tryAcquire())
return;
txn = dbe.beginTransaction (null, null);
cursor = gcsIndex.entities (
txn, 0L, true, System.currentTimeMillis(), false, null
);
for (GCRef gcRef: cursor) {
pIndex.delete (gcRef.getId());
cursor.delete ();
}
cursor.close();
cursor = null;
txn.commit();
txn = null;
if (sl != null) {
synchronized (this) {
if (sl != null && sl.getKeySet().isEmpty())
sl = null;
}
}
} finally {
if (cursor != null)
cursor.close();
if (txn != null)
abort (txn);
gcSem.release();
}
}
public void run() {
try {
gc();
} catch (DatabaseException e) {
warn(e);
}
}
public void close () throws DatabaseException {
gcSem.acquireUninterruptibly();
gcTask.cancel(false);
while (!gcTask.isDone()) {
try {
Thread.sleep(500L);
} catch (InterruptedException ignored) { }
}
store.close ();
dbe.close();
}
public synchronized static JESpace getSpace (String name, String path)
{
JESpace sp = (JESpace) spaceRegistrar.get (name);
if (sp == null) {
|
[
" sp = new JESpace(name, path);"
] | 1,096
|
lcc
|
java
| null |
01b11dc980d93775ce16fd5e630cf5619f66f281ee12947b
| 8
|
Your task is code completion.
/*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2015 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.space;
import java.io.*;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import com.sleepycat.je.*;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.Persistent;
import com.sleepycat.persist.model.PrimaryKey;
import com.sleepycat.persist.model.SecondaryKey;
import com.sleepycat.persist.model.Relationship;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import org.jpos.util.Log;
import org.jpos.util.Loggeable;
/**
* BerkeleyDB Jave Edition based persistent space implementation
*
* @author Alejandro Revilla
* @since 1.6.5
*/
@SuppressWarnings("unchecked")
public class JESpace<K,V> extends Log implements LocalSpace<K,V>, Loggeable, Runnable {
Environment dbe = null;
EntityStore store = null;
PrimaryIndex<Long, Ref> pIndex = null;
PrimaryIndex<Long,GCRef> gcpIndex = null;
SecondaryIndex<String,Long, Ref> sIndex = null;
SecondaryIndex<Long,Long,GCRef> gcsIndex = null;
Semaphore gcSem = new Semaphore(1);
LocalSpace<Object,SpaceListener> sl;
private static final long NRD_RESOLUTION = 500L;
public static final long GC_DELAY = 60*1000L;
private Future gcTask;
static final Map<String,Space> spaceRegistrar =
new HashMap<String,Space> ();
public JESpace(String name, String path) throws SpaceError {
super();
try {
EnvironmentConfig envConfig = new EnvironmentConfig();
StoreConfig storeConfig = new StoreConfig();
envConfig.setAllowCreate (true);
envConfig.setTransactional(true);
// envConfig.setTxnTimeout(5L, TimeUnit.MINUTES);
envConfig.setLockTimeout(5, TimeUnit.SECONDS);
storeConfig.setAllowCreate (true);
storeConfig.setTransactional (true);
File dir = new File(path);
dir.mkdirs();
dbe = new Environment (dir, envConfig);
store = new EntityStore (dbe, name, storeConfig);
pIndex = store.getPrimaryIndex (Long.class, Ref.class);
gcpIndex = store.getPrimaryIndex (Long.class, GCRef.class);
sIndex = store.getSecondaryIndex (pIndex, String.class, "key");
gcsIndex = store.getSecondaryIndex (gcpIndex, Long.class, "expires");
gcTask = SpaceFactory.getGCExecutor().scheduleAtFixedRate(this, GC_DELAY, GC_DELAY, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new SpaceError (e);
}
}
public void out (K key, V value) {
out (key, value, 0L);
}
public void out (K key, V value, long timeout) {
Transaction txn = null;
try {
txn = dbe.beginTransaction (null, null);
Ref ref = new Ref(key.toString(), value, timeout);
pIndex.put (ref);
if (timeout > 0L)
gcpIndex.putNoReturn (
new GCRef (ref.getId(), ref.getExpiration())
);
txn.commit();
txn = null;
synchronized (this) {
notifyAll ();
}
if (sl != null)
notifyListeners(key, value);
} catch (Exception e) {
throw new SpaceError (e);
} finally {
if (txn != null)
abort (txn);
}
}
public void push (K key, V value, long timeout) {
Transaction txn = null;
try {
txn = dbe.beginTransaction (null, null);
Ref ref = new Ref(key.toString(), value, timeout);
pIndex.put (ref);
pIndex.delete (ref.getId());
ref.reverseId();
pIndex.put (ref);
txn.commit();
txn = null;
synchronized (this) {
notifyAll ();
}
if (sl != null)
notifyListeners(key, value);
} catch (Exception e) {
throw new SpaceError (e);
} finally {
if (txn != null)
abort (txn);
}
}
public void push (K key, V value) {
push (key, value, 0L);
}
@SuppressWarnings("unchecked")
public V rdp (Object key) {
try {
return (V) getObject (key, false);
} catch (DatabaseException e) {
throw new SpaceError (e);
}
}
@SuppressWarnings("unchecked")
public synchronized V in (Object key) {
Object obj;
while ((obj = inp (key)) == null) {
try {
this.wait ();
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
@SuppressWarnings("unchecked")
public synchronized V in (Object key, long timeout) {
Object obj;
long now = System.currentTimeMillis();
long end = now + timeout;
while ((obj = inp (key)) == null &&
(now = System.currentTimeMillis()) < end)
{
try {
this.wait (end - now);
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
@SuppressWarnings("unchecked")
public synchronized V rd (Object key) {
Object obj;
while ((obj = rdp (key)) == null) {
try {
this.wait ();
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
@SuppressWarnings("unchecked")
public synchronized V rd (Object key, long timeout) {
Object obj;
long now = System.currentTimeMillis();
long end = now + timeout;
while ((obj = rdp (key)) == null &&
(now = System.currentTimeMillis()) < end)
{
try {
this.wait (end - now);
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
public synchronized void nrd (Object key) {
while (rdp (key) != null) {
try {
this.wait (NRD_RESOLUTION);
} catch (InterruptedException ignored) { }
}
}
public synchronized V nrd (Object key, long timeout) {
Object obj;
long now = System.currentTimeMillis();
long end = now + timeout;
while ((obj = rdp (key)) != null &&
(now = System.currentTimeMillis()) < end)
{
try {
this.wait (Math.min(NRD_RESOLUTION, end - now));
} catch (InterruptedException ignored) { }
}
return (V) obj;
}
@SuppressWarnings("unchecked")
public V inp (Object key) {
try {
return (V) getObject (key, true);
} catch (DatabaseException e) {
throw new SpaceError (e);
}
}
public boolean existAny (Object[] keys) {
for (Object key : keys) {
if (rdp(key) != null) {
return true;
}
}
return false;
}
public boolean existAny (Object[] keys, long timeout) {
long now = System.currentTimeMillis();
long end = now + timeout;
while ((now = System.currentTimeMillis()) < end) {
if (existAny (keys))
return true;
synchronized (this) {
try {
wait (end - now);
} catch (InterruptedException ignored) { }
}
}
return false;
}
public synchronized void put (K key, V value, long timeout) {
while (inp (key) != null)
;
out (key, value, timeout);
}
public synchronized void put (K key, V value) {
while (inp (key) != null)
;
out (key, value);
}
public void gc () throws DatabaseException {
Transaction txn = null;
EntityCursor<GCRef> cursor = null;
try {
if (!gcSem.tryAcquire())
return;
txn = dbe.beginTransaction (null, null);
cursor = gcsIndex.entities (
txn, 0L, true, System.currentTimeMillis(), false, null
);
for (GCRef gcRef: cursor) {
pIndex.delete (gcRef.getId());
cursor.delete ();
}
cursor.close();
cursor = null;
txn.commit();
txn = null;
if (sl != null) {
synchronized (this) {
if (sl != null && sl.getKeySet().isEmpty())
sl = null;
}
}
} finally {
if (cursor != null)
cursor.close();
if (txn != null)
abort (txn);
gcSem.release();
}
}
public void run() {
try {
gc();
} catch (DatabaseException e) {
warn(e);
}
}
public void close () throws DatabaseException {
gcSem.acquireUninterruptibly();
gcTask.cancel(false);
while (!gcTask.isDone()) {
try {
Thread.sleep(500L);
} catch (InterruptedException ignored) { }
}
store.close ();
dbe.close();
}
public synchronized static JESpace getSpace (String name, String path)
{
JESpace sp = (JESpace) spaceRegistrar.get (name);
if (sp == null) {
|
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]
public synchronized static JESpace getSpace (String name, String path)
{
JESpace sp = (JESpace) spaceRegistrar.get (name);
if (sp == null) {
sp = new JESpace(name, path);
spaceRegistrar.put(name, sp);
}
return sp;
}
Cheatsheet (for next line):
- We are in the getSpace() method, which is a static method.
- It is responsible for retrieving or creating a JESpace instance based on the given name and path.
- The method returns the JESpace instance.
- The spaceRegistrar is a HashMap that stores JESpace instances with their names as keys.
- If the JESpace instance is not found in the spaceRegistrar, a new instance is created and added to the map.
- [Relevant lines: method header, spaceRegistrar declaration, null check]
Next line will likely be: return sp;
|
|
Please complete the code given below.
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2021 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.items.spells;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.ShatteredPixelDungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Shopkeeper;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.AlchemicalCatalyst;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.scenes.AlchemyScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.ui.RedButton;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndBag;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndEnergizeItem;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndImp;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndInfoItem;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndTradeItem;
import com.watabou.noosa.audio.Sample;
public class Alchemize extends Spell {
{
image = ItemSpriteSheet.ALCHEMIZE;
}
@Override
protected void onCast(Hero hero) {
GameScene.selectItem( itemSelector );
}
@Override
public int value() {
//prices of ingredients, divided by output quantity
return Math.round(quantity * (40 / 8f));
}
//TODO also allow alchemical catalyst? Or save that for an elixir/brew?
public static class Recipe extends com.shatteredpixel.shatteredpixeldungeon.items.Recipe.SimpleRecipe {
{
inputs = new Class[]{ArcaneCatalyst.class};
inQuantity = new int[]{1};
cost = 3;
output = Alchemize.class;
outQuantity = 8;
}
}
private static WndBag.ItemSelector itemSelector = new WndBag.ItemSelector() {
@Override
public String textPrompt() {
return Messages.get(Alchemize.class, "prompt");
}
@Override
public boolean itemSelectable(Item item) {
return !(item instanceof Alchemize)
&& (Shopkeeper.canSell(item) || item.energyVal() > 0);
}
@Override
public void onSelect( Item item ) {
if (item != null) {
WndBag parentWnd = GameScene.selectItem( itemSelector );
GameScene.show( new WndAlchemizeItem( item, parentWnd ) );
}
}
};
public static class WndAlchemizeItem extends WndInfoItem {
private static final float GAP = 2;
private static final int BTN_HEIGHT = 18;
private WndBag owner;
public WndAlchemizeItem(Item item, WndBag owner) {
super(item);
this.owner = owner;
float pos = height;
if (Shopkeeper.canSell(item)) {
if (item.quantity() == 1) {
RedButton btnSell = new RedButton(Messages.get(this, "sell", item.value())) {
@Override
protected void onClick() {
WndTradeItem.sell(item);
consumeAlchemize();
hide();
}
};
btnSell.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnSell.icon(new ItemSprite(ItemSpriteSheet.GOLD));
add(btnSell);
pos = btnSell.bottom();
} else {
int priceAll = item.value();
RedButton btnSell1 = new RedButton(Messages.get(this, "sell_1", priceAll / item.quantity())) {
@Override
protected void onClick() {
WndTradeItem.sellOne(item);
consumeAlchemize();
hide();
}
};
btnSell1.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnSell1.icon(new ItemSprite(ItemSpriteSheet.GOLD));
add(btnSell1);
RedButton btnSellAll = new RedButton(Messages.get(this, "sell_all", priceAll)) {
@Override
protected void onClick() {
WndTradeItem.sell(item);
consumeAlchemize();
hide();
}
};
btnSellAll.setRect(0, btnSell1.bottom() + 1, width, BTN_HEIGHT);
btnSellAll.icon(new ItemSprite(ItemSpriteSheet.GOLD));
add(btnSellAll);
pos = btnSellAll.bottom();
}
}
if (item.energyVal() > 0) {
if (item.quantity() == 1) {
RedButton btnEnergize = new RedButton(Messages.get(this, "energize", item.energyVal())) {
@Override
protected void onClick() {
WndEnergizeItem.energize(item);
consumeAlchemize();
hide();
}
};
btnEnergize.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnEnergize.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergize);
pos = btnEnergize.bottom();
} else {
int energyAll = item.energyVal();
RedButton btnEnergize1 = new RedButton(Messages.get(this, "energize_1", energyAll / item.quantity())) {
@Override
protected void onClick() {
WndEnergizeItem.energizeOne(item);
consumeAlchemize();
hide();
}
};
btnEnergize1.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnEnergize1.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergize1);
RedButton btnEnergizeAll = new RedButton(Messages.get(this, "energize_all", energyAll)) {
@Override
protected void onClick() {
WndEnergizeItem.energize(item);
consumeAlchemize();
hide();
}
};
btnEnergizeAll.setRect(0, btnEnergize1.bottom() + 1, width, BTN_HEIGHT);
btnEnergizeAll.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergizeAll);
|
[
"\t\t\t\t\tpos = btnEnergizeAll.bottom();"
] | 567
|
lcc
|
java
| null |
64d5f26d486a85e85284229e8d254f996cfafd844cd321c5
| 9
|
Your task is code completion.
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2021 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.items.spells;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.ShatteredPixelDungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Shopkeeper;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.AlchemicalCatalyst;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.scenes.AlchemyScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.ui.RedButton;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndBag;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndEnergizeItem;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndImp;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndInfoItem;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndTradeItem;
import com.watabou.noosa.audio.Sample;
public class Alchemize extends Spell {
{
image = ItemSpriteSheet.ALCHEMIZE;
}
@Override
protected void onCast(Hero hero) {
GameScene.selectItem( itemSelector );
}
@Override
public int value() {
//prices of ingredients, divided by output quantity
return Math.round(quantity * (40 / 8f));
}
//TODO also allow alchemical catalyst? Or save that for an elixir/brew?
public static class Recipe extends com.shatteredpixel.shatteredpixeldungeon.items.Recipe.SimpleRecipe {
{
inputs = new Class[]{ArcaneCatalyst.class};
inQuantity = new int[]{1};
cost = 3;
output = Alchemize.class;
outQuantity = 8;
}
}
private static WndBag.ItemSelector itemSelector = new WndBag.ItemSelector() {
@Override
public String textPrompt() {
return Messages.get(Alchemize.class, "prompt");
}
@Override
public boolean itemSelectable(Item item) {
return !(item instanceof Alchemize)
&& (Shopkeeper.canSell(item) || item.energyVal() > 0);
}
@Override
public void onSelect( Item item ) {
if (item != null) {
WndBag parentWnd = GameScene.selectItem( itemSelector );
GameScene.show( new WndAlchemizeItem( item, parentWnd ) );
}
}
};
public static class WndAlchemizeItem extends WndInfoItem {
private static final float GAP = 2;
private static final int BTN_HEIGHT = 18;
private WndBag owner;
public WndAlchemizeItem(Item item, WndBag owner) {
super(item);
this.owner = owner;
float pos = height;
if (Shopkeeper.canSell(item)) {
if (item.quantity() == 1) {
RedButton btnSell = new RedButton(Messages.get(this, "sell", item.value())) {
@Override
protected void onClick() {
WndTradeItem.sell(item);
consumeAlchemize();
hide();
}
};
btnSell.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnSell.icon(new ItemSprite(ItemSpriteSheet.GOLD));
add(btnSell);
pos = btnSell.bottom();
} else {
int priceAll = item.value();
RedButton btnSell1 = new RedButton(Messages.get(this, "sell_1", priceAll / item.quantity())) {
@Override
protected void onClick() {
WndTradeItem.sellOne(item);
consumeAlchemize();
hide();
}
};
btnSell1.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnSell1.icon(new ItemSprite(ItemSpriteSheet.GOLD));
add(btnSell1);
RedButton btnSellAll = new RedButton(Messages.get(this, "sell_all", priceAll)) {
@Override
protected void onClick() {
WndTradeItem.sell(item);
consumeAlchemize();
hide();
}
};
btnSellAll.setRect(0, btnSell1.bottom() + 1, width, BTN_HEIGHT);
btnSellAll.icon(new ItemSprite(ItemSpriteSheet.GOLD));
add(btnSellAll);
pos = btnSellAll.bottom();
}
}
if (item.energyVal() > 0) {
if (item.quantity() == 1) {
RedButton btnEnergize = new RedButton(Messages.get(this, "energize", item.energyVal())) {
@Override
protected void onClick() {
WndEnergizeItem.energize(item);
consumeAlchemize();
hide();
}
};
btnEnergize.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnEnergize.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergize);
pos = btnEnergize.bottom();
} else {
int energyAll = item.energyVal();
RedButton btnEnergize1 = new RedButton(Messages.get(this, "energize_1", energyAll / item.quantity())) {
@Override
protected void onClick() {
WndEnergizeItem.energizeOne(item);
consumeAlchemize();
hide();
}
};
btnEnergize1.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnEnergize1.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergize1);
RedButton btnEnergizeAll = new RedButton(Messages.get(this, "energize_all", energyAll)) {
@Override
protected void onClick() {
WndEnergizeItem.energize(item);
consumeAlchemize();
hide();
}
};
btnEnergizeAll.setRect(0, btnEnergize1.bottom() + 1, width, BTN_HEIGHT);
btnEnergizeAll.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergizeAll);
|
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]
public class Alchemize extends Spell {
// ...
public static class WndAlchemizeItem extends WndInfoItem {
// ...
private WndBag owner;
public WndAlchemizeItem(Item item, WndBag owner) {
super(item);
this.owner = owner;
float pos = height;
// ...
if (item.energyVal() > 0) {
// ...
if (item.quantity() == 1) {
// ...
RedButton btnEnergize = new RedButton(Messages.get(this, "energize", item.energyVal())) {
@Override
protected void onClick() {
WndEnergizeItem.energize(item);
consumeAlchemize();
hide();
}
};
btnEnergize.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnEnergize.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergize);
pos = btnEnergize.bottom();
} else {
// ...
RedButton btnEnergize1 = new RedButton(Messages.get(this, "energize_1", energyAll / item.quantity())) {
@Override
protected void onClick() {
WndEnergizeItem.energizeOne(item);
consumeAlchemize();
hide();
}
};
btnEnergize1.setRect(0, pos + GAP, width, BTN_HEIGHT);
btnEnergize1.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergize1);
RedButton btnEnergizeAll = new RedButton(Messages.get(this, "energize_all", energyAll)) {
@Override
protected void onClick() {
WndEnergizeItem.energize(item);
consumeAlchemize();
hide();
}
};
btnEnergizeAll.setRect(0, btnEnergize1.bottom() + 1, width, BTN_HEIGHT);
btnEnergizeAll.icon(new ItemSprite(ItemSpriteSheet.ENERGY));
add(btnEnergizeAll);
}
}
}
}
}
Cheatsheet (for next line):
- We are in the WndAlchemizeItem class, in the constructor.
- The constructor is initializing the owner field.
- The owner field is a WndBag object.
- The constructor is also initializing the pos variable.
- The pos variable is a float.
- The code is adding buttons to the window.
- The buttons are added to the window using the add() method.
- The add() method is called on the current object (WndAlchemizeItem).
- The buttons are added at a position calculated by the pos variable.
- The pos variable is updated after each button is added.
- The buttons are added in a specific order (quantity == 1, then quantity > 1).
- The buttons are added in a specific order (Energize, then Energize 1, then Energize All).
Next line will likely be: add(btnEnergizeAll);
|
|
Please complete the code given below.
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3, 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 MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
"""Pythonic simple SOAP Server implementation"""
from __future__ import unicode_literals
import sys
import logging
import re
import traceback
try:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
except ImportError:
from http.server import BaseHTTPRequestHandler, HTTPServer
from . import __author__, __copyright__, __license__, __version__
from .simplexml import SimpleXMLElement, TYPE_MAP, Date, Decimal
log = logging.getLogger(__name__)
# Deprecated?
NS_RX = re.compile(r'xmlns:(\w+)="(.+?)"')
class SoapDispatcher(object):
"""Simple Dispatcher for SOAP Server"""
def __init__(self, name, documentation='', action='', location='',
namespace=None, prefix=False,
soap_uri="http://schemas.xmlsoap.org/soap/envelope/",
soap_ns='soap',
namespaces={},
pretty=False,
debug=False,
**kwargs):
"""
:param namespace: Target namespace; xmlns=targetNamespace
:param prefix: Prefix for target namespace; xmlns:prefix=targetNamespace
:param namespaces: Specify additional namespaces; example: {'external': 'http://external.mt.moboperator'}
:param pretty: Prettifies generated xmls
:param debug: Use to add tracebacks in generated xmls.
Multiple namespaces
===================
It is possible to support multiple namespaces.
You need to specify additional namespaces by passing `namespace` parameter.
>>> dispatcher = SoapDispatcher(
... name = "MTClientWS",
... location = "http://localhost:8008/ws/MTClientWS",
... action = 'http://localhost:8008/ws/MTClientWS', # SOAPAction
... namespace = "http://external.mt.moboperator", prefix="external",
... documentation = 'moboperator MTClientWS',
... namespaces = {
... 'external': 'http://external.mt.moboperator',
... 'model': 'http://model.common.mt.moboperator'
... },
... ns = True)
Now the registered method must return node names with namespaces' prefixes.
>>> def _multi_ns_func(self, serviceMsisdn):
... ret = {
... 'external:activateSubscriptionsReturn': [
... {'model:code': '0'},
... {'model:description': 'desc'},
... ]}
... return ret
Our prefixes will be changed to those used by the client.
"""
self.methods = {}
self.name = name
self.documentation = documentation
self.action = action # base SoapAction
self.location = location
self.namespace = namespace # targetNamespace
self.prefix = prefix
self.soap_ns = soap_ns
self.soap_uri = soap_uri
self.namespaces = namespaces
self.pretty = pretty
self.debug = debug
@staticmethod
def _extra_namespaces(xml, ns):
"""Extends xml with extra namespaces.
:param ns: dict with namespaceUrl:prefix pairs
:param xml: XML node to modify
"""
if ns:
_tpl = 'xmlns:%s="%s"'
_ns_str = " ".join([_tpl % (prefix, uri) for uri, prefix in ns.items() if uri not in xml])
xml = xml.replace('/>', ' ' + _ns_str + '/>')
return xml
def register_function(self, name, fn, returns=None, args=None, doc=None):
self.methods[name] = fn, returns, args, doc or getattr(fn, "__doc__", "")
def dispatch(self, xml, action=None):
"""Receive and process SOAP call"""
# default values:
prefix = self.prefix
ret = fault = None
soap_ns, soap_uri = self.soap_ns, self.soap_uri
soap_fault_code = 'VersionMismatch'
name = None
# namespaces = [('model', 'http://model.common.mt.moboperator'), ('external', 'http://external.mt.moboperator')]
_ns_reversed = dict(((v, k) for k, v in self.namespaces.items())) # Switch keys-values
# _ns_reversed = {'http://external.mt.moboperator': 'external', 'http://model.common.mt.moboperator': 'model'}
try:
request = SimpleXMLElement(xml, namespace=self.namespace)
# detect soap prefix and uri (xmlns attributes of Envelope)
for k, v in request[:]:
if v in ("http://schemas.xmlsoap.org/soap/envelope/",
"http://www.w3.org/2003/05/soap-env",):
soap_ns = request.attributes()[k].localName
soap_uri = request.attributes()[k].value
# If the value from attributes on Envelope is in additional namespaces
elif v in self.namespaces.values():
_ns = request.attributes()[k].localName
_uri = request.attributes()[k].value
_ns_reversed[_uri] = _ns # update with received alias
# Now we change 'external' and 'model' to the received forms i.e. 'ext' and 'mod'
# After that we know how the client has prefixed additional namespaces
ns = NS_RX.findall(xml)
for k, v in ns:
if v in self.namespaces.values():
_ns_reversed[v] = k
soap_fault_code = 'Client'
# parse request message and get local method
method = request('Body', ns=soap_uri).children()(0)
if action:
# method name = action
name = action[len(self.action)+1:-1]
prefix = self.prefix
if not action or not name:
# method name = input message name
name = method.get_local_name()
prefix = method.get_prefix()
log.debug('dispatch method: %s', name)
function, returns_types, args_types, doc = self.methods[name]
log.debug('returns_types %s', returns_types)
# de-serialize parameters (if type definitions given)
if args_types:
args = method.children().unmarshall(args_types)
elif args_types is None:
args = {'request': method} # send raw request
else:
args = {} # no parameters
soap_fault_code = 'Server'
# execute function
ret = function(**args)
log.debug('dispathed method returns: %s', ret)
except Exception: # This shouldn't be one huge try/except
import sys
etype, evalue, etb = sys.exc_info()
log.error(traceback.format_exc())
if self.debug:
detail = ''.join(traceback.format_exception(etype, evalue, etb))
detail += '\n\nXML REQUEST\n\n' + xml
else:
detail = None
fault = {'faultcode': "%s.%s" % (soap_fault_code, etype.__name__),
'faultstring': evalue,
'detail': detail}
# build response message
if not prefix:
xml = """<%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s"/>"""
else:
xml = """<%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s"
xmlns:%(prefix)s="%(namespace)s"/>"""
xml %= { # a %= {} is a shortcut for a = a % {}
'namespace': self.namespace,
'prefix': prefix,
'soap_ns': soap_ns,
'soap_uri': soap_uri
}
# Now we add extra namespaces
xml = SoapDispatcher._extra_namespaces(xml, _ns_reversed)
# Change our namespace alias to that given by the client.
# We put [('model', 'http://model.common.mt.moboperator'), ('external', 'http://external.mt.moboperator')]
# mix it with {'http://external.mt.moboperator': 'ext', 'http://model.common.mt.moboperator': 'mod'}
mapping = dict(((k, _ns_reversed[v]) for k, v in self.namespaces.items())) # Switch keys-values and change value
# and get {'model': u'mod', 'external': u'ext'}
response = SimpleXMLElement(xml,
namespace=self.namespace,
namespaces_map=mapping,
prefix=prefix)
response['xmlns:xsi'] = "http://www.w3.org/2001/XMLSchema-instance"
response['xmlns:xsd'] = "http://www.w3.org/2001/XMLSchema"
body = response.add_child("%s:Body" % soap_ns, ns=False)
if fault:
# generate a Soap Fault (with the python exception)
body.marshall("%s:Fault" % soap_ns, fault, ns=False)
else:
# return normal value
res = body.add_child("%sResponse" % name, ns=prefix)
if not prefix:
res['xmlns'] = self.namespace # add target namespace
# serialize returned values (response) if type definition available
if returns_types:
if not isinstance(ret, dict):
res.marshall(returns_types.keys()[0], ret, )
else:
for k, v in ret.items():
res.marshall(k, v)
elif returns_types is None:
# merge xmlelement returned
res.import_node(ret)
elif returns_types == {}:
log.warning('Given returns_types is an empty dict.')
return response.as_xml(pretty=self.pretty)
# Introspection functions:
def list_methods(self):
"""Return a list of aregistered operations"""
return [(method, doc) for method, (function, returns, args, doc) in self.methods.items()]
def help(self, method=None):
"""Generate sample request and response messages"""
(function, returns, args, doc) = self.methods[method]
xml = """
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body><%(method)s xmlns="%(namespace)s"/></soap:Body>
</soap:Envelope>""" % {'method': method, 'namespace': self.namespace}
request = SimpleXMLElement(xml, namespace=self.namespace, prefix=self.prefix)
if args:
items = args.items()
elif args is None:
items = [('value', None)]
else:
items = []
for k, v in items:
request(method).marshall(k, v, add_comments=True, ns=False)
xml = """
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body><%(method)sResponse xmlns="%(namespace)s"/></soap:Body>
</soap:Envelope>""" % {'method': method, 'namespace': self.namespace}
response = SimpleXMLElement(xml, namespace=self.namespace, prefix=self.prefix)
if returns:
items = returns.items()
elif args is None:
items = [('value', None)]
else:
items = []
for k, v in items:
response('%sResponse' % method).marshall(k, v, add_comments=True, ns=False)
return request.as_xml(pretty=True), response.as_xml(pretty=True), doc
def wsdl(self):
"""Generate Web Service Description v1.1"""
xml = """<?xml version="1.0"?>
<wsdl:definitions name="%(name)s"
targetNamespace="%(namespace)s"
xmlns:tns="%(namespace)s"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">%(documentation)s</wsdl:documentation>
<wsdl:types>
<xsd:schema targetNamespace="%(namespace)s"
elementFormDefault="qualified"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
</xsd:schema>
</wsdl:types>
</wsdl:definitions>
""" % {'namespace': self.namespace, 'name': self.name, 'documentation': self.documentation}
wsdl = SimpleXMLElement(xml)
for method, (function, returns, args, doc) in self.methods.items():
# create elements:
def parse_element(name, values, array=False, complex=False):
if not complex:
element = wsdl('wsdl:types')('xsd:schema').add_child('xsd:element')
complex = element.add_child("xsd:complexType")
else:
complex = wsdl('wsdl:types')('xsd:schema').add_child('xsd:complexType')
element = complex
element['name'] = name
if values:
items = values
elif values is None:
items = [('value', None)]
else:
items = []
if not array and items:
all = complex.add_child("xsd:all")
elif items:
all = complex.add_child("xsd:sequence")
for k, v in items:
e = all.add_child("xsd:element")
e['name'] = k
if array:
e[:] = {'minOccurs': "0", 'maxOccurs': "unbounded"}
if v in TYPE_MAP.keys():
t = 'xsd:%s' % TYPE_MAP[v]
elif v is None:
t = 'xsd:anyType'
elif isinstance(v, list):
n = "ArrayOf%s%s" % (name, k)
l = []
for d in v:
l.extend(d.items())
parse_element(n, l, array=True, complex=True)
t = "tns:%s" % n
elif isinstance(v, dict):
n = "%s%s" % (name, k)
parse_element(n, v.items(), complex=True)
t = "tns:%s" % n
e.add_attribute('type', t)
parse_element("%s" % method, args and args.items())
parse_element("%sResponse" % method, returns and returns.items())
# create messages:
for m, e in ('Input', ''), ('Output', 'Response'):
message = wsdl.add_child('wsdl:message')
message['name'] = "%s%s" % (method, m)
part = message.add_child("wsdl:part")
part[:] = {'name': 'parameters',
'element': 'tns:%s%s' % (method, e)}
# create ports
portType = wsdl.add_child('wsdl:portType')
portType['name'] = "%sPortType" % self.name
for method, (function, returns, args, doc) in self.methods.items():
op = portType.add_child('wsdl:operation')
op['name'] = method
if doc:
op.add_child("wsdl:documentation", doc)
input = op.add_child("wsdl:input")
input['message'] = "tns:%sInput" % method
output = op.add_child("wsdl:output")
output['message'] = "tns:%sOutput" % method
# create bindings
binding = wsdl.add_child('wsdl:binding')
binding['name'] = "%sBinding" % self.name
binding['type'] = "tns:%sPortType" % self.name
soapbinding = binding.add_child('soap:binding')
soapbinding['style'] = "document"
soapbinding['transport'] = "http://schemas.xmlsoap.org/soap/http"
for method in self.methods.keys():
op = binding.add_child('wsdl:operation')
op['name'] = method
soapop = op.add_child('soap:operation')
soapop['soapAction'] = self.action + method
soapop['style'] = 'document'
input = op.add_child("wsdl:input")
##input.add_attribute('name', "%sInput" % method)
soapbody = input.add_child("soap:body")
soapbody["use"] = "literal"
output = op.add_child("wsdl:output")
##output.add_attribute('name', "%sOutput" % method)
soapbody = output.add_child("soap:body")
soapbody["use"] = "literal"
service = wsdl.add_child('wsdl:service')
service["name"] = "%sService" % self.name
service.add_child('wsdl:documentation', text=self.documentation)
port = service.add_child('wsdl:port')
port["name"] = "%s" % self.name
port["binding"] = "tns:%sBinding" % self.name
soapaddress = port.add_child('soap:address')
soapaddress["location"] = self.location
return wsdl.as_xml(pretty=True)
class SOAPHandler(BaseHTTPRequestHandler):
def do_GET(self):
"""User viewable help information and wsdl"""
args = self.path[1:].split("?")
if self.path != "/" and args[0] not in self.server.dispatcher.methods.keys():
self.send_error(404, "Method not found: %s" % args[0])
else:
if self.path == "/":
# return wsdl if no method supplied
response = self.server.dispatcher.wsdl()
else:
# return supplied method help (?request or ?response messages)
req, res, doc = self.server.dispatcher.help(args[0])
if len(args) == 1 or args[1] == "request":
response = req
else:
response = res
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.end_headers()
self.wfile.write(response)
def do_POST(self):
"""SOAP POST gateway"""
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.end_headers()
request = self.rfile.read(int(self.headers.getheader('content-length')))
response = self.server.dispatcher.dispatch(request)
self.wfile.write(response)
class WSGISOAPHandler(object):
def __init__(self, dispatcher):
self.dispatcher = dispatcher
def __call__(self, environ, start_response):
return self.handler(environ, start_response)
def handler(self, environ, start_response):
if environ['REQUEST_METHOD'] == 'GET':
return self.do_get(environ, start_response)
elif environ['REQUEST_METHOD'] == 'POST':
return self.do_post(environ, start_response)
else:
start_response('405 Method not allowed', [('Content-Type', 'text/plain')])
return ['Method not allowed']
def do_get(self, environ, start_response):
path = environ.get('PATH_INFO').lstrip('/')
query = environ.get('QUERY_STRING')
if path != "" and path not in self.dispatcher.methods.keys():
start_response('404 Not Found', [('Content-Type', 'text/plain')])
return ["Method not found: %s" % path]
elif path == "":
# return wsdl if no method supplied
response = self.dispatcher.wsdl()
else:
# return supplied method help (?request or ?response messages)
req, res, doc = self.dispatcher.help(path)
if len(query) == 0 or query == "request":
response = req
else:
response = res
start_response('200 OK', [('Content-Type', 'text/xml'), ('Content-Length', str(len(response)))])
return [response]
def do_post(self, environ, start_response):
|
[
" length = int(environ['CONTENT_LENGTH'])"
] | 1,670
|
lcc
|
python
| null |
8ae06de3dd26783213ae72552d610c4f1518647b7898d383
| 10
|
Your task is code completion.
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3, 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 MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
"""Pythonic simple SOAP Server implementation"""
from __future__ import unicode_literals
import sys
import logging
import re
import traceback
try:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
except ImportError:
from http.server import BaseHTTPRequestHandler, HTTPServer
from . import __author__, __copyright__, __license__, __version__
from .simplexml import SimpleXMLElement, TYPE_MAP, Date, Decimal
log = logging.getLogger(__name__)
# Deprecated?
NS_RX = re.compile(r'xmlns:(\w+)="(.+?)"')
class SoapDispatcher(object):
"""Simple Dispatcher for SOAP Server"""
def __init__(self, name, documentation='', action='', location='',
namespace=None, prefix=False,
soap_uri="http://schemas.xmlsoap.org/soap/envelope/",
soap_ns='soap',
namespaces={},
pretty=False,
debug=False,
**kwargs):
"""
:param namespace: Target namespace; xmlns=targetNamespace
:param prefix: Prefix for target namespace; xmlns:prefix=targetNamespace
:param namespaces: Specify additional namespaces; example: {'external': 'http://external.mt.moboperator'}
:param pretty: Prettifies generated xmls
:param debug: Use to add tracebacks in generated xmls.
Multiple namespaces
===================
It is possible to support multiple namespaces.
You need to specify additional namespaces by passing `namespace` parameter.
>>> dispatcher = SoapDispatcher(
... name = "MTClientWS",
... location = "http://localhost:8008/ws/MTClientWS",
... action = 'http://localhost:8008/ws/MTClientWS', # SOAPAction
... namespace = "http://external.mt.moboperator", prefix="external",
... documentation = 'moboperator MTClientWS',
... namespaces = {
... 'external': 'http://external.mt.moboperator',
... 'model': 'http://model.common.mt.moboperator'
... },
... ns = True)
Now the registered method must return node names with namespaces' prefixes.
>>> def _multi_ns_func(self, serviceMsisdn):
... ret = {
... 'external:activateSubscriptionsReturn': [
... {'model:code': '0'},
... {'model:description': 'desc'},
... ]}
... return ret
Our prefixes will be changed to those used by the client.
"""
self.methods = {}
self.name = name
self.documentation = documentation
self.action = action # base SoapAction
self.location = location
self.namespace = namespace # targetNamespace
self.prefix = prefix
self.soap_ns = soap_ns
self.soap_uri = soap_uri
self.namespaces = namespaces
self.pretty = pretty
self.debug = debug
@staticmethod
def _extra_namespaces(xml, ns):
"""Extends xml with extra namespaces.
:param ns: dict with namespaceUrl:prefix pairs
:param xml: XML node to modify
"""
if ns:
_tpl = 'xmlns:%s="%s"'
_ns_str = " ".join([_tpl % (prefix, uri) for uri, prefix in ns.items() if uri not in xml])
xml = xml.replace('/>', ' ' + _ns_str + '/>')
return xml
def register_function(self, name, fn, returns=None, args=None, doc=None):
self.methods[name] = fn, returns, args, doc or getattr(fn, "__doc__", "")
def dispatch(self, xml, action=None):
"""Receive and process SOAP call"""
# default values:
prefix = self.prefix
ret = fault = None
soap_ns, soap_uri = self.soap_ns, self.soap_uri
soap_fault_code = 'VersionMismatch'
name = None
# namespaces = [('model', 'http://model.common.mt.moboperator'), ('external', 'http://external.mt.moboperator')]
_ns_reversed = dict(((v, k) for k, v in self.namespaces.items())) # Switch keys-values
# _ns_reversed = {'http://external.mt.moboperator': 'external', 'http://model.common.mt.moboperator': 'model'}
try:
request = SimpleXMLElement(xml, namespace=self.namespace)
# detect soap prefix and uri (xmlns attributes of Envelope)
for k, v in request[:]:
if v in ("http://schemas.xmlsoap.org/soap/envelope/",
"http://www.w3.org/2003/05/soap-env",):
soap_ns = request.attributes()[k].localName
soap_uri = request.attributes()[k].value
# If the value from attributes on Envelope is in additional namespaces
elif v in self.namespaces.values():
_ns = request.attributes()[k].localName
_uri = request.attributes()[k].value
_ns_reversed[_uri] = _ns # update with received alias
# Now we change 'external' and 'model' to the received forms i.e. 'ext' and 'mod'
# After that we know how the client has prefixed additional namespaces
ns = NS_RX.findall(xml)
for k, v in ns:
if v in self.namespaces.values():
_ns_reversed[v] = k
soap_fault_code = 'Client'
# parse request message and get local method
method = request('Body', ns=soap_uri).children()(0)
if action:
# method name = action
name = action[len(self.action)+1:-1]
prefix = self.prefix
if not action or not name:
# method name = input message name
name = method.get_local_name()
prefix = method.get_prefix()
log.debug('dispatch method: %s', name)
function, returns_types, args_types, doc = self.methods[name]
log.debug('returns_types %s', returns_types)
# de-serialize parameters (if type definitions given)
if args_types:
args = method.children().unmarshall(args_types)
elif args_types is None:
args = {'request': method} # send raw request
else:
args = {} # no parameters
soap_fault_code = 'Server'
# execute function
ret = function(**args)
log.debug('dispathed method returns: %s', ret)
except Exception: # This shouldn't be one huge try/except
import sys
etype, evalue, etb = sys.exc_info()
log.error(traceback.format_exc())
if self.debug:
detail = ''.join(traceback.format_exception(etype, evalue, etb))
detail += '\n\nXML REQUEST\n\n' + xml
else:
detail = None
fault = {'faultcode': "%s.%s" % (soap_fault_code, etype.__name__),
'faultstring': evalue,
'detail': detail}
# build response message
if not prefix:
xml = """<%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s"/>"""
else:
xml = """<%(soap_ns)s:Envelope xmlns:%(soap_ns)s="%(soap_uri)s"
xmlns:%(prefix)s="%(namespace)s"/>"""
xml %= { # a %= {} is a shortcut for a = a % {}
'namespace': self.namespace,
'prefix': prefix,
'soap_ns': soap_ns,
'soap_uri': soap_uri
}
# Now we add extra namespaces
xml = SoapDispatcher._extra_namespaces(xml, _ns_reversed)
# Change our namespace alias to that given by the client.
# We put [('model', 'http://model.common.mt.moboperator'), ('external', 'http://external.mt.moboperator')]
# mix it with {'http://external.mt.moboperator': 'ext', 'http://model.common.mt.moboperator': 'mod'}
mapping = dict(((k, _ns_reversed[v]) for k, v in self.namespaces.items())) # Switch keys-values and change value
# and get {'model': u'mod', 'external': u'ext'}
response = SimpleXMLElement(xml,
namespace=self.namespace,
namespaces_map=mapping,
prefix=prefix)
response['xmlns:xsi'] = "http://www.w3.org/2001/XMLSchema-instance"
response['xmlns:xsd'] = "http://www.w3.org/2001/XMLSchema"
body = response.add_child("%s:Body" % soap_ns, ns=False)
if fault:
# generate a Soap Fault (with the python exception)
body.marshall("%s:Fault" % soap_ns, fault, ns=False)
else:
# return normal value
res = body.add_child("%sResponse" % name, ns=prefix)
if not prefix:
res['xmlns'] = self.namespace # add target namespace
# serialize returned values (response) if type definition available
if returns_types:
if not isinstance(ret, dict):
res.marshall(returns_types.keys()[0], ret, )
else:
for k, v in ret.items():
res.marshall(k, v)
elif returns_types is None:
# merge xmlelement returned
res.import_node(ret)
elif returns_types == {}:
log.warning('Given returns_types is an empty dict.')
return response.as_xml(pretty=self.pretty)
# Introspection functions:
def list_methods(self):
"""Return a list of aregistered operations"""
return [(method, doc) for method, (function, returns, args, doc) in self.methods.items()]
def help(self, method=None):
"""Generate sample request and response messages"""
(function, returns, args, doc) = self.methods[method]
xml = """
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body><%(method)s xmlns="%(namespace)s"/></soap:Body>
</soap:Envelope>""" % {'method': method, 'namespace': self.namespace}
request = SimpleXMLElement(xml, namespace=self.namespace, prefix=self.prefix)
if args:
items = args.items()
elif args is None:
items = [('value', None)]
else:
items = []
for k, v in items:
request(method).marshall(k, v, add_comments=True, ns=False)
xml = """
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body><%(method)sResponse xmlns="%(namespace)s"/></soap:Body>
</soap:Envelope>""" % {'method': method, 'namespace': self.namespace}
response = SimpleXMLElement(xml, namespace=self.namespace, prefix=self.prefix)
if returns:
items = returns.items()
elif args is None:
items = [('value', None)]
else:
items = []
for k, v in items:
response('%sResponse' % method).marshall(k, v, add_comments=True, ns=False)
return request.as_xml(pretty=True), response.as_xml(pretty=True), doc
def wsdl(self):
"""Generate Web Service Description v1.1"""
xml = """<?xml version="1.0"?>
<wsdl:definitions name="%(name)s"
targetNamespace="%(namespace)s"
xmlns:tns="%(namespace)s"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">%(documentation)s</wsdl:documentation>
<wsdl:types>
<xsd:schema targetNamespace="%(namespace)s"
elementFormDefault="qualified"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
</xsd:schema>
</wsdl:types>
</wsdl:definitions>
""" % {'namespace': self.namespace, 'name': self.name, 'documentation': self.documentation}
wsdl = SimpleXMLElement(xml)
for method, (function, returns, args, doc) in self.methods.items():
# create elements:
def parse_element(name, values, array=False, complex=False):
if not complex:
element = wsdl('wsdl:types')('xsd:schema').add_child('xsd:element')
complex = element.add_child("xsd:complexType")
else:
complex = wsdl('wsdl:types')('xsd:schema').add_child('xsd:complexType')
element = complex
element['name'] = name
if values:
items = values
elif values is None:
items = [('value', None)]
else:
items = []
if not array and items:
all = complex.add_child("xsd:all")
elif items:
all = complex.add_child("xsd:sequence")
for k, v in items:
e = all.add_child("xsd:element")
e['name'] = k
if array:
e[:] = {'minOccurs': "0", 'maxOccurs': "unbounded"}
if v in TYPE_MAP.keys():
t = 'xsd:%s' % TYPE_MAP[v]
elif v is None:
t = 'xsd:anyType'
elif isinstance(v, list):
n = "ArrayOf%s%s" % (name, k)
l = []
for d in v:
l.extend(d.items())
parse_element(n, l, array=True, complex=True)
t = "tns:%s" % n
elif isinstance(v, dict):
n = "%s%s" % (name, k)
parse_element(n, v.items(), complex=True)
t = "tns:%s" % n
e.add_attribute('type', t)
parse_element("%s" % method, args and args.items())
parse_element("%sResponse" % method, returns and returns.items())
# create messages:
for m, e in ('Input', ''), ('Output', 'Response'):
message = wsdl.add_child('wsdl:message')
message['name'] = "%s%s" % (method, m)
part = message.add_child("wsdl:part")
part[:] = {'name': 'parameters',
'element': 'tns:%s%s' % (method, e)}
# create ports
portType = wsdl.add_child('wsdl:portType')
portType['name'] = "%sPortType" % self.name
for method, (function, returns, args, doc) in self.methods.items():
op = portType.add_child('wsdl:operation')
op['name'] = method
if doc:
op.add_child("wsdl:documentation", doc)
input = op.add_child("wsdl:input")
input['message'] = "tns:%sInput" % method
output = op.add_child("wsdl:output")
output['message'] = "tns:%sOutput" % method
# create bindings
binding = wsdl.add_child('wsdl:binding')
binding['name'] = "%sBinding" % self.name
binding['type'] = "tns:%sPortType" % self.name
soapbinding = binding.add_child('soap:binding')
soapbinding['style'] = "document"
soapbinding['transport'] = "http://schemas.xmlsoap.org/soap/http"
for method in self.methods.keys():
op = binding.add_child('wsdl:operation')
op['name'] = method
soapop = op.add_child('soap:operation')
soapop['soapAction'] = self.action + method
soapop['style'] = 'document'
input = op.add_child("wsdl:input")
##input.add_attribute('name', "%sInput" % method)
soapbody = input.add_child("soap:body")
soapbody["use"] = "literal"
output = op.add_child("wsdl:output")
##output.add_attribute('name', "%sOutput" % method)
soapbody = output.add_child("soap:body")
soapbody["use"] = "literal"
service = wsdl.add_child('wsdl:service')
service["name"] = "%sService" % self.name
service.add_child('wsdl:documentation', text=self.documentation)
port = service.add_child('wsdl:port')
port["name"] = "%s" % self.name
port["binding"] = "tns:%sBinding" % self.name
soapaddress = port.add_child('soap:address')
soapaddress["location"] = self.location
return wsdl.as_xml(pretty=True)
class SOAPHandler(BaseHTTPRequestHandler):
def do_GET(self):
"""User viewable help information and wsdl"""
args = self.path[1:].split("?")
if self.path != "/" and args[0] not in self.server.dispatcher.methods.keys():
self.send_error(404, "Method not found: %s" % args[0])
else:
if self.path == "/":
# return wsdl if no method supplied
response = self.server.dispatcher.wsdl()
else:
# return supplied method help (?request or ?response messages)
req, res, doc = self.server.dispatcher.help(args[0])
if len(args) == 1 or args[1] == "request":
response = req
else:
response = res
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.end_headers()
self.wfile.write(response)
def do_POST(self):
"""SOAP POST gateway"""
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.end_headers()
request = self.rfile.read(int(self.headers.getheader('content-length')))
response = self.server.dispatcher.dispatch(request)
self.wfile.write(response)
class WSGISOAPHandler(object):
def __init__(self, dispatcher):
self.dispatcher = dispatcher
def __call__(self, environ, start_response):
return self.handler(environ, start_response)
def handler(self, environ, start_response):
if environ['REQUEST_METHOD'] == 'GET':
return self.do_get(environ, start_response)
elif environ['REQUEST_METHOD'] == 'POST':
return self.do_post(environ, start_response)
else:
start_response('405 Method not allowed', [('Content-Type', 'text/plain')])
return ['Method not allowed']
def do_get(self, environ, start_response):
path = environ.get('PATH_INFO').lstrip('/')
query = environ.get('QUERY_STRING')
if path != "" and path not in self.dispatcher.methods.keys():
start_response('404 Not Found', [('Content-Type', 'text/plain')])
return ["Method not found: %s" % path]
elif path == "":
# return wsdl if no method supplied
response = self.dispatcher.wsdl()
else:
# return supplied method help (?request or ?response messages)
req, res, doc = self.dispatcher.help(path)
if len(query) == 0 or query == "request":
response = req
else:
response = res
start_response('200 OK', [('Content-Type', 'text/xml'), ('Content-Length', str(len(response)))])
return [response]
def do_post(self, environ, start_response):
|
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]
def do_post(self, environ, start_response):
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.end_headers()
request = self.rfile.read(int(self.headers.getheader('content-length')))
response = self.server.dispatcher.dispatch(request)
self.wfile.write(response)
Cheatsheet (for next line):
- We are in do_post(), which handles the POST request.
- The POST request has been read and dispatched.
- The response has been generated by the dispatcher.
- The response needs to be sent back to the client.
- The relevant lines are the ones that handle the response in the do_POST method.
Next line will likely be: return [response]
|
|
Please complete the code given below.
# -*- coding: utf-8 -*-
# Qt widget to implement statuses column in Turpial
#from PyQt4 import QtCore
from PyQt4.QtCore import Qt
from PyQt4.QtCore import QSize
from PyQt4.QtCore import QRect
from PyQt4.QtCore import QLine
from PyQt4.QtGui import QFont
from PyQt4.QtGui import QColor
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QPixmap
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QTextDocument
from PyQt4.QtGui import QStyledItemDelegate
from PyQt4.QtGui import QVBoxLayout, QHBoxLayout
from turpial.ui.lang import i18n
from turpial.ui.qt.widgets import ImageButton, BarLoadIndicator
from turpial.ui.qt.webview import StatusesWebView
from libturpial.common import get_preview_service_from_url, unescape_list_name, OS_MAC
from libturpial.common.tools import get_account_id_from, get_column_slug_from, get_protocol_from,\
get_username_from, detect_os
class StatusesColumn(QWidget):
NOTIFICATION_ERROR = 'error'
NOTIFICATION_SUCCESS = 'success'
NOTIFICATION_WARNING = 'warning'
NOTIFICATION_INFO = 'notice'
def __init__(self, base, column_id, include_header=True):
QWidget.__init__(self)
self.base = base
self.setMinimumWidth(280)
self.statuses = []
self.conversations = {}
self.id_ = None
#self.fgcolor = "#e3e3e3"
#self.fgcolor = "#f9a231"
#self.updating = False
self.last_id = None
self.loader = BarLoadIndicator()
self.loader.setVisible(False)
self.webview = StatusesWebView(self.base, self.id_)
self.webview.link_clicked.connect(self.__link_clicked)
self.webview.hashtag_clicked.connect(self.__hashtag_clicked)
self.webview.profile_clicked.connect(self.__profile_clicked)
self.webview.cmd_clicked.connect(self.__cmd_clicked)
layout = QVBoxLayout()
layout.setSpacing(0)
layout.setContentsMargins(0, 0, 0, 0)
if include_header:
header = self.__build_header(column_id)
layout.addWidget(header)
layout.addWidget(self.loader)
layout.addWidget(self.webview, 1)
self.setLayout(layout)
def __build_header(self, column_id):
self.set_column_id(column_id)
username = get_username_from(self.account_id)
column_slug = get_column_slug_from(column_id)
column_slug = unescape_list_name(column_slug)
column_slug = column_slug.replace('%23', '#')
column_slug = column_slug.replace('%40', '@')
#font = QFont('Titillium Web', 18, QFont.Normal, False)
# This is to handle the 96dpi vs 72dpi screen resolutions on Mac vs the world
if detect_os() == OS_MAC:
font = QFont('Maven Pro Light', 25, 0, False)
font2 = QFont('Monda', 14, 0, False)
else:
font = QFont('Maven Pro Light', 16, QFont.Light, False)
font2 = QFont('Monda', 10, QFont.Light, False)
bg_style = "background-color: %s; color: %s;" % (self.base.bgcolor, self.base.fgcolor)
caption = QLabel(username)
caption.setStyleSheet("QLabel { %s }" % bg_style)
caption.setFont(font)
caption2 = QLabel(column_slug)
caption2.setStyleSheet("QLabel { %s }" % bg_style)
caption2.setFont(font2)
caption2.setAlignment(Qt.AlignLeft | Qt.AlignBottom)
caption_box = QHBoxLayout()
caption_box.setSpacing(8)
caption_box.addWidget(caption)
caption_box.addWidget(caption2)
caption_box.addStretch(1)
close_button = ImageButton(self.base, 'action-delete-shadowed.png', i18n.get('delete_column'))
close_button.clicked.connect(self.__delete_column)
header_layout = QHBoxLayout()
header_layout.addLayout(caption_box, 1)
header_layout.addWidget(close_button)
header = QWidget()
header.setStyleSheet("QWidget { %s }" % bg_style)
header.setLayout(header_layout)
return header
def __delete_column(self):
self.base.core.delete_column(self.id_)
def __link_clicked(self, url):
url = str(url)
preview_service = get_preview_service_from_url(url)
self.base.open_url(url)
def __hashtag_clicked(self, hashtag):
self.base.add_search_column(self.account_id, str(hashtag))
def __profile_clicked(self, username):
self.base.show_profile_dialog(self.account_id, str(username))
def __cmd_clicked(self, url):
status_id = str(url.split(':')[1])
cmd = url.split(':')[0]
status = None
try:
print 'Seeking for status in self array'
for status_ in self.statuses:
if status_.id_ == status_id:
status = status_
break
if status is None:
raise KeyError
except KeyError:
print 'Seeking for status in conversations array'
for status_root, statuses in self.conversations.iteritems():
for item in statuses:
if item.id_ == status_id:
status = item
break
if status is not None:
break
if status is None:
self.notify_error(status_id, i18n.get('try_again'))
if cmd == 'reply':
self.__reply_status(status)
elif cmd == 'quote':
self.__quote_status(status)
elif cmd == 'repeat':
self.__repeat_status(status)
elif cmd == 'delete':
self.__delete_status(status)
elif cmd == 'favorite':
self.__mark_status_as_favorite(status)
elif cmd == 'unfavorite':
self.__unmark_status_as_favorite(status)
elif cmd == 'delete_direct':
self.__delete_direct_message(status)
elif cmd == 'reply_direct':
self.__reply_direct_message(status)
elif cmd == 'view_conversation':
self.__view_conversation(status)
elif cmd == 'hide_conversation':
self.__hide_conversation(status)
elif cmd == 'show_avatar':
self.__show_avatar(status)
def __reply_status(self, status):
self.base.show_update_box_for_reply(self.account_id, status)
def __quote_status(self, status):
self.base.show_update_box_for_quote(self.account_id, status)
def __repeat_status(self, status):
confirmation = self.base.show_confirmation_message(i18n.get('confirm_retweet'),
i18n.get('do_you_want_to_retweet_status'))
if confirmation:
self.lock_status(status.id_)
self.base.repeat_status(self.id_, self.account_id, status)
def __delete_status(self, status):
confirmation = self.base.show_confirmation_message(i18n.get('confirm_delete'),
i18n.get('do_you_want_to_delete_status'))
if confirmation:
self.lock_status(status.id_)
self.base.delete_status(self.id_, self.account_id, status)
def __delete_direct_message(self, status):
confirmation = self.base.show_confirmation_message(i18n.get('confirm_delete'),
i18n.get('do_you_want_to_delete_direct_message'))
if confirmation:
self.lock_status(status.id_)
self.base.delete_direct_message(self.id_, self.account_id, status)
def __reply_direct_message(self, status):
self.base.show_update_box_for_reply_direct(self.account_id, status)
def __mark_status_as_favorite(self, status):
self.lock_status(status.id_)
self.base.mark_status_as_favorite(self.id_, self.account_id, status)
def __unmark_status_as_favorite(self, status):
self.lock_status(status.id_)
self.base.unmark_status_as_favorite(self.id_, self.account_id, status)
def __view_conversation(self, status):
self.webview.view_conversation(status.id_)
self.base.get_conversation(self.account_id, status, self.id_, status.id_)
def __hide_conversation(self, status):
del self.conversations[status.id_]
self.webview.clear_conversation(status.id_)
def __show_avatar(self, status):
self.base.show_profile_image(self.account_id, status.username)
def __set_last_status_id(self, statuses):
if statuses[0].repeated_by:
self.last_id = statuses[0].original_status_id
else:
self.last_id = statuses[0].id_
def set_column_id(self, column_id):
self.id_ = column_id
self.account_id = get_account_id_from(column_id)
self.protocol_id = get_protocol_from(self.account_id)
self.webview.column_id = column_id
def clear(self):
self.webview.clear()
def start_updating(self):
self.loader.setVisible(True)
return self.last_id
def stop_updating(self):
self.loader.setVisible(False)
def update_timestamps(self):
self.webview.sync_timestamps(self.statuses)
def update_statuses(self, statuses):
self.__set_last_status_id(statuses)
self.update_timestamps()
self.webview.update_statuses(statuses)
# Filter repeated statuses
unique_statuses = [s1 for s1 in statuses if s1 not in self.statuses]
# Remove old conversations
to_remove = self.statuses[-(len(unique_statuses)):]
self.statuses = statuses + self.statuses[: -(len(unique_statuses))]
for status in to_remove:
if self.conversations.has_key(status.id_):
del self.conversations[status.id_]
def update_conversation(self, status, status_root_id):
status_root_id = str(status_root_id)
self.webview.update_conversation(status, status_root_id)
if status_root_id in self.conversations:
self.conversations[status_root_id].append(status)
else:
self.conversations[status_root_id] = [status]
def error_in_conversation(self, status_root_id):
self.webview.clear_conversation(status_root_id)
def mark_status_as_favorite(self, status_id):
mark = "setFavorite('%s')" % status_id
self.webview.execute_javascript(mark)
def unmark_status_as_favorite(self, status_id):
mark = "unsetFavorite('%s');" % status_id
self.webview.execute_javascript(mark)
def mark_status_as_repeated(self, status_id):
|
[
" mark = \"setRepeated('%s');\" % status_id"
] | 686
|
lcc
|
python
| null |
14de6afab15eabeb4fec480f9d6b4db78e93e0493851cc35
| 11
|
Your task is code completion.
# -*- coding: utf-8 -*-
# Qt widget to implement statuses column in Turpial
#from PyQt4 import QtCore
from PyQt4.QtCore import Qt
from PyQt4.QtCore import QSize
from PyQt4.QtCore import QRect
from PyQt4.QtCore import QLine
from PyQt4.QtGui import QFont
from PyQt4.QtGui import QColor
from PyQt4.QtGui import QLabel
from PyQt4.QtGui import QPixmap
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QTextDocument
from PyQt4.QtGui import QStyledItemDelegate
from PyQt4.QtGui import QVBoxLayout, QHBoxLayout
from turpial.ui.lang import i18n
from turpial.ui.qt.widgets import ImageButton, BarLoadIndicator
from turpial.ui.qt.webview import StatusesWebView
from libturpial.common import get_preview_service_from_url, unescape_list_name, OS_MAC
from libturpial.common.tools import get_account_id_from, get_column_slug_from, get_protocol_from,\
get_username_from, detect_os
class StatusesColumn(QWidget):
NOTIFICATION_ERROR = 'error'
NOTIFICATION_SUCCESS = 'success'
NOTIFICATION_WARNING = 'warning'
NOTIFICATION_INFO = 'notice'
def __init__(self, base, column_id, include_header=True):
QWidget.__init__(self)
self.base = base
self.setMinimumWidth(280)
self.statuses = []
self.conversations = {}
self.id_ = None
#self.fgcolor = "#e3e3e3"
#self.fgcolor = "#f9a231"
#self.updating = False
self.last_id = None
self.loader = BarLoadIndicator()
self.loader.setVisible(False)
self.webview = StatusesWebView(self.base, self.id_)
self.webview.link_clicked.connect(self.__link_clicked)
self.webview.hashtag_clicked.connect(self.__hashtag_clicked)
self.webview.profile_clicked.connect(self.__profile_clicked)
self.webview.cmd_clicked.connect(self.__cmd_clicked)
layout = QVBoxLayout()
layout.setSpacing(0)
layout.setContentsMargins(0, 0, 0, 0)
if include_header:
header = self.__build_header(column_id)
layout.addWidget(header)
layout.addWidget(self.loader)
layout.addWidget(self.webview, 1)
self.setLayout(layout)
def __build_header(self, column_id):
self.set_column_id(column_id)
username = get_username_from(self.account_id)
column_slug = get_column_slug_from(column_id)
column_slug = unescape_list_name(column_slug)
column_slug = column_slug.replace('%23', '#')
column_slug = column_slug.replace('%40', '@')
#font = QFont('Titillium Web', 18, QFont.Normal, False)
# This is to handle the 96dpi vs 72dpi screen resolutions on Mac vs the world
if detect_os() == OS_MAC:
font = QFont('Maven Pro Light', 25, 0, False)
font2 = QFont('Monda', 14, 0, False)
else:
font = QFont('Maven Pro Light', 16, QFont.Light, False)
font2 = QFont('Monda', 10, QFont.Light, False)
bg_style = "background-color: %s; color: %s;" % (self.base.bgcolor, self.base.fgcolor)
caption = QLabel(username)
caption.setStyleSheet("QLabel { %s }" % bg_style)
caption.setFont(font)
caption2 = QLabel(column_slug)
caption2.setStyleSheet("QLabel { %s }" % bg_style)
caption2.setFont(font2)
caption2.setAlignment(Qt.AlignLeft | Qt.AlignBottom)
caption_box = QHBoxLayout()
caption_box.setSpacing(8)
caption_box.addWidget(caption)
caption_box.addWidget(caption2)
caption_box.addStretch(1)
close_button = ImageButton(self.base, 'action-delete-shadowed.png', i18n.get('delete_column'))
close_button.clicked.connect(self.__delete_column)
header_layout = QHBoxLayout()
header_layout.addLayout(caption_box, 1)
header_layout.addWidget(close_button)
header = QWidget()
header.setStyleSheet("QWidget { %s }" % bg_style)
header.setLayout(header_layout)
return header
def __delete_column(self):
self.base.core.delete_column(self.id_)
def __link_clicked(self, url):
url = str(url)
preview_service = get_preview_service_from_url(url)
self.base.open_url(url)
def __hashtag_clicked(self, hashtag):
self.base.add_search_column(self.account_id, str(hashtag))
def __profile_clicked(self, username):
self.base.show_profile_dialog(self.account_id, str(username))
def __cmd_clicked(self, url):
status_id = str(url.split(':')[1])
cmd = url.split(':')[0]
status = None
try:
print 'Seeking for status in self array'
for status_ in self.statuses:
if status_.id_ == status_id:
status = status_
break
if status is None:
raise KeyError
except KeyError:
print 'Seeking for status in conversations array'
for status_root, statuses in self.conversations.iteritems():
for item in statuses:
if item.id_ == status_id:
status = item
break
if status is not None:
break
if status is None:
self.notify_error(status_id, i18n.get('try_again'))
if cmd == 'reply':
self.__reply_status(status)
elif cmd == 'quote':
self.__quote_status(status)
elif cmd == 'repeat':
self.__repeat_status(status)
elif cmd == 'delete':
self.__delete_status(status)
elif cmd == 'favorite':
self.__mark_status_as_favorite(status)
elif cmd == 'unfavorite':
self.__unmark_status_as_favorite(status)
elif cmd == 'delete_direct':
self.__delete_direct_message(status)
elif cmd == 'reply_direct':
self.__reply_direct_message(status)
elif cmd == 'view_conversation':
self.__view_conversation(status)
elif cmd == 'hide_conversation':
self.__hide_conversation(status)
elif cmd == 'show_avatar':
self.__show_avatar(status)
def __reply_status(self, status):
self.base.show_update_box_for_reply(self.account_id, status)
def __quote_status(self, status):
self.base.show_update_box_for_quote(self.account_id, status)
def __repeat_status(self, status):
confirmation = self.base.show_confirmation_message(i18n.get('confirm_retweet'),
i18n.get('do_you_want_to_retweet_status'))
if confirmation:
self.lock_status(status.id_)
self.base.repeat_status(self.id_, self.account_id, status)
def __delete_status(self, status):
confirmation = self.base.show_confirmation_message(i18n.get('confirm_delete'),
i18n.get('do_you_want_to_delete_status'))
if confirmation:
self.lock_status(status.id_)
self.base.delete_status(self.id_, self.account_id, status)
def __delete_direct_message(self, status):
confirmation = self.base.show_confirmation_message(i18n.get('confirm_delete'),
i18n.get('do_you_want_to_delete_direct_message'))
if confirmation:
self.lock_status(status.id_)
self.base.delete_direct_message(self.id_, self.account_id, status)
def __reply_direct_message(self, status):
self.base.show_update_box_for_reply_direct(self.account_id, status)
def __mark_status_as_favorite(self, status):
self.lock_status(status.id_)
self.base.mark_status_as_favorite(self.id_, self.account_id, status)
def __unmark_status_as_favorite(self, status):
self.lock_status(status.id_)
self.base.unmark_status_as_favorite(self.id_, self.account_id, status)
def __view_conversation(self, status):
self.webview.view_conversation(status.id_)
self.base.get_conversation(self.account_id, status, self.id_, status.id_)
def __hide_conversation(self, status):
del self.conversations[status.id_]
self.webview.clear_conversation(status.id_)
def __show_avatar(self, status):
self.base.show_profile_image(self.account_id, status.username)
def __set_last_status_id(self, statuses):
if statuses[0].repeated_by:
self.last_id = statuses[0].original_status_id
else:
self.last_id = statuses[0].id_
def set_column_id(self, column_id):
self.id_ = column_id
self.account_id = get_account_id_from(column_id)
self.protocol_id = get_protocol_from(self.account_id)
self.webview.column_id = column_id
def clear(self):
self.webview.clear()
def start_updating(self):
self.loader.setVisible(True)
return self.last_id
def stop_updating(self):
self.loader.setVisible(False)
def update_timestamps(self):
self.webview.sync_timestamps(self.statuses)
def update_statuses(self, statuses):
self.__set_last_status_id(statuses)
self.update_timestamps()
self.webview.update_statuses(statuses)
# Filter repeated statuses
unique_statuses = [s1 for s1 in statuses if s1 not in self.statuses]
# Remove old conversations
to_remove = self.statuses[-(len(unique_statuses)):]
self.statuses = statuses + self.statuses[: -(len(unique_statuses))]
for status in to_remove:
if self.conversations.has_key(status.id_):
del self.conversations[status.id_]
def update_conversation(self, status, status_root_id):
status_root_id = str(status_root_id)
self.webview.update_conversation(status, status_root_id)
if status_root_id in self.conversations:
self.conversations[status_root_id].append(status)
else:
self.conversations[status_root_id] = [status]
def error_in_conversation(self, status_root_id):
self.webview.clear_conversation(status_root_id)
def mark_status_as_favorite(self, status_id):
mark = "setFavorite('%s')" % status_id
self.webview.execute_javascript(mark)
def unmark_status_as_favorite(self, status_id):
mark = "unsetFavorite('%s');" % status_id
self.webview.execute_javascript(mark)
def mark_status_as_repeated(self, status_id):
|
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 mark_status_as_repeated(self, status_id):
[Relevant lines: mark_status_as_favorite, unmark_status_as_favorite, update_statuses, update_conversation, error_in_conversation, mark_status_as_favorite, unmark_status_as_favorite]
Cheatsheet (for next line):
- We are in mark_status_as_repeated, which seems to be a method to mark a status as repeated.
- There is a similar method mark_status_as_favorite that marks a status as favorite.
- There is a method update_statuses that updates the statuses.
- There is a method update_conversation that updates a conversation.
- There is a method error_in_conversation that clears a conversation.
- The method mark_status_as_favorite and unmark_status_as_favorite interact with the webview to execute JavaScript commands.
- The method mark_status_as_repeated seems to be missing a similar interaction with the webview.
Based on this, the next line of code is likely to be:
- A call to a method that interacts with the webview to execute a JavaScript command to mark the status as repeated.
Possible next line:
```python
self.webview.execute_javascript("setRepeated('%s');" % status_id)
```
However, this is just a guess based on the available information. The actual next line of code might be different depending on the exact requirements of the mark_status_as_repeated method.
|
|
Please complete the code given below.
import pprint
import select
import traceback
from multiprocessing import Pipe, Process
from beget_msgpack import Controller
from base.exc import Error
from lib.FileManager import FM
from lib.FileManager.OperationStatus import OperationStatus
from lib.FileManager.workers.sftp.analyzeSize import AnalyzeSize
from lib.FileManager.workers.sftp.chmodFiles import ChmodFiles
from lib.FileManager.workers.sftp.copyBetweenSftp import CopyBetweenSftp
from lib.FileManager.workers.sftp.copyFromSftp import CopyFromSftp
from lib.FileManager.workers.sftp.copyFromSftpToFtp import CopyFromSftpToFtp
from lib.FileManager.workers.sftp.copyFromSftpToWebDav import CopyFromSftpToWebDav
from lib.FileManager.workers.sftp.copySftp import CopySftp
from lib.FileManager.workers.sftp.createArchive import CreateArchive
from lib.FileManager.workers.sftp.createConnection import CreateConnection
from lib.FileManager.workers.sftp.createCopy import CreateCopy
from lib.FileManager.workers.sftp.downloadFiles import DownloadFiles
from lib.FileManager.workers.sftp.extractArchive import ExtractArchive
from lib.FileManager.workers.sftp.findFiles import FindFiles
from lib.FileManager.workers.sftp.findText import FindText
from lib.FileManager.workers.sftp.listFiles import ListFiles
from lib.FileManager.workers.sftp.makeDir import MakeDir
from lib.FileManager.workers.sftp.moveBetweenSftp import MoveBetweenSftp
from lib.FileManager.workers.sftp.moveFromSftp import MoveFromSftp
from lib.FileManager.workers.sftp.moveFromSftpToFtp import MoveFromSftpToFtp
from lib.FileManager.workers.sftp.moveFromSftpToWebDav import MoveFromSftpToWebDav
from lib.FileManager.workers.sftp.moveSftp import MoveSftp
from lib.FileManager.workers.sftp.newFile import NewFile
from lib.FileManager.workers.sftp.readFile import ReadFile
from lib.FileManager.workers.sftp.readImages import ReadImages
from lib.FileManager.workers.sftp.removeConnection import RemoveConnection
from lib.FileManager.workers.sftp.removeFiles import RemoveFiles
from lib.FileManager.workers.sftp.renameFile import RenameFile
from lib.FileManager.workers.sftp.updateConnection import UpdateConnection
from lib.FileManager.workers.sftp.uploadFile import UploadFile
from lib.FileManager.workers.sftp.writeFile import WriteFile
from misc.helpers import byte_to_unicode_list, byte_to_unicode_dict
class SftpController(Controller):
def action_create_connection(self, login, password, host, port, sftp_user, sftp_password):
return self.get_process_data(CreateConnection, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"host": host.decode('UTF-8'),
"port": port,
"sftp_user": sftp_user.decode('UTF-8'),
"sftp_password": sftp_password.decode('UTF-8')
})
def action_edit_connection(self, login, password, connection_id, host, port, sftp_user, sftp_password):
return self.get_process_data(UpdateConnection, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"connection_id": connection_id,
"host": host.decode('UTF-8'),
"port": port,
"sftp_user": sftp_user.decode('UTF-8'),
"sftp_password": sftp_password.decode('UTF-8')
})
def action_remove_connection(self, login, password, connection_id):
return self.get_process_data(RemoveConnection, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"connection_id": connection_id
})
def action_list_files(self, login, password, path, session):
return self.get_process_data(ListFiles, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"session": byte_to_unicode_dict(session)
})
def action_make_dir(self, login, password, path, session):
return self.get_process_data(MakeDir, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"session": byte_to_unicode_dict(session)
})
def action_new_file(self, login, password, path, session):
return self.get_process_data(NewFile, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"session": byte_to_unicode_dict(session)
})
def action_read_file(self, login, password, path, encoding, session):
if encoding is None:
encoding = b''
return self.get_process_data(ReadFile, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"session": byte_to_unicode_dict(session),
"encoding": encoding.decode('UTF-8')
})
def action_write_file(self, login, password, path, content, encoding, session):
return self.get_process_data(WriteFile, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"content": content.decode('UTF-8'),
"encoding": encoding.decode('UTF-8'),
"session": byte_to_unicode_dict(session)
})
def action_rename_file(self, login, password, source_path, target_path, session):
return self.get_process_data(RenameFile, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"source_path": source_path.decode("UTF-8"),
"target_path": target_path.decode("UTF-8"),
"session": byte_to_unicode_dict(session)
})
def action_download_files(self, login, password, paths, mode, session):
return self.get_process_data(DownloadFiles, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"paths": byte_to_unicode_list(paths),
"mode": mode.decode('UTF-8'),
"session": byte_to_unicode_dict(session)
}, timeout=7200)
def action_read_images(self, login, password, paths, session):
return self.get_process_data(ReadImages, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"paths": byte_to_unicode_list(paths),
"session": byte_to_unicode_dict(session)
}, timeout=7200)
def action_upload_file(self, login, password, path, file_path, overwrite, session):
params = {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode('UTF-8'),
"file_path": file_path.decode('UTF-8'),
"overwrite": overwrite,
"session": byte_to_unicode_dict(session),
}
return self.get_process_data(UploadFile, params, timeout=7200)
@staticmethod
def run_subprocess(logger, worker_object, status_id, name, params):
logger.info("FM call SFTP long action %s %s %s" % (name, pprint.pformat(status_id), pprint.pformat(params.get("login"))))
def async_check_operation(op_status_id):
operation = OperationStatus.load(op_status_id)
logger.info("Operation id='%s' status is '%s'" % (str(status_id), operation.status))
if operation.status != OperationStatus.STATUS_WAIT:
raise Error("Operation status is not wait - aborting")
def async_on_error(op_status_id, data=None, progress=None, pid=None, pname=None):
logger.info("Process on_error()")
operation = OperationStatus.load(op_status_id)
data = {
'id': status_id,
'status': 'error',
'data': data,
'progress': progress,
'pid': pid,
'pname': pname
}
operation.set_attributes(data)
operation.save()
def async_on_success(op_status_id, data=None, progress=None, pid=None, pname=None):
logger.info("Process on_success()")
operation = OperationStatus.load(op_status_id)
data = {
'id': op_status_id,
'status': OperationStatus.STATUS_SUCCESS,
'data': data,
'progress': progress,
'pid': pid,
'pname': pname
}
operation.set_attributes(data)
operation.save()
def async_on_running(op_status_id, data=None, progress=None, pid=None, pname=None):
logger.info("Process on_running()")
operation = OperationStatus.load(op_status_id)
data = {
'id': op_status_id,
'status': OperationStatus.STATUS_RUNNING,
'data': data,
'progress': progress,
'pid': pid,
'pname': pname
}
operation.set_attributes(data)
operation.save()
def async_on_abort(op_status_id, data=None, progress=None, pid=None, pname=None):
logger.info("Process on_abort()")
operation = OperationStatus.load(op_status_id)
data = {
'id': op_status_id,
'status': OperationStatus.STATUS_ABORT,
'data': data,
'progress': progress,
'pid': pid,
'pname': pname
}
operation.set_attributes(data)
operation.save()
def async_on_finish(worker_process, op_status_id, pid=None, pname=None):
logger.info("Process on_finish()")
logger.info("Process exit code %s info = %s", str(process.exitcode), pprint.pformat(process))
if worker_process.exitcode < 0:
async_on_abort(status_id, pid=pid, pname=pname)
elif worker_process.exitcode > 0:
async_on_error(op_status_id, pid=pid, pname=pname)
try:
async_check_operation(status_id)
kwargs = {
"name": name,
"status_id": status_id,
"logger": logger,
"on_running": async_on_running,
"on_abort": async_on_abort,
"on_error": async_on_error,
"on_success": async_on_success
}
kwargs.update(params)
process = worker_object(**kwargs)
process.start()
process.join()
async_on_finish(process, status_id, pid=process.pid, pname=process.name)
except Exception as e:
result = {
"message": str(e),
"traceback": traceback.format_exc()
}
async_on_error(status_id, result)
def action_remove_files(self, login, password, status_id, paths, session):
try:
self.logger.info("FM starting subprocess worker remove_files %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, RemoveFiles, status_id.decode('UTF-8'), FM.Action.REMOVE, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"paths": byte_to_unicode_list(paths),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_analyze_size(self, login, password, status_id, path, session):
try:
self.logger.info("FM starting subprocess worker analyze_size %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, AnalyzeSize, status_id.decode('UTF-8'), FM.Action.ANALYZE_SIZE, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode('UTF-8'),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_chmod_files(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker chmod_files %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, ChmodFiles, status_id.decode('UTF-8'), FM.Action.CHMOD, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_find_text(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker find_text %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, FindText, status_id.decode('UTF-8'), FM.Action.SEARCH_TEXT, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_find_files(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker find_files %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, FindFiles, status_id.decode('UTF-8'), FM.Action.SEARCH_FILES, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_create_archive(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker create_archive %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, CreateArchive, status_id.decode('UTF-8'), FM.Action.CREATE_ARCHIVE, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
|
[
" return {\"error\": False}"
] | 958
|
lcc
|
python
| null |
1712603d3736689b03586a52e0f51eedd1a2bccd03217fde
| 12
|
Your task is code completion.
import pprint
import select
import traceback
from multiprocessing import Pipe, Process
from beget_msgpack import Controller
from base.exc import Error
from lib.FileManager import FM
from lib.FileManager.OperationStatus import OperationStatus
from lib.FileManager.workers.sftp.analyzeSize import AnalyzeSize
from lib.FileManager.workers.sftp.chmodFiles import ChmodFiles
from lib.FileManager.workers.sftp.copyBetweenSftp import CopyBetweenSftp
from lib.FileManager.workers.sftp.copyFromSftp import CopyFromSftp
from lib.FileManager.workers.sftp.copyFromSftpToFtp import CopyFromSftpToFtp
from lib.FileManager.workers.sftp.copyFromSftpToWebDav import CopyFromSftpToWebDav
from lib.FileManager.workers.sftp.copySftp import CopySftp
from lib.FileManager.workers.sftp.createArchive import CreateArchive
from lib.FileManager.workers.sftp.createConnection import CreateConnection
from lib.FileManager.workers.sftp.createCopy import CreateCopy
from lib.FileManager.workers.sftp.downloadFiles import DownloadFiles
from lib.FileManager.workers.sftp.extractArchive import ExtractArchive
from lib.FileManager.workers.sftp.findFiles import FindFiles
from lib.FileManager.workers.sftp.findText import FindText
from lib.FileManager.workers.sftp.listFiles import ListFiles
from lib.FileManager.workers.sftp.makeDir import MakeDir
from lib.FileManager.workers.sftp.moveBetweenSftp import MoveBetweenSftp
from lib.FileManager.workers.sftp.moveFromSftp import MoveFromSftp
from lib.FileManager.workers.sftp.moveFromSftpToFtp import MoveFromSftpToFtp
from lib.FileManager.workers.sftp.moveFromSftpToWebDav import MoveFromSftpToWebDav
from lib.FileManager.workers.sftp.moveSftp import MoveSftp
from lib.FileManager.workers.sftp.newFile import NewFile
from lib.FileManager.workers.sftp.readFile import ReadFile
from lib.FileManager.workers.sftp.readImages import ReadImages
from lib.FileManager.workers.sftp.removeConnection import RemoveConnection
from lib.FileManager.workers.sftp.removeFiles import RemoveFiles
from lib.FileManager.workers.sftp.renameFile import RenameFile
from lib.FileManager.workers.sftp.updateConnection import UpdateConnection
from lib.FileManager.workers.sftp.uploadFile import UploadFile
from lib.FileManager.workers.sftp.writeFile import WriteFile
from misc.helpers import byte_to_unicode_list, byte_to_unicode_dict
class SftpController(Controller):
def action_create_connection(self, login, password, host, port, sftp_user, sftp_password):
return self.get_process_data(CreateConnection, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"host": host.decode('UTF-8'),
"port": port,
"sftp_user": sftp_user.decode('UTF-8'),
"sftp_password": sftp_password.decode('UTF-8')
})
def action_edit_connection(self, login, password, connection_id, host, port, sftp_user, sftp_password):
return self.get_process_data(UpdateConnection, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"connection_id": connection_id,
"host": host.decode('UTF-8'),
"port": port,
"sftp_user": sftp_user.decode('UTF-8'),
"sftp_password": sftp_password.decode('UTF-8')
})
def action_remove_connection(self, login, password, connection_id):
return self.get_process_data(RemoveConnection, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"connection_id": connection_id
})
def action_list_files(self, login, password, path, session):
return self.get_process_data(ListFiles, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"session": byte_to_unicode_dict(session)
})
def action_make_dir(self, login, password, path, session):
return self.get_process_data(MakeDir, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"session": byte_to_unicode_dict(session)
})
def action_new_file(self, login, password, path, session):
return self.get_process_data(NewFile, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"session": byte_to_unicode_dict(session)
})
def action_read_file(self, login, password, path, encoding, session):
if encoding is None:
encoding = b''
return self.get_process_data(ReadFile, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"session": byte_to_unicode_dict(session),
"encoding": encoding.decode('UTF-8')
})
def action_write_file(self, login, password, path, content, encoding, session):
return self.get_process_data(WriteFile, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode("UTF-8"),
"content": content.decode('UTF-8'),
"encoding": encoding.decode('UTF-8'),
"session": byte_to_unicode_dict(session)
})
def action_rename_file(self, login, password, source_path, target_path, session):
return self.get_process_data(RenameFile, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"source_path": source_path.decode("UTF-8"),
"target_path": target_path.decode("UTF-8"),
"session": byte_to_unicode_dict(session)
})
def action_download_files(self, login, password, paths, mode, session):
return self.get_process_data(DownloadFiles, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"paths": byte_to_unicode_list(paths),
"mode": mode.decode('UTF-8'),
"session": byte_to_unicode_dict(session)
}, timeout=7200)
def action_read_images(self, login, password, paths, session):
return self.get_process_data(ReadImages, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"paths": byte_to_unicode_list(paths),
"session": byte_to_unicode_dict(session)
}, timeout=7200)
def action_upload_file(self, login, password, path, file_path, overwrite, session):
params = {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode('UTF-8'),
"file_path": file_path.decode('UTF-8'),
"overwrite": overwrite,
"session": byte_to_unicode_dict(session),
}
return self.get_process_data(UploadFile, params, timeout=7200)
@staticmethod
def run_subprocess(logger, worker_object, status_id, name, params):
logger.info("FM call SFTP long action %s %s %s" % (name, pprint.pformat(status_id), pprint.pformat(params.get("login"))))
def async_check_operation(op_status_id):
operation = OperationStatus.load(op_status_id)
logger.info("Operation id='%s' status is '%s'" % (str(status_id), operation.status))
if operation.status != OperationStatus.STATUS_WAIT:
raise Error("Operation status is not wait - aborting")
def async_on_error(op_status_id, data=None, progress=None, pid=None, pname=None):
logger.info("Process on_error()")
operation = OperationStatus.load(op_status_id)
data = {
'id': status_id,
'status': 'error',
'data': data,
'progress': progress,
'pid': pid,
'pname': pname
}
operation.set_attributes(data)
operation.save()
def async_on_success(op_status_id, data=None, progress=None, pid=None, pname=None):
logger.info("Process on_success()")
operation = OperationStatus.load(op_status_id)
data = {
'id': op_status_id,
'status': OperationStatus.STATUS_SUCCESS,
'data': data,
'progress': progress,
'pid': pid,
'pname': pname
}
operation.set_attributes(data)
operation.save()
def async_on_running(op_status_id, data=None, progress=None, pid=None, pname=None):
logger.info("Process on_running()")
operation = OperationStatus.load(op_status_id)
data = {
'id': op_status_id,
'status': OperationStatus.STATUS_RUNNING,
'data': data,
'progress': progress,
'pid': pid,
'pname': pname
}
operation.set_attributes(data)
operation.save()
def async_on_abort(op_status_id, data=None, progress=None, pid=None, pname=None):
logger.info("Process on_abort()")
operation = OperationStatus.load(op_status_id)
data = {
'id': op_status_id,
'status': OperationStatus.STATUS_ABORT,
'data': data,
'progress': progress,
'pid': pid,
'pname': pname
}
operation.set_attributes(data)
operation.save()
def async_on_finish(worker_process, op_status_id, pid=None, pname=None):
logger.info("Process on_finish()")
logger.info("Process exit code %s info = %s", str(process.exitcode), pprint.pformat(process))
if worker_process.exitcode < 0:
async_on_abort(status_id, pid=pid, pname=pname)
elif worker_process.exitcode > 0:
async_on_error(op_status_id, pid=pid, pname=pname)
try:
async_check_operation(status_id)
kwargs = {
"name": name,
"status_id": status_id,
"logger": logger,
"on_running": async_on_running,
"on_abort": async_on_abort,
"on_error": async_on_error,
"on_success": async_on_success
}
kwargs.update(params)
process = worker_object(**kwargs)
process.start()
process.join()
async_on_finish(process, status_id, pid=process.pid, pname=process.name)
except Exception as e:
result = {
"message": str(e),
"traceback": traceback.format_exc()
}
async_on_error(status_id, result)
def action_remove_files(self, login, password, status_id, paths, session):
try:
self.logger.info("FM starting subprocess worker remove_files %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, RemoveFiles, status_id.decode('UTF-8'), FM.Action.REMOVE, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"paths": byte_to_unicode_list(paths),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_analyze_size(self, login, password, status_id, path, session):
try:
self.logger.info("FM starting subprocess worker analyze_size %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, AnalyzeSize, status_id.decode('UTF-8'), FM.Action.ANALYZE_SIZE, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"path": path.decode('UTF-8'),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_chmod_files(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker chmod_files %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, ChmodFiles, status_id.decode('UTF-8'), FM.Action.CHMOD, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_find_text(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker find_text %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, FindText, status_id.decode('UTF-8'), FM.Action.SEARCH_TEXT, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_find_files(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker find_files %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, FindFiles, status_id.decode('UTF-8'), FM.Action.SEARCH_FILES, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
return {"error": False}
except Exception as e:
result = {
"error": True,
"message": str(e),
"traceback": traceback.format_exc()
}
return result
def action_create_archive(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker create_archive %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, CreateArchive, status_id.decode('UTF-8'), FM.Action.CREATE_ARCHIVE, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
|
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 action_create_archive(self, login, password, status_id, params, session):
try:
self.logger.info("FM starting subprocess worker create_archive %s %s", pprint.pformat(status_id),
pprint.pformat(login))
p = Process(target=self.run_subprocess,
args=(self.logger, CreateArchive, status_id.decode('UTF-8'), FM.Action.CREATE_ARCHIVE, {
"login": login.decode('UTF-8'),
"password": password.decode('UTF-8'),
"params": byte_to_unicode_dict(params),
"session": byte_to_unicode_dict(session)
}))
p.start()
**Cheat sheet (for next line):**
- We are in the `action_create_archive` method, which is a part of the `SftpController` class.
- The method is currently starting a new process using `Process` and `run_subprocess`.
- The `run_subprocess` method takes several arguments, including `worker_object`, which is set to `CreateArchive`.
- The `CreateArchive` worker object is expected to have a method that takes several keyword arguments, including `name`, `status_id`, `logger`, `on_running`, `on_abort`, `on_error`, `on_success`, and `params`.
- The `params` argument is a dictionary that contains the parameters for the `CreateArchive` worker object.
- The `session` argument is also a dictionary that is being passed to the `CreateArchive` worker object.
**Relevant lines:**
- `p = Process(target=self.run_subprocess, ...`
- `self.run_subprocess` method call
- `CreateArchive` worker object
- `params` dictionary
- `session` dictionary
**Expected next line:**
The next line should be the call to the `start` method on the `CreateArchive` worker object, passing the required keyword arguments. However, since the `CreateArchive` worker object is not shown in the provided code, we cannot determine the exact method name. Assuming the method name is `__init__` (a common method name for worker objects), the next line could be:
```python
create_archive = CreateArchive(**params)
create_archive.start(status_id=status_id, logger=self.logger, on_running=self.on_running, on_abort=self.on_abort, on_error=self.on_error, on_success=self.on_success)
```
However, this is just a guess, and the actual next line may vary depending on the implementation of the `CreateArchive` worker object.
|
|
Please complete the code given below.
//
// ZoneIdentityPermissionTest.cs - NUnit Test Cases for ZoneIdentityPermission
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Security;
using System.Security.Permissions;
namespace MonoTests.System.Security.Permissions {
[TestFixture]
public class ZoneIdentityPermissionTest {
[Test]
public void PermissionStateNone ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (PermissionState.None);
Assert.AreEqual (SecurityZone.NoZone, zip.SecurityZone);
}
#if NET_2_0
[Test]
[Category ("NotWorking")]
public void PermissionStateUnrestricted ()
{
// In 2.0 Unrestricted are permitted for identity permissions
ZoneIdentityPermission zip = new ZoneIdentityPermission (PermissionState.Unrestricted);
Assert.AreEqual (SecurityZone.NoZone, zip.SecurityZone);
SecurityElement se = zip.ToXml ();
Assert.AreEqual (5, se.Children.Count, "Count");
// and they aren't equals to None
Assert.IsFalse (zip.Equals (new ZoneIdentityPermission (PermissionState.None)));
}
#else
[Test]
[ExpectedException (typeof (ArgumentException))]
public void PermissionStateUnrestricted ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (PermissionState.Unrestricted);
}
#endif
[Test]
[ExpectedException (typeof (ArgumentException))]
public void PermissionStateInvalid ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission ((PermissionState)2);
}
private bool Same (ZoneIdentityPermission zip1, ZoneIdentityPermission zip2)
{
#if NET_2_0
return zip1.Equals (zip2);
#else
return (zip1.SecurityZone == zip2.SecurityZone);
#endif
}
private ZoneIdentityPermission BasicTestZone (SecurityZone zone, bool special)
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (zone);
Assert.AreEqual (zone, zip.SecurityZone, "SecurityZone");
ZoneIdentityPermission copy = (ZoneIdentityPermission) zip.Copy ();
Assert.IsTrue (Same (zip, copy), "Equals-Copy");
Assert.IsTrue (zip.IsSubsetOf (copy), "IsSubset-1");
Assert.IsTrue (copy.IsSubsetOf (zip), "IsSubset-2");
if (special) {
Assert.IsFalse (zip.IsSubsetOf (null), "IsSubset-Null");
}
IPermission intersect = zip.Intersect (copy);
if (special) {
Assert.IsTrue (intersect.IsSubsetOf (zip), "IsSubset-3");
Assert.IsFalse (Object.ReferenceEquals (zip, intersect), "!ReferenceEquals1");
Assert.IsTrue (intersect.IsSubsetOf (copy), "IsSubset-4");
Assert.IsFalse (Object.ReferenceEquals (copy, intersect), "!ReferenceEquals2");
}
Assert.IsNull (zip.Intersect (null), "Intersect with null");
intersect = zip.Intersect (new ZoneIdentityPermission (PermissionState.None));
Assert.IsNull (intersect, "Intersect with PS.None");
// note: can't be tested with PermissionState.Unrestricted
// XML roundtrip
SecurityElement se = zip.ToXml ();
copy.FromXml (se);
Assert.IsTrue (Same (zip, copy), "Equals-Xml");
return zip;
}
[Test]
public void SecurityZone_Internet ()
{
BasicTestZone (SecurityZone.Internet, true);
}
[Test]
public void SecurityZone_Intranet ()
{
BasicTestZone (SecurityZone.Intranet, true);
}
[Test]
public void SecurityZone_MyComputer ()
{
BasicTestZone (SecurityZone.MyComputer, true);
}
[Test]
public void SecurityZone_NoZone ()
{
ZoneIdentityPermission zip = BasicTestZone (SecurityZone.NoZone, false);
Assert.IsNull (zip.ToXml ().Attribute ("Zone"), "Zone Attribute");
Assert.IsTrue (zip.IsSubsetOf (null), "IsSubset-Null");
IPermission intersect = zip.Intersect (zip);
Assert.IsNull (intersect, "Intersect with No Zone");
// NoZone is special as it is a subset of all zones
ZoneIdentityPermission ss = new ZoneIdentityPermission (SecurityZone.Internet);
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-Internet");
ss.SecurityZone = SecurityZone.Intranet;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-Intranet");
ss.SecurityZone = SecurityZone.MyComputer;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-MyComputer");
ss.SecurityZone = SecurityZone.NoZone;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-NoZone");
ss.SecurityZone = SecurityZone.Trusted;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-Trusted");
ss.SecurityZone = SecurityZone.Untrusted;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-Untrusted");
}
[Test]
public void SecurityZone_Trusted ()
{
BasicTestZone (SecurityZone.Trusted, true);
}
[Test]
public void SecurityZone_Untrusted ()
{
BasicTestZone (SecurityZone.Untrusted, true);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void SecurityZone_Invalid ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission ((SecurityZone)128);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Intersect_DifferentPermissions ()
{
ZoneIdentityPermission a = new ZoneIdentityPermission (SecurityZone.Trusted);
SecurityPermission b = new SecurityPermission (PermissionState.None);
a.Intersect (b);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void IsSubsetOf_DifferentPermissions ()
{
ZoneIdentityPermission a = new ZoneIdentityPermission (SecurityZone.Trusted);
SecurityPermission b = new SecurityPermission (PermissionState.None);
a.IsSubsetOf (b);
}
[Test]
public void Union ()
{
ZoneIdentityPermission a = new ZoneIdentityPermission (SecurityZone.Trusted);
ZoneIdentityPermission z = (ZoneIdentityPermission) a.Union (null);
Assert.IsTrue (Same (a, z), "Trusted+null");
Assert.IsFalse (Object.ReferenceEquals (a, z), "!ReferenceEquals1");
z = (ZoneIdentityPermission) a.Union (new ZoneIdentityPermission (PermissionState.None));
Assert.IsTrue (Same (a, z), "Trusted+PS.None");
Assert.IsFalse (Object.ReferenceEquals (a, z), "!ReferenceEquals2");
// note: can't be tested with PermissionState.Unrestricted
ZoneIdentityPermission n = new ZoneIdentityPermission (SecurityZone.NoZone);
z = (ZoneIdentityPermission) a.Union (n);
Assert.IsTrue (Same (a, z), "Trusted+NoZone");
Assert.IsFalse (Object.ReferenceEquals (a, z), "!ReferenceEquals3");
z = (ZoneIdentityPermission) n.Union (a);
Assert.IsTrue (Same (a, z), "NoZone+Trusted");
Assert.IsFalse (Object.ReferenceEquals (a, z), "!ReferenceEquals4");
}
#if NET_2_0
[Category ("NotWorking")]
#endif
[Test]
public void Union_DifferentIdentities ()
{
ZoneIdentityPermission a = new ZoneIdentityPermission (SecurityZone.Trusted);
ZoneIdentityPermission b = new ZoneIdentityPermission (SecurityZone.Untrusted);
|
[
"\t\t\tIPermission result = a.Union (b);"
] | 778
|
lcc
|
csharp
| null |
e212994f82962f98d4e1be7a5678cfd25eacb4f645df2198
| 13
|
Your task is code completion.
//
// ZoneIdentityPermissionTest.cs - NUnit Test Cases for ZoneIdentityPermission
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Security;
using System.Security.Permissions;
namespace MonoTests.System.Security.Permissions {
[TestFixture]
public class ZoneIdentityPermissionTest {
[Test]
public void PermissionStateNone ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (PermissionState.None);
Assert.AreEqual (SecurityZone.NoZone, zip.SecurityZone);
}
#if NET_2_0
[Test]
[Category ("NotWorking")]
public void PermissionStateUnrestricted ()
{
// In 2.0 Unrestricted are permitted for identity permissions
ZoneIdentityPermission zip = new ZoneIdentityPermission (PermissionState.Unrestricted);
Assert.AreEqual (SecurityZone.NoZone, zip.SecurityZone);
SecurityElement se = zip.ToXml ();
Assert.AreEqual (5, se.Children.Count, "Count");
// and they aren't equals to None
Assert.IsFalse (zip.Equals (new ZoneIdentityPermission (PermissionState.None)));
}
#else
[Test]
[ExpectedException (typeof (ArgumentException))]
public void PermissionStateUnrestricted ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (PermissionState.Unrestricted);
}
#endif
[Test]
[ExpectedException (typeof (ArgumentException))]
public void PermissionStateInvalid ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission ((PermissionState)2);
}
private bool Same (ZoneIdentityPermission zip1, ZoneIdentityPermission zip2)
{
#if NET_2_0
return zip1.Equals (zip2);
#else
return (zip1.SecurityZone == zip2.SecurityZone);
#endif
}
private ZoneIdentityPermission BasicTestZone (SecurityZone zone, bool special)
{
ZoneIdentityPermission zip = new ZoneIdentityPermission (zone);
Assert.AreEqual (zone, zip.SecurityZone, "SecurityZone");
ZoneIdentityPermission copy = (ZoneIdentityPermission) zip.Copy ();
Assert.IsTrue (Same (zip, copy), "Equals-Copy");
Assert.IsTrue (zip.IsSubsetOf (copy), "IsSubset-1");
Assert.IsTrue (copy.IsSubsetOf (zip), "IsSubset-2");
if (special) {
Assert.IsFalse (zip.IsSubsetOf (null), "IsSubset-Null");
}
IPermission intersect = zip.Intersect (copy);
if (special) {
Assert.IsTrue (intersect.IsSubsetOf (zip), "IsSubset-3");
Assert.IsFalse (Object.ReferenceEquals (zip, intersect), "!ReferenceEquals1");
Assert.IsTrue (intersect.IsSubsetOf (copy), "IsSubset-4");
Assert.IsFalse (Object.ReferenceEquals (copy, intersect), "!ReferenceEquals2");
}
Assert.IsNull (zip.Intersect (null), "Intersect with null");
intersect = zip.Intersect (new ZoneIdentityPermission (PermissionState.None));
Assert.IsNull (intersect, "Intersect with PS.None");
// note: can't be tested with PermissionState.Unrestricted
// XML roundtrip
SecurityElement se = zip.ToXml ();
copy.FromXml (se);
Assert.IsTrue (Same (zip, copy), "Equals-Xml");
return zip;
}
[Test]
public void SecurityZone_Internet ()
{
BasicTestZone (SecurityZone.Internet, true);
}
[Test]
public void SecurityZone_Intranet ()
{
BasicTestZone (SecurityZone.Intranet, true);
}
[Test]
public void SecurityZone_MyComputer ()
{
BasicTestZone (SecurityZone.MyComputer, true);
}
[Test]
public void SecurityZone_NoZone ()
{
ZoneIdentityPermission zip = BasicTestZone (SecurityZone.NoZone, false);
Assert.IsNull (zip.ToXml ().Attribute ("Zone"), "Zone Attribute");
Assert.IsTrue (zip.IsSubsetOf (null), "IsSubset-Null");
IPermission intersect = zip.Intersect (zip);
Assert.IsNull (intersect, "Intersect with No Zone");
// NoZone is special as it is a subset of all zones
ZoneIdentityPermission ss = new ZoneIdentityPermission (SecurityZone.Internet);
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-Internet");
ss.SecurityZone = SecurityZone.Intranet;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-Intranet");
ss.SecurityZone = SecurityZone.MyComputer;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-MyComputer");
ss.SecurityZone = SecurityZone.NoZone;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-NoZone");
ss.SecurityZone = SecurityZone.Trusted;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-Trusted");
ss.SecurityZone = SecurityZone.Untrusted;
Assert.IsTrue (zip.IsSubsetOf (ss), "IsSubset-Untrusted");
}
[Test]
public void SecurityZone_Trusted ()
{
BasicTestZone (SecurityZone.Trusted, true);
}
[Test]
public void SecurityZone_Untrusted ()
{
BasicTestZone (SecurityZone.Untrusted, true);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void SecurityZone_Invalid ()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission ((SecurityZone)128);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Intersect_DifferentPermissions ()
{
ZoneIdentityPermission a = new ZoneIdentityPermission (SecurityZone.Trusted);
SecurityPermission b = new SecurityPermission (PermissionState.None);
a.Intersect (b);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void IsSubsetOf_DifferentPermissions ()
{
ZoneIdentityPermission a = new ZoneIdentityPermission (SecurityZone.Trusted);
SecurityPermission b = new SecurityPermission (PermissionState.None);
a.IsSubsetOf (b);
}
[Test]
public void Union ()
{
ZoneIdentityPermission a = new ZoneIdentityPermission (SecurityZone.Trusted);
ZoneIdentityPermission z = (ZoneIdentityPermission) a.Union (null);
Assert.IsTrue (Same (a, z), "Trusted+null");
Assert.IsFalse (Object.ReferenceEquals (a, z), "!ReferenceEquals1");
z = (ZoneIdentityPermission) a.Union (new ZoneIdentityPermission (PermissionState.None));
Assert.IsTrue (Same (a, z), "Trusted+PS.None");
Assert.IsFalse (Object.ReferenceEquals (a, z), "!ReferenceEquals2");
// note: can't be tested with PermissionState.Unrestricted
ZoneIdentityPermission n = new ZoneIdentityPermission (SecurityZone.NoZone);
z = (ZoneIdentityPermission) a.Union (n);
Assert.IsTrue (Same (a, z), "Trusted+NoZone");
Assert.IsFalse (Object.ReferenceEquals (a, z), "!ReferenceEquals3");
z = (ZoneIdentityPermission) n.Union (a);
Assert.IsTrue (Same (a, z), "NoZone+Trusted");
Assert.IsFalse (Object.ReferenceEquals (a, z), "!ReferenceEquals4");
}
#if NET_2_0
[Category ("NotWorking")]
#endif
[Test]
public void Union_DifferentIdentities ()
{
ZoneIdentityPermission a = new ZoneIdentityPermission (SecurityZone.Trusted);
ZoneIdentityPermission b = new ZoneIdentityPermission (SecurityZone.Untrusted);
|
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 ZoneIdentityPermissionTest.cs:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class ZoneIdentityPermissionTest {
private bool Same(ZoneIdentityPermission zip1, ZoneIdentityPermission zip2)
{
// ...
}
private ZoneIdentityPermission BasicTestZone(SecurityZone zone, bool special)
{
// ...
ZoneIdentityPermission copy = (ZoneIdentityPermission) zip.Copy();
// ...
IPermission intersect = zip.Intersect(copy);
// ...
// note: can't be tested with PermissionState.Unrestricted
// XML roundtrip
SecurityElement se = zip.ToXml();
copy.FromXml(se);
Assert.IsTrue(Same(zip, copy), "Equals-Xml");
return zip;
}
[Test]
public void SecurityZone_Internet()
{
BasicTestZone(SecurityZone.Internet, true);
}
[Test]
public void SecurityZone_Intranet()
{
BasicTestZone(SecurityZone.Intranet, true);
}
[Test]
public void SecurityZone_MyComputer()
{
BasicTestZone(SecurityZone.MyComputer, true);
}
[Test]
public void SecurityZone_NoZone()
{
ZoneIdentityPermission zip = BasicTestZone(SecurityZone.NoZone, false);
// ...
}
[Test]
public void SecurityZone_Trusted()
{
BasicTestZone(SecurityZone.Trusted, true);
}
[Test]
public void SecurityZone_Untrusted()
{
BasicTestZone(SecurityZone.Untrusted, true);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SecurityZone_Invalid()
{
ZoneIdentityPermission zip = new ZoneIdentityPermission((SecurityZone)128);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void Intersect_DifferentPermissions()
{
ZoneIdentityPermission a = new ZoneIdentityPermission(SecurityZone.Trusted);
SecurityPermission b = new SecurityPermission(PermissionState.None);
a.Intersect(b);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void IsSubsetOf_DifferentPermissions()
{
ZoneIdentityPermission a = new ZoneIdentityPermission(SecurityZone.Trusted);
SecurityPermission b = new SecurityPermission(PermissionState.None);
a.IsSubsetOf(b);
}
[Test]
public void Union()
{
ZoneIdentityPermission a = new ZoneIdentityPermission(SecurityZone.Trusted);
ZoneIdentityPermission z = (ZoneIdentityPermission)a.Union(null);
// ...
}
#if NET_2_0
[Category("NotWorking")]
#endif
[Test]
public void Union_DifferentIdentities()
{
ZoneIdentityPermission a = new ZoneIdentityPermission(SecurityZone.Trusted);
ZoneIdentityPermission b = new ZoneIdentityPermission(SecurityZone.Untrusted);
// ...
Cheatsheet (for next line):
- We are in Union_DifferentIdentities() method.
- The method is testing the Union() method with two different ZoneIdentityPermission objects.
- The Union() method should return a new ZoneIdentityPermission object that represents the union of the two input permissions.
- The input permissions are a and b.
- The Union() method should return a new object that is not the same as the input objects a and b.
- The Union() method should return an object that is a superset of both a and b.
Next line will likely be:
- Create a new ZoneIdentityPermission object that represents the union of a and b.
- The new object should be a superset of both a and b.
- The new object should not be the same as a or b.
- The new object should be created using the Union() method.
|
|
Please complete the code given below.
import logging
import sys
import uuid
from array import array
from contextlib import closing
from StringIO import StringIO
from java.io import BufferedInputStream, BufferedReader, FileReader, InputStreamReader, ByteArrayInputStream
from java.security import KeyStore, Security
from java.security.cert import CertificateException, CertificateFactory
from javax.net.ssl import (
X509KeyManager, X509TrustManager, KeyManagerFactory, SSLContext, TrustManager, TrustManagerFactory)
try:
# jarjar-ed version
from org.python.bouncycastle.asn1.pkcs import PrivateKeyInfo
from org.python.bouncycastle.cert import X509CertificateHolder
from org.python.bouncycastle.cert.jcajce import JcaX509CertificateConverter
from org.python.bouncycastle.jce.provider import BouncyCastleProvider
from org.python.bouncycastle.openssl import PEMKeyPair, PEMParser
from org.python.bouncycastle.openssl.jcajce import JcaPEMKeyConverter
except ImportError:
# dev version from extlibs
from org.bouncycastle.asn1.pkcs import PrivateKeyInfo
from org.bouncycastle.cert import X509CertificateHolder
from org.bouncycastle.cert.jcajce import JcaX509CertificateConverter
from org.bouncycastle.jce.provider import BouncyCastleProvider
from org.bouncycastle.openssl import PEMKeyPair, PEMParser
from org.bouncycastle.openssl.jcajce import JcaPEMKeyConverter
log = logging.getLogger("ssl")
# FIXME what happens if reloaded?
Security.addProvider(BouncyCastleProvider())
# build the necessary certificate with a CertificateFactory; this can take the pem format:
# http://docs.oracle.com/javase/7/docs/api/java/security/cert/CertificateFactory.html#generateCertificate(java.io.InputStream)
# not certain if we can include a private key in the pem file; see
# http://stackoverflow.com/questions/7216969/getting-rsa-private-key-from-pem-base64-encoded-private-key-file
# helpful advice for being able to manage ca_certs outside of Java's keystore
# specifically the example ReloadableX509TrustManager
# http://jcalcote.wordpress.com/2010/06/22/managing-a-dynamic-java-trust-store/
# in the case of http://docs.python.org/2/library/ssl.html#ssl.CERT_REQUIRED
# http://docs.python.org/2/library/ssl.html#ssl.CERT_NONE
# https://github.com/rackerlabs/romper/blob/master/romper/trust.py#L15
#
# it looks like CERT_OPTIONAL simply validates certificates if
# provided, probably something in checkServerTrusted - maybe a None
# arg? need to verify as usual with a real system... :)
# http://alesaudate.wordpress.com/2010/08/09/how-to-dynamically-select-a-certificate-alias-when-invoking-web-services/
# is somewhat relevant for managing the keyfile, certfile
def _get_ca_certs_trust_manager(ca_certs):
trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
trust_store.load(None, None)
num_certs_installed = 0
with open(ca_certs) as f:
cf = CertificateFactory.getInstance("X.509")
for cert in cf.generateCertificates(BufferedInputStream(f)):
trust_store.setCertificateEntry(str(uuid.uuid4()), cert)
num_certs_installed += 1
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
tmf.init(trust_store)
log.debug("Installed %s certificates", num_certs_installed, extra={"sock": "*"})
return tmf
def _stringio_as_reader(s):
return BufferedReader(InputStreamReader(ByteArrayInputStream(bytearray(s.getvalue()))))
def _extract_readers(cert_file):
private_key = StringIO()
certs = StringIO()
output = certs
with open(cert_file) as f:
for line in f:
if line.startswith("-----BEGIN PRIVATE KEY-----"):
output = private_key
output.write(line)
if line.startswith("-----END PRIVATE KEY-----"):
output = certs
return _stringio_as_reader(private_key), _stringio_as_reader(certs)
def _get_openssl_key_manager(cert_file, key_file=None):
paths = [key_file] if key_file else []
paths.append(cert_file)
# Go from Bouncy Castle API to Java's; a bit heavyweight for the Python dev ;)
key_converter = JcaPEMKeyConverter().setProvider("BC")
cert_converter = JcaX509CertificateConverter().setProvider("BC")
private_key = None
certs = []
for path in paths:
for br in _extract_readers(path):
while True:
obj = PEMParser(br).readObject()
if obj is None:
break
if isinstance(obj, PEMKeyPair):
private_key = key_converter.getKeyPair(obj).getPrivate()
elif isinstance(obj, PrivateKeyInfo):
private_key = key_converter.getPrivateKey(obj)
elif isinstance(obj, X509CertificateHolder):
certs.append(cert_converter.getCertificate(obj))
assert private_key, "No private key loaded"
key_store = KeyStore.getInstance(KeyStore.getDefaultType())
key_store.load(None, None)
key_store.setKeyEntry(str(uuid.uuid4()), private_key, [], certs)
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
kmf.init(key_store, [])
return kmf
def _get_ssl_context(keyfile, certfile, ca_certs):
if certfile is None and ca_certs is None:
log.debug("Using default SSL context", extra={"sock": "*"})
return SSLContext.getDefault()
else:
log.debug("Setting up a specific SSL context for keyfile=%s, certfile=%s, ca_certs=%s",
keyfile, certfile, ca_certs, extra={"sock": "*"})
if ca_certs:
# should support composite usage below
trust_managers = _get_ca_certs_trust_manager(ca_certs).getTrustManagers()
else:
trust_managers = None
if certfile:
key_managers = _get_openssl_key_manager(certfile, keyfile).getKeyManagers()
else:
key_managers = None
# FIXME FIXME for performance, cache this lookup in the future
# to avoid re-reading files on every lookup
context = SSLContext.getInstance("SSL")
context.init(key_managers, trust_managers, None)
return context
# CompositeX509KeyManager and CompositeX509TrustManager allow for mixing together Java built-in managers
# with new managers to support Python ssl.
#
# See http://tersesystems.com/2014/01/13/fixing-the-most-dangerous-code-in-the-world/
# for a good description of this composite approach.
#
# Ported to Python from http://codyaray.com/2013/04/java-ssl-with-multiple-keystores
# which was inspired by http://stackoverflow.com/questions/1793979/registering-multiple-keystores-in-jvm
class CompositeX509KeyManager(X509KeyManager):
def __init__(self, key_managers):
self.key_managers = key_managers
def chooseClientAlias(self, key_type, issuers, socket):
for key_manager in self.key_managers:
alias = key_manager.chooseClientAlias(key_type, issuers, socket)
if alias:
return alias;
return None
def chooseServerAlias(self, key_type, issuers, socket):
for key_manager in self.key_managers:
alias = key_manager.chooseServerAlias(key_type, issuers, socket)
if alias:
return alias;
return None
def getPrivateKey(self, alias):
for key_manager in self.key_managers:
private_key = keyManager.getPrivateKey(alias)
if private_key:
return private_key
return None
def getCertificateChain(self, alias):
for key_manager in self.key_managers:
chain = key_manager.getCertificateChain(alias)
if chain:
return chain
return None
def getClientAliases(self, key_type, issuers):
aliases = []
for key_manager in self.key_managers:
aliases.extend(key_manager.getClientAliases(key_type, issuers))
if not aliases:
return None
else:
return aliases
def getServerAliases(self, key_type, issuers):
aliases = []
for key_manager in self.key_managers:
aliases.extend(key_manager.getServerAliases(key_type, issuers))
if not aliases:
return None
else:
return aliases
class CompositeX509TrustManager(X509TrustManager):
def __init__(self, trust_managers):
self.trust_managers = trust_managers
def checkClientTrusted(self, chain, auth_type):
for trust_manager in self.trust_managers:
try:
trustManager.checkClientTrusted(chain, auth_type);
return
except CertificateException:
pass
raise CertificateException("None of the TrustManagers trust this certificate chain")
def checkServerTrusted(self, chain, auth_type):
for trust_manager in self.trust_managers:
try:
trustManager.checkServerTrusted(chain, auth_type);
return
except CertificateException:
pass
raise CertificateException("None of the TrustManagers trust this certificate chain")
def getAcceptedIssuers(self):
|
[
" certs = []"
] | 713
|
lcc
|
python
| null |
e6dca363f4644795057dce35d57cdbc53e1e84bea1699bbf
| 14
|
Your task is code completion.
import logging
import sys
import uuid
from array import array
from contextlib import closing
from StringIO import StringIO
from java.io import BufferedInputStream, BufferedReader, FileReader, InputStreamReader, ByteArrayInputStream
from java.security import KeyStore, Security
from java.security.cert import CertificateException, CertificateFactory
from javax.net.ssl import (
X509KeyManager, X509TrustManager, KeyManagerFactory, SSLContext, TrustManager, TrustManagerFactory)
try:
# jarjar-ed version
from org.python.bouncycastle.asn1.pkcs import PrivateKeyInfo
from org.python.bouncycastle.cert import X509CertificateHolder
from org.python.bouncycastle.cert.jcajce import JcaX509CertificateConverter
from org.python.bouncycastle.jce.provider import BouncyCastleProvider
from org.python.bouncycastle.openssl import PEMKeyPair, PEMParser
from org.python.bouncycastle.openssl.jcajce import JcaPEMKeyConverter
except ImportError:
# dev version from extlibs
from org.bouncycastle.asn1.pkcs import PrivateKeyInfo
from org.bouncycastle.cert import X509CertificateHolder
from org.bouncycastle.cert.jcajce import JcaX509CertificateConverter
from org.bouncycastle.jce.provider import BouncyCastleProvider
from org.bouncycastle.openssl import PEMKeyPair, PEMParser
from org.bouncycastle.openssl.jcajce import JcaPEMKeyConverter
log = logging.getLogger("ssl")
# FIXME what happens if reloaded?
Security.addProvider(BouncyCastleProvider())
# build the necessary certificate with a CertificateFactory; this can take the pem format:
# http://docs.oracle.com/javase/7/docs/api/java/security/cert/CertificateFactory.html#generateCertificate(java.io.InputStream)
# not certain if we can include a private key in the pem file; see
# http://stackoverflow.com/questions/7216969/getting-rsa-private-key-from-pem-base64-encoded-private-key-file
# helpful advice for being able to manage ca_certs outside of Java's keystore
# specifically the example ReloadableX509TrustManager
# http://jcalcote.wordpress.com/2010/06/22/managing-a-dynamic-java-trust-store/
# in the case of http://docs.python.org/2/library/ssl.html#ssl.CERT_REQUIRED
# http://docs.python.org/2/library/ssl.html#ssl.CERT_NONE
# https://github.com/rackerlabs/romper/blob/master/romper/trust.py#L15
#
# it looks like CERT_OPTIONAL simply validates certificates if
# provided, probably something in checkServerTrusted - maybe a None
# arg? need to verify as usual with a real system... :)
# http://alesaudate.wordpress.com/2010/08/09/how-to-dynamically-select-a-certificate-alias-when-invoking-web-services/
# is somewhat relevant for managing the keyfile, certfile
def _get_ca_certs_trust_manager(ca_certs):
trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
trust_store.load(None, None)
num_certs_installed = 0
with open(ca_certs) as f:
cf = CertificateFactory.getInstance("X.509")
for cert in cf.generateCertificates(BufferedInputStream(f)):
trust_store.setCertificateEntry(str(uuid.uuid4()), cert)
num_certs_installed += 1
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
tmf.init(trust_store)
log.debug("Installed %s certificates", num_certs_installed, extra={"sock": "*"})
return tmf
def _stringio_as_reader(s):
return BufferedReader(InputStreamReader(ByteArrayInputStream(bytearray(s.getvalue()))))
def _extract_readers(cert_file):
private_key = StringIO()
certs = StringIO()
output = certs
with open(cert_file) as f:
for line in f:
if line.startswith("-----BEGIN PRIVATE KEY-----"):
output = private_key
output.write(line)
if line.startswith("-----END PRIVATE KEY-----"):
output = certs
return _stringio_as_reader(private_key), _stringio_as_reader(certs)
def _get_openssl_key_manager(cert_file, key_file=None):
paths = [key_file] if key_file else []
paths.append(cert_file)
# Go from Bouncy Castle API to Java's; a bit heavyweight for the Python dev ;)
key_converter = JcaPEMKeyConverter().setProvider("BC")
cert_converter = JcaX509CertificateConverter().setProvider("BC")
private_key = None
certs = []
for path in paths:
for br in _extract_readers(path):
while True:
obj = PEMParser(br).readObject()
if obj is None:
break
if isinstance(obj, PEMKeyPair):
private_key = key_converter.getKeyPair(obj).getPrivate()
elif isinstance(obj, PrivateKeyInfo):
private_key = key_converter.getPrivateKey(obj)
elif isinstance(obj, X509CertificateHolder):
certs.append(cert_converter.getCertificate(obj))
assert private_key, "No private key loaded"
key_store = KeyStore.getInstance(KeyStore.getDefaultType())
key_store.load(None, None)
key_store.setKeyEntry(str(uuid.uuid4()), private_key, [], certs)
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
kmf.init(key_store, [])
return kmf
def _get_ssl_context(keyfile, certfile, ca_certs):
if certfile is None and ca_certs is None:
log.debug("Using default SSL context", extra={"sock": "*"})
return SSLContext.getDefault()
else:
log.debug("Setting up a specific SSL context for keyfile=%s, certfile=%s, ca_certs=%s",
keyfile, certfile, ca_certs, extra={"sock": "*"})
if ca_certs:
# should support composite usage below
trust_managers = _get_ca_certs_trust_manager(ca_certs).getTrustManagers()
else:
trust_managers = None
if certfile:
key_managers = _get_openssl_key_manager(certfile, keyfile).getKeyManagers()
else:
key_managers = None
# FIXME FIXME for performance, cache this lookup in the future
# to avoid re-reading files on every lookup
context = SSLContext.getInstance("SSL")
context.init(key_managers, trust_managers, None)
return context
# CompositeX509KeyManager and CompositeX509TrustManager allow for mixing together Java built-in managers
# with new managers to support Python ssl.
#
# See http://tersesystems.com/2014/01/13/fixing-the-most-dangerous-code-in-the-world/
# for a good description of this composite approach.
#
# Ported to Python from http://codyaray.com/2013/04/java-ssl-with-multiple-keystores
# which was inspired by http://stackoverflow.com/questions/1793979/registering-multiple-keystores-in-jvm
class CompositeX509KeyManager(X509KeyManager):
def __init__(self, key_managers):
self.key_managers = key_managers
def chooseClientAlias(self, key_type, issuers, socket):
for key_manager in self.key_managers:
alias = key_manager.chooseClientAlias(key_type, issuers, socket)
if alias:
return alias;
return None
def chooseServerAlias(self, key_type, issuers, socket):
for key_manager in self.key_managers:
alias = key_manager.chooseServerAlias(key_type, issuers, socket)
if alias:
return alias;
return None
def getPrivateKey(self, alias):
for key_manager in self.key_managers:
private_key = keyManager.getPrivateKey(alias)
if private_key:
return private_key
return None
def getCertificateChain(self, alias):
for key_manager in self.key_managers:
chain = key_manager.getCertificateChain(alias)
if chain:
return chain
return None
def getClientAliases(self, key_type, issuers):
aliases = []
for key_manager in self.key_managers:
aliases.extend(key_manager.getClientAliases(key_type, issuers))
if not aliases:
return None
else:
return aliases
def getServerAliases(self, key_type, issuers):
aliases = []
for key_manager in self.key_managers:
aliases.extend(key_manager.getServerAliases(key_type, issuers))
if not aliases:
return None
else:
return aliases
class CompositeX509TrustManager(X509TrustManager):
def __init__(self, trust_managers):
self.trust_managers = trust_managers
def checkClientTrusted(self, chain, auth_type):
for trust_manager in self.trust_managers:
try:
trustManager.checkClientTrusted(chain, auth_type);
return
except CertificateException:
pass
raise CertificateException("None of the TrustManagers trust this certificate chain")
def checkServerTrusted(self, chain, auth_type):
for trust_manager in self.trust_managers:
try:
trustManager.checkServerTrusted(chain, auth_type);
return
except CertificateException:
pass
raise CertificateException("None of the TrustManagers trust this certificate chain")
def getAcceptedIssuers(self):
|
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 CompositeX509TrustManager(X509TrustManager):
def __init__(self, trust_managers):
self.trust_managers = trust_managers
def checkClientTrusted(self, chain, auth_type):
for trust_manager in self.trust_managers:
try:
trustManager.checkClientTrusted(chain, auth_type);
return
except CertificateException:
pass
raise CertificateException("None of the TrustManagers trust this certificate chain")
def checkServerTrusted(self, chain, auth_type):
for trust_manager in self.trust_managers:
try:
trustManager.checkServerTrusted(chain, auth_type);
return
except CertificateException:
pass
raise CertificateException("None of the TrustManagers trust this certificate chain")
def getAcceptedIssuers(self):
**Cheatsheet (for next line):**
- We are in getAcceptedIssuers(), which should return a list of accepted issuers.
- The method is part of the CompositeX509TrustManager class.
- The method is supposed to return a list of issuers, but the exact implementation is not specified.
- The trust_managers attribute is a list of trust managers.
- The getAcceptedIssuers() method in the X509TrustManager class is supposed to return a list of accepted issuers.
**Relevant lines:**
- `def getAcceptedIssuers(self):`
- `self.trust_managers`
- `X509TrustManager` class
**Next line will likely be:**
```python
return [trust_manager.getAcceptedIssuers() for trust_manager in self.trust_managers]
```
This line returns a list of accepted issuers from each trust manager in the trust_managers list.
|
|
Please complete the code given below.
/*
* Jamm
* Copyright (C) 2002 Dave Dribin and Keith Garner
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jamm.webapp;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import jamm.backend.MailManager;
import jamm.backend.MailManagerException;
import jamm.backend.AccountInfo;
import jamm.backend.AliasInfo;
import jamm.backend.MailAddress;
import jamm.backend.DomainInfo;
/**
* Loads data via Mail Manager needed for the domain administration
* page. It puts the following into the request's attributes after
* seeding them from the MailManager: domain, accounts,
* domainAccountForm (a DomainConfigForm), aliases, and
* domainAliasForm (a DomainConfigForm). It then forwards to the
* domain_admin page.
*
* @see jamm.backend.MailManager
* @see jamm.webapp.DomainConfigForm
*
* @struts.action validate="false" path="/private/domain_admin"
* roles="Site Administrator, Domain Administrator"
* @struts.action-forward name="view" path="/private/domain_admin.jsp"
*/
public class DomainAdminAction extends JammAction
{
/**
* Performs the action.
*
* @param mapping The action mapping with possible destinations.
* @param actionForm Not used in this action. Is ignored.
* @param request the http request that caused this action.
* @param response the http response
*
* @return an <code>ActionForward</code>
*
* @exception Exception if an error occurs
*/
public ActionForward execute(ActionMapping mapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
ActionErrors errors = new ActionErrors();
User user = getUser(request);
MailManager manager = getMailManager(user);
String domain = request.getParameter("domain");
if (domain == null)
{
domain = MailAddress.hostFromAddress(user.getUsername());
}
if (domain == null)
{
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("general.error.domain.is.null"));
saveErrors(request, errors);
return mapping.findForward("general_error");
}
request.setAttribute("domain", domain);
Map postmasterPasswordParameters = new HashMap();
postmasterPasswordParameters.put(
"mail", MailAddress.addressFromParts("postmaster", domain));
postmasterPasswordParameters.put("done", "domain_admin");
request.setAttribute("postmasterPasswordParameters",
postmasterPasswordParameters);
// Create the bread crumbs
List breadCrumbs = new ArrayList();
BreadCrumb breadCrumb;
if (user.isUserInRole(User.SITE_ADMIN_ROLE))
{
breadCrumb = new BreadCrumb(
findForward(mapping, "site_admin", request).getPath(),
"Site Admin");
breadCrumbs.add(breadCrumb);
}
breadCrumb = new BreadCrumb(
getDomainAdminForward(mapping, domain).getPath(), "Domain Admin");
breadCrumbs.add(breadCrumb);
request.setAttribute("breadCrumbs", breadCrumbs);
doAccounts(request, manager, domain);
doAliases(request, manager, domain);
doCatchAll(request, manager, domain);
doDomainInfo(request, manager, domain);
return (mapping.findForward("view"));
}
/**
* Prepares the account information and adds it to the web page.
*
* @param request The request we're servicing
* @param manager a mail manager instance to use
* @param domain The domain we're manipulating
* @exception MailManagerException if an error occurs
*/
private void doAccounts(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
List accounts;
String startsWith = request.getParameter("startsWith");
if (StringUtils.isAlphanumeric(startsWith) &&
StringUtils.isNotEmpty(startsWith))
{
accounts = manager.getAccountsStartingWith(startsWith, domain);
}
else
{
accounts = manager.getAccounts(domain);
}
request.setAttribute("accounts", accounts);
List activeAccounts = new ArrayList();
List adminAccounts = new ArrayList();
List deleteAccounts = new ArrayList();
Iterator i = accounts.iterator();
while (i.hasNext())
{
AccountInfo account = (AccountInfo) i.next();
String name = account.getName();
if (account.isActive())
{
activeAccounts.add(name);
}
if (account.isAdministrator())
{
adminAccounts.add(name);
}
if (account.getDelete())
{
deleteAccounts.add(name);
}
}
String[] activeAccountsArray =
(String []) activeAccounts.toArray(new String[0]);
String[] adminAccountsArray =
(String []) adminAccounts.toArray(new String[0]);
String[] deleteAccountsArray =
(String []) deleteAccounts.toArray(new String[0]);
DomainConfigForm dcf = new DomainConfigForm();
dcf.setOriginalActiveItems(activeAccountsArray);
dcf.setActiveItems(activeAccountsArray);
dcf.setOriginalAdminItems(adminAccountsArray);
dcf.setAdminItems(adminAccountsArray);
dcf.setOriginalItemsToDelete(deleteAccountsArray);
dcf.setItemsToDelete(deleteAccountsArray);
dcf.setDomain(domain);
request.setAttribute("domainAccountForm", dcf);
}
/**
* Prepares the aliases for the page.
*
* @param request the request being serviced
* @param manager The mail manager to use
* @param domain which domain are we manipulating
* @exception MailManagerException if an error occurs
*/
private void doAliases(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
List aliases;
String startsWith = request.getParameter("startsWith");
if (StringUtils.isAlphanumeric(startsWith) &&
StringUtils.isNotEmpty(startsWith))
{
aliases = manager.getAliasesStartingWith(startsWith, domain);
}
else
{
aliases = manager.getAliases(domain);
}
request.setAttribute("aliases", aliases);
List activeAliases = new ArrayList();
List adminAliases = new ArrayList();
Iterator i = aliases.iterator();
while (i.hasNext())
{
AliasInfo alias = (AliasInfo) i.next();
if (alias.isActive())
{
activeAliases.add(alias.getName());
}
if (alias.isAdministrator())
{
adminAliases.add(alias.getName());
}
}
String[] activeAliasesArray =
(String []) activeAliases.toArray(new String[0]);
String[] adminAliasesArray =
(String []) adminAliases.toArray(new String[0]);
DomainConfigForm dcf = new DomainConfigForm();
dcf.setOriginalActiveItems(activeAliasesArray);
dcf.setActiveItems(activeAliasesArray);
dcf.setOriginalAdminItems(adminAliasesArray);
dcf.setAdminItems(adminAliasesArray);
dcf.setDomain(domain);
request.setAttribute("domainAliasForm", dcf);
}
/**
* Prepares the info for the CatchAll.
*
* @param request the request being serviced
* @param manager the mail manager
* @param domain the domain
* @exception MailManagerException if an error occurs
*/
private void doCatchAll(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
AliasInfo catchAllAlias = manager.getAlias("@" + domain);
if (catchAllAlias != null)
{
List destinations = catchAllAlias.getMailDestinations();
request.setAttribute("catchAllAlias", destinations.get(0));
}
else
{
request.setAttribute("catchAllAlias", "");
}
}
/**
* Prepares the domain info
*
* @param request the request being serviced
* @param manager the mail manager
* @param domain the domain
* @exception MailManagerException if an error occurs
*/
private void doDomainInfo(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
|
[
" User user = getUser(request);"
] | 847
|
lcc
|
java
| null |
45be6133b10843a59b2ff2272116e322f7dd795025749020
| 15
|
Your task is code completion.
/*
* Jamm
* Copyright (C) 2002 Dave Dribin and Keith Garner
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jamm.webapp;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import jamm.backend.MailManager;
import jamm.backend.MailManagerException;
import jamm.backend.AccountInfo;
import jamm.backend.AliasInfo;
import jamm.backend.MailAddress;
import jamm.backend.DomainInfo;
/**
* Loads data via Mail Manager needed for the domain administration
* page. It puts the following into the request's attributes after
* seeding them from the MailManager: domain, accounts,
* domainAccountForm (a DomainConfigForm), aliases, and
* domainAliasForm (a DomainConfigForm). It then forwards to the
* domain_admin page.
*
* @see jamm.backend.MailManager
* @see jamm.webapp.DomainConfigForm
*
* @struts.action validate="false" path="/private/domain_admin"
* roles="Site Administrator, Domain Administrator"
* @struts.action-forward name="view" path="/private/domain_admin.jsp"
*/
public class DomainAdminAction extends JammAction
{
/**
* Performs the action.
*
* @param mapping The action mapping with possible destinations.
* @param actionForm Not used in this action. Is ignored.
* @param request the http request that caused this action.
* @param response the http response
*
* @return an <code>ActionForward</code>
*
* @exception Exception if an error occurs
*/
public ActionForward execute(ActionMapping mapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
ActionErrors errors = new ActionErrors();
User user = getUser(request);
MailManager manager = getMailManager(user);
String domain = request.getParameter("domain");
if (domain == null)
{
domain = MailAddress.hostFromAddress(user.getUsername());
}
if (domain == null)
{
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("general.error.domain.is.null"));
saveErrors(request, errors);
return mapping.findForward("general_error");
}
request.setAttribute("domain", domain);
Map postmasterPasswordParameters = new HashMap();
postmasterPasswordParameters.put(
"mail", MailAddress.addressFromParts("postmaster", domain));
postmasterPasswordParameters.put("done", "domain_admin");
request.setAttribute("postmasterPasswordParameters",
postmasterPasswordParameters);
// Create the bread crumbs
List breadCrumbs = new ArrayList();
BreadCrumb breadCrumb;
if (user.isUserInRole(User.SITE_ADMIN_ROLE))
{
breadCrumb = new BreadCrumb(
findForward(mapping, "site_admin", request).getPath(),
"Site Admin");
breadCrumbs.add(breadCrumb);
}
breadCrumb = new BreadCrumb(
getDomainAdminForward(mapping, domain).getPath(), "Domain Admin");
breadCrumbs.add(breadCrumb);
request.setAttribute("breadCrumbs", breadCrumbs);
doAccounts(request, manager, domain);
doAliases(request, manager, domain);
doCatchAll(request, manager, domain);
doDomainInfo(request, manager, domain);
return (mapping.findForward("view"));
}
/**
* Prepares the account information and adds it to the web page.
*
* @param request The request we're servicing
* @param manager a mail manager instance to use
* @param domain The domain we're manipulating
* @exception MailManagerException if an error occurs
*/
private void doAccounts(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
List accounts;
String startsWith = request.getParameter("startsWith");
if (StringUtils.isAlphanumeric(startsWith) &&
StringUtils.isNotEmpty(startsWith))
{
accounts = manager.getAccountsStartingWith(startsWith, domain);
}
else
{
accounts = manager.getAccounts(domain);
}
request.setAttribute("accounts", accounts);
List activeAccounts = new ArrayList();
List adminAccounts = new ArrayList();
List deleteAccounts = new ArrayList();
Iterator i = accounts.iterator();
while (i.hasNext())
{
AccountInfo account = (AccountInfo) i.next();
String name = account.getName();
if (account.isActive())
{
activeAccounts.add(name);
}
if (account.isAdministrator())
{
adminAccounts.add(name);
}
if (account.getDelete())
{
deleteAccounts.add(name);
}
}
String[] activeAccountsArray =
(String []) activeAccounts.toArray(new String[0]);
String[] adminAccountsArray =
(String []) adminAccounts.toArray(new String[0]);
String[] deleteAccountsArray =
(String []) deleteAccounts.toArray(new String[0]);
DomainConfigForm dcf = new DomainConfigForm();
dcf.setOriginalActiveItems(activeAccountsArray);
dcf.setActiveItems(activeAccountsArray);
dcf.setOriginalAdminItems(adminAccountsArray);
dcf.setAdminItems(adminAccountsArray);
dcf.setOriginalItemsToDelete(deleteAccountsArray);
dcf.setItemsToDelete(deleteAccountsArray);
dcf.setDomain(domain);
request.setAttribute("domainAccountForm", dcf);
}
/**
* Prepares the aliases for the page.
*
* @param request the request being serviced
* @param manager The mail manager to use
* @param domain which domain are we manipulating
* @exception MailManagerException if an error occurs
*/
private void doAliases(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
List aliases;
String startsWith = request.getParameter("startsWith");
if (StringUtils.isAlphanumeric(startsWith) &&
StringUtils.isNotEmpty(startsWith))
{
aliases = manager.getAliasesStartingWith(startsWith, domain);
}
else
{
aliases = manager.getAliases(domain);
}
request.setAttribute("aliases", aliases);
List activeAliases = new ArrayList();
List adminAliases = new ArrayList();
Iterator i = aliases.iterator();
while (i.hasNext())
{
AliasInfo alias = (AliasInfo) i.next();
if (alias.isActive())
{
activeAliases.add(alias.getName());
}
if (alias.isAdministrator())
{
adminAliases.add(alias.getName());
}
}
String[] activeAliasesArray =
(String []) activeAliases.toArray(new String[0]);
String[] adminAliasesArray =
(String []) adminAliases.toArray(new String[0]);
DomainConfigForm dcf = new DomainConfigForm();
dcf.setOriginalActiveItems(activeAliasesArray);
dcf.setActiveItems(activeAliasesArray);
dcf.setOriginalAdminItems(adminAliasesArray);
dcf.setAdminItems(adminAliasesArray);
dcf.setDomain(domain);
request.setAttribute("domainAliasForm", dcf);
}
/**
* Prepares the info for the CatchAll.
*
* @param request the request being serviced
* @param manager the mail manager
* @param domain the domain
* @exception MailManagerException if an error occurs
*/
private void doCatchAll(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
AliasInfo catchAllAlias = manager.getAlias("@" + domain);
if (catchAllAlias != null)
{
List destinations = catchAllAlias.getMailDestinations();
request.setAttribute("catchAllAlias", destinations.get(0));
}
else
{
request.setAttribute("catchAllAlias", "");
}
}
/**
* Prepares the domain info
*
* @param request the request being serviced
* @param manager the mail manager
* @param domain the domain
* @exception MailManagerException if an error occurs
*/
private void doDomainInfo(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
|
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 DomainAdminAction extends JammAction {
/**
* Prepares the account information and adds it to the web page.
*
* @param request The request we're servicing
* @param manager a mail manager instance to use
* @param domain The domain we're manipulating
* @exception MailManagerException if an error occurs
*/
private void doAccounts(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
List accounts;
String startsWith = request.getParameter("startsWith");
if (StringUtils.isAlphanumeric(startsWith) &&
StringUtils.isNotEmpty(startsWith))
{
accounts = manager.getAccountsStartingWith(startsWith, domain);
}
else
{
accounts = manager.getAccounts(domain);
}
request.setAttribute("accounts", accounts);
List activeAccounts = new ArrayList();
List adminAccounts = new ArrayList();
List deleteAccounts = new ArrayList();
Iterator i = accounts.iterator();
while (i.hasNext())
{
AccountInfo account = (AccountInfo) i.next();
String name = account.getName();
if (account.isActive())
{
activeAccounts.add(name);
}
if (account.isAdministrator())
{
adminAccounts.add(name);
}
if (account.getDelete())
{
deleteAccounts.add(name);
}
}
String[] activeAccountsArray =
(String []) activeAccounts.toArray(new String[0]);
String[] adminAccountsArray =
(String []) adminAccounts.toArray(new String[0]);
String[] deleteAccountsArray =
(String []) deleteAccounts.toArray(new String[0]);
DomainConfigForm dcf = new DomainConfigForm();
dcf.setOriginalActiveItems(activeAccountsArray);
dcf.setActiveItems(activeAccountsArray);
dcf.setOriginalAdminItems(adminAccountsArray);
dcf.setAdminItems(adminAccountsArray);
dcf.setOriginalItemsToDelete(deleteAccountsArray);
dcf.setItemsToDelete(deleteAccountsArray);
dcf.setDomain(domain);
request.setAttribute("domainAccountForm", dcf);
}
/**
* Prepares the aliases for the page.
*
* @param request the request being serviced
* @param manager The mail manager to use
* @param domain which domain are we manipulating
* @exception MailManagerException if an error occurs
*/
private void doAliases(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
List aliases;
String startsWith = request.getParameter("startsWith");
if (StringUtils.isAlphanumeric(startsWith) &&
StringUtils.isNotEmpty(startsWith))
{
aliases = manager.getAliasesStartingWith(startsWith, domain);
}
else
{
aliases = manager.getAliases(domain);
}
request.setAttribute("aliases", aliases);
List activeAliases = new ArrayList();
List adminAliases = new ArrayList();
Iterator i = aliases.iterator();
while (i.hasNext())
{
AliasInfo alias = (AliasInfo) i.next();
if (alias.isActive())
{
activeAliases.add(alias.getName());
}
if (alias.isAdministrator())
{
adminAliases.add(alias.getName());
}
}
String[] activeAliasesArray =
(String []) activeAliases.toArray(new String[0]);
String[] adminAliasesArray =
(String []) adminAliases.toArray(new String[0]);
DomainConfigForm dcf = new DomainConfigForm();
dcf.setOriginalActiveItems(activeAliasesArray);
dcf.setActiveItems(activeAliasesArray);
dcf.setOriginalAdminItems(adminAliasesArray);
dcf.setAdminItems(adminAliasesArray);
dcf.setDomain(domain);
request.setAttribute("domainAliasForm", dcf);
}
/**
* Prepares the info for the CatchAll.
*
* @param request the request being serviced
* @param manager the mail manager
* @param domain the domain
* @exception MailManagerException if an error occurs
*/
private void doCatchAll(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
AliasInfo catchAllAlias = manager.getAlias("@" + domain);
if (catchAllAlias != null)
{
List destinations = catchAllAlias.getMailDestinations();
request.setAttribute("catchAllAlias", destinations.get(0));
}
else
{
request.setAttribute("catchAllAlias", "");
}
}
/**
* Prepares the domain info
*
* @param request the request being serviced
* @param manager the mail manager
* @param domain the domain
* @exception MailManagerException if an error occurs
*/
private void doDomainInfo(HttpServletRequest request, MailManager manager,
String domain)
throws MailManagerException
{
Cheatsheet (for next line):
- We are in doDomainInfo(), which is a method that prepares the domain info.
- The method is supposed to add the domain info to the request.
- The domain info is likely stored in a DomainInfo object.
- The DomainInfo object is not created in this method, but it is used in the doDomainInfo() method of the DomainConfigForm class.
- The DomainInfo object is likely created in the DomainConfigForm class.
- The DomainConfigForm class is used in the doAccounts() and doAliases() methods.
- The DomainConfigForm class has a setDomain() method that sets the domain.
- The DomainConfigForm class has a getDomain() method that returns the domain.
- The DomainInfo object is likely created in the DomainConfigForm class and is used to store the domain info.
- The DomainInfo object is not created in this method, but it is used in the doDomainInfo() method of the DomainConfigForm class.
- The DomainInfo object is likely created in the DomainConfigForm class.
- The DomainConfigForm class is used in the doAccounts() and doAliases() methods.
- The DomainConfigForm class has a setDomain() method that sets the domain.
- The DomainConfigForm class has a getDomain() method that returns the domain.
- The DomainInfo object is likely created in the DomainConfigForm class and is used to store the domain info.
- The DomainInfo object is not created in this method, but it is used in the doDomainInfo() method of the DomainConfigForm class.
- The DomainInfo object is likely created in the DomainConfigForm class.
- The DomainConfigForm class is used in the doAccounts() and doAliases() methods.
- The DomainConfigForm class has a setDomain() method that sets the domain.
- The DomainConfigForm class has a getDomain() method that returns the domain.
- The DomainInfo object is likely created in the DomainConfigForm class and is used to store the domain info.
- The DomainInfo object is not created in this method, but it is used in the doDomainInfo() method of the DomainConfigForm class.
- The DomainInfo object is likely created in the DomainConfigForm class.
- The DomainConfigForm class is used in the doAccounts() and doAliases() methods.
- The DomainConfigForm class has a setDomain() method that sets the domain.
- The DomainConfigForm class has a getDomain() method that returns the domain.
- The DomainInfo object is likely created in the DomainConfigForm class and is used to store the domain info.
- The DomainInfo object is not created in this method, but it is used in the doDomainInfo() method of the DomainConfigForm class.
- The DomainInfo object is likely created in the DomainConfigForm class.
- The DomainConfigForm class is used in the doAccounts() and doAliases() methods.
- The DomainConfigForm class has a setDomain() method that sets the domain.
- The DomainConfigForm class has a getDomain() method that returns the domain.
- The DomainInfo object is likely created in the DomainConfigForm class and is used to store the domain info.
- The DomainInfo object is not created in this method, but it is used in the doDomainInfo() method of the DomainConfigForm class.
- The DomainInfo object is likely created in the DomainConfigForm class.
- The DomainConfigForm class is used in the doAccounts() and doAliases() methods.
- The DomainConfigForm class has a setDomain() method that sets the domain.
- The DomainConfigForm class has a getDomain() method that returns the domain.
- The DomainInfo object is likely created in the DomainConfigForm class and is used to store the domain info.
- The DomainInfo object is not created in this method, but it is used in the doDomainInfo() method of the DomainConfigForm class.
- The DomainInfo object is likely created in the DomainConfigForm class.
- The DomainConfigForm class is used in the doAccounts() and doAliases() methods.
- The DomainConfigForm class has a setDomain() method that sets the domain.
- The DomainConfigForm class has a getDomain() method that returns the domain.
- The DomainInfo object is likely created in the DomainConfigForm class and is used to store the domain info.
- The DomainInfo object is not created in this method, but it is used in the doDomainInfo() method of the DomainConfigForm class.
- The DomainInfo object is likely created in the DomainConfigForm class.
- The DomainConfigForm class is used in the doAccounts() and doAliases() methods.
- The DomainConfigForm class has a setDomain() method that sets the domain.
- The DomainConfigForm class has a getDomain() method that returns the domain.
- The DomainInfo object is likely created in the DomainConfig
|
|
Please complete the code given below.
#!/usr/bin/python3
# @begin:license
#
# Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# @end:license
import asyncio
import errno
import functools
import fractions
import logging
import os
import os.path
import time
import uuid
from typing import cast, Any, Union, Callable, Awaitable, List, Tuple, Text
from noisicaa.core.typing_extra import down_cast
from noisicaa.core import ipc
from noisicaa import audioproc
from noisicaa import lv2
from noisicaa import editor_main_pb2
from . import player
from . import render_pb2
from . import project as project_lib
from . import session_value_store
logger = logging.getLogger(__name__)
class RendererFailed(Exception):
pass
class DataStreamProtocol(asyncio.Protocol):
def __init__(
self, stream: asyncio.StreamWriter, event_loop: asyncio.AbstractEventLoop
) -> None:
super().__init__()
self.__stream = stream
self.__closed = asyncio.Event(loop=event_loop)
async def wait(self) -> None:
await self.__closed.wait()
def data_received(self, data: bytes) -> None:
if not self.__stream.transport.is_closing():
logger.debug("Forward %d bytes to encoder", len(data))
self.__stream.write(data)
def eof_received(self) -> None:
if not self.__stream.transport.is_closing():
self.__stream.write_eof()
self.__closed.set()
class EncoderProtocol(asyncio.streams.FlowControlMixin, asyncio.SubprocessProtocol):
def __init__(
self, *,
data_handler: Callable[[bytes], None],
stderr_handler: Callable[[str], None],
failure_handler: Callable[[int], None],
event_loop: asyncio.AbstractEventLoop
) -> None:
# mypy does know about the loop argument
super().__init__(loop=event_loop) # type: ignore[call-arg]
self.__closed = asyncio.Event(loop=event_loop)
self.__data_handler = data_handler
self.__stderr_handler = stderr_handler
self.__failure_handler = failure_handler
self.__stderr_buf = bytearray()
self.__transport = None # type: asyncio.SubprocessTransport
async def wait(self) -> None:
await self.__closed.wait()
def connection_made(self, transport: asyncio.BaseTransport) -> None:
self.__transport = down_cast(asyncio.SubprocessTransport, transport)
def pipe_data_received(self, fd: int, data: Union[bytes, Text]) -> None:
data = down_cast(bytes, data)
if fd == 1:
logger.debug("Writing %d encoded bytes", len(data))
self.__data_handler(data)
else:
assert fd == 2
self.__stderr_buf.extend(data)
while True:
eol = self.__stderr_buf.find(b'\n')
if eol < 0:
break
line = self.__stderr_buf[:eol].decode('utf-8')
del self.__stderr_buf[:eol+1]
self.__stderr_handler(line)
def process_exited(self) -> None:
if self.__stderr_buf:
line = self.__stderr_buf.decode('utf-8')
del self.__stderr_buf[:]
self.__stderr_handler(line)
rc = self.__transport.get_returncode()
assert rc is not None
if rc != 0:
self.__failure_handler(rc)
self.__closed.set()
class Encoder(object):
def __init__(
self, *,
data_handler: Callable[[bytes], None],
error_handler: Callable[[str], None],
event_loop: asyncio.AbstractEventLoop,
settings: render_pb2.RenderSettings
) -> None:
self.event_loop = event_loop
self.data_handler = data_handler
self.error_handler = error_handler
self.settings = settings
@classmethod
def create(cls, *, settings: render_pb2.RenderSettings, **kwargs: Any) -> 'Encoder':
cls_map = {
render_pb2.RenderSettings.FLAC: FlacEncoder,
render_pb2.RenderSettings.OGG: OggEncoder,
render_pb2.RenderSettings.WAVE: WaveEncoder,
render_pb2.RenderSettings.MP3: Mp3Encoder,
render_pb2.RenderSettings.FAIL__TEST_ONLY__: FailingEncoder,
}
encoder_cls = cls_map[settings.output_format]
return encoder_cls(settings=settings, **kwargs)
def get_writer(self) -> asyncio.StreamWriter:
raise NotImplementedError
async def setup(self) -> None:
logger.info("Setting up %s...", type(self).__name__)
async def cleanup(self) -> None:
logger.info("%s cleaned up.", type(self).__name__)
async def wait(self) -> None:
raise NotImplementedError
class SubprocessEncoder(Encoder):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.__cmdline = None # type: List[str]
self.__transport = None # type: asyncio.SubprocessTransport
self.__protocol = None # type: EncoderProtocol
self.__stdin = None # type: asyncio.StreamWriter
self.__stderr = None # type: List[str]
self.__returncode = None # type: int
def get_writer(self) -> asyncio.StreamWriter:
return self.__stdin
def get_cmd_line(self) -> List[str]:
raise NotImplementedError
def __fail(self, rc: int) -> None:
assert rc
self.error_handler(
"%s failed with returncode %d:\n%s" % (
' '.join(self.__cmdline), rc, '\n'.join(self.__stderr)))
async def setup(self) -> None:
await super().setup()
self.__cmdline = self.get_cmd_line()
logger.info("Starting encoder process: %s", ' '.join(self.__cmdline))
self.__stderr = []
transport, protocol = await self.event_loop.subprocess_exec(
functools.partial(
EncoderProtocol,
data_handler=self.data_handler,
stderr_handler=self.__stderr.append,
failure_handler=self.__fail,
event_loop=self.event_loop),
*self.__cmdline,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
self.__transport = down_cast(asyncio.SubprocessTransport, transport)
self.__protocol = down_cast(EncoderProtocol, protocol)
self.__stdin = asyncio.StreamWriter(
transport=self.__transport.get_pipe_transport(0),
protocol=self.__protocol,
reader=None,
loop=self.event_loop)
async def cleanup(self) -> None:
if self.__transport is not None:
self.__transport.close()
await self.__protocol.wait()
self.__transport = None
self.__protocol = None
await super().cleanup()
async def wait(self) -> None:
if not self.__stdin.transport.is_closing():
await self.__stdin.drain()
logger.info("All bytes written to encoder process.")
logger.info("Waiting for encoder process to complete...")
await self.__protocol.wait()
class FfmpegEncoder(SubprocessEncoder):
def get_cmd_line(self) -> List[str]:
global_flags = [
'-nostdin',
]
input_flags = [
'-f', 'f32le',
'-ar', '%d' % self.settings.sample_rate,
'-ac', '2',
'-i', 'pipe:0',
]
output_flags = [
'pipe:1',
]
return (
['/usr/bin/ffmpeg']
+ global_flags
+ input_flags
+ self.get_encoder_flags()
+ output_flags)
def get_encoder_flags(self) -> List[str]:
raise NotImplementedError
class FlacEncoder(FfmpegEncoder):
def get_encoder_flags(self) -> List[str]:
compression_level = self.settings.flac_settings.compression_level
if not 0 <= compression_level <= 12:
raise ValueError("Invalid flac_settings.compression_level %d" % compression_level)
bits_per_sample = self.settings.flac_settings.bits_per_sample
if bits_per_sample not in (16, 24):
raise ValueError("Invalid flac_settings.bits_per_sample %d" % bits_per_sample)
sample_fmt = {
16: 's16',
24: 's32',
}[bits_per_sample]
return [
'-f', 'flac',
'-compression_level', str(compression_level),
'-sample_fmt', sample_fmt,
]
class OggEncoder(FfmpegEncoder):
def get_encoder_flags(self) -> List[str]:
flags = [
'-f', 'ogg',
]
encode_mode = self.settings.ogg_settings.encode_mode
if encode_mode == render_pb2.RenderSettings.OggSettings.VBR:
quality = self.settings.ogg_settings.quality
if not -1.0 <= quality <= 10.0:
raise ValueError("Invalid ogg_settings.quality %f" % quality)
flags += ['-q', '%.1f' % quality]
elif encode_mode == render_pb2.RenderSettings.OggSettings.CBR:
bitrate = self.settings.ogg_settings.bitrate
if not 45 <= bitrate <= 500:
raise ValueError("Invalid ogg_settings.bitrate %d" % bitrate)
flags += ['-b:a', '%dk' % bitrate]
return flags
class WaveEncoder(FfmpegEncoder):
def get_encoder_flags(self) -> List[str]:
bits_per_sample = self.settings.wave_settings.bits_per_sample
if bits_per_sample not in (16, 24, 32):
raise ValueError("Invalid wave_settings.bits_per_sample %d" % bits_per_sample)
codec = {
16: 'pcm_s16le',
24: 'pcm_s24le',
32: 'pcm_s32le',
}[bits_per_sample]
return [
'-f', 'wav',
'-c:a', codec,
]
class Mp3Encoder(FfmpegEncoder):
def get_encoder_flags(self) -> List[str]:
flags = [
'-f', 'mp3',
'-c:a', 'libmp3lame',
]
encode_mode = self.settings.mp3_settings.encode_mode
if encode_mode == render_pb2.RenderSettings.Mp3Settings.VBR:
compression_level = self.settings.mp3_settings.compression_level
if not 0 <= compression_level <= 9:
raise ValueError("Invalid mp3_settings.compression_level %d" % compression_level)
flags += ['-compression_level', '%d' % compression_level]
elif encode_mode == render_pb2.RenderSettings.Mp3Settings.CBR:
bitrate = self.settings.mp3_settings.bitrate
if not 32 <= bitrate <= 320:
raise ValueError("Invalid mp3_settings.bitrate %d" % bitrate)
flags += ['-b:a', '%dk' % bitrate]
return flags
class FailingEncoder(SubprocessEncoder):
def get_cmd_line(self) -> List[str]:
return [
'/bin/false',
]
class Renderer(object):
def __init__(
self, *,
project: project_lib.BaseProject,
callback_address: str,
render_settings: render_pb2.RenderSettings,
tmp_dir: str,
server: ipc.Server,
manager: ipc.Stub,
urid_mapper: lv2.URIDMapper,
event_loop: asyncio.AbstractEventLoop
) -> None:
self.__project = project
self.__callback_address = callback_address
self.__render_settings = render_settings
self.__tmp_dir = tmp_dir
self.__server = server
self.__manager = manager
self.__urid_mapper = urid_mapper
self.__event_loop = event_loop
self.__failed = asyncio.Event(loop=self.__event_loop)
self.__callback = None # type: ipc.Stub
self.__data_queue = None # type: asyncio.Queue
self.__data_pump_task = None # type: asyncio.Task
self.__datastream_address = None # type: str
self.__datastream_transport = None # type: asyncio.BaseTransport
self.__datastream_protocol = None # type: DataStreamProtocol
self.__datastream_fd = None # type: int
self.__encoder = None # type: Encoder
self.__player_state_changed = None # type: asyncio.Event
self.__player_started = None # type: asyncio.Event
self.__player_finished = None # type: asyncio.Event
self.__playing = None # type: bool
self.__current_time = None # type: audioproc.MusicalTime
self.__duration = self.__project.duration
self.__audioproc_address = None # type: str
self.__audioproc_client = None # type: audioproc.AbstractAudioProcClient
self.__player = None # type: player.Player
self.__next_progress_update = None # type: Tuple[fractions.Fraction, float]
self.__progress_pump_task = None # type: asyncio.Task
self.__session_values = None # type: session_value_store.SessionValueStore
def __fail(self, msg: str) -> None:
logger.error("Encoding failed: %s", msg)
self.__failed.set()
async def __wait_for_some(self, *futures: Awaitable) -> None:
"""Wait until at least one of the futures completed and cancel all uncompleted."""
done, pending = await asyncio.wait(
futures,
loop=self.__event_loop,
return_when=asyncio.FIRST_COMPLETED)
for f in pending:
f.cancel()
for f in done:
f.result()
async def __setup_callback_stub(self) -> None:
self.__callback = ipc.Stub(self.__event_loop, self.__callback_address)
await self.__callback.connect()
async def __data_pump_main(self) -> None:
while True:
get = asyncio.ensure_future(self.__data_queue.get(), loop=self.__event_loop)
await self.__wait_for_some(get, self.__failed.wait())
if self.__failed.is_set():
logger.info("Stopping data pump, because encoder failed.")
break
if get.done():
data = get.result()
if data is None:
logger.info("Shutting down data pump.")
break
response = render_pb2.RenderDataResponse()
await self.__callback.call(
'DATA', render_pb2.RenderDataRequest(data=data), response)
if not response.status:
self.__fail(response.msg)
async def __setup_data_pump(self) -> None:
self.__data_queue = asyncio.Queue(loop=self.__event_loop)
self.__data_pump_task = self.__event_loop.create_task(self.__data_pump_main())
async def __setup_encoder_process(self) -> None:
self.__encoder = Encoder.create(
data_handler=self.__data_queue.put_nowait,
error_handler=self.__fail,
event_loop=self.__event_loop,
settings=self.__render_settings)
await self.__encoder.setup()
async def __setup_datastream_pipe(self) -> None:
self.__datastream_address = os.path.join(
|
[
" self.__tmp_dir, 'datastream.%s.pipe' % uuid.uuid4().hex)"
] | 1,276
|
lcc
|
python
| null |
4b93f91719b36d7aee8a2f7f39b3991d464913e3bc3e77b4
| 16
|
Your task is code completion.
#!/usr/bin/python3
# @begin:license
#
# Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# @end:license
import asyncio
import errno
import functools
import fractions
import logging
import os
import os.path
import time
import uuid
from typing import cast, Any, Union, Callable, Awaitable, List, Tuple, Text
from noisicaa.core.typing_extra import down_cast
from noisicaa.core import ipc
from noisicaa import audioproc
from noisicaa import lv2
from noisicaa import editor_main_pb2
from . import player
from . import render_pb2
from . import project as project_lib
from . import session_value_store
logger = logging.getLogger(__name__)
class RendererFailed(Exception):
pass
class DataStreamProtocol(asyncio.Protocol):
def __init__(
self, stream: asyncio.StreamWriter, event_loop: asyncio.AbstractEventLoop
) -> None:
super().__init__()
self.__stream = stream
self.__closed = asyncio.Event(loop=event_loop)
async def wait(self) -> None:
await self.__closed.wait()
def data_received(self, data: bytes) -> None:
if not self.__stream.transport.is_closing():
logger.debug("Forward %d bytes to encoder", len(data))
self.__stream.write(data)
def eof_received(self) -> None:
if not self.__stream.transport.is_closing():
self.__stream.write_eof()
self.__closed.set()
class EncoderProtocol(asyncio.streams.FlowControlMixin, asyncio.SubprocessProtocol):
def __init__(
self, *,
data_handler: Callable[[bytes], None],
stderr_handler: Callable[[str], None],
failure_handler: Callable[[int], None],
event_loop: asyncio.AbstractEventLoop
) -> None:
# mypy does know about the loop argument
super().__init__(loop=event_loop) # type: ignore[call-arg]
self.__closed = asyncio.Event(loop=event_loop)
self.__data_handler = data_handler
self.__stderr_handler = stderr_handler
self.__failure_handler = failure_handler
self.__stderr_buf = bytearray()
self.__transport = None # type: asyncio.SubprocessTransport
async def wait(self) -> None:
await self.__closed.wait()
def connection_made(self, transport: asyncio.BaseTransport) -> None:
self.__transport = down_cast(asyncio.SubprocessTransport, transport)
def pipe_data_received(self, fd: int, data: Union[bytes, Text]) -> None:
data = down_cast(bytes, data)
if fd == 1:
logger.debug("Writing %d encoded bytes", len(data))
self.__data_handler(data)
else:
assert fd == 2
self.__stderr_buf.extend(data)
while True:
eol = self.__stderr_buf.find(b'\n')
if eol < 0:
break
line = self.__stderr_buf[:eol].decode('utf-8')
del self.__stderr_buf[:eol+1]
self.__stderr_handler(line)
def process_exited(self) -> None:
if self.__stderr_buf:
line = self.__stderr_buf.decode('utf-8')
del self.__stderr_buf[:]
self.__stderr_handler(line)
rc = self.__transport.get_returncode()
assert rc is not None
if rc != 0:
self.__failure_handler(rc)
self.__closed.set()
class Encoder(object):
def __init__(
self, *,
data_handler: Callable[[bytes], None],
error_handler: Callable[[str], None],
event_loop: asyncio.AbstractEventLoop,
settings: render_pb2.RenderSettings
) -> None:
self.event_loop = event_loop
self.data_handler = data_handler
self.error_handler = error_handler
self.settings = settings
@classmethod
def create(cls, *, settings: render_pb2.RenderSettings, **kwargs: Any) -> 'Encoder':
cls_map = {
render_pb2.RenderSettings.FLAC: FlacEncoder,
render_pb2.RenderSettings.OGG: OggEncoder,
render_pb2.RenderSettings.WAVE: WaveEncoder,
render_pb2.RenderSettings.MP3: Mp3Encoder,
render_pb2.RenderSettings.FAIL__TEST_ONLY__: FailingEncoder,
}
encoder_cls = cls_map[settings.output_format]
return encoder_cls(settings=settings, **kwargs)
def get_writer(self) -> asyncio.StreamWriter:
raise NotImplementedError
async def setup(self) -> None:
logger.info("Setting up %s...", type(self).__name__)
async def cleanup(self) -> None:
logger.info("%s cleaned up.", type(self).__name__)
async def wait(self) -> None:
raise NotImplementedError
class SubprocessEncoder(Encoder):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.__cmdline = None # type: List[str]
self.__transport = None # type: asyncio.SubprocessTransport
self.__protocol = None # type: EncoderProtocol
self.__stdin = None # type: asyncio.StreamWriter
self.__stderr = None # type: List[str]
self.__returncode = None # type: int
def get_writer(self) -> asyncio.StreamWriter:
return self.__stdin
def get_cmd_line(self) -> List[str]:
raise NotImplementedError
def __fail(self, rc: int) -> None:
assert rc
self.error_handler(
"%s failed with returncode %d:\n%s" % (
' '.join(self.__cmdline), rc, '\n'.join(self.__stderr)))
async def setup(self) -> None:
await super().setup()
self.__cmdline = self.get_cmd_line()
logger.info("Starting encoder process: %s", ' '.join(self.__cmdline))
self.__stderr = []
transport, protocol = await self.event_loop.subprocess_exec(
functools.partial(
EncoderProtocol,
data_handler=self.data_handler,
stderr_handler=self.__stderr.append,
failure_handler=self.__fail,
event_loop=self.event_loop),
*self.__cmdline,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
self.__transport = down_cast(asyncio.SubprocessTransport, transport)
self.__protocol = down_cast(EncoderProtocol, protocol)
self.__stdin = asyncio.StreamWriter(
transport=self.__transport.get_pipe_transport(0),
protocol=self.__protocol,
reader=None,
loop=self.event_loop)
async def cleanup(self) -> None:
if self.__transport is not None:
self.__transport.close()
await self.__protocol.wait()
self.__transport = None
self.__protocol = None
await super().cleanup()
async def wait(self) -> None:
if not self.__stdin.transport.is_closing():
await self.__stdin.drain()
logger.info("All bytes written to encoder process.")
logger.info("Waiting for encoder process to complete...")
await self.__protocol.wait()
class FfmpegEncoder(SubprocessEncoder):
def get_cmd_line(self) -> List[str]:
global_flags = [
'-nostdin',
]
input_flags = [
'-f', 'f32le',
'-ar', '%d' % self.settings.sample_rate,
'-ac', '2',
'-i', 'pipe:0',
]
output_flags = [
'pipe:1',
]
return (
['/usr/bin/ffmpeg']
+ global_flags
+ input_flags
+ self.get_encoder_flags()
+ output_flags)
def get_encoder_flags(self) -> List[str]:
raise NotImplementedError
class FlacEncoder(FfmpegEncoder):
def get_encoder_flags(self) -> List[str]:
compression_level = self.settings.flac_settings.compression_level
if not 0 <= compression_level <= 12:
raise ValueError("Invalid flac_settings.compression_level %d" % compression_level)
bits_per_sample = self.settings.flac_settings.bits_per_sample
if bits_per_sample not in (16, 24):
raise ValueError("Invalid flac_settings.bits_per_sample %d" % bits_per_sample)
sample_fmt = {
16: 's16',
24: 's32',
}[bits_per_sample]
return [
'-f', 'flac',
'-compression_level', str(compression_level),
'-sample_fmt', sample_fmt,
]
class OggEncoder(FfmpegEncoder):
def get_encoder_flags(self) -> List[str]:
flags = [
'-f', 'ogg',
]
encode_mode = self.settings.ogg_settings.encode_mode
if encode_mode == render_pb2.RenderSettings.OggSettings.VBR:
quality = self.settings.ogg_settings.quality
if not -1.0 <= quality <= 10.0:
raise ValueError("Invalid ogg_settings.quality %f" % quality)
flags += ['-q', '%.1f' % quality]
elif encode_mode == render_pb2.RenderSettings.OggSettings.CBR:
bitrate = self.settings.ogg_settings.bitrate
if not 45 <= bitrate <= 500:
raise ValueError("Invalid ogg_settings.bitrate %d" % bitrate)
flags += ['-b:a', '%dk' % bitrate]
return flags
class WaveEncoder(FfmpegEncoder):
def get_encoder_flags(self) -> List[str]:
bits_per_sample = self.settings.wave_settings.bits_per_sample
if bits_per_sample not in (16, 24, 32):
raise ValueError("Invalid wave_settings.bits_per_sample %d" % bits_per_sample)
codec = {
16: 'pcm_s16le',
24: 'pcm_s24le',
32: 'pcm_s32le',
}[bits_per_sample]
return [
'-f', 'wav',
'-c:a', codec,
]
class Mp3Encoder(FfmpegEncoder):
def get_encoder_flags(self) -> List[str]:
flags = [
'-f', 'mp3',
'-c:a', 'libmp3lame',
]
encode_mode = self.settings.mp3_settings.encode_mode
if encode_mode == render_pb2.RenderSettings.Mp3Settings.VBR:
compression_level = self.settings.mp3_settings.compression_level
if not 0 <= compression_level <= 9:
raise ValueError("Invalid mp3_settings.compression_level %d" % compression_level)
flags += ['-compression_level', '%d' % compression_level]
elif encode_mode == render_pb2.RenderSettings.Mp3Settings.CBR:
bitrate = self.settings.mp3_settings.bitrate
if not 32 <= bitrate <= 320:
raise ValueError("Invalid mp3_settings.bitrate %d" % bitrate)
flags += ['-b:a', '%dk' % bitrate]
return flags
class FailingEncoder(SubprocessEncoder):
def get_cmd_line(self) -> List[str]:
return [
'/bin/false',
]
class Renderer(object):
def __init__(
self, *,
project: project_lib.BaseProject,
callback_address: str,
render_settings: render_pb2.RenderSettings,
tmp_dir: str,
server: ipc.Server,
manager: ipc.Stub,
urid_mapper: lv2.URIDMapper,
event_loop: asyncio.AbstractEventLoop
) -> None:
self.__project = project
self.__callback_address = callback_address
self.__render_settings = render_settings
self.__tmp_dir = tmp_dir
self.__server = server
self.__manager = manager
self.__urid_mapper = urid_mapper
self.__event_loop = event_loop
self.__failed = asyncio.Event(loop=self.__event_loop)
self.__callback = None # type: ipc.Stub
self.__data_queue = None # type: asyncio.Queue
self.__data_pump_task = None # type: asyncio.Task
self.__datastream_address = None # type: str
self.__datastream_transport = None # type: asyncio.BaseTransport
self.__datastream_protocol = None # type: DataStreamProtocol
self.__datastream_fd = None # type: int
self.__encoder = None # type: Encoder
self.__player_state_changed = None # type: asyncio.Event
self.__player_started = None # type: asyncio.Event
self.__player_finished = None # type: asyncio.Event
self.__playing = None # type: bool
self.__current_time = None # type: audioproc.MusicalTime
self.__duration = self.__project.duration
self.__audioproc_address = None # type: str
self.__audioproc_client = None # type: audioproc.AbstractAudioProcClient
self.__player = None # type: player.Player
self.__next_progress_update = None # type: Tuple[fractions.Fraction, float]
self.__progress_pump_task = None # type: asyncio.Task
self.__session_values = None # type: session_value_store.SessionValueStore
def __fail(self, msg: str) -> None:
logger.error("Encoding failed: %s", msg)
self.__failed.set()
async def __wait_for_some(self, *futures: Awaitable) -> None:
"""Wait until at least one of the futures completed and cancel all uncompleted."""
done, pending = await asyncio.wait(
futures,
loop=self.__event_loop,
return_when=asyncio.FIRST_COMPLETED)
for f in pending:
f.cancel()
for f in done:
f.result()
async def __setup_callback_stub(self) -> None:
self.__callback = ipc.Stub(self.__event_loop, self.__callback_address)
await self.__callback.connect()
async def __data_pump_main(self) -> None:
while True:
get = asyncio.ensure_future(self.__data_queue.get(), loop=self.__event_loop)
await self.__wait_for_some(get, self.__failed.wait())
if self.__failed.is_set():
logger.info("Stopping data pump, because encoder failed.")
break
if get.done():
data = get.result()
if data is None:
logger.info("Shutting down data pump.")
break
response = render_pb2.RenderDataResponse()
await self.__callback.call(
'DATA', render_pb2.RenderDataRequest(data=data), response)
if not response.status:
self.__fail(response.msg)
async def __setup_data_pump(self) -> None:
self.__data_queue = asyncio.Queue(loop=self.__event_loop)
self.__data_pump_task = self.__event_loop.create_task(self.__data_pump_main())
async def __setup_encoder_process(self) -> None:
self.__encoder = Encoder.create(
data_handler=self.__data_queue.put_nowait,
error_handler=self.__fail,
event_loop=self.__event_loop,
settings=self.__render_settings)
await self.__encoder.setup()
async def __setup_datastream_pipe(self) -> None:
self.__datastream_address = os.path.join(
|
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]
async def __setup_datastream_pipe(self) -> None:
self.__datastream_address = os.path.join(
self.__tmp_dir, str(uuid.uuid4()))
self.__datastream_fd = os.open(
self.__datastream_address, os.O_RDWR | os.O_CREAT, 0o600)
self.__datastream_transport, self.__datastream_protocol = await self.__event_loop.open_unix_connection(
self.__datastream_address)
self.__datastream_protocol = DataStreamProtocol(
stream=self.__datastream_transport.get_pipe_transport(0),
event_loop=self.__event_loop)
self.__datastream_protocol.__closed = asyncio.Event(loop=self.__event_loop)
self.__datastream_protocol.data_received = functools.partial(
self.__datastream_protocol.data_received, self.__datastream_fd)
self.__datastream_protocol.eof_received = functools.partial(
self.__datastream_protocol.eof_received, self.__datastream_fd)
self.__datastream_protocol.__closed.set()
self.__datastream_fd = self.__datastream_transport.get_pipe_transport(0).get_pipe_fd(0)
Relevant lines and variables:
- `self.__datastream_address` is the path to the data stream file.
- `self.__datastream_fd` is the file descriptor of the data stream file.
- `self.__datastream_transport` and `self.__datastream_protocol` are the transport and protocol for the data stream connection.
- `self.__datastream_protocol` has methods `data_received` and `eof_received` that need to be updated to use `self.__datastream_fd`.
- `self.__event_loop` is the event loop used to open the connection.
Next line will likely be:
- The `data_received` method should be updated to write the received data to the file descriptor `self.__datastream_fd`.
- The `eof_received` method should be updated to close the file descriptor `self.__datastream_fd` and set the `__closed` event.
Here's the completed code:
```python
async def __setup_datastream_pipe(self) -> None:
self.__datastream_address = os.path.join(
self.__tmp_dir, str(uuid.uuid4()))
self.__datastream_fd = os.open(
self.__datastream_address, os.O_RDWR | os.O_CREAT, 0o600)
self.__datastream_transport, self.__datastream_protocol = await self.__event_loop.open_unix_connection(
self.__datastream_address)
self.__datastream_protocol = DataStreamProtocol(
stream=self.__datastream_transport.get_pipe_transport(0),
event_loop=self.__event_loop)
self.__datastream_protocol.__closed = asyncio.Event(loop=self.__event_loop)
self.__datastream_protocol.data_received = functools.partial(
self.__datastream_protocol.data_received, self.__datastream_fd)
self.__datastream_protocol.eof_received = functools.partial(
self.__datastream_protocol.eof_received, self.__datastream_fd)
self.__datastream_protocol.__closed.set()
self.__datastream_fd = self.__datastream_transport.get_pipe_transport(0).get_pipe_fd(0)
# Update data_received method
def data_received(self, data: bytes) -> None:
if not self.__stream.transport.is_closing():
logger.debug("Forward %d bytes to encoder", len(data))
os.write(self.__datastream_fd, data)
# Update eof_received method
def eof_received(self) -> None:
if not self.__stream.transport.is_closing():
os.close(self.__datastream_fd)
self.__closed.set()
```
|
|
Please complete the code given below.
/*
* This file is part of ChronoJump
*
* ChronoJump 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.
*
* ChronoJump is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Copyright (C) 2004-2017 Xavier de Blas <xaviblas@gmail.com>
*/
using System;
using Gtk;
using Glade;
using GLib; //for Value
using System.Text; //StringBuilder
using System.Collections; //ArrayList
using Mono.Unix;
public class ConvertWeightWindow
{
[Widget] Gtk.Window convert_weight;
static ConvertWeightWindow ConvertWeightWindowBox;
[Widget] Gtk.TreeView treeview1;
[Widget] Gtk.Label label_old_weight_value;
[Widget] Gtk.Label label_new_weight_value;
[Widget] Gtk.Button button_accept;
[Widget] Gtk.Button button_cancel;
TreeStore store;
double oldPersonWeight;
double newPersonWeight;
string [] jumpsNormal;
string [] jumpsReactive;
int columnBool1 = 6;
int columnBool2 = 8;
string simpleString;
string reactiveString;
ConvertWeightWindow (double oldPersonWeight, double newPersonWeight, string [] jumpsNormal, string [] jumpsReactive) {
Glade.XML gladeXML;
gladeXML = Glade.XML.FromAssembly (Util.GetGladePath() + "convert_weight.glade", "convert_weight", null);
gladeXML.Autoconnect(this);
//put an icon to window
UtilGtk.IconWindow(convert_weight);
this.oldPersonWeight = oldPersonWeight;
this.newPersonWeight = newPersonWeight;
this.jumpsNormal = jumpsNormal;
this.jumpsReactive = jumpsReactive;
simpleString = Catalog.GetString("Simple");
reactiveString = Catalog.GetString("Reactive");
createTreeViewWithCheckboxes(treeview1);
store = new TreeStore(
typeof (string), //uniqueID
typeof (string), //simple or reactive
typeof (string), //jumpType
typeof (string), //tf
typeof (string), //tc
/* following eg of a subject of 70Kg
* that has done a jump with an extra of 70Kg
* and after (in same session) changes person weight to 80
*/
typeof (string), //weight % + weight kg (old) (eg: 100%-70Kg)
typeof (bool), //mark new option 1
typeof (string), //weight % + weight kg (new option1) (eg: 100%-80Kg)
typeof (bool), //mark new option 2
typeof (string) //weight % + weight kg (new option2) (eg: 87%-70Kg)
);
treeview1.Model = store;
fillTreeView( treeview1, store );
}
static public ConvertWeightWindow Show (
double oldPersonWeight, double newPersonWeight, string [] jumpsNormal, string [] jumpsReactive)
{
if (ConvertWeightWindowBox == null) {
ConvertWeightWindowBox =
new ConvertWeightWindow (oldPersonWeight, newPersonWeight, jumpsNormal, jumpsReactive);
}
ConvertWeightWindowBox.label_old_weight_value.Text = oldPersonWeight.ToString() + " Kg";
ConvertWeightWindowBox.label_new_weight_value.Text = newPersonWeight.ToString() + " Kg";
ConvertWeightWindowBox.convert_weight.Show ();
return ConvertWeightWindowBox;
}
protected void createTreeViewWithCheckboxes (Gtk.TreeView tv) {
tv.HeadersVisible=true;
int count = 0;
tv.AppendColumn ( Catalog.GetString("ID"), new CellRendererText(), "text", count++);
tv.AppendColumn (
Catalog.GetString("Simple") + " " +
Catalog.GetString("or") + " " +
Catalog.GetString("Reactive")
, new CellRendererText(), "text", count++);
tv.AppendColumn ( Catalog.GetString("Type"), new CellRendererText(), "text", count++);
tv.AppendColumn (
Catalog.GetString("TF")
/*
+ "\n" +
Catalog.GetString("TF") + "(" +
Catalog.GetString("AVG") + ")"
*/
, new CellRendererText(), "text", count++);
tv.AppendColumn (
Catalog.GetString("TC")
/*
+ "\n" +
Catalog.GetString("TC") + "(" +
Catalog.GetString("AVG") + ")"
*/
, new CellRendererText(), "text", count++);
tv.AppendColumn ( Catalog.GetString("Old weight"), new CellRendererText(), "text", count++);
CellRendererToggle crt = new CellRendererToggle();
crt.Visible = true;
crt.Activatable = true;
crt.Active = true;
crt.Toggled += ItemToggled1;
TreeViewColumn column = new TreeViewColumn ("", crt, "active", count);
column.Clickable = true;
tv.InsertColumn (column, count++);
tv.AppendColumn ( Catalog.GetString("New weight\noption 1"), new CellRendererText(), "text", count++);
CellRendererToggle crt2 = new CellRendererToggle();
crt2.Visible = true;
crt2.Activatable = true;
crt2.Active = true;
crt2.Toggled += ItemToggled2;
column = new TreeViewColumn ("", crt2, "active", count);
column.Clickable = true;
tv.InsertColumn (column, count++);
tv.AppendColumn ( Catalog.GetString("New weight\noption 2"), new CellRendererText(), "text", count++);
}
void ItemToggled1(object o, ToggledArgs args) {
ItemToggled(columnBool1, columnBool2, o, args);
}
void ItemToggled2(object o, ToggledArgs args) {
ItemToggled(columnBool2, columnBool1, o, args);
}
void ItemToggled(int columnThis, int columnOther, object o, ToggledArgs args) {
TreeIter iter;
if (store.GetIter (out iter, new TreePath(args.Path)))
{
bool val = (bool) store.GetValue (iter, columnThis);
LogB.Information (string.Format("toggled {0} with value {1}", args.Path, !val));
if(args.Path == "0") {
if (store.GetIterFirst(out iter)) {
val = (bool) store.GetValue (iter, columnThis);
store.SetValue (iter, columnThis, !val);
store.SetValue (iter, columnOther, val);
while ( store.IterNext(ref iter) ){
store.SetValue (iter, columnThis, !val);
store.SetValue (iter, columnOther, val);
}
}
} else {
store.SetValue (iter, columnThis, !val);
store.SetValue (iter, columnOther, val);
//usnelect "all" checkboxes
store.GetIterFirst(out iter);
store.SetValue (iter, columnThis, false);
store.SetValue (iter, columnOther, false);
}
}
}
private string createStringCalculatingKgs (double personWeightKg, double jumpWeightPercent) {
return jumpWeightPercent + "% " +
Convert.ToDouble(Util.WeightFromPercentToKg(jumpWeightPercent, personWeightKg)).ToString()
+ "Kg";
}
private string createStringCalculatingPercent (double oldPersonWeightKg, double newPersonWeightKg, double jumpWeightPercent) {
double jumpInKg = Util.WeightFromPercentToKg(jumpWeightPercent, oldPersonWeightKg);
double jumpPercentToNewPersonWeight = Convert.ToDouble(Util.WeightFromKgToPercent(jumpInKg, newPersonWeightKg));
return jumpPercentToNewPersonWeight + "% " + jumpInKg + "Kg";
}
protected void fillTreeView (Gtk.TreeView tv, TreeStore store)
{
//add a string for first row (for checking or unchecking all)
store.AppendValues ( "", "", "", "", "", "", true, "", false, "");
foreach (string jump in jumpsNormal) {
string [] myStringFull = jump.Split(new char[] {':'});
store.AppendValues (
myStringFull[1], //uniqueID
simpleString,
myStringFull[4], //type
myStringFull[5], //tf
myStringFull[6], //tf
createStringCalculatingKgs(oldPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))), //old weight
true,
createStringCalculatingKgs(newPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))), //new weight 1
false,
createStringCalculatingPercent(oldPersonWeight, newPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))) //new weight 2
);
}
foreach (string jump in jumpsReactive) {
string [] myStringFull = jump.Split(new char[] {':'});
store.AppendValues (
myStringFull[1], //uniqueID
reactiveString,
myStringFull[4], //type
myStringFull[10], //tf (AVG)
myStringFull[11], //tf (AVG)
createStringCalculatingKgs(oldPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))), //old weight
true,
createStringCalculatingKgs(newPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))), //new weight 1
false,
createStringCalculatingPercent(oldPersonWeight, newPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))) //new weight 2
);
}
}
protected void on_button_cancel_clicked (object o, EventArgs args)
{
ConvertWeightWindowBox.convert_weight.Hide();
ConvertWeightWindowBox = null;
}
protected void on_delete_event (object o, DeleteEventArgs args)
{
ConvertWeightWindowBox.convert_weight.Hide();
ConvertWeightWindowBox = null;
}
protected void on_button_accept_clicked (object o, EventArgs args)
{
Gtk.TreeIter iter;
int jumpID;
bool option1;
if (store.GetIterFirst(out iter)) {
//don't catch 0 value
while ( store.IterNext(ref iter) ){
option1 = (bool) store.GetValue (iter, columnBool1);
//only change in database if option is 2
//because option 1 leaves the same percent and changes Kg (and database is in %)
|
[
"\t\t\t\tif(! option1) {"
] | 957
|
lcc
|
csharp
| null |
54df7435e6cdeb9cf80f52a45f4c173229b57b7dfcc77ad7
| 17
|
Your task is code completion.
/*
* This file is part of ChronoJump
*
* ChronoJump 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.
*
* ChronoJump is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Copyright (C) 2004-2017 Xavier de Blas <xaviblas@gmail.com>
*/
using System;
using Gtk;
using Glade;
using GLib; //for Value
using System.Text; //StringBuilder
using System.Collections; //ArrayList
using Mono.Unix;
public class ConvertWeightWindow
{
[Widget] Gtk.Window convert_weight;
static ConvertWeightWindow ConvertWeightWindowBox;
[Widget] Gtk.TreeView treeview1;
[Widget] Gtk.Label label_old_weight_value;
[Widget] Gtk.Label label_new_weight_value;
[Widget] Gtk.Button button_accept;
[Widget] Gtk.Button button_cancel;
TreeStore store;
double oldPersonWeight;
double newPersonWeight;
string [] jumpsNormal;
string [] jumpsReactive;
int columnBool1 = 6;
int columnBool2 = 8;
string simpleString;
string reactiveString;
ConvertWeightWindow (double oldPersonWeight, double newPersonWeight, string [] jumpsNormal, string [] jumpsReactive) {
Glade.XML gladeXML;
gladeXML = Glade.XML.FromAssembly (Util.GetGladePath() + "convert_weight.glade", "convert_weight", null);
gladeXML.Autoconnect(this);
//put an icon to window
UtilGtk.IconWindow(convert_weight);
this.oldPersonWeight = oldPersonWeight;
this.newPersonWeight = newPersonWeight;
this.jumpsNormal = jumpsNormal;
this.jumpsReactive = jumpsReactive;
simpleString = Catalog.GetString("Simple");
reactiveString = Catalog.GetString("Reactive");
createTreeViewWithCheckboxes(treeview1);
store = new TreeStore(
typeof (string), //uniqueID
typeof (string), //simple or reactive
typeof (string), //jumpType
typeof (string), //tf
typeof (string), //tc
/* following eg of a subject of 70Kg
* that has done a jump with an extra of 70Kg
* and after (in same session) changes person weight to 80
*/
typeof (string), //weight % + weight kg (old) (eg: 100%-70Kg)
typeof (bool), //mark new option 1
typeof (string), //weight % + weight kg (new option1) (eg: 100%-80Kg)
typeof (bool), //mark new option 2
typeof (string) //weight % + weight kg (new option2) (eg: 87%-70Kg)
);
treeview1.Model = store;
fillTreeView( treeview1, store );
}
static public ConvertWeightWindow Show (
double oldPersonWeight, double newPersonWeight, string [] jumpsNormal, string [] jumpsReactive)
{
if (ConvertWeightWindowBox == null) {
ConvertWeightWindowBox =
new ConvertWeightWindow (oldPersonWeight, newPersonWeight, jumpsNormal, jumpsReactive);
}
ConvertWeightWindowBox.label_old_weight_value.Text = oldPersonWeight.ToString() + " Kg";
ConvertWeightWindowBox.label_new_weight_value.Text = newPersonWeight.ToString() + " Kg";
ConvertWeightWindowBox.convert_weight.Show ();
return ConvertWeightWindowBox;
}
protected void createTreeViewWithCheckboxes (Gtk.TreeView tv) {
tv.HeadersVisible=true;
int count = 0;
tv.AppendColumn ( Catalog.GetString("ID"), new CellRendererText(), "text", count++);
tv.AppendColumn (
Catalog.GetString("Simple") + " " +
Catalog.GetString("or") + " " +
Catalog.GetString("Reactive")
, new CellRendererText(), "text", count++);
tv.AppendColumn ( Catalog.GetString("Type"), new CellRendererText(), "text", count++);
tv.AppendColumn (
Catalog.GetString("TF")
/*
+ "\n" +
Catalog.GetString("TF") + "(" +
Catalog.GetString("AVG") + ")"
*/
, new CellRendererText(), "text", count++);
tv.AppendColumn (
Catalog.GetString("TC")
/*
+ "\n" +
Catalog.GetString("TC") + "(" +
Catalog.GetString("AVG") + ")"
*/
, new CellRendererText(), "text", count++);
tv.AppendColumn ( Catalog.GetString("Old weight"), new CellRendererText(), "text", count++);
CellRendererToggle crt = new CellRendererToggle();
crt.Visible = true;
crt.Activatable = true;
crt.Active = true;
crt.Toggled += ItemToggled1;
TreeViewColumn column = new TreeViewColumn ("", crt, "active", count);
column.Clickable = true;
tv.InsertColumn (column, count++);
tv.AppendColumn ( Catalog.GetString("New weight\noption 1"), new CellRendererText(), "text", count++);
CellRendererToggle crt2 = new CellRendererToggle();
crt2.Visible = true;
crt2.Activatable = true;
crt2.Active = true;
crt2.Toggled += ItemToggled2;
column = new TreeViewColumn ("", crt2, "active", count);
column.Clickable = true;
tv.InsertColumn (column, count++);
tv.AppendColumn ( Catalog.GetString("New weight\noption 2"), new CellRendererText(), "text", count++);
}
void ItemToggled1(object o, ToggledArgs args) {
ItemToggled(columnBool1, columnBool2, o, args);
}
void ItemToggled2(object o, ToggledArgs args) {
ItemToggled(columnBool2, columnBool1, o, args);
}
void ItemToggled(int columnThis, int columnOther, object o, ToggledArgs args) {
TreeIter iter;
if (store.GetIter (out iter, new TreePath(args.Path)))
{
bool val = (bool) store.GetValue (iter, columnThis);
LogB.Information (string.Format("toggled {0} with value {1}", args.Path, !val));
if(args.Path == "0") {
if (store.GetIterFirst(out iter)) {
val = (bool) store.GetValue (iter, columnThis);
store.SetValue (iter, columnThis, !val);
store.SetValue (iter, columnOther, val);
while ( store.IterNext(ref iter) ){
store.SetValue (iter, columnThis, !val);
store.SetValue (iter, columnOther, val);
}
}
} else {
store.SetValue (iter, columnThis, !val);
store.SetValue (iter, columnOther, val);
//usnelect "all" checkboxes
store.GetIterFirst(out iter);
store.SetValue (iter, columnThis, false);
store.SetValue (iter, columnOther, false);
}
}
}
private string createStringCalculatingKgs (double personWeightKg, double jumpWeightPercent) {
return jumpWeightPercent + "% " +
Convert.ToDouble(Util.WeightFromPercentToKg(jumpWeightPercent, personWeightKg)).ToString()
+ "Kg";
}
private string createStringCalculatingPercent (double oldPersonWeightKg, double newPersonWeightKg, double jumpWeightPercent) {
double jumpInKg = Util.WeightFromPercentToKg(jumpWeightPercent, oldPersonWeightKg);
double jumpPercentToNewPersonWeight = Convert.ToDouble(Util.WeightFromKgToPercent(jumpInKg, newPersonWeightKg));
return jumpPercentToNewPersonWeight + "% " + jumpInKg + "Kg";
}
protected void fillTreeView (Gtk.TreeView tv, TreeStore store)
{
//add a string for first row (for checking or unchecking all)
store.AppendValues ( "", "", "", "", "", "", true, "", false, "");
foreach (string jump in jumpsNormal) {
string [] myStringFull = jump.Split(new char[] {':'});
store.AppendValues (
myStringFull[1], //uniqueID
simpleString,
myStringFull[4], //type
myStringFull[5], //tf
myStringFull[6], //tf
createStringCalculatingKgs(oldPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))), //old weight
true,
createStringCalculatingKgs(newPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))), //new weight 1
false,
createStringCalculatingPercent(oldPersonWeight, newPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))) //new weight 2
);
}
foreach (string jump in jumpsReactive) {
string [] myStringFull = jump.Split(new char[] {':'});
store.AppendValues (
myStringFull[1], //uniqueID
reactiveString,
myStringFull[4], //type
myStringFull[10], //tf (AVG)
myStringFull[11], //tf (AVG)
createStringCalculatingKgs(oldPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))), //old weight
true,
createStringCalculatingKgs(newPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))), //new weight 1
false,
createStringCalculatingPercent(oldPersonWeight, newPersonWeight, Convert.ToDouble(Util.ChangeDecimalSeparator(myStringFull[8]))) //new weight 2
);
}
}
protected void on_button_cancel_clicked (object o, EventArgs args)
{
ConvertWeightWindowBox.convert_weight.Hide();
ConvertWeightWindowBox = null;
}
protected void on_delete_event (object o, DeleteEventArgs args)
{
ConvertWeightWindowBox.convert_weight.Hide();
ConvertWeightWindowBox = null;
}
protected void on_button_accept_clicked (object o, EventArgs args)
{
Gtk.TreeIter iter;
int jumpID;
bool option1;
if (store.GetIterFirst(out iter)) {
//don't catch 0 value
while ( store.IterNext(ref iter) ){
option1 = (bool) store.GetValue (iter, columnBool1);
//only change in database if option is 2
//because option 1 leaves the same percent and changes Kg (and database is in %)
|
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]
protected void on_button_accept_clicked (object o, EventArgs args)
{
Gtk.TreeIter iter;
int jumpID;
bool option1;
if (store.GetIterFirst(out iter)) {
//don't catch 0 value
while ( store.IterNext(ref iter) ){
option1 = (bool) store.GetValue (iter, columnBool1);
//only change in database if option is 2
//because option 1 leaves the same percent and changes Kg (and database is in %)
Cheatsheet (for next line):
- We are in a loop that iterates over the rows in the TreeStore.
- The goal is to update the database with the selected options.
- The current row is stored in the 'iter' variable.
- The 'option1' variable stores the value of the first checkbox (columnBool1).
- The 'option1' variable is a boolean, and we want to use it to determine which option to update in the database.
- The database update logic is not shown in the provided code, but it is likely that we need to update the 'tf' or 'tc' columns based on the selected options.
- [Relevant lines: loop, iter variable, option1 variable, columnBool1]
Next line will likely be:
- A conditional statement to check the value of 'option1' and update the 'tf' or 'tc' column accordingly.
However, the exact next line depends on the specific database update logic, which is not shown in the provided code.
|
|
Please complete the code given below.
/*
* $Id: Resources.java 476419 2006-11-18 02:28:07Z niallp $
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts.validator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Arg;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.Msg;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorResources;
import org.apache.commons.validator.Var;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.ModuleUtils;
import org.apache.struts.util.RequestUtils;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
/**
* This class helps provides some useful methods for retrieving objects from
* different scopes of the application.
*
* @version $Rev: 476419 $ $Date: 2005-09-16 23:34:41 -0400 (Fri, 16 Sep 2005)
* $
* @since Struts 1.1
*/
public class Resources {
/**
* The message resources for this package.
*/
private static MessageResources sysmsgs =
MessageResources.getMessageResources(
"org.apache.struts.validator.LocalStrings");
/**
* <p>Commons Logging instance.</p>
*/
private static Log log = LogFactory.getLog(Resources.class);
/**
* Resources key the <code>ServletContext</code> is stored under.
*/
private static String SERVLET_CONTEXT_PARAM =
"javax.servlet.ServletContext";
/**
* Resources key the <code>HttpServletRequest</code> is stored under.
*/
private static String HTTP_SERVLET_REQUEST_PARAM =
"javax.servlet.http.HttpServletRequest";
/**
* Resources key the <code>ActionMessages</code> is stored under.
*/
private static String ACTION_MESSAGES_PARAM =
"org.apache.struts.action.ActionMessages";
/**
* Retrieve <code>ValidatorResources</code> for the current module.
*
* @param application Application Context
* @param request The ServletRequest
*/
public static ValidatorResources getValidatorResources(
ServletContext application, HttpServletRequest request) {
String prefix =
ModuleUtils.getInstance().getModuleConfig(request, application)
.getPrefix();
return (ValidatorResources) application.getAttribute(ValidatorPlugIn.VALIDATOR_KEY
+ prefix);
}
/**
* Retrieve <code>MessageResources</code> for the module.
*
* @param request the servlet request
*/
public static MessageResources getMessageResources(
HttpServletRequest request) {
return (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
}
/**
* Retrieve <code>MessageResources</code> for the module and bundle.
*
* @param application the servlet context
* @param request the servlet request
* @param bundle the bundle key
*/
public static MessageResources getMessageResources(
ServletContext application, HttpServletRequest request, String bundle) {
if (bundle == null) {
bundle = Globals.MESSAGES_KEY;
}
MessageResources resources =
(MessageResources) request.getAttribute(bundle);
if (resources == null) {
ModuleConfig moduleConfig =
ModuleUtils.getInstance().getModuleConfig(request, application);
resources =
(MessageResources) application.getAttribute(bundle
+ moduleConfig.getPrefix());
}
if (resources == null) {
resources = (MessageResources) application.getAttribute(bundle);
}
if (resources == null) {
throw new NullPointerException(
"No message resources found for bundle: " + bundle);
}
return resources;
}
/**
* Get the value of a variable.
*
* @param varName The variable name
* @param field the validator Field
* @param validator The Validator
* @param request the servlet request
* @param required Whether the variable is mandatory
* @return The variable's value
*/
public static String getVarValue(String varName, Field field,
Validator validator, HttpServletRequest request, boolean required) {
Var var = field.getVar(varName);
if (var == null) {
String msg = sysmsgs.getMessage("variable.missing", varName);
if (required) {
throw new IllegalArgumentException(msg);
}
if (log.isDebugEnabled()) {
log.debug(field.getProperty() + ": " + msg);
}
return null;
}
ServletContext application =
(ServletContext) validator.getParameterValue(SERVLET_CONTEXT_PARAM);
return getVarValue(var, application, request, required);
}
/**
* Get the value of a variable.
*
* @param var the validator variable
* @param application The ServletContext
* @param request the servlet request
* @param required Whether the variable is mandatory
* @return The variables values
*/
public static String getVarValue(Var var, ServletContext application,
HttpServletRequest request, boolean required) {
String varName = var.getName();
String varValue = var.getValue();
// Non-resource variable
if (!var.isResource()) {
return varValue;
}
// Get the message resources
String bundle = var.getBundle();
MessageResources messages =
getMessageResources(application, request, bundle);
// Retrieve variable's value from message resources
Locale locale = RequestUtils.getUserLocale(request, null);
String value = messages.getMessage(locale, varValue, null);
// Not found in message resources
if ((value == null) && required) {
throw new IllegalArgumentException(sysmsgs.getMessage(
"variable.resource.notfound", varName, varValue, bundle));
}
if (log.isDebugEnabled()) {
log.debug("Var=[" + varName + "], " + "bundle=[" + bundle + "], "
+ "key=[" + varValue + "], " + "value=[" + value + "]");
}
return value;
}
/**
* Gets the <code>Locale</code> sensitive value based on the key passed
* in.
*
* @param messages The Message resources
* @param locale The locale.
* @param key Key used to lookup the message
*/
public static String getMessage(MessageResources messages, Locale locale,
String key) {
String message = null;
if (messages != null) {
message = messages.getMessage(locale, key);
}
return (message == null) ? "" : message;
}
/**
* Gets the <code>Locale</code> sensitive value based on the key passed
* in.
*
* @param request servlet request
* @param key the request key
*/
public static String getMessage(HttpServletRequest request, String key) {
MessageResources messages = getMessageResources(request);
return getMessage(messages, RequestUtils.getUserLocale(request, null),
key);
}
/**
* Gets the locale sensitive message based on the <code>ValidatorAction</code>
* message and the <code>Field</code>'s arg objects.
*
* @param messages The Message resources
* @param locale The locale
* @param va The Validator Action
* @param field The Validator Field
*/
public static String getMessage(MessageResources messages, Locale locale,
ValidatorAction va, Field field) {
String[] args = getArgs(va.getName(), messages, locale, field);
String msg =
(field.getMsg(va.getName()) != null) ? field.getMsg(va.getName())
: va.getMsg();
return messages.getMessage(locale, msg, args);
}
/**
* Gets the <code>Locale</code> sensitive value based on the key passed
* in.
*
* @param application the servlet context
* @param request the servlet request
* @param defaultMessages The default Message resources
* @param locale The locale
* @param va The Validator Action
* @param field The Validator Field
*/
public static String getMessage(ServletContext application,
HttpServletRequest request, MessageResources defaultMessages,
Locale locale, ValidatorAction va, Field field) {
Msg msg = field.getMessage(va.getName());
if ((msg != null) && !msg.isResource()) {
return msg.getKey();
}
String msgKey = null;
String msgBundle = null;
MessageResources messages = defaultMessages;
if (msg == null) {
msgKey = va.getMsg();
} else {
msgKey = msg.getKey();
msgBundle = msg.getBundle();
if (msg.getBundle() != null) {
messages =
getMessageResources(application, request, msg.getBundle());
}
}
if ((msgKey == null) || (msgKey.length() == 0)) {
return "??? " + va.getName() + "." + field.getProperty() + " ???";
}
// Get the arguments
Arg[] args = field.getArgs(va.getName());
String[] argValues =
getArgValues(application, request, messages, locale, args);
// Return the message
return messages.getMessage(locale, msgKey, argValues);
}
/**
* Gets the <code>ActionMessage</code> based on the
* <code>ValidatorAction</code> message and the <code>Field</code>'s arg
* objects.
* <p>
* <strong>Note:</strong> this method does not respect bundle information
* stored with the field's <msg> or <arg> elements, and localization
* will not work for alternative resource bundles. This method is
* deprecated for this reason, and you should use
* {@link #getActionMessage(Validator,HttpServletRequest,ValidatorAction,Field)}
* instead.
*
* @param request the servlet request
* @param va Validator action
* @param field the validator Field
* @deprecated Use getActionMessage(Validator, HttpServletRequest,
* ValidatorAction, Field) method instead
*/
public static ActionMessage getActionMessage(HttpServletRequest request,
ValidatorAction va, Field field) {
String[] args =
getArgs(va.getName(), getMessageResources(request),
RequestUtils.getUserLocale(request, null), field);
String msg =
(field.getMsg(va.getName()) != null) ? field.getMsg(va.getName())
: va.getMsg();
return new ActionMessage(msg, args);
}
/**
* Gets the <code>ActionMessage</code> based on the
* <code>ValidatorAction</code> message and the <code>Field</code>'s arg
* objects.
*
* @param validator the Validator
* @param request the servlet request
* @param va Validator action
* @param field the validator Field
*/
public static ActionMessage getActionMessage(Validator validator,
HttpServletRequest request, ValidatorAction va, Field field) {
Msg msg = field.getMessage(va.getName());
if ((msg != null) && !msg.isResource()) {
return new ActionMessage(msg.getKey(), false);
}
String msgKey = null;
String msgBundle = null;
if (msg == null) {
msgKey = va.getMsg();
} else {
msgKey = msg.getKey();
msgBundle = msg.getBundle();
}
if ((msgKey == null) || (msgKey.length() == 0)) {
return new ActionMessage("??? " + va.getName() + "."
+ field.getProperty() + " ???", false);
}
ServletContext application =
(ServletContext) validator.getParameterValue(SERVLET_CONTEXT_PARAM);
MessageResources messages =
getMessageResources(application, request, msgBundle);
Locale locale = RequestUtils.getUserLocale(request, null);
Arg[] args = field.getArgs(va.getName());
String[] argValues =
getArgValues(application, request, messages, locale, args);
ActionMessage actionMessage = null;
if (msgBundle == null) {
actionMessage = new ActionMessage(msgKey, argValues);
} else {
String message = messages.getMessage(locale, msgKey, argValues);
actionMessage = new ActionMessage(message, false);
}
return actionMessage;
}
/**
* Gets the message arguments based on the current <code>ValidatorAction</code>
* and <code>Field</code>.
*
* @param actionName action name
* @param messages message resources
* @param locale the locale
* @param field the validator field
*/
public static String[] getArgs(String actionName,
MessageResources messages, Locale locale, Field field) {
String[] argMessages = new String[4];
Arg[] args =
new Arg[] {
field.getArg(actionName, 0), field.getArg(actionName, 1),
field.getArg(actionName, 2), field.getArg(actionName, 3)
};
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
continue;
}
if (args[i].isResource()) {
argMessages[i] = getMessage(messages, locale, args[i].getKey());
} else {
argMessages[i] = args[i].getKey();
}
}
return argMessages;
}
/**
* Gets the message arguments based on the current <code>ValidatorAction</code>
* and <code>Field</code>.
*
* @param application the servlet context
* @param request the servlet request
* @param defaultMessages Default message resources
* @param locale the locale
* @param args The arguments for the message
*/
private static String[] getArgValues(ServletContext application,
HttpServletRequest request, MessageResources defaultMessages,
Locale locale, Arg[] args) {
|
[
" if ((args == null) || (args.length == 0)) {"
] | 1,570
|
lcc
|
java
| null |
e42bb143aca03ffdde352e012ca3991013aa4f1018e60c8f
| 18
|
Your task is code completion.
/*
* $Id: Resources.java 476419 2006-11-18 02:28:07Z niallp $
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts.validator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Arg;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.Msg;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorResources;
import org.apache.commons.validator.Var;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.ModuleUtils;
import org.apache.struts.util.RequestUtils;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
/**
* This class helps provides some useful methods for retrieving objects from
* different scopes of the application.
*
* @version $Rev: 476419 $ $Date: 2005-09-16 23:34:41 -0400 (Fri, 16 Sep 2005)
* $
* @since Struts 1.1
*/
public class Resources {
/**
* The message resources for this package.
*/
private static MessageResources sysmsgs =
MessageResources.getMessageResources(
"org.apache.struts.validator.LocalStrings");
/**
* <p>Commons Logging instance.</p>
*/
private static Log log = LogFactory.getLog(Resources.class);
/**
* Resources key the <code>ServletContext</code> is stored under.
*/
private static String SERVLET_CONTEXT_PARAM =
"javax.servlet.ServletContext";
/**
* Resources key the <code>HttpServletRequest</code> is stored under.
*/
private static String HTTP_SERVLET_REQUEST_PARAM =
"javax.servlet.http.HttpServletRequest";
/**
* Resources key the <code>ActionMessages</code> is stored under.
*/
private static String ACTION_MESSAGES_PARAM =
"org.apache.struts.action.ActionMessages";
/**
* Retrieve <code>ValidatorResources</code> for the current module.
*
* @param application Application Context
* @param request The ServletRequest
*/
public static ValidatorResources getValidatorResources(
ServletContext application, HttpServletRequest request) {
String prefix =
ModuleUtils.getInstance().getModuleConfig(request, application)
.getPrefix();
return (ValidatorResources) application.getAttribute(ValidatorPlugIn.VALIDATOR_KEY
+ prefix);
}
/**
* Retrieve <code>MessageResources</code> for the module.
*
* @param request the servlet request
*/
public static MessageResources getMessageResources(
HttpServletRequest request) {
return (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
}
/**
* Retrieve <code>MessageResources</code> for the module and bundle.
*
* @param application the servlet context
* @param request the servlet request
* @param bundle the bundle key
*/
public static MessageResources getMessageResources(
ServletContext application, HttpServletRequest request, String bundle) {
if (bundle == null) {
bundle = Globals.MESSAGES_KEY;
}
MessageResources resources =
(MessageResources) request.getAttribute(bundle);
if (resources == null) {
ModuleConfig moduleConfig =
ModuleUtils.getInstance().getModuleConfig(request, application);
resources =
(MessageResources) application.getAttribute(bundle
+ moduleConfig.getPrefix());
}
if (resources == null) {
resources = (MessageResources) application.getAttribute(bundle);
}
if (resources == null) {
throw new NullPointerException(
"No message resources found for bundle: " + bundle);
}
return resources;
}
/**
* Get the value of a variable.
*
* @param varName The variable name
* @param field the validator Field
* @param validator The Validator
* @param request the servlet request
* @param required Whether the variable is mandatory
* @return The variable's value
*/
public static String getVarValue(String varName, Field field,
Validator validator, HttpServletRequest request, boolean required) {
Var var = field.getVar(varName);
if (var == null) {
String msg = sysmsgs.getMessage("variable.missing", varName);
if (required) {
throw new IllegalArgumentException(msg);
}
if (log.isDebugEnabled()) {
log.debug(field.getProperty() + ": " + msg);
}
return null;
}
ServletContext application =
(ServletContext) validator.getParameterValue(SERVLET_CONTEXT_PARAM);
return getVarValue(var, application, request, required);
}
/**
* Get the value of a variable.
*
* @param var the validator variable
* @param application The ServletContext
* @param request the servlet request
* @param required Whether the variable is mandatory
* @return The variables values
*/
public static String getVarValue(Var var, ServletContext application,
HttpServletRequest request, boolean required) {
String varName = var.getName();
String varValue = var.getValue();
// Non-resource variable
if (!var.isResource()) {
return varValue;
}
// Get the message resources
String bundle = var.getBundle();
MessageResources messages =
getMessageResources(application, request, bundle);
// Retrieve variable's value from message resources
Locale locale = RequestUtils.getUserLocale(request, null);
String value = messages.getMessage(locale, varValue, null);
// Not found in message resources
if ((value == null) && required) {
throw new IllegalArgumentException(sysmsgs.getMessage(
"variable.resource.notfound", varName, varValue, bundle));
}
if (log.isDebugEnabled()) {
log.debug("Var=[" + varName + "], " + "bundle=[" + bundle + "], "
+ "key=[" + varValue + "], " + "value=[" + value + "]");
}
return value;
}
/**
* Gets the <code>Locale</code> sensitive value based on the key passed
* in.
*
* @param messages The Message resources
* @param locale The locale.
* @param key Key used to lookup the message
*/
public static String getMessage(MessageResources messages, Locale locale,
String key) {
String message = null;
if (messages != null) {
message = messages.getMessage(locale, key);
}
return (message == null) ? "" : message;
}
/**
* Gets the <code>Locale</code> sensitive value based on the key passed
* in.
*
* @param request servlet request
* @param key the request key
*/
public static String getMessage(HttpServletRequest request, String key) {
MessageResources messages = getMessageResources(request);
return getMessage(messages, RequestUtils.getUserLocale(request, null),
key);
}
/**
* Gets the locale sensitive message based on the <code>ValidatorAction</code>
* message and the <code>Field</code>'s arg objects.
*
* @param messages The Message resources
* @param locale The locale
* @param va The Validator Action
* @param field The Validator Field
*/
public static String getMessage(MessageResources messages, Locale locale,
ValidatorAction va, Field field) {
String[] args = getArgs(va.getName(), messages, locale, field);
String msg =
(field.getMsg(va.getName()) != null) ? field.getMsg(va.getName())
: va.getMsg();
return messages.getMessage(locale, msg, args);
}
/**
* Gets the <code>Locale</code> sensitive value based on the key passed
* in.
*
* @param application the servlet context
* @param request the servlet request
* @param defaultMessages The default Message resources
* @param locale The locale
* @param va The Validator Action
* @param field The Validator Field
*/
public static String getMessage(ServletContext application,
HttpServletRequest request, MessageResources defaultMessages,
Locale locale, ValidatorAction va, Field field) {
Msg msg = field.getMessage(va.getName());
if ((msg != null) && !msg.isResource()) {
return msg.getKey();
}
String msgKey = null;
String msgBundle = null;
MessageResources messages = defaultMessages;
if (msg == null) {
msgKey = va.getMsg();
} else {
msgKey = msg.getKey();
msgBundle = msg.getBundle();
if (msg.getBundle() != null) {
messages =
getMessageResources(application, request, msg.getBundle());
}
}
if ((msgKey == null) || (msgKey.length() == 0)) {
return "??? " + va.getName() + "." + field.getProperty() + " ???";
}
// Get the arguments
Arg[] args = field.getArgs(va.getName());
String[] argValues =
getArgValues(application, request, messages, locale, args);
// Return the message
return messages.getMessage(locale, msgKey, argValues);
}
/**
* Gets the <code>ActionMessage</code> based on the
* <code>ValidatorAction</code> message and the <code>Field</code>'s arg
* objects.
* <p>
* <strong>Note:</strong> this method does not respect bundle information
* stored with the field's <msg> or <arg> elements, and localization
* will not work for alternative resource bundles. This method is
* deprecated for this reason, and you should use
* {@link #getActionMessage(Validator,HttpServletRequest,ValidatorAction,Field)}
* instead.
*
* @param request the servlet request
* @param va Validator action
* @param field the validator Field
* @deprecated Use getActionMessage(Validator, HttpServletRequest,
* ValidatorAction, Field) method instead
*/
public static ActionMessage getActionMessage(HttpServletRequest request,
ValidatorAction va, Field field) {
String[] args =
getArgs(va.getName(), getMessageResources(request),
RequestUtils.getUserLocale(request, null), field);
String msg =
(field.getMsg(va.getName()) != null) ? field.getMsg(va.getName())
: va.getMsg();
return new ActionMessage(msg, args);
}
/**
* Gets the <code>ActionMessage</code> based on the
* <code>ValidatorAction</code> message and the <code>Field</code>'s arg
* objects.
*
* @param validator the Validator
* @param request the servlet request
* @param va Validator action
* @param field the validator Field
*/
public static ActionMessage getActionMessage(Validator validator,
HttpServletRequest request, ValidatorAction va, Field field) {
Msg msg = field.getMessage(va.getName());
if ((msg != null) && !msg.isResource()) {
return new ActionMessage(msg.getKey(), false);
}
String msgKey = null;
String msgBundle = null;
if (msg == null) {
msgKey = va.getMsg();
} else {
msgKey = msg.getKey();
msgBundle = msg.getBundle();
}
if ((msgKey == null) || (msgKey.length() == 0)) {
return new ActionMessage("??? " + va.getName() + "."
+ field.getProperty() + " ???", false);
}
ServletContext application =
(ServletContext) validator.getParameterValue(SERVLET_CONTEXT_PARAM);
MessageResources messages =
getMessageResources(application, request, msgBundle);
Locale locale = RequestUtils.getUserLocale(request, null);
Arg[] args = field.getArgs(va.getName());
String[] argValues =
getArgValues(application, request, messages, locale, args);
ActionMessage actionMessage = null;
if (msgBundle == null) {
actionMessage = new ActionMessage(msgKey, argValues);
} else {
String message = messages.getMessage(locale, msgKey, argValues);
actionMessage = new ActionMessage(message, false);
}
return actionMessage;
}
/**
* Gets the message arguments based on the current <code>ValidatorAction</code>
* and <code>Field</code>.
*
* @param actionName action name
* @param messages message resources
* @param locale the locale
* @param field the validator field
*/
public static String[] getArgs(String actionName,
MessageResources messages, Locale locale, Field field) {
String[] argMessages = new String[4];
Arg[] args =
new Arg[] {
field.getArg(actionName, 0), field.getArg(actionName, 1),
field.getArg(actionName, 2), field.getArg(actionName, 3)
};
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
continue;
}
if (args[i].isResource()) {
argMessages[i] = getMessage(messages, locale, args[i].getKey());
} else {
argMessages[i] = args[i].getKey();
}
}
return argMessages;
}
/**
* Gets the message arguments based on the current <code>ValidatorAction</code>
* and <code>Field</code>.
*
* @param application the servlet context
* @param request the servlet request
* @param defaultMessages Default message resources
* @param locale the locale
* @param args The arguments for the message
*/
private static String[] getArgValues(ServletContext application,
HttpServletRequest request, MessageResources defaultMessages,
Locale locale, Arg[] args) {
|
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]
public class Resources {
// ...
/**
* Gets the message arguments based on the current <code>ValidatorAction</code>
* and <code>Field</code>.
*
* @param actionName action name
* @param messages message resources
* @param locale the locale
* @param field the validator field
*/
public static String[] getArgs(String actionName,
MessageResources messages, Locale locale, Field field) {
String[] argMessages = new String[4];
Arg[] args =
new Arg[] {
field.getArg(actionName, 0), field.getArg(actionName, 1),
field.getArg(actionName, 2), field.getArg(actionName, 3)
};
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
continue;
}
if (args[i].isResource()) {
argMessages[i] = getMessage(messages, locale, args[i].getKey());
} else {
argMessages[i] = args[i].getKey();
}
}
return argMessages;
}
/**
* Gets the message arguments based on the current <code>ValidatorAction</code>
* and <code>Field</code>.
*
* @param application the servlet context
* @param request the servlet request
* @param defaultMessages Default message resources
* @param locale the locale
* @param args The arguments for the message
*/
private static String[] getArgValues(ServletContext application,
HttpServletRequest request, MessageResources defaultMessages,
Locale locale, Arg[] args) {
Cheatsheet (for next line):
- We are in getArgValues(), which seems to be a helper method for getArgs().
- getArgs() is called with the same parameters, but with MessageResources messages.
- getArgs() returns an array of message arguments.
- The method is private, suggesting it's an implementation detail.
- [Relevant lines: method header, getArgs() call]
The next line will likely be: return getArgs(application, request, defaultMessages, locale, args);
|
|
Please complete the code given below.
package com.censoredsoftware.capitalism.data;
import com.censoredsoftware.capitalism.Capitalism;
import com.censoredsoftware.capitalism.data.util.ServerDatas;
import com.censoredsoftware.capitalism.data.util.TimedDatas;
import com.censoredsoftware.capitalism.entity.Firm;
import com.censoredsoftware.capitalism.entity.Person;
import com.censoredsoftware.censoredlib.data.ServerData;
import com.censoredsoftware.censoredlib.data.TimedData;
import com.censoredsoftware.censoredlib.helper.ConfigFile;
import com.google.common.collect.Maps;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
public class DataManager
{
// Data
public static ConcurrentMap<String, Person> persons;
public static ConcurrentMap<UUID, Firm> firms;
public static ConcurrentMap<UUID, TimedData> timedData;
public static ConcurrentMap<UUID, ServerData> serverData;
private static ConcurrentMap<String, HashMap<String, Object>> tempData;
static
{
for(File file : File.values())
file.getConfigFile().loadToData();
tempData = Maps.newConcurrentMap();
}
public static void save()
{
for(File file : File.values())
file.getConfigFile().saveToFile();
}
public static void flushData()
{
// Kick everyone
for(Player player : Bukkit.getOnlinePlayers())
player.kickPlayer(ChatColor.GREEN + "Data has been reset, you can rejoin now.");
// Clear the data
persons.clear();
firms.clear();
timedData.clear();
tempData.clear();
serverData.clear();
save();
// Reload the PLUGIN
Bukkit.getServer().getPluginManager().disablePlugin(Capitalism.PLUGIN);
Bukkit.getServer().getPluginManager().enablePlugin(Capitalism.PLUGIN);
}
/*
* Temporary data
*/
public static boolean hasKeyTemp(String key, String subKey)
{
return tempData.containsKey(key) && tempData.get(key).containsKey(subKey);
}
public static Object getValueTemp(String key, String subKey)
{
if(tempData.containsKey(key)) return tempData.get(key).get(subKey);
else return null;
}
public static void saveTemp(String key, String subKey, Object value)
{
if(!tempData.containsKey(key)) tempData.put(key, new HashMap<String, Object>());
tempData.get(key).put(subKey, value);
}
public static void removeTemp(String key, String subKey)
{
if(tempData.containsKey(key) && tempData.get(key).containsKey(subKey)) tempData.get(key).remove(subKey);
}
/*
* Timed data
*/
public static void saveTimed(String key, String subKey, Object data, Integer seconds)
{
// Remove the data if it exists already
TimedDatas.remove(key, subKey);
// Create and save the timed data
TimedData timedData = new TimedData();
timedData.generateId();
timedData.setKey(key);
timedData.setSubKey(subKey);
timedData.setData(data.toString());
timedData.setSeconds(seconds);
DataManager.timedData.put(timedData.getId(), timedData);
}
public static void removeTimed(String key, String subKey)
{
TimedDatas.remove(key, subKey);
}
public static boolean hasTimed(String key, String subKey)
{
return TimedDatas.find(key, subKey) != null;
}
public static Object getTimedValue(String key, String subKey)
{
return TimedDatas.find(key, subKey).getData();
}
public static long getTimedExpiration(String key, String subKey)
{
return TimedDatas.find(key, subKey).getExpiration();
}
/*
* Server data
*/
public static void saveServerData(String key, String subKey, Object data)
{
// Remove the data if it exists already
ServerDatas.remove(key, subKey);
// Create and save the timed data
ServerData serverData = new ServerData();
serverData.generateId();
serverData.setKey(key);
serverData.setSubKey(subKey);
serverData.setData(data.toString());
DataManager.serverData.put(serverData.getId(), serverData);
}
public static void removeServerData(String key, String subKey)
{
ServerDatas.remove(key, subKey);
}
public static boolean hasServerData(String key, String subKey)
{
return ServerDatas.find(key, subKey) != null;
}
public static Object getServerDataValue(String key, String subKey)
{
return ServerDatas.find(key, subKey).getData();
}
public static enum File
{
PLAYER(new ConfigFile<String, Person>()
{
@Override
public Person create(String string, ConfigurationSection conf)
{
return new Person(string, conf);
}
@Override
public ConcurrentMap<String, Person> getLoadedData()
{
return DataManager.persons;
}
@Override
public String getSavePath()
{
return Capitalism.SAVE_PATH;
}
@Override
public String getSaveFile()
{
return "persons.yml";
}
@Override
public Map<String, Object> serialize(String string)
{
return getLoadedData().get(string).serialize();
}
@Override
public String convertFromString(String stringId)
{
return stringId;
}
@Override
public void loadToData()
{
persons = loadFromFile();
}
}), FIRM(new ConfigFile<UUID, Firm>()
{
@Override
public Firm create(UUID id, ConfigurationSection conf)
{
return new Firm(id, conf);
}
@Override
public ConcurrentMap<UUID, Firm> getLoadedData()
{
return DataManager.firms;
}
@Override
public String getSavePath()
{
return Capitalism.SAVE_PATH;
}
@Override
public String getSaveFile()
{
return "firms.yml";
}
@Override
public Map<String, Object> serialize(UUID id)
{
return getLoadedData().get(id).serialize();
}
@Override
public UUID convertFromString(String stringId)
{
return UUID.fromString(stringId);
}
@Override
public void loadToData()
{
|
[
"\t\t\t\tfirms = loadFromFile();"
] | 515
|
lcc
|
java
| null |
04233bb10cad37ee372ddcc1ca95b3e2a853d217fa90929e
| 19
|
Your task is code completion.
package com.censoredsoftware.capitalism.data;
import com.censoredsoftware.capitalism.Capitalism;
import com.censoredsoftware.capitalism.data.util.ServerDatas;
import com.censoredsoftware.capitalism.data.util.TimedDatas;
import com.censoredsoftware.capitalism.entity.Firm;
import com.censoredsoftware.capitalism.entity.Person;
import com.censoredsoftware.censoredlib.data.ServerData;
import com.censoredsoftware.censoredlib.data.TimedData;
import com.censoredsoftware.censoredlib.helper.ConfigFile;
import com.google.common.collect.Maps;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
public class DataManager
{
// Data
public static ConcurrentMap<String, Person> persons;
public static ConcurrentMap<UUID, Firm> firms;
public static ConcurrentMap<UUID, TimedData> timedData;
public static ConcurrentMap<UUID, ServerData> serverData;
private static ConcurrentMap<String, HashMap<String, Object>> tempData;
static
{
for(File file : File.values())
file.getConfigFile().loadToData();
tempData = Maps.newConcurrentMap();
}
public static void save()
{
for(File file : File.values())
file.getConfigFile().saveToFile();
}
public static void flushData()
{
// Kick everyone
for(Player player : Bukkit.getOnlinePlayers())
player.kickPlayer(ChatColor.GREEN + "Data has been reset, you can rejoin now.");
// Clear the data
persons.clear();
firms.clear();
timedData.clear();
tempData.clear();
serverData.clear();
save();
// Reload the PLUGIN
Bukkit.getServer().getPluginManager().disablePlugin(Capitalism.PLUGIN);
Bukkit.getServer().getPluginManager().enablePlugin(Capitalism.PLUGIN);
}
/*
* Temporary data
*/
public static boolean hasKeyTemp(String key, String subKey)
{
return tempData.containsKey(key) && tempData.get(key).containsKey(subKey);
}
public static Object getValueTemp(String key, String subKey)
{
if(tempData.containsKey(key)) return tempData.get(key).get(subKey);
else return null;
}
public static void saveTemp(String key, String subKey, Object value)
{
if(!tempData.containsKey(key)) tempData.put(key, new HashMap<String, Object>());
tempData.get(key).put(subKey, value);
}
public static void removeTemp(String key, String subKey)
{
if(tempData.containsKey(key) && tempData.get(key).containsKey(subKey)) tempData.get(key).remove(subKey);
}
/*
* Timed data
*/
public static void saveTimed(String key, String subKey, Object data, Integer seconds)
{
// Remove the data if it exists already
TimedDatas.remove(key, subKey);
// Create and save the timed data
TimedData timedData = new TimedData();
timedData.generateId();
timedData.setKey(key);
timedData.setSubKey(subKey);
timedData.setData(data.toString());
timedData.setSeconds(seconds);
DataManager.timedData.put(timedData.getId(), timedData);
}
public static void removeTimed(String key, String subKey)
{
TimedDatas.remove(key, subKey);
}
public static boolean hasTimed(String key, String subKey)
{
return TimedDatas.find(key, subKey) != null;
}
public static Object getTimedValue(String key, String subKey)
{
return TimedDatas.find(key, subKey).getData();
}
public static long getTimedExpiration(String key, String subKey)
{
return TimedDatas.find(key, subKey).getExpiration();
}
/*
* Server data
*/
public static void saveServerData(String key, String subKey, Object data)
{
// Remove the data if it exists already
ServerDatas.remove(key, subKey);
// Create and save the timed data
ServerData serverData = new ServerData();
serverData.generateId();
serverData.setKey(key);
serverData.setSubKey(subKey);
serverData.setData(data.toString());
DataManager.serverData.put(serverData.getId(), serverData);
}
public static void removeServerData(String key, String subKey)
{
ServerDatas.remove(key, subKey);
}
public static boolean hasServerData(String key, String subKey)
{
return ServerDatas.find(key, subKey) != null;
}
public static Object getServerDataValue(String key, String subKey)
{
return ServerDatas.find(key, subKey).getData();
}
public static enum File
{
PLAYER(new ConfigFile<String, Person>()
{
@Override
public Person create(String string, ConfigurationSection conf)
{
return new Person(string, conf);
}
@Override
public ConcurrentMap<String, Person> getLoadedData()
{
return DataManager.persons;
}
@Override
public String getSavePath()
{
return Capitalism.SAVE_PATH;
}
@Override
public String getSaveFile()
{
return "persons.yml";
}
@Override
public Map<String, Object> serialize(String string)
{
return getLoadedData().get(string).serialize();
}
@Override
public String convertFromString(String stringId)
{
return stringId;
}
@Override
public void loadToData()
{
persons = loadFromFile();
}
}), FIRM(new ConfigFile<UUID, Firm>()
{
@Override
public Firm create(UUID id, ConfigurationSection conf)
{
return new Firm(id, conf);
}
@Override
public ConcurrentMap<UUID, Firm> getLoadedData()
{
return DataManager.firms;
}
@Override
public String getSavePath()
{
return Capitalism.SAVE_PATH;
}
@Override
public String getSaveFile()
{
return "firms.yml";
}
@Override
public Map<String, Object> serialize(UUID id)
{
return getLoadedData().get(id).serialize();
}
@Override
public UUID convertFromString(String stringId)
{
return UUID.fromString(stringId);
}
@Override
public void loadToData()
{
|
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]
public enum File {
PLAYER(new ConfigFile<String, Person>() {
@Override
public Person create(String string, ConfigurationSection conf) {
return new Person(string, conf);
}
@Override
public ConcurrentMap<String, Person> getLoadedData() {
return DataManager.persons;
}
@Override
public String getSavePath() {
return Capitalism.SAVE_PATH;
}
@Override
public String getSaveFile() {
return "persons.yml";
}
@Override
public Map<String, Object> serialize(String string) {
return getLoadedData().get(string).serialize();
}
@Override
public String convertFromString(String stringId) {
return stringId;
}
@Override
public void loadToData() {
persons = loadFromFile();
}
}), FIRM(new ConfigFile<UUID, Firm>() {
@Override
public Firm create(UUID id, ConfigurationSection conf) {
return new Firm(id, conf);
}
@Override
public ConcurrentMap<UUID, Firm> getLoadedData() {
return DataManager.firms;
}
@Override
public String getSavePath() {
return Capitalism.SAVE_PATH;
}
@Override
public String getSaveFile() {
return "firms.yml";
}
@Override
public Map<String, Object> serialize(UUID id) {
return getLoadedData().get(id).serialize();
}
@Override
public UUID convertFromString(String stringId) {
return UUID.fromString(stringId);
}
@Override
public void loadToData() {
// Implementation missing
}
})
**Cheat sheet:**
- We are in the FIRM enum, which is missing the implementation of the loadToData() method.
- The loadToData() method should load data from a file into the firms map.
- The getLoadedData() method returns the firms map.
- The getSavePath() and getSaveFile() methods return the save path and file name for firms data.
- The serialize() method should return the serialized form of a firm with the given id.
- The convertFromString() method should return a UUID from a string.
- The loadFromFile() method is not shown in the code snippet, but it is likely used to load data from a file into the firms map.
**Relevant lines:**
- The FIRM enum declaration
- The loadToData() method declaration
- The getLoadedData() method
- The getSavePath() and getSaveFile() methods
- The serialize() method
- The convertFromString() method
**Next line:**
The next line should implement the loadToData() method for the FIRM enum, likely by calling the loadFromFile() method and assigning the result to the firms map.
|
|
Please complete the code given below.
package gui;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.IntegerFieldEditor;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.preference.PreferenceManager;
import org.eclipse.jface.preference.PreferenceNode;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import util.PmTransException;
public class Config extends PreferenceStore {
private static Config instance = null;
/**
* Non-configurable stuff
*/
// Config file path
private static String CONFIG_PATH = "./config.properties";
// State file path
public static String STATE_PATH = "./state.transcriber";
// Icon paths
public static String ICON_PATH_PLAY = "/icon/start.png";
public static String ICON_PATH_PAUSE = "/icon/pause.png";
public static String ICON_PATH_RESTART = "/icon/restart.png";
public static String ICON_PATH_OPEN_TRANSCRIPTION = "/icon/open.png";
public static String ICON_PATH_OPEN_AUDIO = "/icon/openAudio.png";
public static String ICON_PATH_SAVE_TRANSCRIPTION = "/icon/save.png";
public static String ICON_PATH_LOOP = "/icon/loop.png";
public static String ICON_PATH_ZOOM_IN = "/icon/zoom_in.png";
public static String ICON_PATH_ZOOM_OUT = "/icon/zoom_out.png";
public static String ICON_PATH_COPY = "/icon/copy.png";
public static String ICON_PATH_CUT = "/icon/cut.png";
public static String ICON_PATH_PASTE = "/icon/paste.png";
public static String ICON_PATH_CROSS = "/icon/cross.png";
public static String ICON_PATH_ADVANCED_SEARCH = "/icon/advancedSearch.png";
public static String ICON_PATH_CHANGE_BACKGROUND_COLOR = "/icon/changeBackgroundColor.png";
public static String ICON_PATH_CHANGE_FONT_COLOR = "/icon/changeFontColor.png";
public static String ICON_PATH_SETTINGS = "/icon/settings.png";
public static String ICON_PATH_CONTRIBUTE = "/icon/contribute.png";
public static String DEFAULT_ACCELERATORS = "cxvfosa";
// Main shell initial dimensions
private int SHELL_HEIGHT_DEFAULT = 600;
private int SHELL_LENGHT_DEFAULT = 600;
public static String SHELL_HEIGHT = "window.height";
public static String SHELL_LENGHT = "window.lenght";
// Last directory paths for file dialogs
private String LAST_OPEN_AUDIO_PATH_DEFAULT = "";
public static String LAST_OPEN_AUDIO_PATH = "last.open.audio.path";
private String LAST_OPEN_TEXT_PATH_DEFAULT = "";
public static String LAST_OPEN_TEXT_PATH = "last.open.text.path";
// Last directory path for the export dialog
private String LAST_EXPORT_TRANSCRIPTION_PATH_DEFALUT = "";
public static String LAST_EXPORT_TRANSCRIPTION_PATH = "last.export.transcription.path";
// URLs
public static String CONTRIBUTE_URL = "https://github.com/juanerasmoe/pmTrans/wiki/Contribute-to-pmTrans";
/**
* Configurable stuff
*/
// Duration of the short rewind in seconds
private int SHORT_REWIND_DEFAULT = 5;
public static String SHORT_REWIND = "short.rewind.duration";
// Duration of the long rewind in seconds
private int LONG_REWIND_DEFAULT = 10;
public static String LONG_REWIND = "long.rewind.duration";
// Duration of the rewind-and-play
private static int REWIND_AND_PLAY_DEFAULT = 2;
public static String REWIND_AND_PLAY = "rewind.and.play.duration";
// Max size of the previous-files list
private static int AUDIO_FILE_CACHE_LENGHT_DEFAULT = 7;
public static String AUDIO_FILE_CACHE_LENGHT = "audio.file.cache.lenght";
private static int TEXT_FILE_CACHE_LENGHT_DEFAULT = 7;
public static String TEXT_FILE_CACHE_LENGHT = "text.file.cache.lenght";
private static int SLOW_DOWN_PLAYBACK_DEFAULT = -5;
public static String SLOW_DOWN_PLAYBACK = "slow.down.playback";
private static int SPEED_UP_PLAYBACK_DEFAULT = 5;
public static String SPEED_UP_PLAYBACK = "speed.up.plaback";
// Auto save
private static boolean AUTO_SAVE_DEFAULT = true;
public static String AUTO_SAVE = "auto.save";
private static int AUTO_SAVE_TIME_DEFAULT = 2;
public static String AUTO_SAVE_TIME = "auto.save.time";
// Mini-mode dialog
private static boolean SHOW_MINI_MODE_DIALOG_DEFAULT = true;
public static String SHOW_MINI_MODE_DIALOG = "show.mini.mode.dialog";
// Font and size
private static String FONT_DEFAULT = "Courier New";
public static String FONT = "font";
private static int FONT_SIZE_DEFAULT = 10;
public static String FONT_SIZE = "font.size";
private static Color FONT_COLOR_DEFAULT = Display.getCurrent()
.getSystemColor(SWT.COLOR_BLACK);
public static String FONT_COLOR = "font.color";
private static Color BACKGROUND_COLOR_DEFAULT = Display.getCurrent()
.getSystemColor(SWT.COLOR_WHITE);
public static String BACKGROUND_COLOR = "background.color";
// CONFIGURABLE ACCELERATORS
private String accelerators;
// Pause
private static String PAUSE_KEY_DEFAULT = " ";
public static String PAUSE_KEY = "pause.key";
// Short rewind
private static String SHORT_REWIND_KEY_DEFAULT = "7";
public static String SHORT_REWIND_KEY = "short.rewind.key";
// Long rewind
private static String LONG_REWIND_KEY_DEFAULT = "8";
public static String LONG_REWIND_KEY = "long.rewind.key";
// Speed up
private static String SPEED_UP_KEY_DEFAULT = "4";
public static String SPEED_UP_KEY = "speed.up.key";
// Slow down
private static String SLOW_DOWN_KEY_DEFAULT = "3";
public static String SLOW_DOWN_KEY = "slow.down.key";
// Audio loops
private static String AUDIO_LOOPS_KEY_DEFAULT = "9";
public static String AUDIO_LOOPS_KEY = "audio.loops.key";
public static String LOOP_FRECUENCY = "loop.frecuency";
private static int LOOP_FRECUENCY_DEFAULT = 5;
public static String LOOP_LENGHT = "loop.lenght";
private static int LOOP_LENGHT_DEFAULT = 2;
// Timestamps
private static String TIMESTAMP_KEY_DEFAULT = "t";
public static String TIMESTAMP_KEY = "timestamp.key";
private Config() {
super(CONFIG_PATH);
// Set up the defaults
setDefault(SHORT_REWIND, SHORT_REWIND_DEFAULT);
setDefault(LONG_REWIND, LONG_REWIND_DEFAULT);
setDefault(REWIND_AND_PLAY, REWIND_AND_PLAY_DEFAULT);
setDefault(SHELL_HEIGHT, SHELL_HEIGHT_DEFAULT);
setDefault(SHELL_LENGHT, SHELL_LENGHT_DEFAULT);
setDefault(TEXT_FILE_CACHE_LENGHT, TEXT_FILE_CACHE_LENGHT_DEFAULT);
setDefault(AUDIO_FILE_CACHE_LENGHT, AUDIO_FILE_CACHE_LENGHT_DEFAULT);
setDefault(SLOW_DOWN_PLAYBACK, SLOW_DOWN_PLAYBACK_DEFAULT);
setDefault(SPEED_UP_PLAYBACK, SPEED_UP_PLAYBACK_DEFAULT);
setDefault(AUTO_SAVE, AUTO_SAVE_DEFAULT);
setDefault(AUTO_SAVE_TIME, AUTO_SAVE_TIME_DEFAULT);
setDefault(SHOW_MINI_MODE_DIALOG, SHOW_MINI_MODE_DIALOG_DEFAULT);
setDefault(FONT, FONT_DEFAULT);
setDefault(FONT_SIZE, FONT_SIZE_DEFAULT);
setDefault(FONT_COLOR, FONT_COLOR_DEFAULT);
setDefault(BACKGROUND_COLOR, BACKGROUND_COLOR_DEFAULT);
// Pause
setDefault(PAUSE_KEY, PAUSE_KEY_DEFAULT);
// Short rewind
setDefault(SHORT_REWIND_KEY, SHORT_REWIND_KEY_DEFAULT);
// Long rewind
setDefault(LONG_REWIND_KEY, LONG_REWIND_KEY_DEFAULT);
// Playback speed
setDefault(SPEED_UP_KEY, SPEED_UP_KEY_DEFAULT);
setDefault(SLOW_DOWN_KEY, SLOW_DOWN_KEY_DEFAULT);
// Audio loops
setDefault(AUDIO_LOOPS_KEY, AUDIO_LOOPS_KEY_DEFAULT);
setDefault(LOOP_FRECUENCY, LOOP_FRECUENCY_DEFAULT);
setDefault(LOOP_LENGHT, LOOP_LENGHT_DEFAULT);
// Timestamp
setDefault(TIMESTAMP_KEY, TIMESTAMP_KEY_DEFAULT);
// Cache
setDefault(LAST_OPEN_AUDIO_PATH, LAST_OPEN_AUDIO_PATH_DEFAULT);
setDefault(LAST_OPEN_TEXT_PATH, LAST_OPEN_TEXT_PATH_DEFAULT);
setDefault(LAST_EXPORT_TRANSCRIPTION_PATH,
LAST_EXPORT_TRANSCRIPTION_PATH_DEFALUT);
try {
load();
} catch (Exception e) {
// The properties will start as default values
}
updateAccelerators();
// Add the listeners
addPropertyChangeListener(new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
try {
updateAccelerators();
save();
} catch (IOException e) {
// ignore
}
}
});
}
public void showConfigurationDialog(Shell parent) throws PmTransException {
// Create the preference manager
PreferenceManager mgr = new PreferenceManager();
// Create the nodes
PreferenceNode playbackNode = new PreferenceNode("playbackPreferences");
PreferencePage playbackPage = new FieldEditorPreferencePage() {
@Override
protected void createFieldEditors() {
addField(new IntegerFieldEditor(SHORT_REWIND,
"Short rewind duration (in sec)",
getFieldEditorParent()));
addField(new IntegerFieldEditor(LONG_REWIND,
"Long rewind duration (in sec)", getFieldEditorParent()));
addField(new IntegerFieldEditor(REWIND_AND_PLAY,
"Rewind-and-resume duartion duration (in sec)",
getFieldEditorParent()));
addField(new IntegerFieldEditor(LOOP_FRECUENCY,
"Loops frecuency (in seconds)", getFieldEditorParent()));
addField(new IntegerFieldEditor(LOOP_LENGHT,
"Loop rewind lenght (in seconds)",
getFieldEditorParent()));
}
};
playbackPage.setTitle("Playback preferences");
playbackNode.setPage(playbackPage);
PreferenceNode shortcutsNode = new PreferenceNode(
"shortcutsPreferences");
PreferencePage shortcutsPage = new FieldEditorPreferencePage() {
@Override
protected void createFieldEditors() {
addField(new ShortcutFieldEditor(SHORT_REWIND_KEY,
"Short rewind", getFieldEditorParent()));
addField(new ShortcutFieldEditor(LONG_REWIND_KEY,
"Long rewind", getFieldEditorParent()));
addField(new ShortcutFieldEditor(PAUSE_KEY, "Pause and resume",
getFieldEditorParent()));
addField(new ShortcutFieldEditor(AUDIO_LOOPS_KEY,
"Enable audio loops", getFieldEditorParent()));
addField(new ShortcutFieldEditor(SLOW_DOWN_KEY,
"Slow down audio playback", getFieldEditorParent()));
addField(new ShortcutFieldEditor(SPEED_UP_KEY,
"Speed up audio playback", getFieldEditorParent()));
addField(new ShortcutFieldEditor(TIMESTAMP_KEY,
"Insert timestamp", getFieldEditorParent()));
}
};
shortcutsPage.setTitle("Shortcuts preferences");
shortcutsNode.setPage(shortcutsPage);
PreferenceNode generalNode = new PreferenceNode("generalPreferences");
|
[
"\t\tPreferencePage generalPage = new FieldEditorPreferencePage() {"
] | 925
|
lcc
|
java
| null |
36799d0d8e06fa5c217eccd67db779ab9866845eb0713e74
| 20
|
Your task is code completion.
package gui;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.IntegerFieldEditor;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.preference.PreferenceManager;
import org.eclipse.jface.preference.PreferenceNode;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import util.PmTransException;
public class Config extends PreferenceStore {
private static Config instance = null;
/**
* Non-configurable stuff
*/
// Config file path
private static String CONFIG_PATH = "./config.properties";
// State file path
public static String STATE_PATH = "./state.transcriber";
// Icon paths
public static String ICON_PATH_PLAY = "/icon/start.png";
public static String ICON_PATH_PAUSE = "/icon/pause.png";
public static String ICON_PATH_RESTART = "/icon/restart.png";
public static String ICON_PATH_OPEN_TRANSCRIPTION = "/icon/open.png";
public static String ICON_PATH_OPEN_AUDIO = "/icon/openAudio.png";
public static String ICON_PATH_SAVE_TRANSCRIPTION = "/icon/save.png";
public static String ICON_PATH_LOOP = "/icon/loop.png";
public static String ICON_PATH_ZOOM_IN = "/icon/zoom_in.png";
public static String ICON_PATH_ZOOM_OUT = "/icon/zoom_out.png";
public static String ICON_PATH_COPY = "/icon/copy.png";
public static String ICON_PATH_CUT = "/icon/cut.png";
public static String ICON_PATH_PASTE = "/icon/paste.png";
public static String ICON_PATH_CROSS = "/icon/cross.png";
public static String ICON_PATH_ADVANCED_SEARCH = "/icon/advancedSearch.png";
public static String ICON_PATH_CHANGE_BACKGROUND_COLOR = "/icon/changeBackgroundColor.png";
public static String ICON_PATH_CHANGE_FONT_COLOR = "/icon/changeFontColor.png";
public static String ICON_PATH_SETTINGS = "/icon/settings.png";
public static String ICON_PATH_CONTRIBUTE = "/icon/contribute.png";
public static String DEFAULT_ACCELERATORS = "cxvfosa";
// Main shell initial dimensions
private int SHELL_HEIGHT_DEFAULT = 600;
private int SHELL_LENGHT_DEFAULT = 600;
public static String SHELL_HEIGHT = "window.height";
public static String SHELL_LENGHT = "window.lenght";
// Last directory paths for file dialogs
private String LAST_OPEN_AUDIO_PATH_DEFAULT = "";
public static String LAST_OPEN_AUDIO_PATH = "last.open.audio.path";
private String LAST_OPEN_TEXT_PATH_DEFAULT = "";
public static String LAST_OPEN_TEXT_PATH = "last.open.text.path";
// Last directory path for the export dialog
private String LAST_EXPORT_TRANSCRIPTION_PATH_DEFALUT = "";
public static String LAST_EXPORT_TRANSCRIPTION_PATH = "last.export.transcription.path";
// URLs
public static String CONTRIBUTE_URL = "https://github.com/juanerasmoe/pmTrans/wiki/Contribute-to-pmTrans";
/**
* Configurable stuff
*/
// Duration of the short rewind in seconds
private int SHORT_REWIND_DEFAULT = 5;
public static String SHORT_REWIND = "short.rewind.duration";
// Duration of the long rewind in seconds
private int LONG_REWIND_DEFAULT = 10;
public static String LONG_REWIND = "long.rewind.duration";
// Duration of the rewind-and-play
private static int REWIND_AND_PLAY_DEFAULT = 2;
public static String REWIND_AND_PLAY = "rewind.and.play.duration";
// Max size of the previous-files list
private static int AUDIO_FILE_CACHE_LENGHT_DEFAULT = 7;
public static String AUDIO_FILE_CACHE_LENGHT = "audio.file.cache.lenght";
private static int TEXT_FILE_CACHE_LENGHT_DEFAULT = 7;
public static String TEXT_FILE_CACHE_LENGHT = "text.file.cache.lenght";
private static int SLOW_DOWN_PLAYBACK_DEFAULT = -5;
public static String SLOW_DOWN_PLAYBACK = "slow.down.playback";
private static int SPEED_UP_PLAYBACK_DEFAULT = 5;
public static String SPEED_UP_PLAYBACK = "speed.up.plaback";
// Auto save
private static boolean AUTO_SAVE_DEFAULT = true;
public static String AUTO_SAVE = "auto.save";
private static int AUTO_SAVE_TIME_DEFAULT = 2;
public static String AUTO_SAVE_TIME = "auto.save.time";
// Mini-mode dialog
private static boolean SHOW_MINI_MODE_DIALOG_DEFAULT = true;
public static String SHOW_MINI_MODE_DIALOG = "show.mini.mode.dialog";
// Font and size
private static String FONT_DEFAULT = "Courier New";
public static String FONT = "font";
private static int FONT_SIZE_DEFAULT = 10;
public static String FONT_SIZE = "font.size";
private static Color FONT_COLOR_DEFAULT = Display.getCurrent()
.getSystemColor(SWT.COLOR_BLACK);
public static String FONT_COLOR = "font.color";
private static Color BACKGROUND_COLOR_DEFAULT = Display.getCurrent()
.getSystemColor(SWT.COLOR_WHITE);
public static String BACKGROUND_COLOR = "background.color";
// CONFIGURABLE ACCELERATORS
private String accelerators;
// Pause
private static String PAUSE_KEY_DEFAULT = " ";
public static String PAUSE_KEY = "pause.key";
// Short rewind
private static String SHORT_REWIND_KEY_DEFAULT = "7";
public static String SHORT_REWIND_KEY = "short.rewind.key";
// Long rewind
private static String LONG_REWIND_KEY_DEFAULT = "8";
public static String LONG_REWIND_KEY = "long.rewind.key";
// Speed up
private static String SPEED_UP_KEY_DEFAULT = "4";
public static String SPEED_UP_KEY = "speed.up.key";
// Slow down
private static String SLOW_DOWN_KEY_DEFAULT = "3";
public static String SLOW_DOWN_KEY = "slow.down.key";
// Audio loops
private static String AUDIO_LOOPS_KEY_DEFAULT = "9";
public static String AUDIO_LOOPS_KEY = "audio.loops.key";
public static String LOOP_FRECUENCY = "loop.frecuency";
private static int LOOP_FRECUENCY_DEFAULT = 5;
public static String LOOP_LENGHT = "loop.lenght";
private static int LOOP_LENGHT_DEFAULT = 2;
// Timestamps
private static String TIMESTAMP_KEY_DEFAULT = "t";
public static String TIMESTAMP_KEY = "timestamp.key";
private Config() {
super(CONFIG_PATH);
// Set up the defaults
setDefault(SHORT_REWIND, SHORT_REWIND_DEFAULT);
setDefault(LONG_REWIND, LONG_REWIND_DEFAULT);
setDefault(REWIND_AND_PLAY, REWIND_AND_PLAY_DEFAULT);
setDefault(SHELL_HEIGHT, SHELL_HEIGHT_DEFAULT);
setDefault(SHELL_LENGHT, SHELL_LENGHT_DEFAULT);
setDefault(TEXT_FILE_CACHE_LENGHT, TEXT_FILE_CACHE_LENGHT_DEFAULT);
setDefault(AUDIO_FILE_CACHE_LENGHT, AUDIO_FILE_CACHE_LENGHT_DEFAULT);
setDefault(SLOW_DOWN_PLAYBACK, SLOW_DOWN_PLAYBACK_DEFAULT);
setDefault(SPEED_UP_PLAYBACK, SPEED_UP_PLAYBACK_DEFAULT);
setDefault(AUTO_SAVE, AUTO_SAVE_DEFAULT);
setDefault(AUTO_SAVE_TIME, AUTO_SAVE_TIME_DEFAULT);
setDefault(SHOW_MINI_MODE_DIALOG, SHOW_MINI_MODE_DIALOG_DEFAULT);
setDefault(FONT, FONT_DEFAULT);
setDefault(FONT_SIZE, FONT_SIZE_DEFAULT);
setDefault(FONT_COLOR, FONT_COLOR_DEFAULT);
setDefault(BACKGROUND_COLOR, BACKGROUND_COLOR_DEFAULT);
// Pause
setDefault(PAUSE_KEY, PAUSE_KEY_DEFAULT);
// Short rewind
setDefault(SHORT_REWIND_KEY, SHORT_REWIND_KEY_DEFAULT);
// Long rewind
setDefault(LONG_REWIND_KEY, LONG_REWIND_KEY_DEFAULT);
// Playback speed
setDefault(SPEED_UP_KEY, SPEED_UP_KEY_DEFAULT);
setDefault(SLOW_DOWN_KEY, SLOW_DOWN_KEY_DEFAULT);
// Audio loops
setDefault(AUDIO_LOOPS_KEY, AUDIO_LOOPS_KEY_DEFAULT);
setDefault(LOOP_FRECUENCY, LOOP_FRECUENCY_DEFAULT);
setDefault(LOOP_LENGHT, LOOP_LENGHT_DEFAULT);
// Timestamp
setDefault(TIMESTAMP_KEY, TIMESTAMP_KEY_DEFAULT);
// Cache
setDefault(LAST_OPEN_AUDIO_PATH, LAST_OPEN_AUDIO_PATH_DEFAULT);
setDefault(LAST_OPEN_TEXT_PATH, LAST_OPEN_TEXT_PATH_DEFAULT);
setDefault(LAST_EXPORT_TRANSCRIPTION_PATH,
LAST_EXPORT_TRANSCRIPTION_PATH_DEFALUT);
try {
load();
} catch (Exception e) {
// The properties will start as default values
}
updateAccelerators();
// Add the listeners
addPropertyChangeListener(new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
try {
updateAccelerators();
save();
} catch (IOException e) {
// ignore
}
}
});
}
public void showConfigurationDialog(Shell parent) throws PmTransException {
// Create the preference manager
PreferenceManager mgr = new PreferenceManager();
// Create the nodes
PreferenceNode playbackNode = new PreferenceNode("playbackPreferences");
PreferencePage playbackPage = new FieldEditorPreferencePage() {
@Override
protected void createFieldEditors() {
addField(new IntegerFieldEditor(SHORT_REWIND,
"Short rewind duration (in sec)",
getFieldEditorParent()));
addField(new IntegerFieldEditor(LONG_REWIND,
"Long rewind duration (in sec)", getFieldEditorParent()));
addField(new IntegerFieldEditor(REWIND_AND_PLAY,
"Rewind-and-resume duartion duration (in sec)",
getFieldEditorParent()));
addField(new IntegerFieldEditor(LOOP_FRECUENCY,
"Loops frecuency (in seconds)", getFieldEditorParent()));
addField(new IntegerFieldEditor(LOOP_LENGHT,
"Loop rewind lenght (in seconds)",
getFieldEditorParent()));
}
};
playbackPage.setTitle("Playback preferences");
playbackNode.setPage(playbackPage);
PreferenceNode shortcutsNode = new PreferenceNode(
"shortcutsPreferences");
PreferencePage shortcutsPage = new FieldEditorPreferencePage() {
@Override
protected void createFieldEditors() {
addField(new ShortcutFieldEditor(SHORT_REWIND_KEY,
"Short rewind", getFieldEditorParent()));
addField(new ShortcutFieldEditor(LONG_REWIND_KEY,
"Long rewind", getFieldEditorParent()));
addField(new ShortcutFieldEditor(PAUSE_KEY, "Pause and resume",
getFieldEditorParent()));
addField(new ShortcutFieldEditor(AUDIO_LOOPS_KEY,
"Enable audio loops", getFieldEditorParent()));
addField(new ShortcutFieldEditor(SLOW_DOWN_KEY,
"Slow down audio playback", getFieldEditorParent()));
addField(new ShortcutFieldEditor(SPEED_UP_KEY,
"Speed up audio playback", getFieldEditorParent()));
addField(new ShortcutFieldEditor(TIMESTAMP_KEY,
"Insert timestamp", getFieldEditorParent()));
}
};
shortcutsPage.setTitle("Shortcuts preferences");
shortcutsNode.setPage(shortcutsPage);
PreferenceNode generalNode = new PreferenceNode("generalPreferences");
|
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]
public class Config extends PreferenceStore {
// ... (many lines of code)
public void showConfigurationDialog(Shell parent) throws PmTransException {
// Create the preference manager
PreferenceManager mgr = new PreferenceManager();
// Create the nodes
PreferenceNode playbackNode = new PreferenceNode("playbackPreferences");
PreferencePage playbackPage = new FieldEditorPreferencePage() {
@Override
protected void createFieldEditors() {
addField(new IntegerFieldEditor(SHORT_REWIND,
"Short rewind duration (in sec)",
getFieldEditorParent()));
addField(new IntegerFieldEditor(LONG_REWIND,
"Long rewind duration (in sec)", getFieldEditorParent()));
addField(new IntegerFieldEditor(REWIND_AND_PLAY,
"Rewind-and-resume duartion duration (in sec)",
getFieldEditorParent()));
addField(new IntegerFieldEditor(LOOP_FRECUENCY,
"Loops frecuency (in seconds)", getFieldEditorParent()));
addField(new IntegerFieldEditor(LOOP_LENGHT,
"Loop rewind lenght (in seconds)",
getFieldEditorParent()));
}
};
playbackPage.setTitle("Playback preferences");
playbackNode.setPage(playbackPage);
PreferenceNode shortcutsNode = new PreferenceNode(
"shortcutsPreferences");
PreferencePage shortcutsPage = new FieldEditorPreferencePage() {
@Override
protected void createFieldEditors() {
addField(new ShortcutFieldEditor(SHORT_REWIND_KEY,
"Short rewind", getFieldEditorParent()));
addField(new ShortcutFieldEditor(LONG_REWIND_KEY,
"Long rewind", getFieldEditorParent()));
addField(new ShortcutFieldEditor(PAUSE_KEY, "Pause and resume",
getFieldEditorParent()));
addField(new ShortcutFieldEditor(AUDIO_LOOPS_KEY,
"Enable audio loops", getFieldEditorParent()));
addField(new ShortcutFieldEditor(SLOW_DOWN_KEY,
"Slow down audio playback", getFieldEditorParent()));
addField(new ShortcutFieldEditor(SPEED_UP_KEY,
"Speed up audio playback", getFieldEditorParent()));
addField(new ShortcutFieldEditor(TIMESTAMP_KEY,
"Insert timestamp", getFieldEditorParent()));
}
};
shortcutsPage.setTitle("Shortcuts preferences");
shortcutsNode.setPage(shortcutsPage);
PreferenceNode generalNode = new PreferenceNode("generalPreferences");
Cheatsheet (for next line):
- We are in showConfigurationDialog(), which is creating a preference dialog.
- The code is creating nodes and pages for different preferences.
- The generalNode is created but not added to the preference manager.
- Convention: Add the generalNode to the preference manager.
- [Relevant lines: creation of playbackNode, shortcutsNode, generalNode]
Next line will likely be: generalNode.setPage(new FieldEditorPreferencePage() { ... });
|
|
Please complete the code given below.
using System;
using System.Collections.Generic;
using Server.Network;
using Server.Items;
using Server.Targeting;
using Server.Engines.PartySystem;
namespace Server.Spells.Fourth
{
public class ArchProtectionSpell : MagerySpell
{
private static SpellInfo m_Info = new SpellInfo(
"Arch Protection", "Vas Uus Sanct",
Core.AOS ? 239 : 215,
9011,
Reagent.Garlic,
Reagent.Ginseng,
Reagent.MandrakeRoot,
Reagent.SulfurousAsh
);
public override SpellCircle Circle { get { return SpellCircle.Fourth; } }
public override void SelectTarget()
{
Caster.Target = new InternalSphereTarget(this);
}
public override void OnSphereCast()
{
if (SpellTarget != null)
{
if (SpellTarget is IPoint3D)
{
Target((IPoint3D)SpellTarget);
}
else
{
Caster.SendAsciiMessage("Invalid target");
}
}
FinishSequence();
}
public ArchProtectionSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info )
{
}
public override void OnCast()
{
Caster.Target = new InternalTarget( this );
}
public void Target( IPoint3D p )
{
if ( !Caster.CanSee( p ) )
{
Caster.SendLocalizedMessage( 500237 ); // Target can not be seen.
}
else if (!CheckLineOfSight(p))
{
this.DoFizzle();
Caster.SendAsciiMessage("Target is not in line of sight");
}
else if ( CheckSequence() )
{
SpellHelper.Turn( Caster, p );
SpellHelper.GetSurfaceTop( ref p );
List<Mobile> targets = new List<Mobile>();
Map map = Caster.Map;
if ( map != null )
{
IPooledEnumerable eable = map.GetMobilesInRange( new Point3D( p ), Core.AOS ? 2 : 3 );
foreach ( Mobile m in eable )
{
if ( Caster.CanBeBeneficial( m, false ) )
targets.Add( m );
}
eable.Free();
}
if ( Core.AOS )
{
Party party = Party.Get( Caster );
for ( int i = 0; i < targets.Count; ++i )
{
Mobile m = targets[i];
if ( m == Caster || ( party != null && party.Contains( m ) ) )
{
Caster.DoBeneficial( m );
Spells.Second.ProtectionSpell.Toggle( Caster, m );
}
}
}
else
{
Effects.PlaySound( p, Caster.Map, 0x299 );
int val = (int)(Caster.Skills[SkillName.Magery].Value/10.0 + 1);
if ( targets.Count > 0 )
{
for ( int i = 0; i < targets.Count; ++i )
{
Mobile m = targets[i];
if ( m.BeginAction( typeof( ArchProtectionSpell ) ) )
{
Caster.DoBeneficial( m );
m.VirtualArmorMod += val;
new InternalTimer( m, Caster, val ).Start();
m.FixedParticles( 0x375A, 9, 20, 5027, EffectLayer.Waist );
m.PlaySound( 0x1F7 );
}
}
}
}
}
FinishSequence();
}
private class InternalTimer : Timer
{
private Mobile m_Owner;
private int m_Val;
public InternalTimer( Mobile target, Mobile caster, int val ) : base( TimeSpan.FromSeconds( 0 ) )
{
double time = caster.Skills[SkillName.Magery].Value * 1.2;
if ( time > 144 )
time = 144;
Delay = TimeSpan.FromSeconds( time );
Priority = TimerPriority.OneSecond;
m_Owner = target;
m_Val = val;
}
protected override void OnTick()
{
m_Owner.EndAction( typeof( ArchProtectionSpell ) );
m_Owner.VirtualArmorMod -= m_Val;
if ( m_Owner.VirtualArmorMod < 0 )
m_Owner.VirtualArmorMod = 0;
}
}
private static Dictionary<Mobile, Int32> _Table = new Dictionary<Mobile, Int32>();
private static void AddEntry(Mobile m, Int32 v)
{
_Table[m] = v;
}
public static void RemoveEntry(Mobile m)
{
if (_Table.ContainsKey(m))
{
int v = _Table[m];
_Table.Remove(m);
m.EndAction(typeof(ArchProtectionSpell));
m.VirtualArmorMod -= v;
if (m.VirtualArmorMod < 0)
m.VirtualArmorMod = 0;
}
}
private class InternalSphereTarget : Target
{
private ArchProtectionSpell m_Owner;
public InternalSphereTarget(ArchProtectionSpell owner)
: base(Core.ML ? 10 : 12, true, TargetFlags.Beneficial)
{
m_Owner = owner;
m_Owner.Caster.SendAsciiMessage("Select target...");
}
protected override void OnTarget(Mobile from, object o)
{
if (o is IPoint3D)
{
m_Owner.SpellTarget = o;
m_Owner.CastSpell();
}
else
{
m_Owner.Caster.SendAsciiMessage("Invalid target");
}
}
protected override void OnTargetFinish(Mobile from)
{
|
[
" if (m_Owner.SpellTarget == null)"
] | 538
|
lcc
|
csharp
| null |
82560c22f3648e5086523b10f22179edb1aebdc379fdfaa5
| 21
|
Your task is code completion.
using System;
using System.Collections.Generic;
using Server.Network;
using Server.Items;
using Server.Targeting;
using Server.Engines.PartySystem;
namespace Server.Spells.Fourth
{
public class ArchProtectionSpell : MagerySpell
{
private static SpellInfo m_Info = new SpellInfo(
"Arch Protection", "Vas Uus Sanct",
Core.AOS ? 239 : 215,
9011,
Reagent.Garlic,
Reagent.Ginseng,
Reagent.MandrakeRoot,
Reagent.SulfurousAsh
);
public override SpellCircle Circle { get { return SpellCircle.Fourth; } }
public override void SelectTarget()
{
Caster.Target = new InternalSphereTarget(this);
}
public override void OnSphereCast()
{
if (SpellTarget != null)
{
if (SpellTarget is IPoint3D)
{
Target((IPoint3D)SpellTarget);
}
else
{
Caster.SendAsciiMessage("Invalid target");
}
}
FinishSequence();
}
public ArchProtectionSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info )
{
}
public override void OnCast()
{
Caster.Target = new InternalTarget( this );
}
public void Target( IPoint3D p )
{
if ( !Caster.CanSee( p ) )
{
Caster.SendLocalizedMessage( 500237 ); // Target can not be seen.
}
else if (!CheckLineOfSight(p))
{
this.DoFizzle();
Caster.SendAsciiMessage("Target is not in line of sight");
}
else if ( CheckSequence() )
{
SpellHelper.Turn( Caster, p );
SpellHelper.GetSurfaceTop( ref p );
List<Mobile> targets = new List<Mobile>();
Map map = Caster.Map;
if ( map != null )
{
IPooledEnumerable eable = map.GetMobilesInRange( new Point3D( p ), Core.AOS ? 2 : 3 );
foreach ( Mobile m in eable )
{
if ( Caster.CanBeBeneficial( m, false ) )
targets.Add( m );
}
eable.Free();
}
if ( Core.AOS )
{
Party party = Party.Get( Caster );
for ( int i = 0; i < targets.Count; ++i )
{
Mobile m = targets[i];
if ( m == Caster || ( party != null && party.Contains( m ) ) )
{
Caster.DoBeneficial( m );
Spells.Second.ProtectionSpell.Toggle( Caster, m );
}
}
}
else
{
Effects.PlaySound( p, Caster.Map, 0x299 );
int val = (int)(Caster.Skills[SkillName.Magery].Value/10.0 + 1);
if ( targets.Count > 0 )
{
for ( int i = 0; i < targets.Count; ++i )
{
Mobile m = targets[i];
if ( m.BeginAction( typeof( ArchProtectionSpell ) ) )
{
Caster.DoBeneficial( m );
m.VirtualArmorMod += val;
new InternalTimer( m, Caster, val ).Start();
m.FixedParticles( 0x375A, 9, 20, 5027, EffectLayer.Waist );
m.PlaySound( 0x1F7 );
}
}
}
}
}
FinishSequence();
}
private class InternalTimer : Timer
{
private Mobile m_Owner;
private int m_Val;
public InternalTimer( Mobile target, Mobile caster, int val ) : base( TimeSpan.FromSeconds( 0 ) )
{
double time = caster.Skills[SkillName.Magery].Value * 1.2;
if ( time > 144 )
time = 144;
Delay = TimeSpan.FromSeconds( time );
Priority = TimerPriority.OneSecond;
m_Owner = target;
m_Val = val;
}
protected override void OnTick()
{
m_Owner.EndAction( typeof( ArchProtectionSpell ) );
m_Owner.VirtualArmorMod -= m_Val;
if ( m_Owner.VirtualArmorMod < 0 )
m_Owner.VirtualArmorMod = 0;
}
}
private static Dictionary<Mobile, Int32> _Table = new Dictionary<Mobile, Int32>();
private static void AddEntry(Mobile m, Int32 v)
{
_Table[m] = v;
}
public static void RemoveEntry(Mobile m)
{
if (_Table.ContainsKey(m))
{
int v = _Table[m];
_Table.Remove(m);
m.EndAction(typeof(ArchProtectionSpell));
m.VirtualArmorMod -= v;
if (m.VirtualArmorMod < 0)
m.VirtualArmorMod = 0;
}
}
private class InternalSphereTarget : Target
{
private ArchProtectionSpell m_Owner;
public InternalSphereTarget(ArchProtectionSpell owner)
: base(Core.ML ? 10 : 12, true, TargetFlags.Beneficial)
{
m_Owner = owner;
m_Owner.Caster.SendAsciiMessage("Select target...");
}
protected override void OnTarget(Mobile from, object o)
{
if (o is IPoint3D)
{
m_Owner.SpellTarget = o;
m_Owner.CastSpell();
}
else
{
m_Owner.Caster.SendAsciiMessage("Invalid target");
}
}
protected override void OnTargetFinish(Mobile from)
{
|
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]
public class ArchProtectionSpell : MagerySpell
{
// ...
public void Target(IPoint3D p)
{
// ...
if (Core.AOS)
{
// ...
for (int i = 0; i < targets.Count; ++i)
{
Mobile m = targets[i];
if (m == Caster || (party != null && party.Contains(m)))
{
Caster.DoBeneficial(m);
Spells.Second.ProtectionSpell.Toggle(Caster, m);
}
}
}
else
{
// ...
for (int i = 0; i < targets.Count; ++i)
{
Mobile m = targets[i];
if (m.BeginAction(typeof(ArchProtectionSpell)))
{
Caster.DoBeneficial(m);
m.VirtualArmorMod += val;
new InternalTimer(m, Caster, val).Start();
m.FixedParticles(0x375A, 9, 20, 5027, EffectLayer.Waist);
m.PlaySound(0x1F7);
}
}
}
FinishSequence();
}
// ...
**Cheat sheet (for next line):**
- We are in the else block of the Target method, which is handling the non-AOS case.
- The code is iterating over the targets list and performing some actions on each target.
- The current target is stored in the variable m.
- The code is using the InternalTimer class to schedule a timer for each target.
- The timer is started with the line `new InternalTimer(m, Caster, val).Start();`.
- The timer class has a constructor that takes three parameters: the target, the caster, and a value.
- The timer class has a method `OnTick` that is called when the timer expires.
**Relevant lines:**
- `new InternalTimer(m, Caster, val).Start();`
- `InternalTimer` class constructor
- `InternalTimer` class `OnTick` method
**Next line will likely be:**
`new InternalTimer(m, Caster, val).Start();` is already written, but the next line should be the closing bracket `}` to end the if statement.
|
|
Please complete the code given below.
# orm/session.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Provides the Session class and related utilities."""
import weakref
from itertools import chain
from sqlalchemy import util, sql, engine, log, exc as sa_exc
from sqlalchemy.sql import util as sql_util, expression
from sqlalchemy.orm import (
SessionExtension, attributes, exc, query, unitofwork, util as mapperutil, state
)
from sqlalchemy.orm.util import object_mapper as _object_mapper
from sqlalchemy.orm.util import class_mapper as _class_mapper
from sqlalchemy.orm.util import (
_class_to_mapper, _state_mapper,
)
from sqlalchemy.orm.mapper import Mapper, _none_set
from sqlalchemy.orm.unitofwork import UOWTransaction
from sqlalchemy.orm import identity
from sqlalchemy import event
from sqlalchemy.orm.events import SessionEvents
import sys
__all__ = ['Session', 'SessionTransaction', 'SessionExtension']
def sessionmaker(bind=None, class_=None, autoflush=True, autocommit=False,
expire_on_commit=True, **kwargs):
"""Generate a custom-configured :class:`.Session` class.
The returned object is a subclass of :class:`.Session`, which, when instantiated
with no arguments, uses the keyword arguments configured here as its
constructor arguments.
It is intended that the :func:`.sessionmaker()` function be called within the
global scope of an application, and the returned class be made available
to the rest of the application as the single class used to instantiate
sessions.
e.g.::
# global scope
Session = sessionmaker(autoflush=False)
# later, in a local scope, create and use a session:
sess = Session()
Any keyword arguments sent to the constructor itself will override the
"configured" keywords::
Session = sessionmaker()
# bind an individual session to a connection
sess = Session(bind=connection)
The class also includes a special classmethod ``configure()``, which
allows additional configurational options to take place after the custom
``Session`` class has been generated. This is useful particularly for
defining the specific ``Engine`` (or engines) to which new instances of
``Session`` should be bound::
Session = sessionmaker()
Session.configure(bind=create_engine('sqlite:///foo.db'))
sess = Session()
For options, see the constructor options for :class:`.Session`.
"""
kwargs['bind'] = bind
kwargs['autoflush'] = autoflush
kwargs['autocommit'] = autocommit
kwargs['expire_on_commit'] = expire_on_commit
if class_ is None:
class_ = Session
class Sess(object):
def __init__(self, **local_kwargs):
for k in kwargs:
local_kwargs.setdefault(k, kwargs[k])
super(Sess, self).__init__(**local_kwargs)
@classmethod
def configure(self, **new_kwargs):
"""(Re)configure the arguments for this sessionmaker.
e.g.::
Session = sessionmaker()
Session.configure(bind=create_engine('sqlite://'))
"""
kwargs.update(new_kwargs)
return type("SessionMaker", (Sess, class_), {})
class SessionTransaction(object):
"""A :class:`.Session`-level transaction.
:class:`.SessionTransaction` is a mostly behind-the-scenes object
not normally referenced directly by application code. It coordinates
among multiple :class:`.Connection` objects, maintaining a database
transaction for each one individually, committing or rolling them
back all at once. It also provides optional two-phase commit behavior
which can augment this coordination operation.
The :attr:`.Session.transaction` attribute of :class:`.Session` refers to the
current :class:`.SessionTransaction` object in use, if any.
A :class:`.SessionTransaction` is associated with a :class:`.Session`
in its default mode of ``autocommit=False`` immediately, associated
with no database connections. As the :class:`.Session` is called upon
to emit SQL on behalf of various :class:`.Engine` or :class:`.Connection`
objects, a corresponding :class:`.Connection` and associated :class:`.Transaction`
is added to a collection within the :class:`.SessionTransaction` object,
becoming one of the connection/transaction pairs maintained by the
:class:`.SessionTransaction`.
The lifespan of the :class:`.SessionTransaction` ends when the
:meth:`.Session.commit`, :meth:`.Session.rollback` or :meth:`.Session.close`
methods are called. At this point, the :class:`.SessionTransaction` removes
its association with its parent :class:`.Session`. A :class:`.Session`
that is in ``autocommit=False`` mode will create a new
:class:`.SessionTransaction` to replace it immediately, whereas a
:class:`.Session` that's in ``autocommit=True``
mode will remain without a :class:`.SessionTransaction` until the
:meth:`.Session.begin` method is called.
Another detail of :class:`.SessionTransaction` behavior is that it is
capable of "nesting". This means that the :meth:`.begin` method can
be called while an existing :class:`.SessionTransaction` is already present,
producing a new :class:`.SessionTransaction` that temporarily replaces
the parent :class:`.SessionTransaction`. When a :class:`.SessionTransaction`
is produced as nested, it assigns itself to the :attr:`.Session.transaction`
attribute. When it is ended via :meth:`.Session.commit` or :meth:`.Session.rollback`,
it restores its parent :class:`.SessionTransaction` back onto the
:attr:`.Session.transaction` attribute. The
behavior is effectively a stack, where :attr:`.Session.transaction` refers
to the current head of the stack.
The purpose of this stack is to allow nesting of :meth:`.rollback` or
:meth:`.commit` calls in context with various flavors of :meth:`.begin`.
This nesting behavior applies to when :meth:`.Session.begin_nested`
is used to emit a SAVEPOINT transaction, and is also used to produce
a so-called "subtransaction" which allows a block of code to use a
begin/rollback/commit sequence regardless of whether or not its enclosing
code block has begun a transaction. The :meth:`.flush` method, whether called
explicitly or via autoflush, is the primary consumer of the "subtransaction"
feature, in that it wishes to guarantee that it works within in a transaction block
regardless of whether or not the :class:`.Session` is in transactional mode
when the method is called.
See also:
:meth:`.Session.rollback`
:meth:`.Session.commit`
:meth:`.Session.begin`
:meth:`.Session.begin_nested`
:attr:`.Session.is_active`
:meth:`.SessionEvents.after_commit`
:meth:`.SessionEvents.after_rollback`
:meth:`.SessionEvents.after_soft_rollback`
"""
_rollback_exception = None
def __init__(self, session, parent=None, nested=False):
self.session = session
self._connections = {}
self._parent = parent
self.nested = nested
self._active = True
self._prepared = False
if not parent and nested:
raise sa_exc.InvalidRequestError(
"Can't start a SAVEPOINT transaction when no existing "
"transaction is in progress")
if self.session._enable_transaction_accounting:
self._take_snapshot()
@property
def is_active(self):
return self.session is not None and self._active
def _assert_is_active(self):
self._assert_is_open()
if not self._active:
if self._rollback_exception:
raise sa_exc.InvalidRequestError(
"This Session's transaction has been rolled back "
"due to a previous exception during flush."
" To begin a new transaction with this Session, "
"first issue Session.rollback()."
" Original exception was: %s"
% self._rollback_exception
)
else:
raise sa_exc.InvalidRequestError(
"This Session's transaction has been rolled back "
"by a nested rollback() call. To begin a new "
"transaction, issue Session.rollback() first."
)
def _assert_is_open(self, error_msg="The transaction is closed"):
if self.session is None:
raise sa_exc.ResourceClosedError(error_msg)
@property
def _is_transaction_boundary(self):
return self.nested or not self._parent
def connection(self, bindkey, **kwargs):
self._assert_is_active()
engine = self.session.get_bind(bindkey, **kwargs)
return self._connection_for_bind(engine)
def _begin(self, nested=False):
self._assert_is_active()
return SessionTransaction(
self.session, self, nested=nested)
def _iterate_parents(self, upto=None):
if self._parent is upto:
return (self,)
else:
if self._parent is None:
raise sa_exc.InvalidRequestError(
"Transaction %s is not on the active transaction list" % (
upto))
return (self,) + self._parent._iterate_parents(upto)
def _take_snapshot(self):
if not self._is_transaction_boundary:
self._new = self._parent._new
self._deleted = self._parent._deleted
self._key_switches = self._parent._key_switches
return
if not self.session._flushing:
self.session.flush()
self._new = weakref.WeakKeyDictionary()
self._deleted = weakref.WeakKeyDictionary()
self._key_switches = weakref.WeakKeyDictionary()
def _restore_snapshot(self):
assert self._is_transaction_boundary
for s in set(self._new).union(self.session._new):
self.session._expunge_state(s)
if s.key:
del s.key
for s, (oldkey, newkey) in self._key_switches.items():
self.session.identity_map.discard(s)
s.key = oldkey
self.session.identity_map.replace(s)
for s in set(self._deleted).union(self.session._deleted):
if s.deleted:
#assert s in self._deleted
del s.deleted
self.session._update_impl(s, discard_existing=True)
assert not self.session._deleted
for s in self.session.identity_map.all_states():
s.expire(s.dict, self.session.identity_map._modified)
def _remove_snapshot(self):
assert self._is_transaction_boundary
if not self.nested and self.session.expire_on_commit:
for s in self.session.identity_map.all_states():
s.expire(s.dict, self.session.identity_map._modified)
def _connection_for_bind(self, bind):
self._assert_is_active()
if bind in self._connections:
return self._connections[bind][0]
if self._parent:
conn = self._parent._connection_for_bind(bind)
if not self.nested:
return conn
else:
if isinstance(bind, engine.Connection):
conn = bind
if conn.engine in self._connections:
raise sa_exc.InvalidRequestError(
"Session already has a Connection associated for the "
"given Connection's Engine")
else:
conn = bind.contextual_connect()
if self.session.twophase and self._parent is None:
transaction = conn.begin_twophase()
elif self.nested:
transaction = conn.begin_nested()
else:
transaction = conn.begin()
self._connections[conn] = self._connections[conn.engine] = \
(conn, transaction, conn is not bind)
self.session.dispatch.after_begin(self.session, self, conn)
return conn
def prepare(self):
if self._parent is not None or not self.session.twophase:
raise sa_exc.InvalidRequestError(
"Only root two phase transactions of can be prepared")
self._prepare_impl()
def _prepare_impl(self):
self._assert_is_active()
if self._parent is None or self.nested:
self.session.dispatch.before_commit(self.session)
stx = self.session.transaction
if stx is not self:
for subtransaction in stx._iterate_parents(upto=self):
subtransaction.commit()
if not self.session._flushing:
for _flush_guard in xrange(100):
if self.session._is_clean():
break
self.session.flush()
else:
raise exc.FlushError(
"Over 100 subsequent flushes have occurred within "
"session.commit() - is an after_flush() hook "
"creating new objects?")
if self._parent is None and self.session.twophase:
try:
for t in set(self._connections.values()):
t[1].prepare()
except:
self.rollback()
raise
self._deactivate()
self._prepared = True
def commit(self):
self._assert_is_open()
if not self._prepared:
self._prepare_impl()
if self._parent is None or self.nested:
for t in set(self._connections.values()):
t[1].commit()
self.session.dispatch.after_commit(self.session)
if self.session._enable_transaction_accounting:
self._remove_snapshot()
self.close()
return self._parent
def rollback(self, _capture_exception=False):
self._assert_is_open()
stx = self.session.transaction
if stx is not self:
for subtransaction in stx._iterate_parents(upto=self):
subtransaction.close()
if self.is_active or self._prepared:
for transaction in self._iterate_parents():
if transaction._parent is None or transaction.nested:
transaction._rollback_impl()
transaction._deactivate()
break
else:
transaction._deactivate()
sess = self.session
if self.session._enable_transaction_accounting and \
not sess._is_clean():
# if items were added, deleted, or mutated
# here, we need to re-restore the snapshot
util.warn(
"Session's state has been changed on "
"a non-active transaction - this state "
"will be discarded.")
self._restore_snapshot()
self.close()
if self._parent and _capture_exception:
self._parent._rollback_exception = sys.exc_info()[1]
sess.dispatch.after_soft_rollback(sess, self)
return self._parent
def _rollback_impl(self):
for t in set(self._connections.values()):
t[1].rollback()
if self.session._enable_transaction_accounting:
self._restore_snapshot()
self.session.dispatch.after_rollback(self.session)
def _deactivate(self):
self._active = False
def close(self):
self.session.transaction = self._parent
if self._parent is None:
for connection, transaction, autoclose in \
set(self._connections.values()):
if autoclose:
connection.close()
else:
transaction.close()
if not self.session.autocommit:
self.session.begin()
self._deactivate()
self.session = None
self._connections = None
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self._assert_is_open("Cannot end transaction context. The transaction "
"was closed from within the context")
if self.session.transaction is None:
return
if type is None:
try:
self.commit()
except:
self.rollback()
raise
else:
self.rollback()
class Session(object):
"""Manages persistence operations for ORM-mapped objects.
The Session's usage paradigm is described at :ref:`session_toplevel`.
"""
public_methods = (
'__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested',
'close', 'commit', 'connection', 'delete', 'execute', 'expire',
'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind',
'is_modified',
'merge', 'query', 'refresh', 'rollback',
'scalar')
def __init__(self, bind=None, autoflush=True, expire_on_commit=True,
_enable_transaction_accounting=True,
autocommit=False, twophase=False,
weak_identity_map=True, binds=None, extension=None,
query_cls=query.Query):
"""Construct a new Session.
See also the :func:`.sessionmaker` function which is used to
generate a :class:`.Session`-producing callable with a given
set of arguments.
:param autocommit: Defaults to ``False``. When ``True``, the ``Session``
does not keep a persistent transaction running, and will acquire
connections from the engine on an as-needed basis, returning them
immediately after their use. Flushes will begin and commit (or possibly
rollback) their own transaction if no transaction is present. When using
this mode, the `session.begin()` method may be used to begin a
transaction explicitly.
Leaving it on its default value of ``False`` means that the ``Session``
will acquire a connection and begin a transaction the first time it is
used, which it will maintain persistently until ``rollback()``,
``commit()``, or ``close()`` is called. When the transaction is released
by any of these methods, the ``Session`` is ready for the next usage,
which will again acquire and maintain a new connection/transaction.
:param autoflush: When ``True``, all query operations will issue a
``flush()`` call to this ``Session`` before proceeding. This is a
convenience feature so that ``flush()`` need not be called repeatedly
in order for database queries to retrieve results. It's typical that
``autoflush`` is used in conjunction with ``autocommit=False``. In this
scenario, explicit calls to ``flush()`` are rarely needed; you usually
only need to call ``commit()`` (which flushes) to finalize changes.
:param bind: An optional ``Engine`` or ``Connection`` to which this
``Session`` should be bound. When specified, all SQL operations
performed by this session will execute via this connectable.
:param binds: An optional dictionary which contains more granular "bind"
information than the ``bind`` parameter provides. This dictionary can
map individual ``Table`` instances as well as ``Mapper`` instances to
individual ``Engine`` or ``Connection`` objects. Operations which
proceed relative to a particular ``Mapper`` will consult this
dictionary for the direct ``Mapper`` instance as well as the mapper's
``mapped_table`` attribute in order to locate an connectable to use.
The full resolution is described in the ``get_bind()`` method of
``Session``. Usage looks like::
Session = sessionmaker(binds={
SomeMappedClass: create_engine('postgresql://engine1'),
somemapper: create_engine('postgresql://engine2'),
some_table: create_engine('postgresql://engine3'),
})
Also see the :meth:`.Session.bind_mapper` and :meth:`.Session.bind_table` methods.
:param \class_: Specify an alternate class other than
``sqlalchemy.orm.session.Session`` which should be used by the returned
class. This is the only argument that is local to the
``sessionmaker()`` function, and is not sent directly to the
constructor for ``Session``.
:param _enable_transaction_accounting: Defaults to ``True``. A
legacy-only flag which when ``False`` disables *all* 0.5-style object
accounting on transaction boundaries, including auto-expiry of
instances on rollback and commit, maintenance of the "new" and
"deleted" lists upon rollback, and autoflush of pending changes upon
begin(), all of which are interdependent.
:param expire_on_commit: Defaults to ``True``. When ``True``, all
instances will be fully expired after each ``commit()``, so that all
attribute/object access subsequent to a completed transaction will load
from the most recent database state.
:param extension: An optional
:class:`~.SessionExtension` instance, or a list
of such instances, which will receive pre- and post- commit and flush
events, as well as a post-rollback event. **Deprecated.**
Please see :class:`.SessionEvents`.
:param query_cls: Class which should be used to create new Query objects,
as returned by the ``query()`` method. Defaults to
:class:`~sqlalchemy.orm.query.Query`.
:param twophase: When ``True``, all transactions will be started as
a "two phase" transaction, i.e. using the "two phase" semantics
of the database in use along with an XID. During a ``commit()``,
after ``flush()`` has been issued for all attached databases, the
``prepare()`` method on each database's ``TwoPhaseTransaction`` will
be called. This allows each database to roll back the entire
transaction, before each transaction is committed.
:param weak_identity_map: Defaults to ``True`` - when set to
``False``, objects placed in the :class:`.Session` will be
strongly referenced until explicitly removed or the
:class:`.Session` is closed. **Deprecated** - this option
is obsolete.
"""
if weak_identity_map:
self._identity_cls = identity.WeakInstanceDict
else:
util.warn_deprecated("weak_identity_map=False is deprecated. "
"This feature is not needed.")
self._identity_cls = identity.StrongInstanceDict
self.identity_map = self._identity_cls()
self._new = {} # InstanceState->object, strong refs object
self._deleted = {} # same
self.bind = bind
self.__binds = {}
self._flushing = False
self.transaction = None
self.hash_key = _new_sessionid()
self.autoflush = autoflush
self.autocommit = autocommit
self.expire_on_commit = expire_on_commit
self._enable_transaction_accounting = _enable_transaction_accounting
self.twophase = twophase
self._query_cls = query_cls
if extension:
for ext in util.to_list(extension):
SessionExtension._adapt_listener(self, ext)
if binds is not None:
for mapperortable, bind in binds.iteritems():
if isinstance(mapperortable, (type, Mapper)):
self.bind_mapper(mapperortable, bind)
else:
self.bind_table(mapperortable, bind)
if not self.autocommit:
self.begin()
_sessions[self.hash_key] = self
dispatch = event.dispatcher(SessionEvents)
connection_callable = None
transaction = None
"""The current active or inactive :class:`.SessionTransaction`."""
def begin(self, subtransactions=False, nested=False):
"""Begin a transaction on this Session.
If this Session is already within a transaction, either a plain
transaction or nested transaction, an error is raised, unless
``subtransactions=True`` or ``nested=True`` is specified.
The ``subtransactions=True`` flag indicates that this :meth:`~.Session.begin`
can create a subtransaction if a transaction is already in progress.
For documentation on subtransactions, please see :ref:`session_subtransactions`.
The ``nested`` flag begins a SAVEPOINT transaction and is equivalent
to calling :meth:`~.Session.begin_nested`. For documentation on SAVEPOINT
transactions, please see :ref:`session_begin_nested`.
"""
if self.transaction is not None:
if subtransactions or nested:
self.transaction = self.transaction._begin(
nested=nested)
else:
raise sa_exc.InvalidRequestError(
"A transaction is already begun. Use subtransactions=True "
"to allow subtransactions.")
else:
self.transaction = SessionTransaction(
self, nested=nested)
return self.transaction # needed for __enter__/__exit__ hook
def begin_nested(self):
"""Begin a `nested` transaction on this Session.
The target database(s) must support SQL SAVEPOINTs or a
SQLAlchemy-supported vendor implementation of the idea.
For documentation on SAVEPOINT
transactions, please see :ref:`session_begin_nested`.
"""
return self.begin(nested=True)
def rollback(self):
"""Rollback the current transaction in progress.
If no transaction is in progress, this method is a pass-through.
This method rolls back the current transaction or nested transaction
regardless of subtransactions being in effect. All subtransactions up
to the first real transaction are closed. Subtransactions occur when
begin() is called multiple times.
"""
if self.transaction is None:
pass
else:
self.transaction.rollback()
def commit(self):
"""Flush pending changes and commit the current transaction.
If no transaction is in progress, this method raises an
InvalidRequestError.
By default, the :class:`.Session` also expires all database
loaded state on all ORM-managed attributes after transaction commit.
This so that subsequent operations load the most recent
data from the database. This behavior can be disabled using
the ``expire_on_commit=False`` option to :func:`.sessionmaker` or
the :class:`.Session` constructor.
If a subtransaction is in effect (which occurs when begin() is called
multiple times), the subtransaction will be closed, and the next call
to ``commit()`` will operate on the enclosing transaction.
For a session configured with autocommit=False, a new transaction will
be begun immediately after the commit, but note that the newly begun
transaction does *not* use any connection resources until the first
SQL is actually emitted.
"""
if self.transaction is None:
if not self.autocommit:
self.begin()
else:
raise sa_exc.InvalidRequestError("No transaction is begun.")
self.transaction.commit()
def prepare(self):
"""Prepare the current transaction in progress for two phase commit.
If no transaction is in progress, this method raises an
InvalidRequestError.
Only root transactions of two phase sessions can be prepared. If the
current transaction is not such, an InvalidRequestError is raised.
"""
if self.transaction is None:
if not self.autocommit:
self.begin()
else:
raise sa_exc.InvalidRequestError("No transaction is begun.")
self.transaction.prepare()
def connection(self, mapper=None, clause=None,
bind=None,
close_with_result=False,
**kw):
"""Return a :class:`.Connection` object corresponding to this
:class:`.Session` object's transactional state.
If this :class:`.Session` is configured with ``autocommit=False``,
either the :class:`.Connection` corresponding to the current transaction
is returned, or if no transaction is in progress, a new one is begun
and the :class:`.Connection` returned (note that no transactional state
is established with the DBAPI until the first SQL statement is emitted).
Alternatively, if this :class:`.Session` is configured with ``autocommit=True``,
an ad-hoc :class:`.Connection` is returned using :meth:`.Engine.contextual_connect`
on the underlying :class:`.Engine`.
Ambiguity in multi-bind or unbound :class:`.Session` objects can be resolved through
any of the optional keyword arguments. This ultimately makes usage of the
:meth:`.get_bind` method for resolution.
:param bind:
Optional :class:`.Engine` to be used as the bind. If
this engine is already involved in an ongoing transaction,
that connection will be used. This argument takes precedence
over ``mapper``, ``clause``.
:param mapper:
Optional :func:`.mapper` mapped class, used to identify
the appropriate bind. This argument takes precedence over
``clause``.
:param clause:
A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`,
:func:`~.sql.expression.text`,
etc.) which will be used to locate a bind, if a bind
cannot otherwise be identified.
:param close_with_result: Passed to :meth:`Engine.connect`, indicating
the :class:`.Connection` should be considered "single use", automatically
closing when the first result set is closed. This flag only has
an effect if this :class:`.Session` is configured with ``autocommit=True``
and does not already have a transaction in progress.
:param \**kw:
Additional keyword arguments are sent to :meth:`get_bind()`,
allowing additional arguments to be passed to custom
implementations of :meth:`get_bind`.
"""
if bind is None:
bind = self.get_bind(mapper, clause=clause, **kw)
return self._connection_for_bind(bind,
close_with_result=close_with_result)
def _connection_for_bind(self, engine, **kwargs):
if self.transaction is not None:
return self.transaction._connection_for_bind(engine)
else:
return engine.contextual_connect(**kwargs)
def execute(self, clause, params=None, mapper=None, bind=None, **kw):
"""Execute a SQL expression construct or string statement within
the current transaction.
Returns a :class:`.ResultProxy` representing
results of the statement execution, in the same manner as that of an
:class:`.Engine` or
:class:`.Connection`.
E.g.::
result = session.execute(
user_table.select().where(user_table.c.id == 5)
)
:meth:`~.Session.execute` accepts any executable clause construct, such
as :func:`~.sql.expression.select`,
:func:`~.sql.expression.insert`,
:func:`~.sql.expression.update`,
:func:`~.sql.expression.delete`, and
:func:`~.sql.expression.text`. Plain SQL strings can be passed
as well, which in the case of :meth:`.Session.execute` only
will be interpreted the same as if it were passed via a :func:`~.expression.text`
construct. That is, the following usage::
result = session.execute(
"SELECT * FROM user WHERE id=:param",
{"param":5}
)
is equivalent to::
from sqlalchemy import text
result = session.execute(
text("SELECT * FROM user WHERE id=:param"),
{"param":5}
)
The second positional argument to :meth:`.Session.execute` is an
optional parameter set. Similar to that of :meth:`.Connection.execute`, whether this
is passed as a single dictionary, or a list of dictionaries, determines
whether the DBAPI cursor's ``execute()`` or ``executemany()`` is used to execute the
statement. An INSERT construct may be invoked for a single row::
result = session.execute(users.insert(), {"id": 7, "name": "somename"})
or for multiple rows::
result = session.execute(users.insert(), [
{"id": 7, "name": "somename7"},
{"id": 8, "name": "somename8"},
{"id": 9, "name": "somename9"}
])
The statement is executed within the current transactional context of
this :class:`.Session`. The :class:`.Connection` which is used
to execute the statement can also be acquired directly by
calling the :meth:`.Session.connection` method. Both methods use
a rule-based resolution scheme in order to determine the
:class:`.Connection`, which in the average case is derived directly
from the "bind" of the :class:`.Session` itself, and in other cases
can be based on the :func:`.mapper`
and :class:`.Table` objects passed to the method; see the documentation
for :meth:`.Session.get_bind` for a full description of this scheme.
The :meth:`.Session.execute` method does *not* invoke autoflush.
The :class:`.ResultProxy` returned by the :meth:`.Session.execute`
method is returned with the "close_with_result" flag set to true;
the significance of this flag is that if this :class:`.Session` is
autocommitting and does not have a transaction-dedicated :class:`.Connection`
available, a temporary :class:`.Connection` is established for the
statement execution, which is closed (meaning, returned to the connection
pool) when the :class:`.ResultProxy` has consumed all available data.
This applies *only* when the :class:`.Session` is configured with
autocommit=True and no transaction has been started.
:param clause:
An executable statement (i.e. an :class:`.Executable` expression
such as :func:`.expression.select`) or string SQL statement
to be executed.
:param params:
Optional dictionary, or list of dictionaries, containing
bound parameter values. If a single dictionary, single-row
execution occurs; if a list of dictionaries, an
"executemany" will be invoked. The keys in each dictionary
must correspond to parameter names present in the statement.
:param mapper:
Optional :func:`.mapper` or mapped class, used to identify
the appropriate bind. This argument takes precedence over
``clause`` when locating a bind. See :meth:`.Session.get_bind`
for more details.
:param bind:
Optional :class:`.Engine` to be used as the bind. If
this engine is already involved in an ongoing transaction,
that connection will be used. This argument takes
precedence over ``mapper`` and ``clause`` when locating
a bind.
:param \**kw:
Additional keyword arguments are sent to :meth:`.Session.get_bind()`
to allow extensibility of "bind" schemes.
.. seealso::
:ref:`sqlexpression_toplevel` - Tutorial on using Core SQL
constructs.
:ref:`connections_toplevel` - Further information on direct
statement execution.
:meth:`.Connection.execute` - core level statement execution
method, which is :meth:`.Session.execute` ultimately uses
in order to execute the statement.
"""
clause = expression._literal_as_text(clause)
if bind is None:
bind = self.get_bind(mapper, clause=clause, **kw)
return self._connection_for_bind(bind, close_with_result=True).execute(
clause, params or {})
def scalar(self, clause, params=None, mapper=None, bind=None, **kw):
"""Like :meth:`~.Session.execute` but return a scalar result."""
return self.execute(clause, params=params, mapper=mapper, bind=bind, **kw).scalar()
def close(self):
"""Close this Session.
This clears all items and ends any transaction in progress.
If this session were created with ``autocommit=False``, a new
transaction is immediately begun. Note that this new transaction does
not use any connection resources until they are first needed.
"""
self.expunge_all()
if self.transaction is not None:
for transaction in self.transaction._iterate_parents():
transaction.close()
@classmethod
def close_all(cls):
"""Close *all* sessions in memory."""
for sess in _sessions.values():
sess.close()
def expunge_all(self):
"""Remove all object instances from this ``Session``.
This is equivalent to calling ``expunge(obj)`` on all objects in this
``Session``.
"""
for state in self.identity_map.all_states() + list(self._new):
state.detach()
self.identity_map = self._identity_cls()
self._new = {}
self._deleted = {}
# TODO: need much more test coverage for bind_mapper() and similar !
# TODO: + crystalize + document resolution order vis. bind_mapper/bind_table
def bind_mapper(self, mapper, bind):
"""Bind operations for a mapper to a Connectable.
mapper
A mapper instance or mapped class
bind
Any Connectable: a ``Engine`` or ``Connection``.
All subsequent operations involving this mapper will use the given
`bind`.
"""
if isinstance(mapper, type):
mapper = _class_mapper(mapper)
self.__binds[mapper.base_mapper] = bind
for t in mapper._all_tables:
self.__binds[t] = bind
def bind_table(self, table, bind):
"""Bind operations on a Table to a Connectable.
table
A ``Table`` instance
bind
Any Connectable: a ``Engine`` or ``Connection``.
All subsequent operations involving this ``Table`` will use the
given `bind`.
"""
self.__binds[table] = bind
def get_bind(self, mapper=None, clause=None):
"""Return a "bind" to which this :class:`.Session` is bound.
The "bind" is usually an instance of :class:`.Engine`,
except in the case where the :class:`.Session` has been
explicitly bound directly to a :class:`.Connection`.
For a multiply-bound or unbound :class:`.Session`, the
``mapper`` or ``clause`` arguments are used to determine the
appropriate bind to return.
Note that the "mapper" argument is usually present
when :meth:`.Session.get_bind` is called via an ORM
operation such as a :meth:`.Session.query`, each
individual INSERT/UPDATE/DELETE operation within a
:meth:`.Session.flush`, call, etc.
The order of resolution is:
1. if mapper given and session.binds is present,
locate a bind based on mapper.
2. if clause given and session.binds is present,
locate a bind based on :class:`.Table` objects
found in the given clause present in session.binds.
3. if session.bind is present, return that.
4. if clause given, attempt to return a bind
linked to the :class:`.MetaData` ultimately
associated with the clause.
5. if mapper given, attempt to return a bind
linked to the :class:`.MetaData` ultimately
associated with the :class:`.Table` or other
selectable to which the mapper is mapped.
6. No bind can be found, :class:`.UnboundExecutionError`
is raised.
:param mapper:
Optional :func:`.mapper` mapped class or instance of
:class:`.Mapper`. The bind can be derived from a :class:`.Mapper`
first by consulting the "binds" map associated with this
:class:`.Session`, and secondly by consulting the :class:`.MetaData`
associated with the :class:`.Table` to which the :class:`.Mapper`
is mapped for a bind.
:param clause:
A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`,
:func:`~.sql.expression.text`,
etc.). If the ``mapper`` argument is not present or could not produce
a bind, the given expression construct will be searched for a bound
element, typically a :class:`.Table` associated with bound
:class:`.MetaData`.
"""
if mapper is clause is None:
if self.bind:
return self.bind
else:
raise sa_exc.UnboundExecutionError(
"This session is not bound to a single Engine or "
"Connection, and no context was provided to locate "
"a binding.")
c_mapper = mapper is not None and _class_to_mapper(mapper) or None
# manually bound?
if self.__binds:
if c_mapper:
if c_mapper.base_mapper in self.__binds:
return self.__binds[c_mapper.base_mapper]
elif c_mapper.mapped_table in self.__binds:
return self.__binds[c_mapper.mapped_table]
if clause is not None:
for t in sql_util.find_tables(clause, include_crud=True):
if t in self.__binds:
return self.__binds[t]
if self.bind:
return self.bind
if isinstance(clause, sql.expression.ClauseElement) and clause.bind:
return clause.bind
if c_mapper and c_mapper.mapped_table.bind:
return c_mapper.mapped_table.bind
context = []
if mapper is not None:
context.append('mapper %s' % c_mapper)
if clause is not None:
context.append('SQL expression')
raise sa_exc.UnboundExecutionError(
"Could not locate a bind configured on %s or this Session" % (
', '.join(context)))
def query(self, *entities, **kwargs):
"""Return a new ``Query`` object corresponding to this ``Session``."""
return self._query_cls(entities, self, **kwargs)
@property
@util.contextmanager
def no_autoflush(self):
"""Return a context manager that disables autoflush.
e.g.::
with session.no_autoflush:
some_object = SomeClass()
session.add(some_object)
# won't autoflush
some_object.related_thing = session.query(SomeRelated).first()
Operations that proceed within the ``with:`` block
will not be subject to flushes occurring upon query
access. This is useful when initializing a series
of objects which involve existing database queries,
where the uncompleted object should not yet be flushed.
.. versionadded:: 0.7.6
"""
autoflush = self.autoflush
self.autoflush = False
yield self
self.autoflush = autoflush
def _autoflush(self):
if self.autoflush and not self._flushing:
self.flush()
def _finalize_loaded(self, states):
|
[
" for state, dict_ in states.items():"
] | 4,268
|
lcc
|
python
| null |
52b05f3e84a4fe67c9a1b15719fbecb75dda4932f22567e9
| 22
|
Your task is code completion.
# orm/session.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Provides the Session class and related utilities."""
import weakref
from itertools import chain
from sqlalchemy import util, sql, engine, log, exc as sa_exc
from sqlalchemy.sql import util as sql_util, expression
from sqlalchemy.orm import (
SessionExtension, attributes, exc, query, unitofwork, util as mapperutil, state
)
from sqlalchemy.orm.util import object_mapper as _object_mapper
from sqlalchemy.orm.util import class_mapper as _class_mapper
from sqlalchemy.orm.util import (
_class_to_mapper, _state_mapper,
)
from sqlalchemy.orm.mapper import Mapper, _none_set
from sqlalchemy.orm.unitofwork import UOWTransaction
from sqlalchemy.orm import identity
from sqlalchemy import event
from sqlalchemy.orm.events import SessionEvents
import sys
__all__ = ['Session', 'SessionTransaction', 'SessionExtension']
def sessionmaker(bind=None, class_=None, autoflush=True, autocommit=False,
expire_on_commit=True, **kwargs):
"""Generate a custom-configured :class:`.Session` class.
The returned object is a subclass of :class:`.Session`, which, when instantiated
with no arguments, uses the keyword arguments configured here as its
constructor arguments.
It is intended that the :func:`.sessionmaker()` function be called within the
global scope of an application, and the returned class be made available
to the rest of the application as the single class used to instantiate
sessions.
e.g.::
# global scope
Session = sessionmaker(autoflush=False)
# later, in a local scope, create and use a session:
sess = Session()
Any keyword arguments sent to the constructor itself will override the
"configured" keywords::
Session = sessionmaker()
# bind an individual session to a connection
sess = Session(bind=connection)
The class also includes a special classmethod ``configure()``, which
allows additional configurational options to take place after the custom
``Session`` class has been generated. This is useful particularly for
defining the specific ``Engine`` (or engines) to which new instances of
``Session`` should be bound::
Session = sessionmaker()
Session.configure(bind=create_engine('sqlite:///foo.db'))
sess = Session()
For options, see the constructor options for :class:`.Session`.
"""
kwargs['bind'] = bind
kwargs['autoflush'] = autoflush
kwargs['autocommit'] = autocommit
kwargs['expire_on_commit'] = expire_on_commit
if class_ is None:
class_ = Session
class Sess(object):
def __init__(self, **local_kwargs):
for k in kwargs:
local_kwargs.setdefault(k, kwargs[k])
super(Sess, self).__init__(**local_kwargs)
@classmethod
def configure(self, **new_kwargs):
"""(Re)configure the arguments for this sessionmaker.
e.g.::
Session = sessionmaker()
Session.configure(bind=create_engine('sqlite://'))
"""
kwargs.update(new_kwargs)
return type("SessionMaker", (Sess, class_), {})
class SessionTransaction(object):
"""A :class:`.Session`-level transaction.
:class:`.SessionTransaction` is a mostly behind-the-scenes object
not normally referenced directly by application code. It coordinates
among multiple :class:`.Connection` objects, maintaining a database
transaction for each one individually, committing or rolling them
back all at once. It also provides optional two-phase commit behavior
which can augment this coordination operation.
The :attr:`.Session.transaction` attribute of :class:`.Session` refers to the
current :class:`.SessionTransaction` object in use, if any.
A :class:`.SessionTransaction` is associated with a :class:`.Session`
in its default mode of ``autocommit=False`` immediately, associated
with no database connections. As the :class:`.Session` is called upon
to emit SQL on behalf of various :class:`.Engine` or :class:`.Connection`
objects, a corresponding :class:`.Connection` and associated :class:`.Transaction`
is added to a collection within the :class:`.SessionTransaction` object,
becoming one of the connection/transaction pairs maintained by the
:class:`.SessionTransaction`.
The lifespan of the :class:`.SessionTransaction` ends when the
:meth:`.Session.commit`, :meth:`.Session.rollback` or :meth:`.Session.close`
methods are called. At this point, the :class:`.SessionTransaction` removes
its association with its parent :class:`.Session`. A :class:`.Session`
that is in ``autocommit=False`` mode will create a new
:class:`.SessionTransaction` to replace it immediately, whereas a
:class:`.Session` that's in ``autocommit=True``
mode will remain without a :class:`.SessionTransaction` until the
:meth:`.Session.begin` method is called.
Another detail of :class:`.SessionTransaction` behavior is that it is
capable of "nesting". This means that the :meth:`.begin` method can
be called while an existing :class:`.SessionTransaction` is already present,
producing a new :class:`.SessionTransaction` that temporarily replaces
the parent :class:`.SessionTransaction`. When a :class:`.SessionTransaction`
is produced as nested, it assigns itself to the :attr:`.Session.transaction`
attribute. When it is ended via :meth:`.Session.commit` or :meth:`.Session.rollback`,
it restores its parent :class:`.SessionTransaction` back onto the
:attr:`.Session.transaction` attribute. The
behavior is effectively a stack, where :attr:`.Session.transaction` refers
to the current head of the stack.
The purpose of this stack is to allow nesting of :meth:`.rollback` or
:meth:`.commit` calls in context with various flavors of :meth:`.begin`.
This nesting behavior applies to when :meth:`.Session.begin_nested`
is used to emit a SAVEPOINT transaction, and is also used to produce
a so-called "subtransaction" which allows a block of code to use a
begin/rollback/commit sequence regardless of whether or not its enclosing
code block has begun a transaction. The :meth:`.flush` method, whether called
explicitly or via autoflush, is the primary consumer of the "subtransaction"
feature, in that it wishes to guarantee that it works within in a transaction block
regardless of whether or not the :class:`.Session` is in transactional mode
when the method is called.
See also:
:meth:`.Session.rollback`
:meth:`.Session.commit`
:meth:`.Session.begin`
:meth:`.Session.begin_nested`
:attr:`.Session.is_active`
:meth:`.SessionEvents.after_commit`
:meth:`.SessionEvents.after_rollback`
:meth:`.SessionEvents.after_soft_rollback`
"""
_rollback_exception = None
def __init__(self, session, parent=None, nested=False):
self.session = session
self._connections = {}
self._parent = parent
self.nested = nested
self._active = True
self._prepared = False
if not parent and nested:
raise sa_exc.InvalidRequestError(
"Can't start a SAVEPOINT transaction when no existing "
"transaction is in progress")
if self.session._enable_transaction_accounting:
self._take_snapshot()
@property
def is_active(self):
return self.session is not None and self._active
def _assert_is_active(self):
self._assert_is_open()
if not self._active:
if self._rollback_exception:
raise sa_exc.InvalidRequestError(
"This Session's transaction has been rolled back "
"due to a previous exception during flush."
" To begin a new transaction with this Session, "
"first issue Session.rollback()."
" Original exception was: %s"
% self._rollback_exception
)
else:
raise sa_exc.InvalidRequestError(
"This Session's transaction has been rolled back "
"by a nested rollback() call. To begin a new "
"transaction, issue Session.rollback() first."
)
def _assert_is_open(self, error_msg="The transaction is closed"):
if self.session is None:
raise sa_exc.ResourceClosedError(error_msg)
@property
def _is_transaction_boundary(self):
return self.nested or not self._parent
def connection(self, bindkey, **kwargs):
self._assert_is_active()
engine = self.session.get_bind(bindkey, **kwargs)
return self._connection_for_bind(engine)
def _begin(self, nested=False):
self._assert_is_active()
return SessionTransaction(
self.session, self, nested=nested)
def _iterate_parents(self, upto=None):
if self._parent is upto:
return (self,)
else:
if self._parent is None:
raise sa_exc.InvalidRequestError(
"Transaction %s is not on the active transaction list" % (
upto))
return (self,) + self._parent._iterate_parents(upto)
def _take_snapshot(self):
if not self._is_transaction_boundary:
self._new = self._parent._new
self._deleted = self._parent._deleted
self._key_switches = self._parent._key_switches
return
if not self.session._flushing:
self.session.flush()
self._new = weakref.WeakKeyDictionary()
self._deleted = weakref.WeakKeyDictionary()
self._key_switches = weakref.WeakKeyDictionary()
def _restore_snapshot(self):
assert self._is_transaction_boundary
for s in set(self._new).union(self.session._new):
self.session._expunge_state(s)
if s.key:
del s.key
for s, (oldkey, newkey) in self._key_switches.items():
self.session.identity_map.discard(s)
s.key = oldkey
self.session.identity_map.replace(s)
for s in set(self._deleted).union(self.session._deleted):
if s.deleted:
#assert s in self._deleted
del s.deleted
self.session._update_impl(s, discard_existing=True)
assert not self.session._deleted
for s in self.session.identity_map.all_states():
s.expire(s.dict, self.session.identity_map._modified)
def _remove_snapshot(self):
assert self._is_transaction_boundary
if not self.nested and self.session.expire_on_commit:
for s in self.session.identity_map.all_states():
s.expire(s.dict, self.session.identity_map._modified)
def _connection_for_bind(self, bind):
self._assert_is_active()
if bind in self._connections:
return self._connections[bind][0]
if self._parent:
conn = self._parent._connection_for_bind(bind)
if not self.nested:
return conn
else:
if isinstance(bind, engine.Connection):
conn = bind
if conn.engine in self._connections:
raise sa_exc.InvalidRequestError(
"Session already has a Connection associated for the "
"given Connection's Engine")
else:
conn = bind.contextual_connect()
if self.session.twophase and self._parent is None:
transaction = conn.begin_twophase()
elif self.nested:
transaction = conn.begin_nested()
else:
transaction = conn.begin()
self._connections[conn] = self._connections[conn.engine] = \
(conn, transaction, conn is not bind)
self.session.dispatch.after_begin(self.session, self, conn)
return conn
def prepare(self):
if self._parent is not None or not self.session.twophase:
raise sa_exc.InvalidRequestError(
"Only root two phase transactions of can be prepared")
self._prepare_impl()
def _prepare_impl(self):
self._assert_is_active()
if self._parent is None or self.nested:
self.session.dispatch.before_commit(self.session)
stx = self.session.transaction
if stx is not self:
for subtransaction in stx._iterate_parents(upto=self):
subtransaction.commit()
if not self.session._flushing:
for _flush_guard in xrange(100):
if self.session._is_clean():
break
self.session.flush()
else:
raise exc.FlushError(
"Over 100 subsequent flushes have occurred within "
"session.commit() - is an after_flush() hook "
"creating new objects?")
if self._parent is None and self.session.twophase:
try:
for t in set(self._connections.values()):
t[1].prepare()
except:
self.rollback()
raise
self._deactivate()
self._prepared = True
def commit(self):
self._assert_is_open()
if not self._prepared:
self._prepare_impl()
if self._parent is None or self.nested:
for t in set(self._connections.values()):
t[1].commit()
self.session.dispatch.after_commit(self.session)
if self.session._enable_transaction_accounting:
self._remove_snapshot()
self.close()
return self._parent
def rollback(self, _capture_exception=False):
self._assert_is_open()
stx = self.session.transaction
if stx is not self:
for subtransaction in stx._iterate_parents(upto=self):
subtransaction.close()
if self.is_active or self._prepared:
for transaction in self._iterate_parents():
if transaction._parent is None or transaction.nested:
transaction._rollback_impl()
transaction._deactivate()
break
else:
transaction._deactivate()
sess = self.session
if self.session._enable_transaction_accounting and \
not sess._is_clean():
# if items were added, deleted, or mutated
# here, we need to re-restore the snapshot
util.warn(
"Session's state has been changed on "
"a non-active transaction - this state "
"will be discarded.")
self._restore_snapshot()
self.close()
if self._parent and _capture_exception:
self._parent._rollback_exception = sys.exc_info()[1]
sess.dispatch.after_soft_rollback(sess, self)
return self._parent
def _rollback_impl(self):
for t in set(self._connections.values()):
t[1].rollback()
if self.session._enable_transaction_accounting:
self._restore_snapshot()
self.session.dispatch.after_rollback(self.session)
def _deactivate(self):
self._active = False
def close(self):
self.session.transaction = self._parent
if self._parent is None:
for connection, transaction, autoclose in \
set(self._connections.values()):
if autoclose:
connection.close()
else:
transaction.close()
if not self.session.autocommit:
self.session.begin()
self._deactivate()
self.session = None
self._connections = None
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self._assert_is_open("Cannot end transaction context. The transaction "
"was closed from within the context")
if self.session.transaction is None:
return
if type is None:
try:
self.commit()
except:
self.rollback()
raise
else:
self.rollback()
class Session(object):
"""Manages persistence operations for ORM-mapped objects.
The Session's usage paradigm is described at :ref:`session_toplevel`.
"""
public_methods = (
'__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested',
'close', 'commit', 'connection', 'delete', 'execute', 'expire',
'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind',
'is_modified',
'merge', 'query', 'refresh', 'rollback',
'scalar')
def __init__(self, bind=None, autoflush=True, expire_on_commit=True,
_enable_transaction_accounting=True,
autocommit=False, twophase=False,
weak_identity_map=True, binds=None, extension=None,
query_cls=query.Query):
"""Construct a new Session.
See also the :func:`.sessionmaker` function which is used to
generate a :class:`.Session`-producing callable with a given
set of arguments.
:param autocommit: Defaults to ``False``. When ``True``, the ``Session``
does not keep a persistent transaction running, and will acquire
connections from the engine on an as-needed basis, returning them
immediately after their use. Flushes will begin and commit (or possibly
rollback) their own transaction if no transaction is present. When using
this mode, the `session.begin()` method may be used to begin a
transaction explicitly.
Leaving it on its default value of ``False`` means that the ``Session``
will acquire a connection and begin a transaction the first time it is
used, which it will maintain persistently until ``rollback()``,
``commit()``, or ``close()`` is called. When the transaction is released
by any of these methods, the ``Session`` is ready for the next usage,
which will again acquire and maintain a new connection/transaction.
:param autoflush: When ``True``, all query operations will issue a
``flush()`` call to this ``Session`` before proceeding. This is a
convenience feature so that ``flush()`` need not be called repeatedly
in order for database queries to retrieve results. It's typical that
``autoflush`` is used in conjunction with ``autocommit=False``. In this
scenario, explicit calls to ``flush()`` are rarely needed; you usually
only need to call ``commit()`` (which flushes) to finalize changes.
:param bind: An optional ``Engine`` or ``Connection`` to which this
``Session`` should be bound. When specified, all SQL operations
performed by this session will execute via this connectable.
:param binds: An optional dictionary which contains more granular "bind"
information than the ``bind`` parameter provides. This dictionary can
map individual ``Table`` instances as well as ``Mapper`` instances to
individual ``Engine`` or ``Connection`` objects. Operations which
proceed relative to a particular ``Mapper`` will consult this
dictionary for the direct ``Mapper`` instance as well as the mapper's
``mapped_table`` attribute in order to locate an connectable to use.
The full resolution is described in the ``get_bind()`` method of
``Session``. Usage looks like::
Session = sessionmaker(binds={
SomeMappedClass: create_engine('postgresql://engine1'),
somemapper: create_engine('postgresql://engine2'),
some_table: create_engine('postgresql://engine3'),
})
Also see the :meth:`.Session.bind_mapper` and :meth:`.Session.bind_table` methods.
:param \class_: Specify an alternate class other than
``sqlalchemy.orm.session.Session`` which should be used by the returned
class. This is the only argument that is local to the
``sessionmaker()`` function, and is not sent directly to the
constructor for ``Session``.
:param _enable_transaction_accounting: Defaults to ``True``. A
legacy-only flag which when ``False`` disables *all* 0.5-style object
accounting on transaction boundaries, including auto-expiry of
instances on rollback and commit, maintenance of the "new" and
"deleted" lists upon rollback, and autoflush of pending changes upon
begin(), all of which are interdependent.
:param expire_on_commit: Defaults to ``True``. When ``True``, all
instances will be fully expired after each ``commit()``, so that all
attribute/object access subsequent to a completed transaction will load
from the most recent database state.
:param extension: An optional
:class:`~.SessionExtension` instance, or a list
of such instances, which will receive pre- and post- commit and flush
events, as well as a post-rollback event. **Deprecated.**
Please see :class:`.SessionEvents`.
:param query_cls: Class which should be used to create new Query objects,
as returned by the ``query()`` method. Defaults to
:class:`~sqlalchemy.orm.query.Query`.
:param twophase: When ``True``, all transactions will be started as
a "two phase" transaction, i.e. using the "two phase" semantics
of the database in use along with an XID. During a ``commit()``,
after ``flush()`` has been issued for all attached databases, the
``prepare()`` method on each database's ``TwoPhaseTransaction`` will
be called. This allows each database to roll back the entire
transaction, before each transaction is committed.
:param weak_identity_map: Defaults to ``True`` - when set to
``False``, objects placed in the :class:`.Session` will be
strongly referenced until explicitly removed or the
:class:`.Session` is closed. **Deprecated** - this option
is obsolete.
"""
if weak_identity_map:
self._identity_cls = identity.WeakInstanceDict
else:
util.warn_deprecated("weak_identity_map=False is deprecated. "
"This feature is not needed.")
self._identity_cls = identity.StrongInstanceDict
self.identity_map = self._identity_cls()
self._new = {} # InstanceState->object, strong refs object
self._deleted = {} # same
self.bind = bind
self.__binds = {}
self._flushing = False
self.transaction = None
self.hash_key = _new_sessionid()
self.autoflush = autoflush
self.autocommit = autocommit
self.expire_on_commit = expire_on_commit
self._enable_transaction_accounting = _enable_transaction_accounting
self.twophase = twophase
self._query_cls = query_cls
if extension:
for ext in util.to_list(extension):
SessionExtension._adapt_listener(self, ext)
if binds is not None:
for mapperortable, bind in binds.iteritems():
if isinstance(mapperortable, (type, Mapper)):
self.bind_mapper(mapperortable, bind)
else:
self.bind_table(mapperortable, bind)
if not self.autocommit:
self.begin()
_sessions[self.hash_key] = self
dispatch = event.dispatcher(SessionEvents)
connection_callable = None
transaction = None
"""The current active or inactive :class:`.SessionTransaction`."""
def begin(self, subtransactions=False, nested=False):
"""Begin a transaction on this Session.
If this Session is already within a transaction, either a plain
transaction or nested transaction, an error is raised, unless
``subtransactions=True`` or ``nested=True`` is specified.
The ``subtransactions=True`` flag indicates that this :meth:`~.Session.begin`
can create a subtransaction if a transaction is already in progress.
For documentation on subtransactions, please see :ref:`session_subtransactions`.
The ``nested`` flag begins a SAVEPOINT transaction and is equivalent
to calling :meth:`~.Session.begin_nested`. For documentation on SAVEPOINT
transactions, please see :ref:`session_begin_nested`.
"""
if self.transaction is not None:
if subtransactions or nested:
self.transaction = self.transaction._begin(
nested=nested)
else:
raise sa_exc.InvalidRequestError(
"A transaction is already begun. Use subtransactions=True "
"to allow subtransactions.")
else:
self.transaction = SessionTransaction(
self, nested=nested)
return self.transaction # needed for __enter__/__exit__ hook
def begin_nested(self):
"""Begin a `nested` transaction on this Session.
The target database(s) must support SQL SAVEPOINTs or a
SQLAlchemy-supported vendor implementation of the idea.
For documentation on SAVEPOINT
transactions, please see :ref:`session_begin_nested`.
"""
return self.begin(nested=True)
def rollback(self):
"""Rollback the current transaction in progress.
If no transaction is in progress, this method is a pass-through.
This method rolls back the current transaction or nested transaction
regardless of subtransactions being in effect. All subtransactions up
to the first real transaction are closed. Subtransactions occur when
begin() is called multiple times.
"""
if self.transaction is None:
pass
else:
self.transaction.rollback()
def commit(self):
"""Flush pending changes and commit the current transaction.
If no transaction is in progress, this method raises an
InvalidRequestError.
By default, the :class:`.Session` also expires all database
loaded state on all ORM-managed attributes after transaction commit.
This so that subsequent operations load the most recent
data from the database. This behavior can be disabled using
the ``expire_on_commit=False`` option to :func:`.sessionmaker` or
the :class:`.Session` constructor.
If a subtransaction is in effect (which occurs when begin() is called
multiple times), the subtransaction will be closed, and the next call
to ``commit()`` will operate on the enclosing transaction.
For a session configured with autocommit=False, a new transaction will
be begun immediately after the commit, but note that the newly begun
transaction does *not* use any connection resources until the first
SQL is actually emitted.
"""
if self.transaction is None:
if not self.autocommit:
self.begin()
else:
raise sa_exc.InvalidRequestError("No transaction is begun.")
self.transaction.commit()
def prepare(self):
"""Prepare the current transaction in progress for two phase commit.
If no transaction is in progress, this method raises an
InvalidRequestError.
Only root transactions of two phase sessions can be prepared. If the
current transaction is not such, an InvalidRequestError is raised.
"""
if self.transaction is None:
if not self.autocommit:
self.begin()
else:
raise sa_exc.InvalidRequestError("No transaction is begun.")
self.transaction.prepare()
def connection(self, mapper=None, clause=None,
bind=None,
close_with_result=False,
**kw):
"""Return a :class:`.Connection` object corresponding to this
:class:`.Session` object's transactional state.
If this :class:`.Session` is configured with ``autocommit=False``,
either the :class:`.Connection` corresponding to the current transaction
is returned, or if no transaction is in progress, a new one is begun
and the :class:`.Connection` returned (note that no transactional state
is established with the DBAPI until the first SQL statement is emitted).
Alternatively, if this :class:`.Session` is configured with ``autocommit=True``,
an ad-hoc :class:`.Connection` is returned using :meth:`.Engine.contextual_connect`
on the underlying :class:`.Engine`.
Ambiguity in multi-bind or unbound :class:`.Session` objects can be resolved through
any of the optional keyword arguments. This ultimately makes usage of the
:meth:`.get_bind` method for resolution.
:param bind:
Optional :class:`.Engine` to be used as the bind. If
this engine is already involved in an ongoing transaction,
that connection will be used. This argument takes precedence
over ``mapper``, ``clause``.
:param mapper:
Optional :func:`.mapper` mapped class, used to identify
the appropriate bind. This argument takes precedence over
``clause``.
:param clause:
A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`,
:func:`~.sql.expression.text`,
etc.) which will be used to locate a bind, if a bind
cannot otherwise be identified.
:param close_with_result: Passed to :meth:`Engine.connect`, indicating
the :class:`.Connection` should be considered "single use", automatically
closing when the first result set is closed. This flag only has
an effect if this :class:`.Session` is configured with ``autocommit=True``
and does not already have a transaction in progress.
:param \**kw:
Additional keyword arguments are sent to :meth:`get_bind()`,
allowing additional arguments to be passed to custom
implementations of :meth:`get_bind`.
"""
if bind is None:
bind = self.get_bind(mapper, clause=clause, **kw)
return self._connection_for_bind(bind,
close_with_result=close_with_result)
def _connection_for_bind(self, engine, **kwargs):
if self.transaction is not None:
return self.transaction._connection_for_bind(engine)
else:
return engine.contextual_connect(**kwargs)
def execute(self, clause, params=None, mapper=None, bind=None, **kw):
"""Execute a SQL expression construct or string statement within
the current transaction.
Returns a :class:`.ResultProxy` representing
results of the statement execution, in the same manner as that of an
:class:`.Engine` or
:class:`.Connection`.
E.g.::
result = session.execute(
user_table.select().where(user_table.c.id == 5)
)
:meth:`~.Session.execute` accepts any executable clause construct, such
as :func:`~.sql.expression.select`,
:func:`~.sql.expression.insert`,
:func:`~.sql.expression.update`,
:func:`~.sql.expression.delete`, and
:func:`~.sql.expression.text`. Plain SQL strings can be passed
as well, which in the case of :meth:`.Session.execute` only
will be interpreted the same as if it were passed via a :func:`~.expression.text`
construct. That is, the following usage::
result = session.execute(
"SELECT * FROM user WHERE id=:param",
{"param":5}
)
is equivalent to::
from sqlalchemy import text
result = session.execute(
text("SELECT * FROM user WHERE id=:param"),
{"param":5}
)
The second positional argument to :meth:`.Session.execute` is an
optional parameter set. Similar to that of :meth:`.Connection.execute`, whether this
is passed as a single dictionary, or a list of dictionaries, determines
whether the DBAPI cursor's ``execute()`` or ``executemany()`` is used to execute the
statement. An INSERT construct may be invoked for a single row::
result = session.execute(users.insert(), {"id": 7, "name": "somename"})
or for multiple rows::
result = session.execute(users.insert(), [
{"id": 7, "name": "somename7"},
{"id": 8, "name": "somename8"},
{"id": 9, "name": "somename9"}
])
The statement is executed within the current transactional context of
this :class:`.Session`. The :class:`.Connection` which is used
to execute the statement can also be acquired directly by
calling the :meth:`.Session.connection` method. Both methods use
a rule-based resolution scheme in order to determine the
:class:`.Connection`, which in the average case is derived directly
from the "bind" of the :class:`.Session` itself, and in other cases
can be based on the :func:`.mapper`
and :class:`.Table` objects passed to the method; see the documentation
for :meth:`.Session.get_bind` for a full description of this scheme.
The :meth:`.Session.execute` method does *not* invoke autoflush.
The :class:`.ResultProxy` returned by the :meth:`.Session.execute`
method is returned with the "close_with_result" flag set to true;
the significance of this flag is that if this :class:`.Session` is
autocommitting and does not have a transaction-dedicated :class:`.Connection`
available, a temporary :class:`.Connection` is established for the
statement execution, which is closed (meaning, returned to the connection
pool) when the :class:`.ResultProxy` has consumed all available data.
This applies *only* when the :class:`.Session` is configured with
autocommit=True and no transaction has been started.
:param clause:
An executable statement (i.e. an :class:`.Executable` expression
such as :func:`.expression.select`) or string SQL statement
to be executed.
:param params:
Optional dictionary, or list of dictionaries, containing
bound parameter values. If a single dictionary, single-row
execution occurs; if a list of dictionaries, an
"executemany" will be invoked. The keys in each dictionary
must correspond to parameter names present in the statement.
:param mapper:
Optional :func:`.mapper` or mapped class, used to identify
the appropriate bind. This argument takes precedence over
``clause`` when locating a bind. See :meth:`.Session.get_bind`
for more details.
:param bind:
Optional :class:`.Engine` to be used as the bind. If
this engine is already involved in an ongoing transaction,
that connection will be used. This argument takes
precedence over ``mapper`` and ``clause`` when locating
a bind.
:param \**kw:
Additional keyword arguments are sent to :meth:`.Session.get_bind()`
to allow extensibility of "bind" schemes.
.. seealso::
:ref:`sqlexpression_toplevel` - Tutorial on using Core SQL
constructs.
:ref:`connections_toplevel` - Further information on direct
statement execution.
:meth:`.Connection.execute` - core level statement execution
method, which is :meth:`.Session.execute` ultimately uses
in order to execute the statement.
"""
clause = expression._literal_as_text(clause)
if bind is None:
bind = self.get_bind(mapper, clause=clause, **kw)
return self._connection_for_bind(bind, close_with_result=True).execute(
clause, params or {})
def scalar(self, clause, params=None, mapper=None, bind=None, **kw):
"""Like :meth:`~.Session.execute` but return a scalar result."""
return self.execute(clause, params=params, mapper=mapper, bind=bind, **kw).scalar()
def close(self):
"""Close this Session.
This clears all items and ends any transaction in progress.
If this session were created with ``autocommit=False``, a new
transaction is immediately begun. Note that this new transaction does
not use any connection resources until they are first needed.
"""
self.expunge_all()
if self.transaction is not None:
for transaction in self.transaction._iterate_parents():
transaction.close()
@classmethod
def close_all(cls):
"""Close *all* sessions in memory."""
for sess in _sessions.values():
sess.close()
def expunge_all(self):
"""Remove all object instances from this ``Session``.
This is equivalent to calling ``expunge(obj)`` on all objects in this
``Session``.
"""
for state in self.identity_map.all_states() + list(self._new):
state.detach()
self.identity_map = self._identity_cls()
self._new = {}
self._deleted = {}
# TODO: need much more test coverage for bind_mapper() and similar !
# TODO: + crystalize + document resolution order vis. bind_mapper/bind_table
def bind_mapper(self, mapper, bind):
"""Bind operations for a mapper to a Connectable.
mapper
A mapper instance or mapped class
bind
Any Connectable: a ``Engine`` or ``Connection``.
All subsequent operations involving this mapper will use the given
`bind`.
"""
if isinstance(mapper, type):
mapper = _class_mapper(mapper)
self.__binds[mapper.base_mapper] = bind
for t in mapper._all_tables:
self.__binds[t] = bind
def bind_table(self, table, bind):
"""Bind operations on a Table to a Connectable.
table
A ``Table`` instance
bind
Any Connectable: a ``Engine`` or ``Connection``.
All subsequent operations involving this ``Table`` will use the
given `bind`.
"""
self.__binds[table] = bind
def get_bind(self, mapper=None, clause=None):
"""Return a "bind" to which this :class:`.Session` is bound.
The "bind" is usually an instance of :class:`.Engine`,
except in the case where the :class:`.Session` has been
explicitly bound directly to a :class:`.Connection`.
For a multiply-bound or unbound :class:`.Session`, the
``mapper`` or ``clause`` arguments are used to determine the
appropriate bind to return.
Note that the "mapper" argument is usually present
when :meth:`.Session.get_bind` is called via an ORM
operation such as a :meth:`.Session.query`, each
individual INSERT/UPDATE/DELETE operation within a
:meth:`.Session.flush`, call, etc.
The order of resolution is:
1. if mapper given and session.binds is present,
locate a bind based on mapper.
2. if clause given and session.binds is present,
locate a bind based on :class:`.Table` objects
found in the given clause present in session.binds.
3. if session.bind is present, return that.
4. if clause given, attempt to return a bind
linked to the :class:`.MetaData` ultimately
associated with the clause.
5. if mapper given, attempt to return a bind
linked to the :class:`.MetaData` ultimately
associated with the :class:`.Table` or other
selectable to which the mapper is mapped.
6. No bind can be found, :class:`.UnboundExecutionError`
is raised.
:param mapper:
Optional :func:`.mapper` mapped class or instance of
:class:`.Mapper`. The bind can be derived from a :class:`.Mapper`
first by consulting the "binds" map associated with this
:class:`.Session`, and secondly by consulting the :class:`.MetaData`
associated with the :class:`.Table` to which the :class:`.Mapper`
is mapped for a bind.
:param clause:
A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`,
:func:`~.sql.expression.text`,
etc.). If the ``mapper`` argument is not present or could not produce
a bind, the given expression construct will be searched for a bound
element, typically a :class:`.Table` associated with bound
:class:`.MetaData`.
"""
if mapper is clause is None:
if self.bind:
return self.bind
else:
raise sa_exc.UnboundExecutionError(
"This session is not bound to a single Engine or "
"Connection, and no context was provided to locate "
"a binding.")
c_mapper = mapper is not None and _class_to_mapper(mapper) or None
# manually bound?
if self.__binds:
if c_mapper:
if c_mapper.base_mapper in self.__binds:
return self.__binds[c_mapper.base_mapper]
elif c_mapper.mapped_table in self.__binds:
return self.__binds[c_mapper.mapped_table]
if clause is not None:
for t in sql_util.find_tables(clause, include_crud=True):
if t in self.__binds:
return self.__binds[t]
if self.bind:
return self.bind
if isinstance(clause, sql.expression.ClauseElement) and clause.bind:
return clause.bind
if c_mapper and c_mapper.mapped_table.bind:
return c_mapper.mapped_table.bind
context = []
if mapper is not None:
context.append('mapper %s' % c_mapper)
if clause is not None:
context.append('SQL expression')
raise sa_exc.UnboundExecutionError(
"Could not locate a bind configured on %s or this Session" % (
', '.join(context)))
def query(self, *entities, **kwargs):
"""Return a new ``Query`` object corresponding to this ``Session``."""
return self._query_cls(entities, self, **kwargs)
@property
@util.contextmanager
def no_autoflush(self):
"""Return a context manager that disables autoflush.
e.g.::
with session.no_autoflush:
some_object = SomeClass()
session.add(some_object)
# won't autoflush
some_object.related_thing = session.query(SomeRelated).first()
Operations that proceed within the ``with:`` block
will not be subject to flushes occurring upon query
access. This is useful when initializing a series
of objects which involve existing database queries,
where the uncompleted object should not yet be flushed.
.. versionadded:: 0.7.6
"""
autoflush = self.autoflush
self.autoflush = False
yield self
self.autoflush = autoflush
def _autoflush(self):
if self.autoflush and not self._flushing:
self.flush()
def _finalize_loaded(self, states):
|
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
|
Context:
[Previous code... ~10,000 lines omitted for brevity]
def get_bind(self, mapper=None, clause=None):
"""Return a "bind" to which this :class:`.Session` is bound.
...
:param mapper:
Optional :func:`.mapper` mapped class or instance of
:class:`.Mapper`. The bind can be derived from a :class:`.Mapper`
first by consulting the "binds" map associated with this
:class:`.Session`, and secondly by consulting the :class:`.MetaData`
associated with the :class:`.Table` to which the :class:`.Mapper`
is mapped for a bind.
:param clause:
A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`,
:func:`~.sql.expression.text`,
etc.). If the ``mapper`` argument is not present or could not produce
a bind, the given expression construct will be searched for a bound
element, typically a :class:`.Table` associated with bound
:class:`.MetaData`.
"""
if mapper is clause is None:
if self.bind:
return self.bind
else:
raise sa_exc.UnboundExecutionError(
"This session is not bound to a single Engine or "
"Connection, and no context was provided to locate "
"a binding.")
c_mapper = mapper is not None and _class_to_mapper(mapper) or None
# manually bound?
if self.__binds:
if c_mapper:
if c_mapper.base_mapper in self.__binds:
return self.__binds[c_mapper.base_mapper]
elif c_mapper.mapped_table in self.__binds:
return self.__binds[c_mapper.mapped_table]
if clause is not None:
for t in sql_util.find_tables(clause, include_crud=True):
if t in self.__binds:
return self.__binds[t]
if self.bind:
return self.bind
if isinstance(clause, sql.expression.ClauseElement) and clause.bind:
return clause.bind
if c_mapper and c_mapper.mapped_table.bind:
return c_mapper.mapped_table.bind
context = []
if mapper is not None:
context.append('mapper %s' % c_mapper)
if clause is not None:
context.append('SQL expression')
raise sa_exc.UnboundExecutionError(
"Could not locate a bind configured on %s or this Session" % (
', '.join(context)))
Cheatsheet (for next line):
- We are in the get_bind() method of the Session class.
- The method is trying to return a bind to which the Session is bound.
- The bind can be derived from a Mapper, a ClauseElement, or the Session's bind.
- The method has already checked if the Session is bound to a single Engine or Connection.
- The method has also checked if the mapper or clause is None.
- The method has checked if the Session has a binds map and if the mapper or clause is in it.
- The method has checked if the Session is bound to a single Engine or Connection.
- The method has checked if the ClauseElement has a bind.
- The method has checked if the mapper's mapped table has a bind.
- The method has checked if the context is empty.
- The method raises an UnboundExecutionError if it cannot find a bind.
Next line will likely be: raise sa_exc.UnboundExecutionError("Could not locate a bind configured on %s or this Session" % (', '.join(context)));
|
|
Please complete the code given below.
/******************************************************************************
* Copyright (c) 2009 - 2015 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
/**
*
*/
package com.ibm.wala.memsat.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.ibm.wala.cast.java.ipa.callgraph.AstJavaSSAPropagationCallGraphBuilder.EnclosingObjectReferenceKey;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.ShrikeBTMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.ArrayContentsKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey;
import com.ibm.wala.ipa.callgraph.propagation.rta.CallSite;
import com.ibm.wala.ipa.modref.ArrayLengthKey;
import com.ibm.wala.memsat.frontEnd.InlinedInstruction;
import com.ibm.wala.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.graph.Graph;
import kodkod.ast.Node;
/**
* A set of utility functions for string manipulation and pretty printing of Kodkod nodes,
* IRs, etc.
*
* @author Emina Torlak
*/
public final class Strings {
/**
* Returns a pretty-printed string representation of the
* given nodes, with each line offset with at least the given
* number of whitespaces. The display parameter determines how
* the mapped nodes are displayed; that is, a descendant d of the
* given node is displayed as display.get(d.toString()) if
* display.containsKey(d.toString()) is true.
* @requires 0 <= offset < line
* @return a pretty-printed string representation of the
* given nodes
*/
public static String prettyPrint(Collection<Node> nodes, int offset, int line, Map<String,String> display) {
return PrettyPrinter.print(nodes, offset, 80, display);
}
/**
* Returns a pretty-printed string representation of the
* given node, with each line offset with at least the given
* number of whitespaces. The display parameter determines how
* the mapped nodes are displayed; that is, a descendant d of the
* given node is displayed as display.get(d.toString()) if
* display.containsKey(d.toString()) is true.
* @requires 0 <= offset < line
* @return a pretty-printed string representation of the
* given node
*/
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
return prettyPrint(node, offset, 80, display);
}
/**
* Returns a pretty-printed string representation of the
* given node, with each line offset with at least the given
* number of whitespaces. The line parameter determines the
* length of each pretty-printed line, including the offset.
* The display parameter determines how
* the mapped nodes are displayed; that is, a descendant d of the
* given node is displayed as display.get(d.toString()) if
* display.containsKey(d.toString()) is true.
* @requires 0 <= offset < line
* @return a pretty-printed string representation of the
* given node
*/
public static String prettyPrint(Node node, int offset, int line, final Map<String, String> display) {
return prettyPrint(Collections.singleton(node), offset, line, display);
}
/**
* Returns a pretty-printed string representation of the
* given node, with each line offset with at least the given
* number of whitespaces. The line parameter determines the
* length of each pretty-printed line, including the offset.
* @requires 0 <= offset < line
* @return a pretty-printed string representation of the
* given node
*/
@SuppressWarnings("unchecked")
public static String prettyPrint(Node node, int offset, int line) {
assert offset >= 0 && offset < line && line > 0;
return prettyPrint(node, offset, line, Collections.EMPTY_MAP);
}
/**
* Returns a pretty-printed string representation of the
* given node, with each line offset with at least the given
* number of whitespaces.
* @requires 0 <= offset < 80
* @return a pretty-printed string representation of the
* given node
*/
public static String prettyPrint(Node node, int offset) {
return prettyPrint(node,offset,80);
}
/**
* Returns a string that consists of the given number of repetitions
* of the specified string.
* @return str^reps
*/
public static String repeat(String str, int reps) {
final StringBuffer result = new StringBuffer();
for(int i = 0; i < reps; i++) {
result.append(str);
}
return result.toString();
}
/**
* Returns the given string, with all new lines replaced with new lines indented
* by the given number of spaces.
* @return given string, with all new lines replaced with new lines indented
* by the given number of spaces.
*/
public static String indent(String str, int offset) {
assert offset >= 0;
final String indent = repeat(" ", offset);
return indent + str.replaceAll("\\n", "\n"+indent);
}
/**
* Returns a pretty-print String representation
* of the given graph.
* @return pretty-print String representation
* of the given graph
*/
public static String prettyPrint(Graph<?> graph) {
return prettyPrint(graph,0);
}
/**
* Returns a pretty-print String representation
* of the given graph, with each new line starting
* indented at least the given number of spaces.
* @return pretty-print String representation
* of the given graph
*/
public static <T> String prettyPrint(Graph<T> graph, int offset) {
assert offset>=0;
final StringBuffer result = new StringBuffer();
final String indent = repeat(" ", offset);
for(T o : graph) {
result.append("\n");
result.append(indent);
result.append(o);
for(Iterator<?> itr = graph.getSuccNodes(o); itr.hasNext(); ) {
result.append("\n" + indent + " --> " + itr.next());
}
result.append(",\n");
}
result.delete(result.length()-2, result.length());
return result.toString();
}
/**
* Returns a pretty-print String representation
* of the given IR, with each new line starting
* indented at least the given number of spaces.
* @return pretty-print String representation
* of the given IR
*/
public static String prettyPrint(IR ir, int offset) {
return indent(ir.toString(), offset);
/*
final StringBuffer result = new StringBuffer();
result.append("\n"+indent+"CFG:\n");
final SSACFG cfg = ir.getControlFlowGraph();
for (int i = 0; i <= cfg.getNumber(cfg.exit()); i++) {
BasicBlock bb = cfg.getNode(i);
result.append(indent+"BB").append(i).append("[").append(bb.getFirstInstructionIndex()).append("..").append(bb.getLastInstructionIndex())
.append("]\n");
Iterator<ISSABasicBlock> succNodes = cfg.getSuccNodes(bb);
while (succNodes.hasNext()) {
result.append(indent+" -> BB").append(((BasicBlock) succNodes.next()).getNumber()).append("\n");
}
}
result.append(indent+"Instructions:\n");
for (int i = 0; i <= cfg.getMaxNumber(); i++) {
BasicBlock bb = cfg.getNode(i);
int start = bb.getFirstInstructionIndex();
int end = bb.getLastInstructionIndex();
result.append(indent+"BB").append(bb.getNumber());
if (bb instanceof ExceptionHandlerBasicBlock) {
result.append(indent+"<Handler>");
}
result.append("\n");
final SymbolTable symbolTable = ir.getSymbolTable();
for (Iterator<SSAPhiInstruction> it = bb.iteratePhis(); it.hasNext();) {
SSAPhiInstruction phi = it.next();
if (phi != null) {
result.append(indent+" " + phi.toString(symbolTable)).append("\n");
}
}
if (bb instanceof ExceptionHandlerBasicBlock) {
ExceptionHandlerBasicBlock ebb = (ExceptionHandlerBasicBlock) bb;
SSAGetCaughtExceptionInstruction s = ebb.getCatchInstruction();
if (s != null) {
result.append(indent+" " + s.toString(symbolTable)).append("\n");
} else {
result.append(indent+" " + " No catch instruction. Unreachable?\n");
}
}
final SSAInstruction[] instructions = ir.getInstructions();
for (int j = start; j <= end; j++) {
if (instructions[j] != null) {
StringBuffer x = new StringBuffer(indent+j + " " + instructions[j].toString(symbolTable));
StringStuff.padWithSpaces(x, 45);
result.append(indent+x);
result.append("\n");
}
}
for (Iterator<SSAPiInstruction> it = bb.iteratePis(); it.hasNext();) {
SSAPiInstruction pi = it.next();
if (pi != null) {
result.append(indent+" " + pi.toString(symbolTable)).append("\n");
}
}
}
return result.toString();
*/
}
/**
* Returns a pretty-print String representation
* of the given IR.
* @return pretty-print String representation
* of the given IR
*/
public static String prettyPrint(IR ir) { return prettyPrint(ir,0); }
/**
* Returns a pretty-print String representation
* of the given collection.
* @return pretty-print String representation
* of the given collection
*/
public static String prettyPrint(Collection<?> c) {
return prettyPrint(c,0);
}
/**
* Returns a pretty-print String representation
* of the given collection, with each new line starting
* indented at least the given number of spaces.
* @return pretty-print String representation
* of the given collection
*/
public static String prettyPrint(Collection<?> c, int offset) {
assert offset>=0;
final StringBuffer result = new StringBuffer();
final String indent = repeat(" ", offset);
for(Object o : c) {
result.append(indent);
result.append(o);
result.append("\n");
}
return result.toString();
}
/**
* Returns a String representation of the position in the source of the given method corresponding
* to the instruction at the specified index, or the empty string if the line is unknown.
* @return a String representation of the position in the source of the given method corresponding
* to the instruction at the specified index, or the empty string if the line is unknown.
*/
public static final String line(IMethod method, int instructionIndex) {
if (instructionIndex>=0) {
if (method instanceof ShrikeBTMethod) {
try {
return String.valueOf(method.getLineNumber(((ShrikeBTMethod)method).getBytecodeIndex(instructionIndex)));
} catch (InvalidClassFileException e) { } // ignore
} else if (method instanceof AstMethod) {
final Position pos = ((AstMethod)method).getSourcePosition(instructionIndex);
if (pos!=null)
return String.valueOf(pos.getFirstLine());
}
}
return "";
}
/**
* Returns a map from each InlinedInstruction in the given set to a unique name.
* The names are constructed from the names of the concrete instructions wrapped
* in each inlined instruction. Short type names are used whenever possible.
* @return a map from each InlinedInstruction in the given set to a unique name.
*/
public static Map<InlinedInstruction, String> instructionNames(Set<InlinedInstruction> insts) {
final Map<CGNode,String> methodNames = nodeNames(Programs.relevantMethods(insts));
final Map<String, List<InlinedInstruction>> name2Inst = new LinkedHashMap<String, List<InlinedInstruction>>();
final Map<InlinedInstruction, String> inst2Name = new LinkedHashMap<InlinedInstruction, String>();
for(InlinedInstruction inst : insts) {
final String m = methodNames.get(inst.cgNode());
final String infix;
final int idx = inst.instructionIndex();
if (idx==Integer.MIN_VALUE) {
infix = "start";
} else if (idx==Integer.MAX_VALUE) {
infix = "end";
} else {
final String cname = "";//inst.instruction().getClass().getSimpleName().replaceAll("SSA", "").replaceAll("Instruction", "");
infix = cname+idx;
}
final String name = m + "[" + infix + "]"; // m+"_"+infix;
List<InlinedInstruction> named = name2Inst.get(name);
if (named==null) {
named = new ArrayList<InlinedInstruction>(3);
name2Inst.put(name, named);
}
named.add(inst);
}
for(Map.Entry<String, List<InlinedInstruction>> entry : name2Inst.entrySet()) {
final List<InlinedInstruction> named = entry.getValue();
if (named.size()==1) {
inst2Name.put(named.get(0), entry.getKey());
} else {
for(InlinedInstruction inst : named) {
final StringBuilder b = new StringBuilder();
assert !inst.callStack().empty();
final Iterator<CallSite> itr = inst.callStack().iterator();
b.append(methodNames.get(itr.next().getNode()));
while(itr.hasNext()) {
b.append("_" + methodNames.get(itr.next().getNode()));
}
b.append("_" + entry.getKey());
inst2Name.put(inst, b.toString());
}
}
}
return inst2Name;
}
/**
* Returns a map from each CGNode in the given set to a unique name derived
* from the signature of that node. Short type names are used whenever possible.
* @return a map from each CGNode in the given set to a unique name derived
* from the signature of that node.
*/
public static Map<CGNode, String> nodeNames(Set<CGNode> nodes) {
final Map<String, List<CGNode>> name2Node = new LinkedHashMap<String, List<CGNode>>();
final Map<CGNode,String> node2Name = new LinkedHashMap<CGNode, String>();
for(CGNode ref : nodes) {
final String name = ref.getMethod().getName().toString();
List<CGNode> named = name2Node.get(name);
if (named==null) {
named = new ArrayList<CGNode>(3);
name2Node.put(name, named);
}
named.add(ref);
}
for(Map.Entry<String,List<CGNode>> entry: name2Node.entrySet()) {
final List<CGNode> named = entry.getValue();
if (named.size()==1) {
node2Name.put(named.get(0), entry.getKey());
} else {
for(CGNode ref : named) {
node2Name.put(ref, ref.getMethod().getSignature());
}
}
}
return node2Name;
}
/**
* Returns a map from each InstanceKey in the given set to a unique name.
* The names are constructed from the names of the concrete types represented
* by each instance key. If there is more than one instance key for the same
* type, unique suffixes are appended to make the names unique. Short type names
* are used whenever possible.
* @return a map from each InstanceKey in the given set to a unique name.
*/
public static Map<InstanceKey, String> instanceNames(Set<InstanceKey> instances) {
final Map<TypeName, List<InstanceKey>> nameToKey = new LinkedHashMap<TypeName,List<InstanceKey>>();
final Map<String, Boolean> uniqueShort = new HashMap<String,Boolean>();
final Map<InstanceKey, String> keyToName = new LinkedHashMap<InstanceKey,String>();
for(InstanceKey key : instances) {
final TypeName fullName = key.getConcreteType().getName();
List<InstanceKey> named = nameToKey.get(fullName);
if (named==null) {
named = new ArrayList<InstanceKey>(3);
nameToKey.put(fullName, named);
}
named.add(key);
}
for(TypeName fullName : nameToKey.keySet()) {
final String shortName = fullName.getClassName().toString();
final Boolean unique = uniqueShort.get(shortName);
if (unique==null) { uniqueShort.put(shortName, Boolean.TRUE); }
else { uniqueShort.put(shortName, Boolean.FALSE); }
}
for(Map.Entry<TypeName, List<InstanceKey>> entry : nameToKey.entrySet()) {
final TypeName fullName = entry.getKey();
final List<InstanceKey> named = entry.getValue();
final String shortName = fullName.getClassName().toString();
final String name = uniqueShort.get(shortName) ? shortName : fullName.toString();
final int size = named.size();
if (size==1) {
keyToName.put(named.get(0), name);
} else {
for(int i = 0; i < size; i++) {
keyToName.put(named.get(i), name + i);
}
}
}
assert keyToName.size() == instances.size();
return keyToName;
}
/**
* Returns a map from each IField in the given set to a unique name.
* The names are constructed from the names of the fields represented
* by IField. Short field names are used whenever possible.
* @return a map from each IField in the given set to a unique name.
*/
public static Map<IField, String> fieldNames(Set<IField> fields) {
final Map<String, List<IField>> name2Field = new LinkedHashMap<String, List<IField>>();
final Map<IField,String> field2Name = new LinkedHashMap<IField, String>();
|
[
"\t\tfor(IField field : fields) { "
] | 1,985
|
lcc
|
java
| null |
1e32291c11bc48e0917860b1de8446dde3fedecd450ef073
| 23
|
Your task is code completion.
/******************************************************************************
* Copyright (c) 2009 - 2015 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
/**
*
*/
package com.ibm.wala.memsat.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.ibm.wala.cast.java.ipa.callgraph.AstJavaSSAPropagationCallGraphBuilder.EnclosingObjectReferenceKey;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.ShrikeBTMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.ArrayContentsKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey;
import com.ibm.wala.ipa.callgraph.propagation.rta.CallSite;
import com.ibm.wala.ipa.modref.ArrayLengthKey;
import com.ibm.wala.memsat.frontEnd.InlinedInstruction;
import com.ibm.wala.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.graph.Graph;
import kodkod.ast.Node;
/**
* A set of utility functions for string manipulation and pretty printing of Kodkod nodes,
* IRs, etc.
*
* @author Emina Torlak
*/
public final class Strings {
/**
* Returns a pretty-printed string representation of the
* given nodes, with each line offset with at least the given
* number of whitespaces. The display parameter determines how
* the mapped nodes are displayed; that is, a descendant d of the
* given node is displayed as display.get(d.toString()) if
* display.containsKey(d.toString()) is true.
* @requires 0 <= offset < line
* @return a pretty-printed string representation of the
* given nodes
*/
public static String prettyPrint(Collection<Node> nodes, int offset, int line, Map<String,String> display) {
return PrettyPrinter.print(nodes, offset, 80, display);
}
/**
* Returns a pretty-printed string representation of the
* given node, with each line offset with at least the given
* number of whitespaces. The display parameter determines how
* the mapped nodes are displayed; that is, a descendant d of the
* given node is displayed as display.get(d.toString()) if
* display.containsKey(d.toString()) is true.
* @requires 0 <= offset < line
* @return a pretty-printed string representation of the
* given node
*/
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
return prettyPrint(node, offset, 80, display);
}
/**
* Returns a pretty-printed string representation of the
* given node, with each line offset with at least the given
* number of whitespaces. The line parameter determines the
* length of each pretty-printed line, including the offset.
* The display parameter determines how
* the mapped nodes are displayed; that is, a descendant d of the
* given node is displayed as display.get(d.toString()) if
* display.containsKey(d.toString()) is true.
* @requires 0 <= offset < line
* @return a pretty-printed string representation of the
* given node
*/
public static String prettyPrint(Node node, int offset, int line, final Map<String, String> display) {
return prettyPrint(Collections.singleton(node), offset, line, display);
}
/**
* Returns a pretty-printed string representation of the
* given node, with each line offset with at least the given
* number of whitespaces. The line parameter determines the
* length of each pretty-printed line, including the offset.
* @requires 0 <= offset < line
* @return a pretty-printed string representation of the
* given node
*/
@SuppressWarnings("unchecked")
public static String prettyPrint(Node node, int offset, int line) {
assert offset >= 0 && offset < line && line > 0;
return prettyPrint(node, offset, line, Collections.EMPTY_MAP);
}
/**
* Returns a pretty-printed string representation of the
* given node, with each line offset with at least the given
* number of whitespaces.
* @requires 0 <= offset < 80
* @return a pretty-printed string representation of the
* given node
*/
public static String prettyPrint(Node node, int offset) {
return prettyPrint(node,offset,80);
}
/**
* Returns a string that consists of the given number of repetitions
* of the specified string.
* @return str^reps
*/
public static String repeat(String str, int reps) {
final StringBuffer result = new StringBuffer();
for(int i = 0; i < reps; i++) {
result.append(str);
}
return result.toString();
}
/**
* Returns the given string, with all new lines replaced with new lines indented
* by the given number of spaces.
* @return given string, with all new lines replaced with new lines indented
* by the given number of spaces.
*/
public static String indent(String str, int offset) {
assert offset >= 0;
final String indent = repeat(" ", offset);
return indent + str.replaceAll("\\n", "\n"+indent);
}
/**
* Returns a pretty-print String representation
* of the given graph.
* @return pretty-print String representation
* of the given graph
*/
public static String prettyPrint(Graph<?> graph) {
return prettyPrint(graph,0);
}
/**
* Returns a pretty-print String representation
* of the given graph, with each new line starting
* indented at least the given number of spaces.
* @return pretty-print String representation
* of the given graph
*/
public static <T> String prettyPrint(Graph<T> graph, int offset) {
assert offset>=0;
final StringBuffer result = new StringBuffer();
final String indent = repeat(" ", offset);
for(T o : graph) {
result.append("\n");
result.append(indent);
result.append(o);
for(Iterator<?> itr = graph.getSuccNodes(o); itr.hasNext(); ) {
result.append("\n" + indent + " --> " + itr.next());
}
result.append(",\n");
}
result.delete(result.length()-2, result.length());
return result.toString();
}
/**
* Returns a pretty-print String representation
* of the given IR, with each new line starting
* indented at least the given number of spaces.
* @return pretty-print String representation
* of the given IR
*/
public static String prettyPrint(IR ir, int offset) {
return indent(ir.toString(), offset);
/*
final StringBuffer result = new StringBuffer();
result.append("\n"+indent+"CFG:\n");
final SSACFG cfg = ir.getControlFlowGraph();
for (int i = 0; i <= cfg.getNumber(cfg.exit()); i++) {
BasicBlock bb = cfg.getNode(i);
result.append(indent+"BB").append(i).append("[").append(bb.getFirstInstructionIndex()).append("..").append(bb.getLastInstructionIndex())
.append("]\n");
Iterator<ISSABasicBlock> succNodes = cfg.getSuccNodes(bb);
while (succNodes.hasNext()) {
result.append(indent+" -> BB").append(((BasicBlock) succNodes.next()).getNumber()).append("\n");
}
}
result.append(indent+"Instructions:\n");
for (int i = 0; i <= cfg.getMaxNumber(); i++) {
BasicBlock bb = cfg.getNode(i);
int start = bb.getFirstInstructionIndex();
int end = bb.getLastInstructionIndex();
result.append(indent+"BB").append(bb.getNumber());
if (bb instanceof ExceptionHandlerBasicBlock) {
result.append(indent+"<Handler>");
}
result.append("\n");
final SymbolTable symbolTable = ir.getSymbolTable();
for (Iterator<SSAPhiInstruction> it = bb.iteratePhis(); it.hasNext();) {
SSAPhiInstruction phi = it.next();
if (phi != null) {
result.append(indent+" " + phi.toString(symbolTable)).append("\n");
}
}
if (bb instanceof ExceptionHandlerBasicBlock) {
ExceptionHandlerBasicBlock ebb = (ExceptionHandlerBasicBlock) bb;
SSAGetCaughtExceptionInstruction s = ebb.getCatchInstruction();
if (s != null) {
result.append(indent+" " + s.toString(symbolTable)).append("\n");
} else {
result.append(indent+" " + " No catch instruction. Unreachable?\n");
}
}
final SSAInstruction[] instructions = ir.getInstructions();
for (int j = start; j <= end; j++) {
if (instructions[j] != null) {
StringBuffer x = new StringBuffer(indent+j + " " + instructions[j].toString(symbolTable));
StringStuff.padWithSpaces(x, 45);
result.append(indent+x);
result.append("\n");
}
}
for (Iterator<SSAPiInstruction> it = bb.iteratePis(); it.hasNext();) {
SSAPiInstruction pi = it.next();
if (pi != null) {
result.append(indent+" " + pi.toString(symbolTable)).append("\n");
}
}
}
return result.toString();
*/
}
/**
* Returns a pretty-print String representation
* of the given IR.
* @return pretty-print String representation
* of the given IR
*/
public static String prettyPrint(IR ir) { return prettyPrint(ir,0); }
/**
* Returns a pretty-print String representation
* of the given collection.
* @return pretty-print String representation
* of the given collection
*/
public static String prettyPrint(Collection<?> c) {
return prettyPrint(c,0);
}
/**
* Returns a pretty-print String representation
* of the given collection, with each new line starting
* indented at least the given number of spaces.
* @return pretty-print String representation
* of the given collection
*/
public static String prettyPrint(Collection<?> c, int offset) {
assert offset>=0;
final StringBuffer result = new StringBuffer();
final String indent = repeat(" ", offset);
for(Object o : c) {
result.append(indent);
result.append(o);
result.append("\n");
}
return result.toString();
}
/**
* Returns a String representation of the position in the source of the given method corresponding
* to the instruction at the specified index, or the empty string if the line is unknown.
* @return a String representation of the position in the source of the given method corresponding
* to the instruction at the specified index, or the empty string if the line is unknown.
*/
public static final String line(IMethod method, int instructionIndex) {
if (instructionIndex>=0) {
if (method instanceof ShrikeBTMethod) {
try {
return String.valueOf(method.getLineNumber(((ShrikeBTMethod)method).getBytecodeIndex(instructionIndex)));
} catch (InvalidClassFileException e) { } // ignore
} else if (method instanceof AstMethod) {
final Position pos = ((AstMethod)method).getSourcePosition(instructionIndex);
if (pos!=null)
return String.valueOf(pos.getFirstLine());
}
}
return "";
}
/**
* Returns a map from each InlinedInstruction in the given set to a unique name.
* The names are constructed from the names of the concrete instructions wrapped
* in each inlined instruction. Short type names are used whenever possible.
* @return a map from each InlinedInstruction in the given set to a unique name.
*/
public static Map<InlinedInstruction, String> instructionNames(Set<InlinedInstruction> insts) {
final Map<CGNode,String> methodNames = nodeNames(Programs.relevantMethods(insts));
final Map<String, List<InlinedInstruction>> name2Inst = new LinkedHashMap<String, List<InlinedInstruction>>();
final Map<InlinedInstruction, String> inst2Name = new LinkedHashMap<InlinedInstruction, String>();
for(InlinedInstruction inst : insts) {
final String m = methodNames.get(inst.cgNode());
final String infix;
final int idx = inst.instructionIndex();
if (idx==Integer.MIN_VALUE) {
infix = "start";
} else if (idx==Integer.MAX_VALUE) {
infix = "end";
} else {
final String cname = "";//inst.instruction().getClass().getSimpleName().replaceAll("SSA", "").replaceAll("Instruction", "");
infix = cname+idx;
}
final String name = m + "[" + infix + "]"; // m+"_"+infix;
List<InlinedInstruction> named = name2Inst.get(name);
if (named==null) {
named = new ArrayList<InlinedInstruction>(3);
name2Inst.put(name, named);
}
named.add(inst);
}
for(Map.Entry<String, List<InlinedInstruction>> entry : name2Inst.entrySet()) {
final List<InlinedInstruction> named = entry.getValue();
if (named.size()==1) {
inst2Name.put(named.get(0), entry.getKey());
} else {
for(InlinedInstruction inst : named) {
final StringBuilder b = new StringBuilder();
assert !inst.callStack().empty();
final Iterator<CallSite> itr = inst.callStack().iterator();
b.append(methodNames.get(itr.next().getNode()));
while(itr.hasNext()) {
b.append("_" + methodNames.get(itr.next().getNode()));
}
b.append("_" + entry.getKey());
inst2Name.put(inst, b.toString());
}
}
}
return inst2Name;
}
/**
* Returns a map from each CGNode in the given set to a unique name derived
* from the signature of that node. Short type names are used whenever possible.
* @return a map from each CGNode in the given set to a unique name derived
* from the signature of that node.
*/
public static Map<CGNode, String> nodeNames(Set<CGNode> nodes) {
final Map<String, List<CGNode>> name2Node = new LinkedHashMap<String, List<CGNode>>();
final Map<CGNode,String> node2Name = new LinkedHashMap<CGNode, String>();
for(CGNode ref : nodes) {
final String name = ref.getMethod().getName().toString();
List<CGNode> named = name2Node.get(name);
if (named==null) {
named = new ArrayList<CGNode>(3);
name2Node.put(name, named);
}
named.add(ref);
}
for(Map.Entry<String,List<CGNode>> entry: name2Node.entrySet()) {
final List<CGNode> named = entry.getValue();
if (named.size()==1) {
node2Name.put(named.get(0), entry.getKey());
} else {
for(CGNode ref : named) {
node2Name.put(ref, ref.getMethod().getSignature());
}
}
}
return node2Name;
}
/**
* Returns a map from each InstanceKey in the given set to a unique name.
* The names are constructed from the names of the concrete types represented
* by each instance key. If there is more than one instance key for the same
* type, unique suffixes are appended to make the names unique. Short type names
* are used whenever possible.
* @return a map from each InstanceKey in the given set to a unique name.
*/
public static Map<InstanceKey, String> instanceNames(Set<InstanceKey> instances) {
final Map<TypeName, List<InstanceKey>> nameToKey = new LinkedHashMap<TypeName,List<InstanceKey>>();
final Map<String, Boolean> uniqueShort = new HashMap<String,Boolean>();
final Map<InstanceKey, String> keyToName = new LinkedHashMap<InstanceKey,String>();
for(InstanceKey key : instances) {
final TypeName fullName = key.getConcreteType().getName();
List<InstanceKey> named = nameToKey.get(fullName);
if (named==null) {
named = new ArrayList<InstanceKey>(3);
nameToKey.put(fullName, named);
}
named.add(key);
}
for(TypeName fullName : nameToKey.keySet()) {
final String shortName = fullName.getClassName().toString();
final Boolean unique = uniqueShort.get(shortName);
if (unique==null) { uniqueShort.put(shortName, Boolean.TRUE); }
else { uniqueShort.put(shortName, Boolean.FALSE); }
}
for(Map.Entry<TypeName, List<InstanceKey>> entry : nameToKey.entrySet()) {
final TypeName fullName = entry.getKey();
final List<InstanceKey> named = entry.getValue();
final String shortName = fullName.getClassName().toString();
final String name = uniqueShort.get(shortName) ? shortName : fullName.toString();
final int size = named.size();
if (size==1) {
keyToName.put(named.get(0), name);
} else {
for(int i = 0; i < size; i++) {
keyToName.put(named.get(i), name + i);
}
}
}
assert keyToName.size() == instances.size();
return keyToName;
}
/**
* Returns a map from each IField in the given set to a unique name.
* The names are constructed from the names of the fields represented
* by IField. Short field names are used whenever possible.
* @return a map from each IField in the given set to a unique name.
*/
public static Map<IField, String> fieldNames(Set<IField> fields) {
final Map<String, List<IField>> name2Field = new LinkedHashMap<String, List<IField>>();
final Map<IField,String> field2Name = new LinkedHashMap<IField, String>();
|
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]
public class Strings {
// ... (many methods and variables)
public static Map<InstanceKey, String> instanceNames(Set<InstanceKey> instances) {
// ... (code)
}
public static Map<IField, String> fieldNames(Set<IField> fields) {
// ... (code)
}
public static Map<CGNode, String> nodeNames(Set<CGNode> nodes) {
// ... (code)
}
public static Map<InlinedInstruction, String> instructionNames(Set<InlinedInstruction> insts) {
// ... (code)
}
public static String line(IMethod method, int instructionIndex) {
// ... (code)
}
public static String prettyPrint(Graph<?> graph) {
// ... (code)
}
public static String prettyPrint(Graph<?> graph, int offset) {
// ... (code)
}
public static String prettyPrint(IR ir) {
// ... (code)
}
public static String prettyPrint(IR ir, int offset) {
// ... (code)
}
public static String prettyPrint(Collection<?> c) {
// ... (code)
}
public static String prettyPrint(Collection<?> c, int offset) {
// ... (code)
}
public static String prettyPrint(Node node, int offset) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, int line) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, int line, final Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node, int offset, Map<String, String> display) {
// ... (code)
}
public static String prettyPrint(Node node,
|
|
Please complete the code given below.
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""``tornado.web`` provides a simple web framework with asynchronous
features that allow it to scale to large numbers of open connections,
making it ideal for `long polling
<http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.
Here is a simple "Hello, world" example app:
.. testcode::
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
.. testoutput::
:hide:
See the :doc:`guide` for additional information.
Thread-safety notes
-------------------
In general, methods on `RequestHandler` and elsewhere in Tornado are
not thread-safe. In particular, methods such as
`~RequestHandler.write()`, `~RequestHandler.finish()`, and
`~RequestHandler.flush()` must only be called from the main thread. If
you use multiple threads it is important to use `.IOLoop.add_callback`
to transfer control back to the main thread before finishing the
request.
"""
from __future__ import (absolute_import, division,
print_function, with_statement)
import base64
import binascii
import datetime
import email.utils
import functools
import gzip
import hashlib
import hmac
import mimetypes
import numbers
import os.path
import re
import stat
import sys
import threading
import time
import tornado
import traceback
import types
from io import BytesIO
from tornado.concurrent import Future, is_future
from tornado import escape
from tornado import gen
from tornado import httputil
from tornado import iostream
from tornado import locale
from tornado.log import access_log, app_log, gen_log
from tornado import stack_context
from tornado import template
from tornado.escape import utf8, _unicode
from tornado.util import (import_object, ObjectDict, raise_exc_info,
unicode_type, _websocket_mask)
from tornado.httputil import split_host_and_port
try:
import Cookie # py2
except ImportError:
import http.cookies as Cookie # py3
try:
import urlparse # py2
except ImportError:
import urllib.parse as urlparse # py3
try:
from urllib import urlencode # py2
except ImportError:
from urllib.parse import urlencode # py3
MIN_SUPPORTED_SIGNED_VALUE_VERSION = 1
"""The oldest signed value version supported by this version of Tornado.
Signed values older than this version cannot be decoded.
.. versionadded:: 3.2.1
"""
MAX_SUPPORTED_SIGNED_VALUE_VERSION = 2
"""The newest signed value version supported by this version of Tornado.
Signed values newer than this version cannot be decoded.
.. versionadded:: 3.2.1
"""
DEFAULT_SIGNED_VALUE_VERSION = 2
"""The signed value version produced by `.RequestHandler.create_signed_value`.
May be overridden by passing a ``version`` keyword argument.
.. versionadded:: 3.2.1
"""
DEFAULT_SIGNED_VALUE_MIN_VERSION = 1
"""The oldest signed value accepted by `.RequestHandler.get_secure_cookie`.
May be overridden by passing a ``min_version`` keyword argument.
.. versionadded:: 3.2.1
"""
class RequestHandler(object):
"""Base class for HTTP request handlers.
Subclasses must define at least one of the methods defined in the
"Entry points" section below.
"""
SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT",
"OPTIONS")
_template_loaders = {} # {path: template.BaseLoader}
_template_loader_lock = threading.Lock()
_remove_control_chars_regex = re.compile(r"[\x00-\x08\x0e-\x1f]")
def __init__(self, application, request, **kwargs):
super(RequestHandler, self).__init__()
self.application = application
self.request = request
self._headers_written = False
self._finished = False
self._auto_finish = True
self._transforms = None # will be set in _execute
self._prepared_future = None
self.path_args = None
self.path_kwargs = None
self.ui = ObjectDict((n, self._ui_method(m)) for n, m in
application.ui_methods.items())
# UIModules are available as both `modules` and `_tt_modules` in the
# template namespace. Historically only `modules` was available
# but could be clobbered by user additions to the namespace.
# The template {% module %} directive looks in `_tt_modules` to avoid
# possible conflicts.
self.ui["_tt_modules"] = _UIModuleNamespace(self,
application.ui_modules)
self.ui["modules"] = self.ui["_tt_modules"]
self.clear()
self.request.connection.set_close_callback(self.on_connection_close)
self.initialize(**kwargs)
def initialize(self):
"""Hook for subclass initialization.
A dictionary passed as the third argument of a url spec will be
supplied as keyword arguments to initialize().
Example::
class ProfileHandler(RequestHandler):
def initialize(self, database):
self.database = database
def get(self, username):
...
app = Application([
(r'/user/(.*)', ProfileHandler, dict(database=database)),
])
"""
pass
@property
def settings(self):
"""An alias for `self.application.settings <Application.settings>`."""
return self.application.settings
def head(self, *args, **kwargs):
raise HTTPError(405)
def get(self, *args, **kwargs):
raise HTTPError(405)
def post(self, *args, **kwargs):
raise HTTPError(405)
def delete(self, *args, **kwargs):
raise HTTPError(405)
def patch(self, *args, **kwargs):
raise HTTPError(405)
def put(self, *args, **kwargs):
raise HTTPError(405)
def options(self, *args, **kwargs):
raise HTTPError(405)
def prepare(self):
"""Called at the beginning of a request before `get`/`post`/etc.
Override this method to perform common initialization regardless
of the request method.
Asynchronous support: Decorate this method with `.gen.coroutine`
or `.return_future` to make it asynchronous (the
`asynchronous` decorator cannot be used on `prepare`).
If this method returns a `.Future` execution will not proceed
until the `.Future` is done.
.. versionadded:: 3.1
Asynchronous support.
"""
pass
def on_finish(self):
"""Called after the end of a request.
Override this method to perform cleanup, logging, etc.
This method is a counterpart to `prepare`. ``on_finish`` may
not produce any output, as it is called after the response
has been sent to the client.
"""
pass
def on_connection_close(self):
"""Called in async handlers if the client closed the connection.
Override this to clean up resources associated with
long-lived connections. Note that this method is called only if
the connection was closed during asynchronous processing; if you
need to do cleanup after every request override `on_finish`
instead.
Proxies may keep a connection open for a time (perhaps
indefinitely) after the client has gone away, so this method
may not be called promptly after the end user closes their
connection.
"""
if _has_stream_request_body(self.__class__):
if not self.request.body.done():
self.request.body.set_exception(iostream.StreamClosedError())
self.request.body.exception()
def clear(self):
"""Resets all headers and content for this response."""
self._headers = httputil.HTTPHeaders({
"Server": "TornadoServer/%s" % tornado.version,
"Content-Type": "text/html; charset=UTF-8",
"Date": httputil.format_timestamp(time.time()),
})
self.set_default_headers()
self._write_buffer = []
self._status_code = 200
self._reason = httputil.responses[200]
def set_default_headers(self):
"""Override this to set HTTP headers at the beginning of the request.
For example, this is the place to set a custom ``Server`` header.
Note that setting such headers in the normal flow of request
processing may not do what you want, since headers may be reset
during error handling.
"""
pass
def set_status(self, status_code, reason=None):
"""Sets the status code for our response.
:arg int status_code: Response status code. If ``reason`` is ``None``,
it must be present in `httplib.responses <http.client.responses>`.
:arg string reason: Human-readable reason phrase describing the status
code. If ``None``, it will be filled in from
`httplib.responses <http.client.responses>`.
"""
self._status_code = status_code
if reason is not None:
self._reason = escape.native_str(reason)
else:
try:
self._reason = httputil.responses[status_code]
except KeyError:
raise ValueError("unknown status code %d", status_code)
def get_status(self):
"""Returns the status code for our response."""
return self._status_code
def set_header(self, name, value):
"""Sets the given response header name and value.
If a datetime is given, we automatically format it according to the
HTTP specification. If the value is not a string, we convert it to
a string. All header values are then encoded as UTF-8.
"""
self._headers[name] = self._convert_header_value(value)
def add_header(self, name, value):
"""Adds the given response header and value.
Unlike `set_header`, `add_header` may be called multiple times
to return multiple values for the same header.
"""
self._headers.add(name, self._convert_header_value(value))
def clear_header(self, name):
"""Clears an outgoing header, undoing a previous `set_header` call.
Note that this method does not apply to multi-valued headers
set by `add_header`.
"""
if name in self._headers:
del self._headers[name]
_INVALID_HEADER_CHAR_RE = re.compile(br"[\x00-\x1f]")
def _convert_header_value(self, value):
if isinstance(value, bytes):
pass
elif isinstance(value, unicode_type):
value = value.encode('utf-8')
elif isinstance(value, numbers.Integral):
# return immediately since we know the converted value will be safe
return str(value)
elif isinstance(value, datetime.datetime):
return httputil.format_timestamp(value)
else:
raise TypeError("Unsupported header value %r" % value)
# If \n is allowed into the header, it is possible to inject
# additional headers or split the request.
if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
raise ValueError("Unsafe header value %r", value)
return value
_ARG_DEFAULT = []
def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
"""
return self._get_argument(name, default, self.request.arguments, strip)
def get_arguments(self, name, strip=True):
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
"""
# Make sure `get_arguments` isn't accidentally being called with a
# positional argument that's assumed to be a default (like in
# `get_argument`.)
assert isinstance(strip, bool)
return self._get_arguments(name, self.request.arguments, strip)
def get_body_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name
from the request body.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
.. versionadded:: 3.2
"""
return self._get_argument(name, default, self.request.body_arguments,
strip)
def get_body_arguments(self, name, strip=True):
"""Returns a list of the body arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
.. versionadded:: 3.2
"""
return self._get_arguments(name, self.request.body_arguments, strip)
def get_query_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name
from the request query string.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
.. versionadded:: 3.2
"""
return self._get_argument(name, default,
self.request.query_arguments, strip)
def get_query_arguments(self, name, strip=True):
"""Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
.. versionadded:: 3.2
"""
return self._get_arguments(name, self.request.query_arguments, strip)
def _get_argument(self, name, default, source, strip=True):
args = self._get_arguments(name, source, strip=strip)
if not args:
if default is self._ARG_DEFAULT:
raise MissingArgumentError(name)
return default
return args[-1]
def _get_arguments(self, name, source, strip=True):
values = []
for v in source.get(name, []):
v = self.decode_argument(v, name=name)
if isinstance(v, unicode_type):
# Get rid of any weird control chars (unless decoding gave
# us bytes, in which case leave it alone)
v = RequestHandler._remove_control_chars_regex.sub(" ", v)
if strip:
v = v.strip()
values.append(v)
return values
def decode_argument(self, value, name=None):
"""Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string.
By default, this method decodes the argument as utf-8 and returns
a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both `get_argument()` and for
values extracted from the url and passed to `get()`/`post()`/etc.
The name of the argument is provided if known, but may be None
(e.g. for unnamed groups in the url regex).
"""
try:
return _unicode(value)
except UnicodeDecodeError:
raise HTTPError(400, "Invalid unicode in %s: %r" %
(name or "url", value[:40]))
@property
def cookies(self):
"""An alias for
`self.request.cookies <.httputil.HTTPServerRequest.cookies>`."""
return self.request.cookies
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if self.request.cookies is not None and name in self.request.cookies:
return self.request.cookies[name].value
return default
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
# The cookie library only accepts type str, in both python 2 and 3
name = escape.native_str(name)
value = escape.native_str(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookie"):
self._new_cookie = Cookie.SimpleCookie()
if name in self._new_cookie:
del self._new_cookie[name]
self._new_cookie[name] = value
morsel = self._new_cookie[name]
if domain:
morsel["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(
days=expires_days)
if expires:
morsel["expires"] = httputil.format_timestamp(expires)
if path:
morsel["path"] = path
for k, v in kwargs.items():
if k == 'max_age':
k = 'max-age'
# skip falsy values for httponly and secure flags because
# SimpleCookie sets them regardless
if k in ['httponly', 'secure'] and not v:
continue
morsel[k] = v
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name.
Due to limitations of the cookie protocol, you must pass the same
path and domain to clear a cookie as were used when that cookie
was set (but there is no way to find out on the server side
which values were used for a given cookie).
"""
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
self.set_cookie(name, value="", path=path, expires=expires,
domain=domain)
def clear_all_cookies(self, path="/", domain=None):
"""Deletes all the cookies the user sent with this request.
See `clear_cookie` for more information on the path and domain
parameters.
.. versionchanged:: 3.2
Added the ``path`` and ``domain`` parameters.
"""
for name in self.request.cookies:
self.clear_cookie(name, path=path, domain=domain)
def set_secure_cookie(self, name, value, expires_days=30, version=None,
**kwargs):
"""Signs and timestamps a cookie so it cannot be forged.
You must specify the ``cookie_secret`` setting in your Application
to use this method. It should be a long, random sequence of bytes
to be used as the HMAC secret for the signature.
To read a cookie set with this method, use `get_secure_cookie()`.
Note that the ``expires_days`` parameter sets the lifetime of the
cookie in the browser, but is independent of the ``max_age_days``
parameter to `get_secure_cookie`.
Secure cookies may contain arbitrary byte values, not just unicode
strings (unlike regular cookies)
.. versionchanged:: 3.2.1
Added the ``version`` argument. Introduced cookie version 2
and made it the default.
"""
self.set_cookie(name, self.create_signed_value(name, value,
version=version),
expires_days=expires_days, **kwargs)
def create_signed_value(self, name, value, version=None):
"""Signs and timestamps a string so it cannot be forged.
Normally used via set_secure_cookie, but provided as a separate
method for non-cookie uses. To decode a value not stored
as a cookie use the optional value argument to get_secure_cookie.
.. versionchanged:: 3.2.1
Added the ``version`` argument. Introduced cookie version 2
and made it the default.
"""
self.require_setting("cookie_secret", "secure cookies")
secret = self.application.settings["cookie_secret"]
key_version = None
if isinstance(secret, dict):
if self.application.settings.get("key_version") is None:
raise Exception("key_version setting must be used for secret_key dicts")
key_version = self.application.settings["key_version"]
return create_signed_value(secret, name, value, version=version,
key_version=key_version)
def get_secure_cookie(self, name, value=None, max_age_days=31,
min_version=None):
"""Returns the given signed cookie if it validates, or None.
The decoded cookie value is returned as a byte string (unlike
`get_cookie`).
.. versionchanged:: 3.2.1
Added the ``min_version`` argument. Introduced cookie version 2;
both versions 1 and 2 are accepted by default.
"""
self.require_setting("cookie_secret", "secure cookies")
if value is None:
value = self.get_cookie(name)
return decode_signed_value(self.application.settings["cookie_secret"],
name, value, max_age_days=max_age_days,
min_version=min_version)
def get_secure_cookie_key_version(self, name, value=None):
"""Returns the signing key version of the secure cookie.
The version is returned as int.
"""
self.require_setting("cookie_secret", "secure cookies")
if value is None:
value = self.get_cookie(name)
return get_signature_key_version(value)
def redirect(self, url, permanent=False, status=None):
"""Sends a redirect to the given (optionally relative) URL.
If the ``status`` argument is specified, that value is used as the
HTTP status code; otherwise either 301 (permanent) or 302
(temporary) is chosen based on the ``permanent`` argument.
The default is 302 (temporary).
"""
if self._headers_written:
raise Exception("Cannot redirect after headers have been written")
if status is None:
status = 301 if permanent else 302
else:
assert isinstance(status, int) and 300 <= status <= 399
self.set_status(status)
self.set_header("Location", utf8(url))
self.finish()
def write(self, chunk):
"""Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be ``application/json``.
(if you want to send JSON as a different ``Content-Type``, call
set_header *after* calling write()).
Note that lists are not converted to JSON because of a potential
cross-site security vulnerability. All JSON output should be
wrapped in a dictionary. More details at
http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and
https://github.com/facebook/tornado/issues/1009
"""
if self._finished:
raise RuntimeError("Cannot write() after finish()")
if not isinstance(chunk, (bytes, unicode_type, dict)):
message = "write() only accepts bytes, unicode, and dict objects"
if isinstance(chunk, list):
message += ". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
raise TypeError(message)
if isinstance(chunk, dict):
if 'unwrap_json' in chunk:
chunk = chunk['unwrap_json']
else:
chunk = escape.json_encode(chunk)
self.set_header("Content-Type", "application/json; charset=UTF-8")
chunk = utf8(chunk)
self._write_buffer.append(chunk)
def render(self, template_name, **kwargs):
"""Renders the template with the given arguments as the response."""
html = self.render_string(template_name, **kwargs)
# Insert the additional JS and CSS added by the modules on the page
js_embed = []
js_files = []
css_embed = []
css_files = []
html_heads = []
html_bodies = []
for module in getattr(self, "_active_modules", {}).values():
embed_part = module.embedded_javascript()
if embed_part:
js_embed.append(utf8(embed_part))
file_part = module.javascript_files()
if file_part:
if isinstance(file_part, (unicode_type, bytes)):
js_files.append(file_part)
else:
js_files.extend(file_part)
embed_part = module.embedded_css()
if embed_part:
css_embed.append(utf8(embed_part))
file_part = module.css_files()
if file_part:
if isinstance(file_part, (unicode_type, bytes)):
css_files.append(file_part)
else:
css_files.extend(file_part)
head_part = module.html_head()
if head_part:
html_heads.append(utf8(head_part))
body_part = module.html_body()
if body_part:
html_bodies.append(utf8(body_part))
def is_absolute(path):
return any(path.startswith(x) for x in ["/", "http:", "https:"])
if js_files:
# Maintain order of JavaScript files given by modules
paths = []
unique_paths = set()
for path in js_files:
if not is_absolute(path):
path = self.static_url(path)
if path not in unique_paths:
paths.append(path)
unique_paths.add(path)
js = ''.join('<script src="' + escape.xhtml_escape(p) +
'" type="text/javascript"></script>'
for p in paths)
sloc = html.rindex(b'</body>')
html = html[:sloc] + utf8(js) + b'\n' + html[sloc:]
if js_embed:
js = b'<script type="text/javascript">\n//<![CDATA[\n' + \
b'\n'.join(js_embed) + b'\n//]]>\n</script>'
sloc = html.rindex(b'</body>')
html = html[:sloc] + js + b'\n' + html[sloc:]
if css_files:
paths = []
unique_paths = set()
for path in css_files:
if not is_absolute(path):
path = self.static_url(path)
if path not in unique_paths:
paths.append(path)
unique_paths.add(path)
css = ''.join('<link href="' + escape.xhtml_escape(p) + '" '
'type="text/css" rel="stylesheet"/>'
for p in paths)
hloc = html.index(b'</head>')
html = html[:hloc] + utf8(css) + b'\n' + html[hloc:]
if css_embed:
css = b'<style type="text/css">\n' + b'\n'.join(css_embed) + \
b'\n</style>'
hloc = html.index(b'</head>')
html = html[:hloc] + css + b'\n' + html[hloc:]
if html_heads:
hloc = html.index(b'</head>')
html = html[:hloc] + b''.join(html_heads) + b'\n' + html[hloc:]
if html_bodies:
hloc = html.index(b'</body>')
html = html[:hloc] + b''.join(html_bodies) + b'\n' + html[hloc:]
self.finish(html)
def render_string(self, template_name, **kwargs):
"""Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate and
write a template as a response, use render() above.
"""
# If no template_path is specified, use the path of the calling file
template_path = self.get_template_path()
if not template_path:
frame = sys._getframe(0)
web_file = frame.f_code.co_filename
while frame.f_code.co_filename == web_file:
frame = frame.f_back
template_path = os.path.dirname(frame.f_code.co_filename)
with RequestHandler._template_loader_lock:
if template_path not in RequestHandler._template_loaders:
loader = self.create_template_loader(template_path)
RequestHandler._template_loaders[template_path] = loader
else:
loader = RequestHandler._template_loaders[template_path]
t = loader.load(template_name)
namespace = self.get_template_namespace()
namespace.update(kwargs)
return t.generate(**namespace)
def get_template_namespace(self):
"""Returns a dictionary to be used as the default template namespace.
May be overridden by subclasses to add or modify values.
The results of this method will be combined with additional
defaults in the `tornado.template` module and keyword arguments
to `render` or `render_string`.
"""
namespace = dict(
handler=self,
request=self.request,
current_user=self.current_user,
locale=self.locale,
_=self.locale.translate,
pgettext=self.locale.pgettext,
static_url=self.static_url,
xsrf_form_html=self.xsrf_form_html,
reverse_url=self.reverse_url
)
namespace.update(self.ui)
return namespace
def create_template_loader(self, template_path):
"""Returns a new template loader for the given path.
May be overridden by subclasses. By default returns a
directory-based loader on the given path, using the
``autoescape`` and ``template_whitespace`` application
settings. If a ``template_loader`` application setting is
supplied, uses that instead.
"""
settings = self.application.settings
if "template_loader" in settings:
return settings["template_loader"]
kwargs = {}
if "autoescape" in settings:
# autoescape=None means "no escaping", so we have to be sure
# to only pass this kwarg if the user asked for it.
kwargs["autoescape"] = settings["autoescape"]
if "template_whitespace" in settings:
kwargs["whitespace"] = settings["template_whitespace"]
return template.Loader(template_path, **kwargs)
def flush(self, include_footers=False, callback=None):
"""Flushes the current output buffer to the network.
The ``callback`` argument, if given, can be used for flow control:
it will be run when all flushed data has been written to the socket.
Note that only one flush callback can be outstanding at a time;
if another flush occurs before the previous flush's callback
has been run, the previous callback will be discarded.
.. versionchanged:: 4.0
Now returns a `.Future` if no callback is given.
"""
chunk = b"".join(self._write_buffer)
self._write_buffer = []
if not self._headers_written:
self._headers_written = True
for transform in self._transforms:
self._status_code, self._headers, chunk = \
transform.transform_first_chunk(
self._status_code, self._headers,
chunk, include_footers)
# Ignore the chunk and only write the headers for HEAD requests
if self.request.method == "HEAD":
chunk = None
# Finalize the cookie headers (which have been stored in a side
# object so an outgoing cookie could be overwritten before it
# is sent).
if hasattr(self, "_new_cookie"):
for cookie in self._new_cookie.values():
self.add_header("Set-Cookie", cookie.OutputString(None))
start_line = httputil.ResponseStartLine('',
self._status_code,
self._reason)
return self.request.connection.write_headers(
start_line, self._headers, chunk, callback=callback)
else:
for transform in self._transforms:
chunk = transform.transform_chunk(chunk, include_footers)
# Ignore the chunk and only write the headers for HEAD requests
if self.request.method != "HEAD":
return self.request.connection.write(chunk, callback=callback)
else:
future = Future()
future.set_result(None)
return future
def finish(self, chunk=None):
"""Finishes this response, ending the HTTP request."""
if self._finished:
raise RuntimeError("finish() called twice")
if chunk is not None:
self.write(chunk)
# Automatically support ETags and add the Content-Length header if
# we have not flushed any content yet.
if not self._headers_written:
if (self._status_code == 200 and
self.request.method in ("GET", "HEAD") and
"Etag" not in self._headers):
self.set_etag_header()
if self.check_etag_header():
self._write_buffer = []
self.set_status(304)
if self._status_code == 304:
assert not self._write_buffer, "Cannot send body with 304"
self._clear_headers_for_304()
elif "Content-Length" not in self._headers:
content_length = sum(len(part) for part in self._write_buffer)
self.set_header("Content-Length", content_length)
if hasattr(self.request, "connection"):
# Now that the request is finished, clear the callback we
# set on the HTTPConnection (which would otherwise prevent the
# garbage collection of the RequestHandler when there
# are keepalive connections)
self.request.connection.set_close_callback(None)
self.flush(include_footers=True)
self.request.finish()
self._log()
self._finished = True
self.on_finish()
# Break up a reference cycle between this handler and the
# _ui_module closures to allow for faster GC on CPython.
self.ui = None
def send_error(self, status_code=500, **kwargs):
"""Sends the given HTTP error code to the browser.
If `flush()` has already been called, it is not possible to send
an error, so this method will simply terminate the response.
If output has been written but not yet flushed, it will be discarded
and replaced with the error page.
Override `write_error()` to customize the error page that is returned.
Additional keyword arguments are passed through to `write_error`.
"""
if self._headers_written:
gen_log.error("Cannot send error response after headers written")
if not self._finished:
# If we get an error between writing headers and finishing,
# we are unlikely to be able to finish due to a
# Content-Length mismatch. Try anyway to release the
# socket.
try:
self.finish()
except Exception:
gen_log.error("Failed to flush partial response",
exc_info=True)
return
self.clear()
reason = kwargs.get('reason')
if 'exc_info' in kwargs:
exception = kwargs['exc_info'][1]
if isinstance(exception, HTTPError) and exception.reason:
reason = exception.reason
self.set_status(status_code, reason=reason)
try:
self.write_error(status_code, **kwargs)
except Exception:
app_log.error("Uncaught exception in write_error", exc_info=True)
if not self._finished:
self.finish()
def write_error(self, status_code, **kwargs):
"""Override to implement custom error pages.
``write_error`` may call `write`, `render`, `set_header`, etc
to produce output as usual.
If this error was caused by an uncaught exception (including
HTTPError), an ``exc_info`` triple will be available as
``kwargs["exc_info"]``. Note that this exception may not be
the "current" exception for purposes of methods like
``sys.exc_info()`` or ``traceback.format_exc``.
"""
if self.settings.get("serve_traceback") and "exc_info" in kwargs:
# in debug mode, try to send a traceback
self.set_header('Content-Type', 'text/plain')
for line in traceback.format_exception(*kwargs["exc_info"]):
self.write(line)
self.finish()
else:
self.finish("<html><title>%(code)d: %(message)s</title>"
"<body>%(code)d: %(message)s</body></html>" % {
"code": status_code,
"message": self._reason,
})
@property
def locale(self):
"""The locale for the current session.
Determined by either `get_user_locale`, which you can override to
set the locale based on, e.g., a user preference stored in a
database, or `get_browser_locale`, which uses the ``Accept-Language``
header.
.. versionchanged: 4.1
Added a property setter.
"""
if not hasattr(self, "_locale"):
self._locale = self.get_user_locale()
if not self._locale:
self._locale = self.get_browser_locale()
assert self._locale
return self._locale
@locale.setter
def locale(self, value):
self._locale = value
def get_user_locale(self):
"""Override to determine the locale from the authenticated user.
If None is returned, we fall back to `get_browser_locale()`.
This method should return a `tornado.locale.Locale` object,
most likely obtained via a call like ``tornado.locale.get("en")``
"""
return None
def get_browser_locale(self, default="en_US"):
"""Determines the user's locale from ``Accept-Language`` header.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
"""
if "Accept-Language" in self.request.headers:
languages = self.request.headers["Accept-Language"].split(",")
locales = []
for language in languages:
parts = language.strip().split(";")
if len(parts) > 1 and parts[1].startswith("q="):
try:
score = float(parts[1][2:])
except (ValueError, TypeError):
score = 0.0
else:
score = 1.0
locales.append((parts[0], score))
if locales:
locales.sort(key=lambda pair: pair[1], reverse=True)
codes = [l[0] for l in locales]
return locale.get(*codes)
return locale.get(default)
@property
def current_user(self):
"""The authenticated user for this request.
This is a cached version of `get_current_user`, which you can
override to set the user based on, e.g., a cookie. If that
method is not overridden, this method always returns None.
We lazy-load the current user the first time this method is called
and cache the result after that.
"""
if not hasattr(self, "_current_user"):
self._current_user = self.get_current_user()
return self._current_user
@current_user.setter
def current_user(self, value):
self._current_user = value
def get_current_user(self):
"""Override to determine the current user from, e.g., a cookie."""
return None
def get_login_url(self):
"""Override to customize the login URL based on the request.
By default, we use the ``login_url`` application setting.
"""
self.require_setting("login_url", "@tornado.web.authenticated")
return self.application.settings["login_url"]
def get_template_path(self):
"""Override to customize template path for each handler.
By default, we use the ``template_path`` application setting.
Return None to load templates relative to the calling file.
"""
return self.application.settings.get("template_path")
@property
def xsrf_token(self):
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
.. versionchanged:: 3.2.2
The xsrf token will now be have a random mask applied in every
request, which makes it safe to include the token in pages
that are compressed. See http://breachattack.com for more
information on the issue fixed by this change. Old (version 1)
cookies will be converted to version 2 when this method is called
unless the ``xsrf_cookie_version`` `Application` setting is
set to 1.
"""
if not hasattr(self, "_xsrf_token"):
version, token, timestamp = self._get_raw_xsrf_token()
output_version = self.settings.get("xsrf_cookie_version", 2)
if output_version == 1:
self._xsrf_token = binascii.b2a_hex(token)
elif output_version == 2:
mask = os.urandom(4)
self._xsrf_token = b"|".join([
b"2",
binascii.b2a_hex(mask),
binascii.b2a_hex(_websocket_mask(mask, token)),
utf8(str(int(timestamp)))])
else:
raise ValueError("unknown xsrf cookie version %d",
output_version)
if version is None:
expires_days = 30 if self.current_user else None
self.set_cookie("_xsrf", self._xsrf_token,
expires_days=expires_days)
return self._xsrf_token
def _get_raw_xsrf_token(self):
"""Read or generate the xsrf token in its raw form.
The raw_xsrf_token is a tuple containing:
* version: the version of the cookie from which this token was read,
or None if we generated a new token in this request.
* token: the raw token data; random (non-ascii) bytes.
* timestamp: the time this token was generated (will not be accurate
for version 1 cookies)
"""
if not hasattr(self, '_raw_xsrf_token'):
cookie = self.get_cookie("_xsrf")
if cookie:
version, token, timestamp = self._decode_xsrf_token(cookie)
else:
version, token, timestamp = None, None, None
if token is None:
version = None
token = os.urandom(16)
timestamp = time.time()
self._raw_xsrf_token = (version, token, timestamp)
return self._raw_xsrf_token
def _decode_xsrf_token(self, cookie):
"""Convert a cookie string into a the tuple form returned by
_get_raw_xsrf_token.
"""
try:
m = _signed_value_version_re.match(utf8(cookie))
if m:
version = int(m.group(1))
if version == 2:
_, mask, masked_token, timestamp = cookie.split("|")
mask = binascii.a2b_hex(utf8(mask))
token = _websocket_mask(
mask, binascii.a2b_hex(utf8(masked_token)))
timestamp = int(timestamp)
return version, token, timestamp
else:
# Treat unknown versions as not present instead of failing.
raise Exception("Unknown xsrf cookie version")
else:
version = 1
try:
token = binascii.a2b_hex(utf8(cookie))
except (binascii.Error, TypeError):
token = utf8(cookie)
# We don't have a usable timestamp in older versions.
timestamp = int(time.time())
return (version, token, timestamp)
except Exception:
# Catch exceptions and return nothing instead of failing.
gen_log.debug("Uncaught exception in _decode_xsrf_token",
exc_info=True)
return None, None, None
def check_xsrf_cookie(self):
"""Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
reject the form submission as a potential forgery.
The ``_xsrf`` value may be set as either a form field named ``_xsrf``
or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
(the latter is accepted for compatibility with Django).
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
Prior to release 1.1.1, this check was ignored if the HTTP header
``X-Requested-With: XMLHTTPRequest`` was present. This exception
has been shown to be insecure and has been removed. For more
information please see
http://www.djangoproject.com/weblog/2011/feb/08/security/
http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
.. versionchanged:: 3.2.2
Added support for cookie version 2. Both versions 1 and 2 are
supported.
"""
token = (self.get_argument("_xsrf", None) or
self.request.headers.get("X-Xsrftoken") or
self.request.headers.get("X-Csrftoken"))
if not token:
raise HTTPError(403, "'_xsrf' argument missing from POST")
_, token, _ = self._decode_xsrf_token(token)
_, expected_token, _ = self._get_raw_xsrf_token()
if not _time_independent_equals(utf8(token), utf8(expected_token)):
raise HTTPError(403, "XSRF cookie does not match POST argument")
def xsrf_form_html(self):
"""An HTML ``<input/>`` element to be included with all POST forms.
It defines the ``_xsrf`` input value, which we check on all POST
requests to prevent cross-site request forgery. If you have set
the ``xsrf_cookies`` application setting, you must include this
HTML within all of your HTML forms.
In a template, this method should be called with ``{% module
xsrf_form_html() %}``
See `check_xsrf_cookie()` above for more information.
"""
return '<input type="hidden" name="_xsrf" value="' + \
escape.xhtml_escape(self.xsrf_token) + '"/>'
def static_url(self, path, include_host=None, **kwargs):
"""Returns a static URL for the given relative static file path.
This method requires you set the ``static_path`` setting in your
application (which specifies the root directory of your static
files).
This method returns a versioned url (by default appending
``?v=<signature>``), which allows the static files to be
cached indefinitely. This can be disabled by passing
``include_version=False`` (in the default implementation;
other static file implementations are not required to support
this, but they may support other options).
By default this method returns URLs relative to the current
host, but if ``include_host`` is true the URL returned will be
absolute. If this handler has an ``include_host`` attribute,
that value will be used as the default for all `static_url`
calls that do not pass ``include_host`` as a keyword argument.
"""
self.require_setting("static_path", "static_url")
get_url = self.settings.get("static_handler_class",
StaticFileHandler).make_static_url
if include_host is None:
include_host = getattr(self, "include_host", False)
if include_host:
base = self.request.protocol + "://" + self.request.host
else:
base = ""
return base + get_url(self.settings, path, **kwargs)
def require_setting(self, name, feature="this feature"):
"""Raises an exception if the given app setting is not defined."""
if not self.application.settings.get(name):
raise Exception("You must define the '%s' setting in your "
"application to use %s" % (name, feature))
def reverse_url(self, name, *args):
"""Alias for `Application.reverse_url`."""
return self.application.reverse_url(name, *args)
def compute_etag(self):
"""Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations,
or may return None to disable tornado's default etag support.
"""
hasher = hashlib.sha1()
for part in self._write_buffer:
hasher.update(part)
return '"%s"' % hasher.hexdigest()
def set_etag_header(self):
"""Sets the response's Etag header using ``self.compute_etag()``.
Note: no header will be set if ``compute_etag()`` returns ``None``.
This method is called automatically when the request is finished.
"""
etag = self.compute_etag()
if etag is not None:
self.set_header("Etag", etag)
def check_etag_header(self):
"""Checks the ``Etag`` header against requests's ``If-None-Match``.
Returns ``True`` if the request's Etag matches and a 304 should be
returned. For example::
self.set_etag_header()
if self.check_etag_header():
self.set_status(304)
return
This method is called automatically when the request is finished,
but may be called earlier for applications that override
`compute_etag` and want to do an early check for ``If-None-Match``
before completing the request. The ``Etag`` header should be set
(perhaps with `set_etag_header`) before calling this method.
"""
computed_etag = utf8(self._headers.get("Etag", ""))
# Find all weak and strong etag values from If-None-Match header
# because RFC 7232 allows multiple etag values in a single header.
etags = re.findall(
br'\*|(?:W/)?"[^"]*"',
utf8(self.request.headers.get("If-None-Match", ""))
)
if not computed_etag or not etags:
return False
match = False
if etags[0] == b'*':
match = True
else:
# Use a weak comparison when comparing entity-tags.
val = lambda x: x[2:] if x.startswith(b'W/') else x
for etag in etags:
if val(etag) == val(computed_etag):
match = True
break
return match
def _stack_context_handle_exception(self, type, value, traceback):
try:
# For historical reasons _handle_request_exception only takes
# the exception value instead of the full triple,
# so re-raise the exception to ensure that it's in
# sys.exc_info()
raise_exc_info((type, value, traceback))
except Exception:
self._handle_request_exception(value)
return True
@gen.coroutine
def _execute(self, transforms, *args, **kwargs):
"""Executes this request with the given output transforms."""
self._transforms = transforms
try:
if self.request.method not in self.SUPPORTED_METHODS:
raise HTTPError(405)
self.path_args = [self.decode_argument(arg) for arg in args]
self.path_kwargs = dict((k, self.decode_argument(v, name=k))
for (k, v) in kwargs.items())
# If XSRF cookies are turned on, reject form submissions without
# the proper cookie
if self.request.method not in ("GET", "HEAD", "OPTIONS") and \
self.application.settings.get("xsrf_cookies"):
self.check_xsrf_cookie()
result = self.prepare()
if result is not None:
result = yield result
if self._prepared_future is not None:
# Tell the Application we've finished with prepare()
# and are ready for the body to arrive.
self._prepared_future.set_result(None)
if self._finished:
return
if _has_stream_request_body(self.__class__):
# In streaming mode request.body is a Future that signals
# the body has been completely received. The Future has no
# result; the data has been passed to self.data_received
# instead.
try:
yield self.request.body
except iostream.StreamClosedError:
return
method = getattr(self, self.request.method.lower())
result = method(*self.path_args, **self.path_kwargs)
if result is not None:
result = yield result
if self._auto_finish and not self._finished:
self.finish()
except Exception as e:
try:
self._handle_request_exception(e)
except Exception:
app_log.error("Exception in exception handler", exc_info=True)
if (self._prepared_future is not None and
not self._prepared_future.done()):
# In case we failed before setting _prepared_future, do it
# now (to unblock the HTTP server). Note that this is not
# in a finally block to avoid GC issues prior to Python 3.4.
self._prepared_future.set_result(None)
def data_received(self, chunk):
"""Implement this method to handle streamed request data.
Requires the `.stream_request_body` decorator.
"""
raise NotImplementedError()
def _log(self):
"""Logs the current request.
Sort of deprecated since this functionality was moved to the
Application, but left in place for the benefit of existing apps
that have overridden this method.
"""
self.application.log_request(self)
def _request_summary(self):
return "%s %s (%s)" % (self.request.method, self.request.uri,
self.request.remote_ip)
def _handle_request_exception(self, e):
if isinstance(e, Finish):
# Not an error; just finish the request without logging.
if not self._finished:
self.finish()
return
try:
self.log_exception(*sys.exc_info())
except Exception:
# An error here should still get a best-effort send_error()
# to avoid leaking the connection.
app_log.error("Error in exception logger", exc_info=True)
if self._finished:
# Extra errors after the request has been finished should
# be logged, but there is no reason to continue to try and
# send a response.
return
if isinstance(e, HTTPError):
if e.status_code not in httputil.responses and not e.reason:
gen_log.error("Bad HTTP status code: %d", e.status_code)
self.send_error(500, exc_info=sys.exc_info())
else:
self.send_error(e.status_code, exc_info=sys.exc_info())
else:
self.send_error(500, exc_info=sys.exc_info())
def log_exception(self, typ, value, tb):
"""Override to customize logging of uncaught exceptions.
By default logs instances of `HTTPError` as warnings without
stack traces (on the ``tornado.general`` logger), and all
other exceptions as errors with stack traces (on the
``tornado.application`` logger).
.. versionadded:: 3.1
"""
if isinstance(value, HTTPError):
if value.log_message:
format = "%d %s: " + value.log_message
args = ([value.status_code, self._request_summary()] +
list(value.args))
gen_log.warning(format, *args)
else:
app_log.error("Uncaught exception %s\n%r", self._request_summary(),
self.request, exc_info=(typ, value, tb))
def _ui_module(self, name, module):
def render(*args, **kwargs):
if not hasattr(self, "_active_modules"):
self._active_modules = {}
if name not in self._active_modules:
self._active_modules[name] = module(self)
rendered = self._active_modules[name].render(*args, **kwargs)
return rendered
return render
def _ui_method(self, method):
return lambda *args, **kwargs: method(self, *args, **kwargs)
def _clear_headers_for_304(self):
# 304 responses should not contain entity headers (defined in
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
# not explicitly allowed by
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
headers = ["Allow", "Content-Encoding", "Content-Language",
"Content-Length", "Content-MD5", "Content-Range",
"Content-Type", "Last-Modified"]
for h in headers:
self.clear_header(h)
def asynchronous(method):
"""Wrap request handler methods with this if they are asynchronous.
This decorator is for callback-style asynchronous methods; for
coroutines, use the ``@gen.coroutine`` decorator without
``@asynchronous``. (It is legal for legacy reasons to use the two
decorators together provided ``@asynchronous`` is first, but
``@asynchronous`` will be ignored in this case)
This decorator should only be applied to the :ref:`HTTP verb
methods <verbs>`; its behavior is undefined for any other method.
This decorator does not *make* a method asynchronous; it tells
the framework that the method *is* asynchronous. For this decorator
to be useful the method must (at least sometimes) do something
asynchronous.
If this decorator is given, the response is not finished when the
method returns. It is up to the request handler to call
`self.finish() <RequestHandler.finish>` to finish the HTTP
request. Without this decorator, the request is automatically
finished when the ``get()`` or ``post()`` method returns. Example:
.. testcode::
class MyRequestHandler(RequestHandler):
@asynchronous
def get(self):
http = httpclient.AsyncHTTPClient()
http.fetch("http://friendfeed.com/", self._on_download)
def _on_download(self, response):
self.write("Downloaded!")
self.finish()
.. testoutput::
:hide:
.. versionadded:: 3.1
The ability to use ``@gen.coroutine`` without ``@asynchronous``.
"""
# Delay the IOLoop import because it's not available on app engine.
from tornado.ioloop import IOLoop
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
self._auto_finish = False
with stack_context.ExceptionStackContext(
self._stack_context_handle_exception):
result = method(self, *args, **kwargs)
if is_future(result):
# If @asynchronous is used with @gen.coroutine, (but
# not @gen.engine), we can automatically finish the
# request when the future resolves. Additionally,
# the Future will swallow any exceptions so we need
# to throw them back out to the stack context to finish
# the request.
def future_complete(f):
f.result()
if not self._finished:
self.finish()
IOLoop.current().add_future(result, future_complete)
# Once we have done this, hide the Future from our
# caller (i.e. RequestHandler._when_complete), which
# would otherwise set up its own callback and
# exception handler (resulting in exceptions being
# logged twice).
return None
return result
return wrapper
def stream_request_body(cls):
"""Apply to `RequestHandler` subclasses to enable streaming body support.
This decorator implies the following changes:
* `.HTTPServerRequest.body` is undefined, and body arguments will not
be included in `RequestHandler.get_argument`.
* `RequestHandler.prepare` is called when the request headers have been
read instead of after the entire body has been read.
* The subclass must define a method ``data_received(self, data):``, which
will be called zero or more times as data is available. Note that
if the request has an empty body, ``data_received`` may not be called.
* ``prepare`` and ``data_received`` may return Futures (such as via
``@gen.coroutine``, in which case the next method will not be called
until those futures have completed.
* The regular HTTP method (``post``, ``put``, etc) will be called after
the entire body has been read.
There is a subtle interaction between ``data_received`` and asynchronous
``prepare``: The first call to ``data_received`` may occur at any point
after the call to ``prepare`` has returned *or yielded*.
"""
if not issubclass(cls, RequestHandler):
raise TypeError("expected subclass of RequestHandler, got %r", cls)
cls._stream_request_body = True
return cls
def _has_stream_request_body(cls):
if not issubclass(cls, RequestHandler):
raise TypeError("expected subclass of RequestHandler, got %r", cls)
return getattr(cls, '_stream_request_body', False)
def removeslash(method):
"""Use this decorator to remove trailing slashes from the request path.
For example, a request to ``/foo/`` would redirect to ``/foo`` with this
decorator. Your request handler mapping should use a regular expression
like ``r'/foo/*'`` in conjunction with using the decorator.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if self.request.path.endswith("/"):
if self.request.method in ("GET", "HEAD"):
uri = self.request.path.rstrip("/")
if uri: # don't try to redirect '/' to ''
if self.request.query:
uri += "?" + self.request.query
self.redirect(uri, permanent=True)
return
else:
raise HTTPError(404)
return method(self, *args, **kwargs)
return wrapper
def addslash(method):
"""Use this decorator to add a missing trailing slash to the request path.
For example, a request to ``/foo`` would redirect to ``/foo/`` with this
decorator. Your request handler mapping should use a regular expression
|
[
" like ``r'/foo/?'`` in conjunction with using the decorator."
] | 6,502
|
lcc
|
python
| null |
d5dde130982bcbe6f095c65d1d5a928669bc3a458df26cc6
| 24
|
Your task is code completion.
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""``tornado.web`` provides a simple web framework with asynchronous
features that allow it to scale to large numbers of open connections,
making it ideal for `long polling
<http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.
Here is a simple "Hello, world" example app:
.. testcode::
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
.. testoutput::
:hide:
See the :doc:`guide` for additional information.
Thread-safety notes
-------------------
In general, methods on `RequestHandler` and elsewhere in Tornado are
not thread-safe. In particular, methods such as
`~RequestHandler.write()`, `~RequestHandler.finish()`, and
`~RequestHandler.flush()` must only be called from the main thread. If
you use multiple threads it is important to use `.IOLoop.add_callback`
to transfer control back to the main thread before finishing the
request.
"""
from __future__ import (absolute_import, division,
print_function, with_statement)
import base64
import binascii
import datetime
import email.utils
import functools
import gzip
import hashlib
import hmac
import mimetypes
import numbers
import os.path
import re
import stat
import sys
import threading
import time
import tornado
import traceback
import types
from io import BytesIO
from tornado.concurrent import Future, is_future
from tornado import escape
from tornado import gen
from tornado import httputil
from tornado import iostream
from tornado import locale
from tornado.log import access_log, app_log, gen_log
from tornado import stack_context
from tornado import template
from tornado.escape import utf8, _unicode
from tornado.util import (import_object, ObjectDict, raise_exc_info,
unicode_type, _websocket_mask)
from tornado.httputil import split_host_and_port
try:
import Cookie # py2
except ImportError:
import http.cookies as Cookie # py3
try:
import urlparse # py2
except ImportError:
import urllib.parse as urlparse # py3
try:
from urllib import urlencode # py2
except ImportError:
from urllib.parse import urlencode # py3
MIN_SUPPORTED_SIGNED_VALUE_VERSION = 1
"""The oldest signed value version supported by this version of Tornado.
Signed values older than this version cannot be decoded.
.. versionadded:: 3.2.1
"""
MAX_SUPPORTED_SIGNED_VALUE_VERSION = 2
"""The newest signed value version supported by this version of Tornado.
Signed values newer than this version cannot be decoded.
.. versionadded:: 3.2.1
"""
DEFAULT_SIGNED_VALUE_VERSION = 2
"""The signed value version produced by `.RequestHandler.create_signed_value`.
May be overridden by passing a ``version`` keyword argument.
.. versionadded:: 3.2.1
"""
DEFAULT_SIGNED_VALUE_MIN_VERSION = 1
"""The oldest signed value accepted by `.RequestHandler.get_secure_cookie`.
May be overridden by passing a ``min_version`` keyword argument.
.. versionadded:: 3.2.1
"""
class RequestHandler(object):
"""Base class for HTTP request handlers.
Subclasses must define at least one of the methods defined in the
"Entry points" section below.
"""
SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT",
"OPTIONS")
_template_loaders = {} # {path: template.BaseLoader}
_template_loader_lock = threading.Lock()
_remove_control_chars_regex = re.compile(r"[\x00-\x08\x0e-\x1f]")
def __init__(self, application, request, **kwargs):
super(RequestHandler, self).__init__()
self.application = application
self.request = request
self._headers_written = False
self._finished = False
self._auto_finish = True
self._transforms = None # will be set in _execute
self._prepared_future = None
self.path_args = None
self.path_kwargs = None
self.ui = ObjectDict((n, self._ui_method(m)) for n, m in
application.ui_methods.items())
# UIModules are available as both `modules` and `_tt_modules` in the
# template namespace. Historically only `modules` was available
# but could be clobbered by user additions to the namespace.
# The template {% module %} directive looks in `_tt_modules` to avoid
# possible conflicts.
self.ui["_tt_modules"] = _UIModuleNamespace(self,
application.ui_modules)
self.ui["modules"] = self.ui["_tt_modules"]
self.clear()
self.request.connection.set_close_callback(self.on_connection_close)
self.initialize(**kwargs)
def initialize(self):
"""Hook for subclass initialization.
A dictionary passed as the third argument of a url spec will be
supplied as keyword arguments to initialize().
Example::
class ProfileHandler(RequestHandler):
def initialize(self, database):
self.database = database
def get(self, username):
...
app = Application([
(r'/user/(.*)', ProfileHandler, dict(database=database)),
])
"""
pass
@property
def settings(self):
"""An alias for `self.application.settings <Application.settings>`."""
return self.application.settings
def head(self, *args, **kwargs):
raise HTTPError(405)
def get(self, *args, **kwargs):
raise HTTPError(405)
def post(self, *args, **kwargs):
raise HTTPError(405)
def delete(self, *args, **kwargs):
raise HTTPError(405)
def patch(self, *args, **kwargs):
raise HTTPError(405)
def put(self, *args, **kwargs):
raise HTTPError(405)
def options(self, *args, **kwargs):
raise HTTPError(405)
def prepare(self):
"""Called at the beginning of a request before `get`/`post`/etc.
Override this method to perform common initialization regardless
of the request method.
Asynchronous support: Decorate this method with `.gen.coroutine`
or `.return_future` to make it asynchronous (the
`asynchronous` decorator cannot be used on `prepare`).
If this method returns a `.Future` execution will not proceed
until the `.Future` is done.
.. versionadded:: 3.1
Asynchronous support.
"""
pass
def on_finish(self):
"""Called after the end of a request.
Override this method to perform cleanup, logging, etc.
This method is a counterpart to `prepare`. ``on_finish`` may
not produce any output, as it is called after the response
has been sent to the client.
"""
pass
def on_connection_close(self):
"""Called in async handlers if the client closed the connection.
Override this to clean up resources associated with
long-lived connections. Note that this method is called only if
the connection was closed during asynchronous processing; if you
need to do cleanup after every request override `on_finish`
instead.
Proxies may keep a connection open for a time (perhaps
indefinitely) after the client has gone away, so this method
may not be called promptly after the end user closes their
connection.
"""
if _has_stream_request_body(self.__class__):
if not self.request.body.done():
self.request.body.set_exception(iostream.StreamClosedError())
self.request.body.exception()
def clear(self):
"""Resets all headers and content for this response."""
self._headers = httputil.HTTPHeaders({
"Server": "TornadoServer/%s" % tornado.version,
"Content-Type": "text/html; charset=UTF-8",
"Date": httputil.format_timestamp(time.time()),
})
self.set_default_headers()
self._write_buffer = []
self._status_code = 200
self._reason = httputil.responses[200]
def set_default_headers(self):
"""Override this to set HTTP headers at the beginning of the request.
For example, this is the place to set a custom ``Server`` header.
Note that setting such headers in the normal flow of request
processing may not do what you want, since headers may be reset
during error handling.
"""
pass
def set_status(self, status_code, reason=None):
"""Sets the status code for our response.
:arg int status_code: Response status code. If ``reason`` is ``None``,
it must be present in `httplib.responses <http.client.responses>`.
:arg string reason: Human-readable reason phrase describing the status
code. If ``None``, it will be filled in from
`httplib.responses <http.client.responses>`.
"""
self._status_code = status_code
if reason is not None:
self._reason = escape.native_str(reason)
else:
try:
self._reason = httputil.responses[status_code]
except KeyError:
raise ValueError("unknown status code %d", status_code)
def get_status(self):
"""Returns the status code for our response."""
return self._status_code
def set_header(self, name, value):
"""Sets the given response header name and value.
If a datetime is given, we automatically format it according to the
HTTP specification. If the value is not a string, we convert it to
a string. All header values are then encoded as UTF-8.
"""
self._headers[name] = self._convert_header_value(value)
def add_header(self, name, value):
"""Adds the given response header and value.
Unlike `set_header`, `add_header` may be called multiple times
to return multiple values for the same header.
"""
self._headers.add(name, self._convert_header_value(value))
def clear_header(self, name):
"""Clears an outgoing header, undoing a previous `set_header` call.
Note that this method does not apply to multi-valued headers
set by `add_header`.
"""
if name in self._headers:
del self._headers[name]
_INVALID_HEADER_CHAR_RE = re.compile(br"[\x00-\x1f]")
def _convert_header_value(self, value):
if isinstance(value, bytes):
pass
elif isinstance(value, unicode_type):
value = value.encode('utf-8')
elif isinstance(value, numbers.Integral):
# return immediately since we know the converted value will be safe
return str(value)
elif isinstance(value, datetime.datetime):
return httputil.format_timestamp(value)
else:
raise TypeError("Unsupported header value %r" % value)
# If \n is allowed into the header, it is possible to inject
# additional headers or split the request.
if RequestHandler._INVALID_HEADER_CHAR_RE.search(value):
raise ValueError("Unsafe header value %r", value)
return value
_ARG_DEFAULT = []
def get_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
"""
return self._get_argument(name, default, self.request.arguments, strip)
def get_arguments(self, name, strip=True):
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
"""
# Make sure `get_arguments` isn't accidentally being called with a
# positional argument that's assumed to be a default (like in
# `get_argument`.)
assert isinstance(strip, bool)
return self._get_arguments(name, self.request.arguments, strip)
def get_body_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name
from the request body.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
.. versionadded:: 3.2
"""
return self._get_argument(name, default, self.request.body_arguments,
strip)
def get_body_arguments(self, name, strip=True):
"""Returns a list of the body arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
.. versionadded:: 3.2
"""
return self._get_arguments(name, self.request.body_arguments, strip)
def get_query_argument(self, name, default=_ARG_DEFAULT, strip=True):
"""Returns the value of the argument with the given name
from the request query string.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the url more than once, we return the
last value.
The returned value is always unicode.
.. versionadded:: 3.2
"""
return self._get_argument(name, default,
self.request.query_arguments, strip)
def get_query_arguments(self, name, strip=True):
"""Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
.. versionadded:: 3.2
"""
return self._get_arguments(name, self.request.query_arguments, strip)
def _get_argument(self, name, default, source, strip=True):
args = self._get_arguments(name, source, strip=strip)
if not args:
if default is self._ARG_DEFAULT:
raise MissingArgumentError(name)
return default
return args[-1]
def _get_arguments(self, name, source, strip=True):
values = []
for v in source.get(name, []):
v = self.decode_argument(v, name=name)
if isinstance(v, unicode_type):
# Get rid of any weird control chars (unless decoding gave
# us bytes, in which case leave it alone)
v = RequestHandler._remove_control_chars_regex.sub(" ", v)
if strip:
v = v.strip()
values.append(v)
return values
def decode_argument(self, value, name=None):
"""Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string.
By default, this method decodes the argument as utf-8 and returns
a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both `get_argument()` and for
values extracted from the url and passed to `get()`/`post()`/etc.
The name of the argument is provided if known, but may be None
(e.g. for unnamed groups in the url regex).
"""
try:
return _unicode(value)
except UnicodeDecodeError:
raise HTTPError(400, "Invalid unicode in %s: %r" %
(name or "url", value[:40]))
@property
def cookies(self):
"""An alias for
`self.request.cookies <.httputil.HTTPServerRequest.cookies>`."""
return self.request.cookies
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if self.request.cookies is not None and name in self.request.cookies:
return self.request.cookies[name].value
return default
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
# The cookie library only accepts type str, in both python 2 and 3
name = escape.native_str(name)
value = escape.native_str(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookie"):
self._new_cookie = Cookie.SimpleCookie()
if name in self._new_cookie:
del self._new_cookie[name]
self._new_cookie[name] = value
morsel = self._new_cookie[name]
if domain:
morsel["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(
days=expires_days)
if expires:
morsel["expires"] = httputil.format_timestamp(expires)
if path:
morsel["path"] = path
for k, v in kwargs.items():
if k == 'max_age':
k = 'max-age'
# skip falsy values for httponly and secure flags because
# SimpleCookie sets them regardless
if k in ['httponly', 'secure'] and not v:
continue
morsel[k] = v
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name.
Due to limitations of the cookie protocol, you must pass the same
path and domain to clear a cookie as were used when that cookie
was set (but there is no way to find out on the server side
which values were used for a given cookie).
"""
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
self.set_cookie(name, value="", path=path, expires=expires,
domain=domain)
def clear_all_cookies(self, path="/", domain=None):
"""Deletes all the cookies the user sent with this request.
See `clear_cookie` for more information on the path and domain
parameters.
.. versionchanged:: 3.2
Added the ``path`` and ``domain`` parameters.
"""
for name in self.request.cookies:
self.clear_cookie(name, path=path, domain=domain)
def set_secure_cookie(self, name, value, expires_days=30, version=None,
**kwargs):
"""Signs and timestamps a cookie so it cannot be forged.
You must specify the ``cookie_secret`` setting in your Application
to use this method. It should be a long, random sequence of bytes
to be used as the HMAC secret for the signature.
To read a cookie set with this method, use `get_secure_cookie()`.
Note that the ``expires_days`` parameter sets the lifetime of the
cookie in the browser, but is independent of the ``max_age_days``
parameter to `get_secure_cookie`.
Secure cookies may contain arbitrary byte values, not just unicode
strings (unlike regular cookies)
.. versionchanged:: 3.2.1
Added the ``version`` argument. Introduced cookie version 2
and made it the default.
"""
self.set_cookie(name, self.create_signed_value(name, value,
version=version),
expires_days=expires_days, **kwargs)
def create_signed_value(self, name, value, version=None):
"""Signs and timestamps a string so it cannot be forged.
Normally used via set_secure_cookie, but provided as a separate
method for non-cookie uses. To decode a value not stored
as a cookie use the optional value argument to get_secure_cookie.
.. versionchanged:: 3.2.1
Added the ``version`` argument. Introduced cookie version 2
and made it the default.
"""
self.require_setting("cookie_secret", "secure cookies")
secret = self.application.settings["cookie_secret"]
key_version = None
if isinstance(secret, dict):
if self.application.settings.get("key_version") is None:
raise Exception("key_version setting must be used for secret_key dicts")
key_version = self.application.settings["key_version"]
return create_signed_value(secret, name, value, version=version,
key_version=key_version)
def get_secure_cookie(self, name, value=None, max_age_days=31,
min_version=None):
"""Returns the given signed cookie if it validates, or None.
The decoded cookie value is returned as a byte string (unlike
`get_cookie`).
.. versionchanged:: 3.2.1
Added the ``min_version`` argument. Introduced cookie version 2;
both versions 1 and 2 are accepted by default.
"""
self.require_setting("cookie_secret", "secure cookies")
if value is None:
value = self.get_cookie(name)
return decode_signed_value(self.application.settings["cookie_secret"],
name, value, max_age_days=max_age_days,
min_version=min_version)
def get_secure_cookie_key_version(self, name, value=None):
"""Returns the signing key version of the secure cookie.
The version is returned as int.
"""
self.require_setting("cookie_secret", "secure cookies")
if value is None:
value = self.get_cookie(name)
return get_signature_key_version(value)
def redirect(self, url, permanent=False, status=None):
"""Sends a redirect to the given (optionally relative) URL.
If the ``status`` argument is specified, that value is used as the
HTTP status code; otherwise either 301 (permanent) or 302
(temporary) is chosen based on the ``permanent`` argument.
The default is 302 (temporary).
"""
if self._headers_written:
raise Exception("Cannot redirect after headers have been written")
if status is None:
status = 301 if permanent else 302
else:
assert isinstance(status, int) and 300 <= status <= 399
self.set_status(status)
self.set_header("Location", utf8(url))
self.finish()
def write(self, chunk):
"""Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be ``application/json``.
(if you want to send JSON as a different ``Content-Type``, call
set_header *after* calling write()).
Note that lists are not converted to JSON because of a potential
cross-site security vulnerability. All JSON output should be
wrapped in a dictionary. More details at
http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and
https://github.com/facebook/tornado/issues/1009
"""
if self._finished:
raise RuntimeError("Cannot write() after finish()")
if not isinstance(chunk, (bytes, unicode_type, dict)):
message = "write() only accepts bytes, unicode, and dict objects"
if isinstance(chunk, list):
message += ". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
raise TypeError(message)
if isinstance(chunk, dict):
if 'unwrap_json' in chunk:
chunk = chunk['unwrap_json']
else:
chunk = escape.json_encode(chunk)
self.set_header("Content-Type", "application/json; charset=UTF-8")
chunk = utf8(chunk)
self._write_buffer.append(chunk)
def render(self, template_name, **kwargs):
"""Renders the template with the given arguments as the response."""
html = self.render_string(template_name, **kwargs)
# Insert the additional JS and CSS added by the modules on the page
js_embed = []
js_files = []
css_embed = []
css_files = []
html_heads = []
html_bodies = []
for module in getattr(self, "_active_modules", {}).values():
embed_part = module.embedded_javascript()
if embed_part:
js_embed.append(utf8(embed_part))
file_part = module.javascript_files()
if file_part:
if isinstance(file_part, (unicode_type, bytes)):
js_files.append(file_part)
else:
js_files.extend(file_part)
embed_part = module.embedded_css()
if embed_part:
css_embed.append(utf8(embed_part))
file_part = module.css_files()
if file_part:
if isinstance(file_part, (unicode_type, bytes)):
css_files.append(file_part)
else:
css_files.extend(file_part)
head_part = module.html_head()
if head_part:
html_heads.append(utf8(head_part))
body_part = module.html_body()
if body_part:
html_bodies.append(utf8(body_part))
def is_absolute(path):
return any(path.startswith(x) for x in ["/", "http:", "https:"])
if js_files:
# Maintain order of JavaScript files given by modules
paths = []
unique_paths = set()
for path in js_files:
if not is_absolute(path):
path = self.static_url(path)
if path not in unique_paths:
paths.append(path)
unique_paths.add(path)
js = ''.join('<script src="' + escape.xhtml_escape(p) +
'" type="text/javascript"></script>'
for p in paths)
sloc = html.rindex(b'</body>')
html = html[:sloc] + utf8(js) + b'\n' + html[sloc:]
if js_embed:
js = b'<script type="text/javascript">\n//<![CDATA[\n' + \
b'\n'.join(js_embed) + b'\n//]]>\n</script>'
sloc = html.rindex(b'</body>')
html = html[:sloc] + js + b'\n' + html[sloc:]
if css_files:
paths = []
unique_paths = set()
for path in css_files:
if not is_absolute(path):
path = self.static_url(path)
if path not in unique_paths:
paths.append(path)
unique_paths.add(path)
css = ''.join('<link href="' + escape.xhtml_escape(p) + '" '
'type="text/css" rel="stylesheet"/>'
for p in paths)
hloc = html.index(b'</head>')
html = html[:hloc] + utf8(css) + b'\n' + html[hloc:]
if css_embed:
css = b'<style type="text/css">\n' + b'\n'.join(css_embed) + \
b'\n</style>'
hloc = html.index(b'</head>')
html = html[:hloc] + css + b'\n' + html[hloc:]
if html_heads:
hloc = html.index(b'</head>')
html = html[:hloc] + b''.join(html_heads) + b'\n' + html[hloc:]
if html_bodies:
hloc = html.index(b'</body>')
html = html[:hloc] + b''.join(html_bodies) + b'\n' + html[hloc:]
self.finish(html)
def render_string(self, template_name, **kwargs):
"""Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate and
write a template as a response, use render() above.
"""
# If no template_path is specified, use the path of the calling file
template_path = self.get_template_path()
if not template_path:
frame = sys._getframe(0)
web_file = frame.f_code.co_filename
while frame.f_code.co_filename == web_file:
frame = frame.f_back
template_path = os.path.dirname(frame.f_code.co_filename)
with RequestHandler._template_loader_lock:
if template_path not in RequestHandler._template_loaders:
loader = self.create_template_loader(template_path)
RequestHandler._template_loaders[template_path] = loader
else:
loader = RequestHandler._template_loaders[template_path]
t = loader.load(template_name)
namespace = self.get_template_namespace()
namespace.update(kwargs)
return t.generate(**namespace)
def get_template_namespace(self):
"""Returns a dictionary to be used as the default template namespace.
May be overridden by subclasses to add or modify values.
The results of this method will be combined with additional
defaults in the `tornado.template` module and keyword arguments
to `render` or `render_string`.
"""
namespace = dict(
handler=self,
request=self.request,
current_user=self.current_user,
locale=self.locale,
_=self.locale.translate,
pgettext=self.locale.pgettext,
static_url=self.static_url,
xsrf_form_html=self.xsrf_form_html,
reverse_url=self.reverse_url
)
namespace.update(self.ui)
return namespace
def create_template_loader(self, template_path):
"""Returns a new template loader for the given path.
May be overridden by subclasses. By default returns a
directory-based loader on the given path, using the
``autoescape`` and ``template_whitespace`` application
settings. If a ``template_loader`` application setting is
supplied, uses that instead.
"""
settings = self.application.settings
if "template_loader" in settings:
return settings["template_loader"]
kwargs = {}
if "autoescape" in settings:
# autoescape=None means "no escaping", so we have to be sure
# to only pass this kwarg if the user asked for it.
kwargs["autoescape"] = settings["autoescape"]
if "template_whitespace" in settings:
kwargs["whitespace"] = settings["template_whitespace"]
return template.Loader(template_path, **kwargs)
def flush(self, include_footers=False, callback=None):
"""Flushes the current output buffer to the network.
The ``callback`` argument, if given, can be used for flow control:
it will be run when all flushed data has been written to the socket.
Note that only one flush callback can be outstanding at a time;
if another flush occurs before the previous flush's callback
has been run, the previous callback will be discarded.
.. versionchanged:: 4.0
Now returns a `.Future` if no callback is given.
"""
chunk = b"".join(self._write_buffer)
self._write_buffer = []
if not self._headers_written:
self._headers_written = True
for transform in self._transforms:
self._status_code, self._headers, chunk = \
transform.transform_first_chunk(
self._status_code, self._headers,
chunk, include_footers)
# Ignore the chunk and only write the headers for HEAD requests
if self.request.method == "HEAD":
chunk = None
# Finalize the cookie headers (which have been stored in a side
# object so an outgoing cookie could be overwritten before it
# is sent).
if hasattr(self, "_new_cookie"):
for cookie in self._new_cookie.values():
self.add_header("Set-Cookie", cookie.OutputString(None))
start_line = httputil.ResponseStartLine('',
self._status_code,
self._reason)
return self.request.connection.write_headers(
start_line, self._headers, chunk, callback=callback)
else:
for transform in self._transforms:
chunk = transform.transform_chunk(chunk, include_footers)
# Ignore the chunk and only write the headers for HEAD requests
if self.request.method != "HEAD":
return self.request.connection.write(chunk, callback=callback)
else:
future = Future()
future.set_result(None)
return future
def finish(self, chunk=None):
"""Finishes this response, ending the HTTP request."""
if self._finished:
raise RuntimeError("finish() called twice")
if chunk is not None:
self.write(chunk)
# Automatically support ETags and add the Content-Length header if
# we have not flushed any content yet.
if not self._headers_written:
if (self._status_code == 200 and
self.request.method in ("GET", "HEAD") and
"Etag" not in self._headers):
self.set_etag_header()
if self.check_etag_header():
self._write_buffer = []
self.set_status(304)
if self._status_code == 304:
assert not self._write_buffer, "Cannot send body with 304"
self._clear_headers_for_304()
elif "Content-Length" not in self._headers:
content_length = sum(len(part) for part in self._write_buffer)
self.set_header("Content-Length", content_length)
if hasattr(self.request, "connection"):
# Now that the request is finished, clear the callback we
# set on the HTTPConnection (which would otherwise prevent the
# garbage collection of the RequestHandler when there
# are keepalive connections)
self.request.connection.set_close_callback(None)
self.flush(include_footers=True)
self.request.finish()
self._log()
self._finished = True
self.on_finish()
# Break up a reference cycle between this handler and the
# _ui_module closures to allow for faster GC on CPython.
self.ui = None
def send_error(self, status_code=500, **kwargs):
"""Sends the given HTTP error code to the browser.
If `flush()` has already been called, it is not possible to send
an error, so this method will simply terminate the response.
If output has been written but not yet flushed, it will be discarded
and replaced with the error page.
Override `write_error()` to customize the error page that is returned.
Additional keyword arguments are passed through to `write_error`.
"""
if self._headers_written:
gen_log.error("Cannot send error response after headers written")
if not self._finished:
# If we get an error between writing headers and finishing,
# we are unlikely to be able to finish due to a
# Content-Length mismatch. Try anyway to release the
# socket.
try:
self.finish()
except Exception:
gen_log.error("Failed to flush partial response",
exc_info=True)
return
self.clear()
reason = kwargs.get('reason')
if 'exc_info' in kwargs:
exception = kwargs['exc_info'][1]
if isinstance(exception, HTTPError) and exception.reason:
reason = exception.reason
self.set_status(status_code, reason=reason)
try:
self.write_error(status_code, **kwargs)
except Exception:
app_log.error("Uncaught exception in write_error", exc_info=True)
if not self._finished:
self.finish()
def write_error(self, status_code, **kwargs):
"""Override to implement custom error pages.
``write_error`` may call `write`, `render`, `set_header`, etc
to produce output as usual.
If this error was caused by an uncaught exception (including
HTTPError), an ``exc_info`` triple will be available as
``kwargs["exc_info"]``. Note that this exception may not be
the "current" exception for purposes of methods like
``sys.exc_info()`` or ``traceback.format_exc``.
"""
if self.settings.get("serve_traceback") and "exc_info" in kwargs:
# in debug mode, try to send a traceback
self.set_header('Content-Type', 'text/plain')
for line in traceback.format_exception(*kwargs["exc_info"]):
self.write(line)
self.finish()
else:
self.finish("<html><title>%(code)d: %(message)s</title>"
"<body>%(code)d: %(message)s</body></html>" % {
"code": status_code,
"message": self._reason,
})
@property
def locale(self):
"""The locale for the current session.
Determined by either `get_user_locale`, which you can override to
set the locale based on, e.g., a user preference stored in a
database, or `get_browser_locale`, which uses the ``Accept-Language``
header.
.. versionchanged: 4.1
Added a property setter.
"""
if not hasattr(self, "_locale"):
self._locale = self.get_user_locale()
if not self._locale:
self._locale = self.get_browser_locale()
assert self._locale
return self._locale
@locale.setter
def locale(self, value):
self._locale = value
def get_user_locale(self):
"""Override to determine the locale from the authenticated user.
If None is returned, we fall back to `get_browser_locale()`.
This method should return a `tornado.locale.Locale` object,
most likely obtained via a call like ``tornado.locale.get("en")``
"""
return None
def get_browser_locale(self, default="en_US"):
"""Determines the user's locale from ``Accept-Language`` header.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
"""
if "Accept-Language" in self.request.headers:
languages = self.request.headers["Accept-Language"].split(",")
locales = []
for language in languages:
parts = language.strip().split(";")
if len(parts) > 1 and parts[1].startswith("q="):
try:
score = float(parts[1][2:])
except (ValueError, TypeError):
score = 0.0
else:
score = 1.0
locales.append((parts[0], score))
if locales:
locales.sort(key=lambda pair: pair[1], reverse=True)
codes = [l[0] for l in locales]
return locale.get(*codes)
return locale.get(default)
@property
def current_user(self):
"""The authenticated user for this request.
This is a cached version of `get_current_user`, which you can
override to set the user based on, e.g., a cookie. If that
method is not overridden, this method always returns None.
We lazy-load the current user the first time this method is called
and cache the result after that.
"""
if not hasattr(self, "_current_user"):
self._current_user = self.get_current_user()
return self._current_user
@current_user.setter
def current_user(self, value):
self._current_user = value
def get_current_user(self):
"""Override to determine the current user from, e.g., a cookie."""
return None
def get_login_url(self):
"""Override to customize the login URL based on the request.
By default, we use the ``login_url`` application setting.
"""
self.require_setting("login_url", "@tornado.web.authenticated")
return self.application.settings["login_url"]
def get_template_path(self):
"""Override to customize template path for each handler.
By default, we use the ``template_path`` application setting.
Return None to load templates relative to the calling file.
"""
return self.application.settings.get("template_path")
@property
def xsrf_token(self):
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
.. versionchanged:: 3.2.2
The xsrf token will now be have a random mask applied in every
request, which makes it safe to include the token in pages
that are compressed. See http://breachattack.com for more
information on the issue fixed by this change. Old (version 1)
cookies will be converted to version 2 when this method is called
unless the ``xsrf_cookie_version`` `Application` setting is
set to 1.
"""
if not hasattr(self, "_xsrf_token"):
version, token, timestamp = self._get_raw_xsrf_token()
output_version = self.settings.get("xsrf_cookie_version", 2)
if output_version == 1:
self._xsrf_token = binascii.b2a_hex(token)
elif output_version == 2:
mask = os.urandom(4)
self._xsrf_token = b"|".join([
b"2",
binascii.b2a_hex(mask),
binascii.b2a_hex(_websocket_mask(mask, token)),
utf8(str(int(timestamp)))])
else:
raise ValueError("unknown xsrf cookie version %d",
output_version)
if version is None:
expires_days = 30 if self.current_user else None
self.set_cookie("_xsrf", self._xsrf_token,
expires_days=expires_days)
return self._xsrf_token
def _get_raw_xsrf_token(self):
"""Read or generate the xsrf token in its raw form.
The raw_xsrf_token is a tuple containing:
* version: the version of the cookie from which this token was read,
or None if we generated a new token in this request.
* token: the raw token data; random (non-ascii) bytes.
* timestamp: the time this token was generated (will not be accurate
for version 1 cookies)
"""
if not hasattr(self, '_raw_xsrf_token'):
cookie = self.get_cookie("_xsrf")
if cookie:
version, token, timestamp = self._decode_xsrf_token(cookie)
else:
version, token, timestamp = None, None, None
if token is None:
version = None
token = os.urandom(16)
timestamp = time.time()
self._raw_xsrf_token = (version, token, timestamp)
return self._raw_xsrf_token
def _decode_xsrf_token(self, cookie):
"""Convert a cookie string into a the tuple form returned by
_get_raw_xsrf_token.
"""
try:
m = _signed_value_version_re.match(utf8(cookie))
if m:
version = int(m.group(1))
if version == 2:
_, mask, masked_token, timestamp = cookie.split("|")
mask = binascii.a2b_hex(utf8(mask))
token = _websocket_mask(
mask, binascii.a2b_hex(utf8(masked_token)))
timestamp = int(timestamp)
return version, token, timestamp
else:
# Treat unknown versions as not present instead of failing.
raise Exception("Unknown xsrf cookie version")
else:
version = 1
try:
token = binascii.a2b_hex(utf8(cookie))
except (binascii.Error, TypeError):
token = utf8(cookie)
# We don't have a usable timestamp in older versions.
timestamp = int(time.time())
return (version, token, timestamp)
except Exception:
# Catch exceptions and return nothing instead of failing.
gen_log.debug("Uncaught exception in _decode_xsrf_token",
exc_info=True)
return None, None, None
def check_xsrf_cookie(self):
"""Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
reject the form submission as a potential forgery.
The ``_xsrf`` value may be set as either a form field named ``_xsrf``
or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
(the latter is accepted for compatibility with Django).
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
Prior to release 1.1.1, this check was ignored if the HTTP header
``X-Requested-With: XMLHTTPRequest`` was present. This exception
has been shown to be insecure and has been removed. For more
information please see
http://www.djangoproject.com/weblog/2011/feb/08/security/
http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
.. versionchanged:: 3.2.2
Added support for cookie version 2. Both versions 1 and 2 are
supported.
"""
token = (self.get_argument("_xsrf", None) or
self.request.headers.get("X-Xsrftoken") or
self.request.headers.get("X-Csrftoken"))
if not token:
raise HTTPError(403, "'_xsrf' argument missing from POST")
_, token, _ = self._decode_xsrf_token(token)
_, expected_token, _ = self._get_raw_xsrf_token()
if not _time_independent_equals(utf8(token), utf8(expected_token)):
raise HTTPError(403, "XSRF cookie does not match POST argument")
def xsrf_form_html(self):
"""An HTML ``<input/>`` element to be included with all POST forms.
It defines the ``_xsrf`` input value, which we check on all POST
requests to prevent cross-site request forgery. If you have set
the ``xsrf_cookies`` application setting, you must include this
HTML within all of your HTML forms.
In a template, this method should be called with ``{% module
xsrf_form_html() %}``
See `check_xsrf_cookie()` above for more information.
"""
return '<input type="hidden" name="_xsrf" value="' + \
escape.xhtml_escape(self.xsrf_token) + '"/>'
def static_url(self, path, include_host=None, **kwargs):
"""Returns a static URL for the given relative static file path.
This method requires you set the ``static_path`` setting in your
application (which specifies the root directory of your static
files).
This method returns a versioned url (by default appending
``?v=<signature>``), which allows the static files to be
cached indefinitely. This can be disabled by passing
``include_version=False`` (in the default implementation;
other static file implementations are not required to support
this, but they may support other options).
By default this method returns URLs relative to the current
host, but if ``include_host`` is true the URL returned will be
absolute. If this handler has an ``include_host`` attribute,
that value will be used as the default for all `static_url`
calls that do not pass ``include_host`` as a keyword argument.
"""
self.require_setting("static_path", "static_url")
get_url = self.settings.get("static_handler_class",
StaticFileHandler).make_static_url
if include_host is None:
include_host = getattr(self, "include_host", False)
if include_host:
base = self.request.protocol + "://" + self.request.host
else:
base = ""
return base + get_url(self.settings, path, **kwargs)
def require_setting(self, name, feature="this feature"):
"""Raises an exception if the given app setting is not defined."""
if not self.application.settings.get(name):
raise Exception("You must define the '%s' setting in your "
"application to use %s" % (name, feature))
def reverse_url(self, name, *args):
"""Alias for `Application.reverse_url`."""
return self.application.reverse_url(name, *args)
def compute_etag(self):
"""Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations,
or may return None to disable tornado's default etag support.
"""
hasher = hashlib.sha1()
for part in self._write_buffer:
hasher.update(part)
return '"%s"' % hasher.hexdigest()
def set_etag_header(self):
"""Sets the response's Etag header using ``self.compute_etag()``.
Note: no header will be set if ``compute_etag()`` returns ``None``.
This method is called automatically when the request is finished.
"""
etag = self.compute_etag()
if etag is not None:
self.set_header("Etag", etag)
def check_etag_header(self):
"""Checks the ``Etag`` header against requests's ``If-None-Match``.
Returns ``True`` if the request's Etag matches and a 304 should be
returned. For example::
self.set_etag_header()
if self.check_etag_header():
self.set_status(304)
return
This method is called automatically when the request is finished,
but may be called earlier for applications that override
`compute_etag` and want to do an early check for ``If-None-Match``
before completing the request. The ``Etag`` header should be set
(perhaps with `set_etag_header`) before calling this method.
"""
computed_etag = utf8(self._headers.get("Etag", ""))
# Find all weak and strong etag values from If-None-Match header
# because RFC 7232 allows multiple etag values in a single header.
etags = re.findall(
br'\*|(?:W/)?"[^"]*"',
utf8(self.request.headers.get("If-None-Match", ""))
)
if not computed_etag or not etags:
return False
match = False
if etags[0] == b'*':
match = True
else:
# Use a weak comparison when comparing entity-tags.
val = lambda x: x[2:] if x.startswith(b'W/') else x
for etag in etags:
if val(etag) == val(computed_etag):
match = True
break
return match
def _stack_context_handle_exception(self, type, value, traceback):
try:
# For historical reasons _handle_request_exception only takes
# the exception value instead of the full triple,
# so re-raise the exception to ensure that it's in
# sys.exc_info()
raise_exc_info((type, value, traceback))
except Exception:
self._handle_request_exception(value)
return True
@gen.coroutine
def _execute(self, transforms, *args, **kwargs):
"""Executes this request with the given output transforms."""
self._transforms = transforms
try:
if self.request.method not in self.SUPPORTED_METHODS:
raise HTTPError(405)
self.path_args = [self.decode_argument(arg) for arg in args]
self.path_kwargs = dict((k, self.decode_argument(v, name=k))
for (k, v) in kwargs.items())
# If XSRF cookies are turned on, reject form submissions without
# the proper cookie
if self.request.method not in ("GET", "HEAD", "OPTIONS") and \
self.application.settings.get("xsrf_cookies"):
self.check_xsrf_cookie()
result = self.prepare()
if result is not None:
result = yield result
if self._prepared_future is not None:
# Tell the Application we've finished with prepare()
# and are ready for the body to arrive.
self._prepared_future.set_result(None)
if self._finished:
return
if _has_stream_request_body(self.__class__):
# In streaming mode request.body is a Future that signals
# the body has been completely received. The Future has no
# result; the data has been passed to self.data_received
# instead.
try:
yield self.request.body
except iostream.StreamClosedError:
return
method = getattr(self, self.request.method.lower())
result = method(*self.path_args, **self.path_kwargs)
if result is not None:
result = yield result
if self._auto_finish and not self._finished:
self.finish()
except Exception as e:
try:
self._handle_request_exception(e)
except Exception:
app_log.error("Exception in exception handler", exc_info=True)
if (self._prepared_future is not None and
not self._prepared_future.done()):
# In case we failed before setting _prepared_future, do it
# now (to unblock the HTTP server). Note that this is not
# in a finally block to avoid GC issues prior to Python 3.4.
self._prepared_future.set_result(None)
def data_received(self, chunk):
"""Implement this method to handle streamed request data.
Requires the `.stream_request_body` decorator.
"""
raise NotImplementedError()
def _log(self):
"""Logs the current request.
Sort of deprecated since this functionality was moved to the
Application, but left in place for the benefit of existing apps
that have overridden this method.
"""
self.application.log_request(self)
def _request_summary(self):
return "%s %s (%s)" % (self.request.method, self.request.uri,
self.request.remote_ip)
def _handle_request_exception(self, e):
if isinstance(e, Finish):
# Not an error; just finish the request without logging.
if not self._finished:
self.finish()
return
try:
self.log_exception(*sys.exc_info())
except Exception:
# An error here should still get a best-effort send_error()
# to avoid leaking the connection.
app_log.error("Error in exception logger", exc_info=True)
if self._finished:
# Extra errors after the request has been finished should
# be logged, but there is no reason to continue to try and
# send a response.
return
if isinstance(e, HTTPError):
if e.status_code not in httputil.responses and not e.reason:
gen_log.error("Bad HTTP status code: %d", e.status_code)
self.send_error(500, exc_info=sys.exc_info())
else:
self.send_error(e.status_code, exc_info=sys.exc_info())
else:
self.send_error(500, exc_info=sys.exc_info())
def log_exception(self, typ, value, tb):
"""Override to customize logging of uncaught exceptions.
By default logs instances of `HTTPError` as warnings without
stack traces (on the ``tornado.general`` logger), and all
other exceptions as errors with stack traces (on the
``tornado.application`` logger).
.. versionadded:: 3.1
"""
if isinstance(value, HTTPError):
if value.log_message:
format = "%d %s: " + value.log_message
args = ([value.status_code, self._request_summary()] +
list(value.args))
gen_log.warning(format, *args)
else:
app_log.error("Uncaught exception %s\n%r", self._request_summary(),
self.request, exc_info=(typ, value, tb))
def _ui_module(self, name, module):
def render(*args, **kwargs):
if not hasattr(self, "_active_modules"):
self._active_modules = {}
if name not in self._active_modules:
self._active_modules[name] = module(self)
rendered = self._active_modules[name].render(*args, **kwargs)
return rendered
return render
def _ui_method(self, method):
return lambda *args, **kwargs: method(self, *args, **kwargs)
def _clear_headers_for_304(self):
# 304 responses should not contain entity headers (defined in
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
# not explicitly allowed by
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
headers = ["Allow", "Content-Encoding", "Content-Language",
"Content-Length", "Content-MD5", "Content-Range",
"Content-Type", "Last-Modified"]
for h in headers:
self.clear_header(h)
def asynchronous(method):
"""Wrap request handler methods with this if they are asynchronous.
This decorator is for callback-style asynchronous methods; for
coroutines, use the ``@gen.coroutine`` decorator without
``@asynchronous``. (It is legal for legacy reasons to use the two
decorators together provided ``@asynchronous`` is first, but
``@asynchronous`` will be ignored in this case)
This decorator should only be applied to the :ref:`HTTP verb
methods <verbs>`; its behavior is undefined for any other method.
This decorator does not *make* a method asynchronous; it tells
the framework that the method *is* asynchronous. For this decorator
to be useful the method must (at least sometimes) do something
asynchronous.
If this decorator is given, the response is not finished when the
method returns. It is up to the request handler to call
`self.finish() <RequestHandler.finish>` to finish the HTTP
request. Without this decorator, the request is automatically
finished when the ``get()`` or ``post()`` method returns. Example:
.. testcode::
class MyRequestHandler(RequestHandler):
@asynchronous
def get(self):
http = httpclient.AsyncHTTPClient()
http.fetch("http://friendfeed.com/", self._on_download)
def _on_download(self, response):
self.write("Downloaded!")
self.finish()
.. testoutput::
:hide:
.. versionadded:: 3.1
The ability to use ``@gen.coroutine`` without ``@asynchronous``.
"""
# Delay the IOLoop import because it's not available on app engine.
from tornado.ioloop import IOLoop
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
self._auto_finish = False
with stack_context.ExceptionStackContext(
self._stack_context_handle_exception):
result = method(self, *args, **kwargs)
if is_future(result):
# If @asynchronous is used with @gen.coroutine, (but
# not @gen.engine), we can automatically finish the
# request when the future resolves. Additionally,
# the Future will swallow any exceptions so we need
# to throw them back out to the stack context to finish
# the request.
def future_complete(f):
f.result()
if not self._finished:
self.finish()
IOLoop.current().add_future(result, future_complete)
# Once we have done this, hide the Future from our
# caller (i.e. RequestHandler._when_complete), which
# would otherwise set up its own callback and
# exception handler (resulting in exceptions being
# logged twice).
return None
return result
return wrapper
def stream_request_body(cls):
"""Apply to `RequestHandler` subclasses to enable streaming body support.
This decorator implies the following changes:
* `.HTTPServerRequest.body` is undefined, and body arguments will not
be included in `RequestHandler.get_argument`.
* `RequestHandler.prepare` is called when the request headers have been
read instead of after the entire body has been read.
* The subclass must define a method ``data_received(self, data):``, which
will be called zero or more times as data is available. Note that
if the request has an empty body, ``data_received`` may not be called.
* ``prepare`` and ``data_received`` may return Futures (such as via
``@gen.coroutine``, in which case the next method will not be called
until those futures have completed.
* The regular HTTP method (``post``, ``put``, etc) will be called after
the entire body has been read.
There is a subtle interaction between ``data_received`` and asynchronous
``prepare``: The first call to ``data_received`` may occur at any point
after the call to ``prepare`` has returned *or yielded*.
"""
if not issubclass(cls, RequestHandler):
raise TypeError("expected subclass of RequestHandler, got %r", cls)
cls._stream_request_body = True
return cls
def _has_stream_request_body(cls):
if not issubclass(cls, RequestHandler):
raise TypeError("expected subclass of RequestHandler, got %r", cls)
return getattr(cls, '_stream_request_body', False)
def removeslash(method):
"""Use this decorator to remove trailing slashes from the request path.
For example, a request to ``/foo/`` would redirect to ``/foo`` with this
decorator. Your request handler mapping should use a regular expression
like ``r'/foo/*'`` in conjunction with using the decorator.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if self.request.path.endswith("/"):
if self.request.method in ("GET", "HEAD"):
uri = self.request.path.rstrip("/")
if uri: # don't try to redirect '/' to ''
if self.request.query:
uri += "?" + self.request.query
self.redirect(uri, permanent=True)
return
else:
raise HTTPError(404)
return method(self, *args, **kwargs)
return wrapper
def addslash(method):
"""Use this decorator to add a missing trailing slash to the request path.
For example, a request to ``/foo`` would redirect to ``/foo/`` with this
decorator. Your request handler mapping should use a regular expression
|
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
|
Context:
[Previous code... ~10,000 lines omitted for brevity]
def _handle_request_exception(self, e):
if isinstance(e, Finish):
# Not an error; just finish the request without logging.
if not self._finished:
self.finish()
return
try:
self.log_exception(*sys.exc_info())
except Exception:
# An error here should still get a best-effort send_error()
# to avoid leaking the connection.
app_log.error("Error in exception logger", exc_info=True)
if self._finished:
# Extra errors after the request has been finished should
# be logged, but there is no reason to continue to try and
# send a response.
return
if isinstance(e, HTTPError):
if e.status_code not in httputil.responses and not e.reason:
gen_log.error("Bad HTTP status code: %d", e.status_code)
self.send_error(500, exc_info=sys.exc_info())
else:
self.send_error(e.status_code, exc_info=sys.exc_info())
else:
self.send_error(500, exc_info=sys.exc_info())
def log_exception(self, typ, value, tb):
"""Override to customize logging of uncaught exceptions.
By default logs instances of `HTTPError` as warnings without
stack traces (on the ``tornado.general`` logger), and all
other exceptions as errors with stack traces (on the
``tornado.application`` logger).
.. versionadded:: 3.1
"""
if isinstance(value, HTTPError):
if value.log_message:
format = "%d %s: " + value.log_message
args = ([value.status_code, self._request_summary()] +
list(value.args))
gen_log.warning(format, *args)
else:
app_log.error("Uncaught exception %s\n%r", self._request_summary(),
self.request, exc_info=(typ, value, tb))
def _ui_module(self, name, module):
def render(*args, **kwargs):
if not hasattr(self, "_active_modules"):
self._active_modules = {}
if name not in self._active_modules:
self._active_modules[name] = module(self)
rendered = self._active_modules[name].render(*args, **kwargs)
return rendered
return render
def _ui_method(self, method):
return lambda *args, **kwargs: method(self, *args, **kwargs)
def _clear_headers_for_304(self):
# 304 responses should not contain entity headers (defined in
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
# not explicitly allowed by
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
headers = ["Allow", "Content-Encoding", "Content-Language",
"Content-Length", "Content-MD5", "Content-Range",
"Content-Type", "Last-Modified"]
for h in headers:
self.clear_header(h)
def _stack_context_handle_exception(self, type, value, traceback):
try:
# For historical reasons _handle_request_exception only takes
# the exception value instead of the full triple,
# so re-raise the exception to ensure that it's in
# sys.exc_info()
raise_exc_info((type, value, traceback))
except Exception:
self._handle_request_exception(value)
return True
@gen.coroutine
def _execute(self, transforms, *args, **kwargs):
self._transforms = transforms
try:
if self.request.method not in self.SUPPORTED_METHODS:
raise HTTPError(405)
self.path_args = [self.decode_argument(arg) for arg in args]
self.path_kwargs = dict((k, self.decode_argument(v, name=k))
for (k, v) in kwargs.items())
# If XSRF cookies are turned on, reject form submissions without
# the proper cookie
if self.request.method not in ("GET", "HEAD", "OPTIONS") and \
self.application.settings.get("xsrf_cookies"):
self.check_xsrf_cookie()
result = self.prepare()
if result is not None:
result = yield result
if self._prepared_future is not None:
# Tell the Application we've finished with prepare()
# and are ready for the body to arrive.
self._prepared_future.set_result(None)
if self._finished:
return
if _has_stream_request_body(self.__class__):
# In streaming mode request.body is a Future that signals
# the body has been completely received. The Future has no
# result; the data has been passed to self.data_received
# instead.
try:
yield self.request.body
except iostream.StreamClosedError:
return
method = getattr(self, self.request.method.lower())
result = method(*self.path_args, **self.path_kwargs)
if result is not None:
result = yield result
if self._auto_finish and not self._finished:
self.finish()
except Exception as e:
try:
self._handle_request_exception(e)
except Exception:
app_log.error("Exception in exception handler", exc_info=True)
if (self._prepared_future is not None and
not self._prepared_future.done()):
# In case we failed before setting _prepared_future, do it
# now (to unblock the HTTP server). Note that this is not
# in a finally block to avoid GC issues prior to Python 3.4.
self._prepared_future.set_result(None)
def data_received(self, chunk):
"""Implement this method to handle streamed request data.
Requires the `.stream_request_body` decorator.
"""
raise NotImplementedError()
def _log(self):
"""Logs the current request.
Sort of deprecated since this functionality was moved to the
Application, but left in place for the benefit of existing apps
that have overridden this method.
"""
self.application.log_request(self)
def _request_summary(self):
return "%s %s (%s)" % (self.request.method, self.request.uri,
self.request.remote_ip)
def _handle_request_exception(self, e):
if isinstance(e, Finish):
# Not an error; just finish the request without logging.
if not self._finished:
self.finish()
return
try:
self.log_exception(*sys.exc_info())
except Exception:
# An error here should still get a best-effort send_error()
# to avoid leaking the connection.
app_log.error("Error in exception logger", exc_info=True)
if self._finished:
# Extra errors after the request has been finished should
# be logged, but there is no reason to continue to try and
# send a response.
return
if isinstance(e, HTTPError):
if e.status_code not in httputil.responses and not e.reason:
gen_log.error("Bad HTTP status code: %d", e.status_code)
self.send_error(500, exc_info=sys.exc_info())
else:
self.send_error(e.status_code, exc_info=sys.exc_info())
else:
self.send_error(500, exc_info=sys.exc_info())
def log_exception(self, typ, value, tb):
"""Override to customize logging of uncaught exceptions.
By default logs instances of `HTTPError` as warnings without
stack traces (on the ``tornado.general`` logger), and all
other exceptions as errors with stack traces (on the
``tornado.application`` logger).
.. versionadded:: 3.1
"""
if isinstance(value, HTTPError):
if value.log_message:
format = "%d %s: " + value.log_message
args = ([value.status_code, self._request_summary()] +
list(value.args))
gen_log.warning(format, *args)
else:
app_log.error("Uncaught exception %s\n%r", self._request_summary(),
self.request, exc_info=(typ, value, tb))
def _ui_module(self, name, module):
def render(*args, **kwargs):
if not hasattr(self, "_active_modules"):
self._active_modules = {}
if name not in self._active_modules:
self._active_modules[name] = module(self)
rendered = self._active_modules[name].render(*args, **kwargs)
return rendered
return render
def _ui_method(self, method):
return lambda *args, **kwargs: method(self, *args, **kwargs)
def _clear_headers_for_304(self):
# 304 responses should not contain entity headers (defined in
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
# not explicitly allowed by
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
headers = ["Allow", "Content-Encoding", "Content-Language",
"Content-Length", "Content-MD5", "Content-Range",
"Content-Type", "Last-Modified"]
for h in headers:
self.clear_header(h)
def _stack_context_handle_exception(self, type, value, traceback):
try:
# For historical reasons _handle_request_exception only takes
# the exception value instead of the full triple,
# so re-raise the exception to ensure
|
|
Please complete the code given below.
//
// System.Web.UI.WebControls.MultiView.cs
//
// Authors:
// Lluis Sanchez Gual (lluis@novell.com)
//
// (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
using System;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
namespace System.Web.UI.WebControls
{
[ControlBuilder (typeof(MultiViewControlBuilder))]
[Designer ("System.Web.UI.Design.WebControls.MultiViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
[ToolboxData ("<{0}:MultiView runat=\"server\"></{0}:MultiView>")]
[ParseChildren (typeof(View))]
[DefaultEvent ("ActiveViewChanged")]
public class MultiView: Control
{
public static readonly string NextViewCommandName = "NextView";
public static readonly string PreviousViewCommandName = "PrevView";
public static readonly string SwitchViewByIDCommandName = "SwitchViewByID";
public static readonly string SwitchViewByIndexCommandName = "SwitchViewByIndex";
static readonly object ActiveViewChangedEvent = new object();
int viewIndex = -1;
int initialIndex = -1;
public event EventHandler ActiveViewChanged {
add { Events.AddHandler (ActiveViewChangedEvent, value); }
remove { Events.RemoveHandler (ActiveViewChangedEvent, value); }
}
protected override void AddParsedSubObject (object ob)
{
if (ob is View)
Controls.Add (ob as View);
// LAMESPEC: msdn talks that only View contorls are allowed, for others controls HttpException should be thrown
// but actually, aspx praser adds LiteralControl controls.
//else
// throw new HttpException ("MultiView cannot have children of type 'Control'. It can only have children of type View.");
}
protected override ControlCollection CreateControlCollection ()
{
return new ViewCollection (this);
}
public View GetActiveView ()
{
if (viewIndex < 0 || viewIndex >= Controls.Count)
throw new HttpException ("The ActiveViewIndex is not set to a valid View control");
return Controls [viewIndex] as View;
}
public void SetActiveView (View view)
{
int i = Controls.IndexOf (view);
if (i == -1)
throw new HttpException ("The provided view is not contained in the MultiView control.");
ActiveViewIndex = i;
}
[DefaultValue (-1)]
public virtual int ActiveViewIndex {
get
{
if (Controls.Count == 0)
return initialIndex;
return viewIndex;
}
set
{
if (Controls.Count == 0) {
initialIndex = value;
return;
}
if (value < -1 || value >= Controls.Count)
throw new ArgumentOutOfRangeException ();
if (viewIndex != -1)
((View)Controls [viewIndex]).NotifyActivation (false);
viewIndex = value;
if (viewIndex != -1)
((View)Controls [viewIndex]).NotifyActivation (true);
UpdateViewVisibility ();
OnActiveViewChanged (EventArgs.Empty);
}
}
[Browsable (true)]
public virtual new bool EnableTheming
{
get { return base.EnableTheming; }
set { base.EnableTheming = value; }
}
[PersistenceMode (PersistenceMode.InnerDefaultProperty)]
[Browsable (false)]
public virtual ViewCollection Views {
get { return Controls as ViewCollection; }
}
protected override bool OnBubbleEvent (object source, EventArgs e)
{
CommandEventArgs ca = e as CommandEventArgs;
if (ca != null) {
switch (ca.CommandName) {
case "NextView":
if (viewIndex < Controls.Count - 1 && Controls.Count > 0)
ActiveViewIndex = viewIndex + 1;
break;
case "PrevView":
if (viewIndex > 0)
ActiveViewIndex = viewIndex - 1;
break;
case "SwitchViewByID":
foreach (View v in Controls)
if (v.ID == (string)ca.CommandArgument) {
SetActiveView (v);
break;
}
break;
case "SwitchViewByIndex":
int i = (int) Convert.ChangeType (ca.CommandArgument, typeof(int));
ActiveViewIndex = i;
break;
}
}
return false;
}
protected internal override void OnInit (EventArgs e)
{
Page.RegisterRequiresControlState (this);
if (initialIndex != -1) {
ActiveViewIndex = initialIndex;
initialIndex = -1;
}
base.OnInit (e);
}
void UpdateViewVisibility ()
{
for (int n=0; n<Views.Count; n++)
Views [n].VisibleInternal = (n == viewIndex);
}
protected internal override void RemovedControl (Control ctl)
{
if (viewIndex >= Controls.Count) {
viewIndex = Controls.Count - 1;
UpdateViewVisibility ();
}
base.RemovedControl (ctl);
}
protected internal override void LoadControlState (object state)
{
if (state != null) {
viewIndex = (int)state;
UpdateViewVisibility ();
}
else viewIndex = -1;
}
protected internal override object SaveControlState ()
{
if (viewIndex != -1) return viewIndex;
else return null;
}
protected virtual void OnActiveViewChanged (EventArgs e)
{
if (Events != null) {
EventHandler eh = (EventHandler) Events [ActiveViewChangedEvent];
if (eh != null) eh (this, e);
}
}
protected internal override void Render (HtmlTextWriter writer)
{
|
[
"\t\t\tif ((Controls.Count == 0) && (initialIndex != -1)) "
] | 777
|
lcc
|
csharp
| null |
5dbe65a9966abf6a6fdc04cf78e20977f8d24df06849e8e7
| 25
|
Your task is code completion.
//
// System.Web.UI.WebControls.MultiView.cs
//
// Authors:
// Lluis Sanchez Gual (lluis@novell.com)
//
// (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
using System;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
namespace System.Web.UI.WebControls
{
[ControlBuilder (typeof(MultiViewControlBuilder))]
[Designer ("System.Web.UI.Design.WebControls.MultiViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
[ToolboxData ("<{0}:MultiView runat=\"server\"></{0}:MultiView>")]
[ParseChildren (typeof(View))]
[DefaultEvent ("ActiveViewChanged")]
public class MultiView: Control
{
public static readonly string NextViewCommandName = "NextView";
public static readonly string PreviousViewCommandName = "PrevView";
public static readonly string SwitchViewByIDCommandName = "SwitchViewByID";
public static readonly string SwitchViewByIndexCommandName = "SwitchViewByIndex";
static readonly object ActiveViewChangedEvent = new object();
int viewIndex = -1;
int initialIndex = -1;
public event EventHandler ActiveViewChanged {
add { Events.AddHandler (ActiveViewChangedEvent, value); }
remove { Events.RemoveHandler (ActiveViewChangedEvent, value); }
}
protected override void AddParsedSubObject (object ob)
{
if (ob is View)
Controls.Add (ob as View);
// LAMESPEC: msdn talks that only View contorls are allowed, for others controls HttpException should be thrown
// but actually, aspx praser adds LiteralControl controls.
//else
// throw new HttpException ("MultiView cannot have children of type 'Control'. It can only have children of type View.");
}
protected override ControlCollection CreateControlCollection ()
{
return new ViewCollection (this);
}
public View GetActiveView ()
{
if (viewIndex < 0 || viewIndex >= Controls.Count)
throw new HttpException ("The ActiveViewIndex is not set to a valid View control");
return Controls [viewIndex] as View;
}
public void SetActiveView (View view)
{
int i = Controls.IndexOf (view);
if (i == -1)
throw new HttpException ("The provided view is not contained in the MultiView control.");
ActiveViewIndex = i;
}
[DefaultValue (-1)]
public virtual int ActiveViewIndex {
get
{
if (Controls.Count == 0)
return initialIndex;
return viewIndex;
}
set
{
if (Controls.Count == 0) {
initialIndex = value;
return;
}
if (value < -1 || value >= Controls.Count)
throw new ArgumentOutOfRangeException ();
if (viewIndex != -1)
((View)Controls [viewIndex]).NotifyActivation (false);
viewIndex = value;
if (viewIndex != -1)
((View)Controls [viewIndex]).NotifyActivation (true);
UpdateViewVisibility ();
OnActiveViewChanged (EventArgs.Empty);
}
}
[Browsable (true)]
public virtual new bool EnableTheming
{
get { return base.EnableTheming; }
set { base.EnableTheming = value; }
}
[PersistenceMode (PersistenceMode.InnerDefaultProperty)]
[Browsable (false)]
public virtual ViewCollection Views {
get { return Controls as ViewCollection; }
}
protected override bool OnBubbleEvent (object source, EventArgs e)
{
CommandEventArgs ca = e as CommandEventArgs;
if (ca != null) {
switch (ca.CommandName) {
case "NextView":
if (viewIndex < Controls.Count - 1 && Controls.Count > 0)
ActiveViewIndex = viewIndex + 1;
break;
case "PrevView":
if (viewIndex > 0)
ActiveViewIndex = viewIndex - 1;
break;
case "SwitchViewByID":
foreach (View v in Controls)
if (v.ID == (string)ca.CommandArgument) {
SetActiveView (v);
break;
}
break;
case "SwitchViewByIndex":
int i = (int) Convert.ChangeType (ca.CommandArgument, typeof(int));
ActiveViewIndex = i;
break;
}
}
return false;
}
protected internal override void OnInit (EventArgs e)
{
Page.RegisterRequiresControlState (this);
if (initialIndex != -1) {
ActiveViewIndex = initialIndex;
initialIndex = -1;
}
base.OnInit (e);
}
void UpdateViewVisibility ()
{
for (int n=0; n<Views.Count; n++)
Views [n].VisibleInternal = (n == viewIndex);
}
protected internal override void RemovedControl (Control ctl)
{
if (viewIndex >= Controls.Count) {
viewIndex = Controls.Count - 1;
UpdateViewVisibility ();
}
base.RemovedControl (ctl);
}
protected internal override void LoadControlState (object state)
{
if (state != null) {
viewIndex = (int)state;
UpdateViewVisibility ();
}
else viewIndex = -1;
}
protected internal override object SaveControlState ()
{
if (viewIndex != -1) return viewIndex;
else return null;
}
protected virtual void OnActiveViewChanged (EventArgs e)
{
if (Events != null) {
EventHandler eh = (EventHandler) Events [ActiveViewChangedEvent];
if (eh != null) eh (this, e);
}
}
protected internal override void Render (HtmlTextWriter writer)
{
|
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 snippet:
Context:
[Previous code... ~10,000 lines omitted for brevity]
public class MultiView: Control
{
// ...
protected override void OnBubbleEvent (object source, EventArgs e)
{
CommandEventArgs ca = e as CommandEventArgs;
if (ca != null) {
switch (ca.CommandName) {
case "NextView":
if (viewIndex < Controls.Count - 1 && Controls.Count > 0)
ActiveViewIndex = viewIndex + 1;
break;
case "PrevView":
if (viewIndex > 0)
ActiveViewIndex = viewIndex - 1;
break;
case "SwitchViewByID":
foreach (View v in Controls)
if (v.ID == (string)ca.CommandArgument) {
SetActiveView (v);
break;
}
break;
case "SwitchViewByIndex":
int i = (int) Convert.ChangeType (ca.CommandArgument, typeof(int));
ActiveViewIndex = i;
break;
}
}
return false;
}
// ...
Relevant lines and variables:
- We are in the OnBubbleEvent method, which handles events bubbled up from child controls.
- The method iterates over different CommandName cases to perform actions based on the command name.
- The current case is "SwitchViewByIndex".
- The CommandArgument is cast to an integer using Convert.ChangeType.
- The ActiveViewIndex is set to the CommandArgument value.
Next line will likely be:
- The code should set the ActiveViewIndex to the CommandArgument value, which is already done in the current case.
- However, the task is likely to complete the switch statement, so the next line will be the closing bracket for the switch statement.
Cheatsheet:
- We are in the switch statement, which should be closed.
- The current case is "SwitchViewByIndex".
- The switch statement should be closed with a closing bracket.
- [Relevant lines: switch statement header, current case]
Next line will likely be: }
|
|
Please complete the code given below.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## version 2 as published by the Free Software Foundation.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##
## author: Leonardo Tonetto
__author__ = "Leonardo Tonetto"
__copyright__ = "Copyright 2016, Leonardo Tonetto"
__license__ = "GPLv2"
__version__ = "0.1"
import sys
try:
import wigle
except ImportError:
print >> sys.stderr, 'Please install wigle (eg. pip install wigle)'
sys.exit(1)
import argparse, pickle, time
def drange(start, stop, step):
"""
Float point implementation of range()
Based on (but not exactly):
http://stackoverflow.com/questions/477486/python-decimal-range-step-value
"""
## few sanity checks first
if start < stop and step < 0:
raise RuntimeError('Wrong input variables, step should be > 0.')
if start > stop and step > 0:
raise RuntimeError('Wrong input variables, step should be < 0.')
r = start
while start < stop and r < stop:
yield r
r += step
while start > stop and r > stop:
yield r
r += step
class WigleDownloader:
"""
Downloads AP info from wigle.net
[HARDCODED] YEEEAH!
lat/lon_min/max : interval of the desired area.
lat_lon_div : number of divisions along each axis (used to double check).
div_map: initial num. of subdivisions inside each original division
this has to have the same number of columns/rows as the *_div arg.
Ref.: [0][0] is the upper left box
In case none is given, 1 is applied to all boxes
"""
## Some constants
wigle_downloads_per_page = wigle.WIGLE_PAGESIZE
wigle_max_ap_per_query = 10000
## These add up to 24h, time we would expect to have the quota renewed
wigle_timeout_backoff = [0.25*3600, ## 15 minutes
0.25*3600,
0.5*3600,
1*3600,
2*3600,
4*3600,
8*3600,
8*3600] ## 8 hours
file_default_remain = './coord.remain'
def __init__( self, user, password, coordfile, outpath ):
try:
## Wigle, wigle, wigle :-)
self.wigle = wigle.Wigle( user, password )
except wigle.WigleAuthenticationError as wae:
print >> sys.stderr, 'Authentication error for {1}.'.format(user)
print >> sys.stderr, wae.message
sys.exit(-1)
except wigle.WigleError as werr:
print >> sys.stderr, werr.message
sys.exit(-2)
self.outpath = outpath
self.coordfile = coordfile
## This is for the city of Munich-DE
## TODO: replace this with geocoding
self.latmin = 47.95
self.latmax = 48.43
self.lonmin = 11.00
self.lonmax = 12.15
self.latdiv = 6
self.londiv = 10
## For the lazy: use this one
## Do not modify this lazy map after this point since rows will be the same object...
#self.div_map = [[1]*self.londiv]*self.latdiv
## Or you can do it like that
self.div_map = [[ 2, 2, 2, 2, 2, 2, 8, 2, 2, 2],
[ 2, 2, 2, 2, 4, 3, 2, 5, 2, 2],
[ 2, 4, 5, 4, 4, 5, 2, 4, 2, 2],
[ 2, 4, 4, 8,18, 8, 8, 6, 2, 2],
[ 2, 2, 3, 4,16, 8, 4, 2, 2, 2],
[ 2, 2, 4, 4, 4, 4, 2, 2, 2, 2]]
self.INTERVALS = []
self.REMAINING_INTERVALS = []
def run(self):
"""
Just so that it does not look so ugly
"""
## We either call compute_intervals() or parse_coordfile()
if self.coordfile:
self.parse_coordfile(self.coordfile)
else:
self.compute_intervals()
self.REMAINING_INTERVALS = self.INTERVALS[:]
self.REMAINING_INTERVALS.reverse()
## Now we (continue) download(ing)
self.download()
def download(self):
"""
Download whatever is inside self.INTERVALS using
wigle pythong API (not official apparently)
"""
def callback_newpage(since):
pass
def _download( lat1, lat2, lon1, lon2, backoff_idx=0 ):
"""
This one will be called recursively until the subdivision
is fully downloaded. In case it reaches 10k it breaks down
this subdivision into two parts by dividing the longitude
interval into two. Something like this:
lat2
-----------------
| | ^
| | | N
lon1 | | lon2
| |
| |
-----------------
lat1
Becomes:
lat2
-----------------
| | | ^
| | | | N
lon1 | | | lon2
| |lon1_5 |
| | |
-----------------
lat1
"""
print >> sys.stdout, 'Downloading ({0},{1},{2},{3})'.format( lat1, lat2, lon1, lon2 )
try:
RESULTS = self.wigle.search( lat_range = ( lat1, lat2 ),
long_range = ( lon1, lon2 ),
on_new_page = callback_newpage,
max_results = WigleDownloader.wigle_max_ap_per_query )
# Need to double check this
if len(RESULTS) >= 9998:
print >> sys.stderr, 'Subdividing {0} {1} {2} {3}'.format(lat1,lat2,lon1,lon2)
## Will break down longitude interval into two parts
lon1_5 = (lon2-lon1)/2.0
R1 = _download( lat1, lat2, lon1, lon1_5 )
R2 = _download( lat1, lat2, lon1_5, lon2 )
RESULTS = R1.copy()
RESULTS.update(R2)
except wigle.WigleRatelimitExceeded as wrle:
wait_s = WigleDownloader.wigle_timeout_backoff[backoff_idx]
print >> sys.stderr, 'Already got WigleRatelimitExceeded.'
print >> sys.stderr, 'Sleeping for {0} seconds before trying again.'.format(wait_s)
time.sleep(wait_s)
## We may enter an infinite loop here...
## TODO: solve it (for now check the stdout for problems)
return _download(lat1, lat2, lon1, lon2,
backoff_idx=(backoff_idx+1)%len(WigleDownloader.wigle_timeout_backoff))
except wigle.WigleError as we:
print >> sys.stderr, we
print >> sys.stderr, 'Something wrong with Wigle, stopping..'
raise
except KeyboardInterrupt:
print >> sys.stderr, 'Stopping the script.'
sys.exit(0)
except:
print >> sys.stderr, 'This looks like a bug.', sys.exc_info()[0]
return []
else:
sucess_string = 'Sucess downloading ({0},{1},{2},{3}) with {4} APs'
print >> sys.stdout, sucess_string.format( lat1, lat2, lon1, lon2, len(RESULTS) )
return RESULTS
try:
##
for interval in self.INTERVALS:
assert len(interval) == 4, 'Something wrong generating self.INTERVALS.'
lat1,lat2,lon1,lon2 = interval
AP_SUBDIVISION = _download( lat1, lat2, lon1, lon2 )
## Write this out using pickle
## TODO: write out as sqlite file
pickle_file = '{0}/{1}_{2}_{3}_{4}.p'.format( self.outpath, lat1, lat2, lon1, lon2 )
pickle.dump(AP_SUBDIVISION, open( pickle_file, "wb" ))
## Note: this was .reverse()'ed before
## Pop'ing from the end of the list is much quicker
self.REMAINING_INTERVALS.pop()
## Write out coord.remain
with open( WigleDownloader.file_default_remain, 'wb' ) as coord_remain_file:
for interval in self.REMAINING_INTERVALS:
print >> coord_remain_file, ','.join(map(str,interval))
except KeyboardInterrupt:
print >> sys.stderr, 'Stopping the script.'
sys.exit(0)
except:
print >> sys.stderr, 'This looks like a bug.', sys.exc_info()[0]
sys.exit(-3)
def compute_intervals(self):
"""
Returns a list with tuples containing:
[(box_lat_min,box_lat_max,box_lon_min,box_lon_max),...]
Since [0][0] is the upper left corner, lon grows positively
but lat grows negatively.
"""
if len(self.div_map) != self.latdiv or len(self.div_map[0]) != self.londiv:
raise RuntimeError('Map dimensions not correct!')
## Compute the size of each initial box (in degrees).
lat_step = -(self.latmax - self.latmin) / self.latdiv
lon_step = (self.lonmax - self.lonmin) / self.londiv
## Compute the intervals.
initial_lat = self.latmax
initial_lon = self.lonmin
for row in self.div_map:
initial_lon = self.lonmin
for subdivisions in row:
lat_sub_step = lat_step / float(subdivisions)
lon_sub_step = lon_step / float(subdivisions)
## min for each subdivision, for max we just add sub_step to it.
lats = list(drange(initial_lat,initial_lat+lat_step,lat_sub_step))
lons = list(drange(initial_lon,initial_lon+lon_step,lon_sub_step))
self.INTERVALS.extend([( lat, lat+lat_sub_step,
lon, lon+lon_sub_step ) for lat,lon in zip( lats, lons )])
initial_lon += lon_step
initial_lat += lat_step
def parse_coordfile( self, coordfile ):
"""
Parses the coord.remain file with the following format:
lat1,lat2,lon1,lon2
"""
print >> sys.stdout, 'Parsing coord.remain file.'
with open(coordfile) as f:
line = f.readline()
while line:
COORDS = line.strip().split(',')
assert len(COORDS) == 4, 'Something is wrong with coord.remain file.'
self.INTERVALS.append(tuple(COORDS))
line = f.readline()
print >> sys.stdout, 'Found {0} subdivisions to download'.format(len(self.INTERVALS))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Wigle Downloader arguments')
parser.add_argument(
'-u', '--user', help='Wigle username', required=True )
parser.add_argument(
'-p', '--password', help='Wigle password', required=True )
parser.add_argument(
'--coordfile', help='coord.remain file path', required=False, default=None )
parser.add_argument(
'-o', '--outpath', help='Path to store pickle files.')
|
[
" args = parser.parse_args()"
] | 1,225
|
lcc
|
python
| null |
43954d45633ac63acc4badb3892fdb276e080592cc147b1e
| 26
|
Your task is code completion.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## version 2 as published by the Free Software Foundation.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##
## author: Leonardo Tonetto
__author__ = "Leonardo Tonetto"
__copyright__ = "Copyright 2016, Leonardo Tonetto"
__license__ = "GPLv2"
__version__ = "0.1"
import sys
try:
import wigle
except ImportError:
print >> sys.stderr, 'Please install wigle (eg. pip install wigle)'
sys.exit(1)
import argparse, pickle, time
def drange(start, stop, step):
"""
Float point implementation of range()
Based on (but not exactly):
http://stackoverflow.com/questions/477486/python-decimal-range-step-value
"""
## few sanity checks first
if start < stop and step < 0:
raise RuntimeError('Wrong input variables, step should be > 0.')
if start > stop and step > 0:
raise RuntimeError('Wrong input variables, step should be < 0.')
r = start
while start < stop and r < stop:
yield r
r += step
while start > stop and r > stop:
yield r
r += step
class WigleDownloader:
"""
Downloads AP info from wigle.net
[HARDCODED] YEEEAH!
lat/lon_min/max : interval of the desired area.
lat_lon_div : number of divisions along each axis (used to double check).
div_map: initial num. of subdivisions inside each original division
this has to have the same number of columns/rows as the *_div arg.
Ref.: [0][0] is the upper left box
In case none is given, 1 is applied to all boxes
"""
## Some constants
wigle_downloads_per_page = wigle.WIGLE_PAGESIZE
wigle_max_ap_per_query = 10000
## These add up to 24h, time we would expect to have the quota renewed
wigle_timeout_backoff = [0.25*3600, ## 15 minutes
0.25*3600,
0.5*3600,
1*3600,
2*3600,
4*3600,
8*3600,
8*3600] ## 8 hours
file_default_remain = './coord.remain'
def __init__( self, user, password, coordfile, outpath ):
try:
## Wigle, wigle, wigle :-)
self.wigle = wigle.Wigle( user, password )
except wigle.WigleAuthenticationError as wae:
print >> sys.stderr, 'Authentication error for {1}.'.format(user)
print >> sys.stderr, wae.message
sys.exit(-1)
except wigle.WigleError as werr:
print >> sys.stderr, werr.message
sys.exit(-2)
self.outpath = outpath
self.coordfile = coordfile
## This is for the city of Munich-DE
## TODO: replace this with geocoding
self.latmin = 47.95
self.latmax = 48.43
self.lonmin = 11.00
self.lonmax = 12.15
self.latdiv = 6
self.londiv = 10
## For the lazy: use this one
## Do not modify this lazy map after this point since rows will be the same object...
#self.div_map = [[1]*self.londiv]*self.latdiv
## Or you can do it like that
self.div_map = [[ 2, 2, 2, 2, 2, 2, 8, 2, 2, 2],
[ 2, 2, 2, 2, 4, 3, 2, 5, 2, 2],
[ 2, 4, 5, 4, 4, 5, 2, 4, 2, 2],
[ 2, 4, 4, 8,18, 8, 8, 6, 2, 2],
[ 2, 2, 3, 4,16, 8, 4, 2, 2, 2],
[ 2, 2, 4, 4, 4, 4, 2, 2, 2, 2]]
self.INTERVALS = []
self.REMAINING_INTERVALS = []
def run(self):
"""
Just so that it does not look so ugly
"""
## We either call compute_intervals() or parse_coordfile()
if self.coordfile:
self.parse_coordfile(self.coordfile)
else:
self.compute_intervals()
self.REMAINING_INTERVALS = self.INTERVALS[:]
self.REMAINING_INTERVALS.reverse()
## Now we (continue) download(ing)
self.download()
def download(self):
"""
Download whatever is inside self.INTERVALS using
wigle pythong API (not official apparently)
"""
def callback_newpage(since):
pass
def _download( lat1, lat2, lon1, lon2, backoff_idx=0 ):
"""
This one will be called recursively until the subdivision
is fully downloaded. In case it reaches 10k it breaks down
this subdivision into two parts by dividing the longitude
interval into two. Something like this:
lat2
-----------------
| | ^
| | | N
lon1 | | lon2
| |
| |
-----------------
lat1
Becomes:
lat2
-----------------
| | | ^
| | | | N
lon1 | | | lon2
| |lon1_5 |
| | |
-----------------
lat1
"""
print >> sys.stdout, 'Downloading ({0},{1},{2},{3})'.format( lat1, lat2, lon1, lon2 )
try:
RESULTS = self.wigle.search( lat_range = ( lat1, lat2 ),
long_range = ( lon1, lon2 ),
on_new_page = callback_newpage,
max_results = WigleDownloader.wigle_max_ap_per_query )
# Need to double check this
if len(RESULTS) >= 9998:
print >> sys.stderr, 'Subdividing {0} {1} {2} {3}'.format(lat1,lat2,lon1,lon2)
## Will break down longitude interval into two parts
lon1_5 = (lon2-lon1)/2.0
R1 = _download( lat1, lat2, lon1, lon1_5 )
R2 = _download( lat1, lat2, lon1_5, lon2 )
RESULTS = R1.copy()
RESULTS.update(R2)
except wigle.WigleRatelimitExceeded as wrle:
wait_s = WigleDownloader.wigle_timeout_backoff[backoff_idx]
print >> sys.stderr, 'Already got WigleRatelimitExceeded.'
print >> sys.stderr, 'Sleeping for {0} seconds before trying again.'.format(wait_s)
time.sleep(wait_s)
## We may enter an infinite loop here...
## TODO: solve it (for now check the stdout for problems)
return _download(lat1, lat2, lon1, lon2,
backoff_idx=(backoff_idx+1)%len(WigleDownloader.wigle_timeout_backoff))
except wigle.WigleError as we:
print >> sys.stderr, we
print >> sys.stderr, 'Something wrong with Wigle, stopping..'
raise
except KeyboardInterrupt:
print >> sys.stderr, 'Stopping the script.'
sys.exit(0)
except:
print >> sys.stderr, 'This looks like a bug.', sys.exc_info()[0]
return []
else:
sucess_string = 'Sucess downloading ({0},{1},{2},{3}) with {4} APs'
print >> sys.stdout, sucess_string.format( lat1, lat2, lon1, lon2, len(RESULTS) )
return RESULTS
try:
##
for interval in self.INTERVALS:
assert len(interval) == 4, 'Something wrong generating self.INTERVALS.'
lat1,lat2,lon1,lon2 = interval
AP_SUBDIVISION = _download( lat1, lat2, lon1, lon2 )
## Write this out using pickle
## TODO: write out as sqlite file
pickle_file = '{0}/{1}_{2}_{3}_{4}.p'.format( self.outpath, lat1, lat2, lon1, lon2 )
pickle.dump(AP_SUBDIVISION, open( pickle_file, "wb" ))
## Note: this was .reverse()'ed before
## Pop'ing from the end of the list is much quicker
self.REMAINING_INTERVALS.pop()
## Write out coord.remain
with open( WigleDownloader.file_default_remain, 'wb' ) as coord_remain_file:
for interval in self.REMAINING_INTERVALS:
print >> coord_remain_file, ','.join(map(str,interval))
except KeyboardInterrupt:
print >> sys.stderr, 'Stopping the script.'
sys.exit(0)
except:
print >> sys.stderr, 'This looks like a bug.', sys.exc_info()[0]
sys.exit(-3)
def compute_intervals(self):
"""
Returns a list with tuples containing:
[(box_lat_min,box_lat_max,box_lon_min,box_lon_max),...]
Since [0][0] is the upper left corner, lon grows positively
but lat grows negatively.
"""
if len(self.div_map) != self.latdiv or len(self.div_map[0]) != self.londiv:
raise RuntimeError('Map dimensions not correct!')
## Compute the size of each initial box (in degrees).
lat_step = -(self.latmax - self.latmin) / self.latdiv
lon_step = (self.lonmax - self.lonmin) / self.londiv
## Compute the intervals.
initial_lat = self.latmax
initial_lon = self.lonmin
for row in self.div_map:
initial_lon = self.lonmin
for subdivisions in row:
lat_sub_step = lat_step / float(subdivisions)
lon_sub_step = lon_step / float(subdivisions)
## min for each subdivision, for max we just add sub_step to it.
lats = list(drange(initial_lat,initial_lat+lat_step,lat_sub_step))
lons = list(drange(initial_lon,initial_lon+lon_step,lon_sub_step))
self.INTERVALS.extend([( lat, lat+lat_sub_step,
lon, lon+lon_sub_step ) for lat,lon in zip( lats, lons )])
initial_lon += lon_step
initial_lat += lat_step
def parse_coordfile( self, coordfile ):
"""
Parses the coord.remain file with the following format:
lat1,lat2,lon1,lon2
"""
print >> sys.stdout, 'Parsing coord.remain file.'
with open(coordfile) as f:
line = f.readline()
while line:
COORDS = line.strip().split(',')
assert len(COORDS) == 4, 'Something is wrong with coord.remain file.'
self.INTERVALS.append(tuple(COORDS))
line = f.readline()
print >> sys.stdout, 'Found {0} subdivisions to download'.format(len(self.INTERVALS))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Wigle Downloader arguments')
parser.add_argument(
'-u', '--user', help='Wigle username', required=True )
parser.add_argument(
'-p', '--password', help='Wigle password', required=True )
parser.add_argument(
'--coordfile', help='coord.remain file path', required=False, default=None )
parser.add_argument(
'-o', '--outpath', help='Path to store pickle files.')
|
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 Wigle Downloader code completion task:
**Context:**
[Previous code... ~10,000 lines omitted for brevity]
def download(self):
...
try:
for interval in self.INTERVALS:
assert len(interval) == 4, 'Something wrong generating self.INTERVALS.'
lat1,lat2,lon1,lon2 = interval
AP_SUBDIVISION = _download( lat1, lat2, lon1, lon2 )
## Write this out using pickle
## TODO: write out as sqlite file
pickle_file = '{0}/{1}_{2}_{3}_{4}.p'.format( self.outpath, lat1, lat2, lon1, lon2 )
pickle.dump(AP_SUBDIVISION, open( pickle_file, "wb" ))
## Note: this was .reverse()'ed before
## Pop'ing from the end of the list is much quicker
self.REMAINING_INTERVALS.pop()
## Write out coord.remain
with open( WigleDownloader.file_default_remain, 'wb' ) as coord_remain_file:
for interval in self.REMAINING_INTERVALS:
print >> coord_remain_file, ','.join(map(str,interval))
except KeyboardInterrupt:
print >> sys.stderr, 'Stopping the script.'
sys.exit(0)
except:
print >> sys.stderr, 'This looks like a bug.', sys.exc_info()[0]
sys.exit(-3)
**Cheat sheet:**
- We are in the download() method, which is responsible for downloading AP info from Wigle.net.
- The current loop is iterating over self.INTERVALS, which is a list of tuples containing latitude and longitude coordinates.
- The current interval is being processed, and its coordinates are stored in lat1, lat2, lon1, and lon2 variables.
- The _download() function is called to download AP info for the current interval.
- The downloaded data is stored in the AP_SUBDIVISION variable.
- The downloaded data is written to a pickle file using pickle.dump().
- The current interval is removed from self.INTERVALS using pop().
- The remaining intervals are written to the coord.remain file.
**Next line(s) of code:**
The next line of code should be responsible for writing the remaining intervals to the coord.remain file. Since the current interval has just been removed from self.REMAINING_INTERVALS, we need to write the next interval in the list.
The relevant lines are:
- self.REMAINING_INTERVALS.pop() (removes the current interval)
- for interval in self.REMAINING_INTERVALS: (iterates over the remaining intervals)
The next line of code should be:
```python
print >> coord_remain_file, ','.join(map(str,interval))
```
However, this line is already present in the code. The next line should be the next iteration of the for loop, which is:
```python
interval = self.REMAINING_INTERVALS.pop()
```
But this is not correct, because we want to iterate over the remaining intervals, not pop them. So, the correct next line of code is:
```python
interval = self.REMAINING_INTERVALS.pop(0)
```
This line pops the first element from the list and assigns it to the interval variable.
|
|
Please complete the code given below.
using System;
using Server;
using Server.Targeting;
using Server.Mobiles;
using Server.Network;
using Server.Items;
using Server.Gumps;
using System.Collections;
using System.Collections.Generic;
using Server.ContextMenus;
using Server.SkillHandlers;
namespace Server.Gumps
{
public class ImbuingGumpC : Gump
{
private const int LabelHue = 0x480;
private const int LabelColor = 0x7FFF; //Localized
private const int FontColor = 0xFFFFFF; //string
private const int ValueColor = 0xCCCCFF;
public const int MaxProps = 5;
private int m_Mod, m_Value;
private Item m_Item;
private int m_GemAmount = 0, m_PrimResAmount = 0, m_SpecResAmount = 0;
private int m_TotalItemWeight;
private int m_TotalProps;
private int m_PropWeight;
private int m_MaxWeight;
private ImbuingDefinition m_Definition;
public ImbuingGumpC(Mobile from, Item item, int mod, int value) : base(520, 340)
{
PlayerMobile m = from as PlayerMobile;
from.CloseGump(typeof(ImbuingGump));
from.CloseGump(typeof(ImbuingGumpB));
// SoulForge Check
if (!Imbuing.CheckSoulForge(from, 1))
return;
ImbuingContext context = Imbuing.GetContext(m);
m_Item = item;
m_Mod = mod;
m_Value = value;
// = Check Type of Ingredients Needed
if (!Imbuing.Table.ContainsKey(m_Mod))
return;
m_Definition = Imbuing.Table[m_Mod];
int maxInt = m_Definition.MaxIntensity;
int inc = m_Definition.IncAmount;
int weight = m_Definition.Weight;
if (m_Item is BaseJewel && m_Mod == 12)
maxInt /= 2;
if (m_Value < inc)
m_Value = inc;
if (m_Value > maxInt)
m_Value = maxInt;
if (m_Value <= 0)
m_Value = 1;
//double currentIntensity = ((double)m_Value / (double)maxInt) * 100.0;
//currentIntensity = Math.Round(currentIntensity, 1);
double currentIntensity = ((double)weight / (double)maxInt * m_Value);
currentIntensity = Math.Floor(currentIntensity);
//Set context
context.LastImbued = item;
context.Imbue_Mod = mod;
context.Imbue_ModVal = weight;
context.ImbMenu_ModInc = inc;
context.Imbue_ModInt = value;
// - Current Mod Weight
m_TotalItemWeight = Imbuing.GetTotalWeight(m_Item, m_Mod);
m_TotalProps = Imbuing.GetTotalMods(m_Item, m_Mod);
if (maxInt <= 1)
currentIntensity= 100;
double propweight = ((double)weight / (double)maxInt) * m_Value;
//propweight = Math.Round(propweight);
propweight = Math.Floor(propweight);
m_PropWeight = Convert.ToInt32(propweight);
// - Maximum allowed Property Weight & Item Mod Count
m_MaxWeight = Imbuing.GetMaxWeight(m_Item);
// = Times Item has been Imbued
int timesImbued = 0;
if (m_Item is BaseWeapon)
timesImbued = ((BaseWeapon)m_Item).TimesImbued;
if (m_Item is BaseArmor)
timesImbued = ((BaseArmor)m_Item).TimesImbued;
if (m_Item is BaseJewel)
timesImbued = ((BaseJewel)m_Item).TimesImbued;
if (m_Item is BaseHat)
timesImbued = ((BaseHat)m_Item).TimesImbued;
// = Check Ingredients needed at the current Intensity
m_GemAmount = Imbuing.GetGemAmount(m_Item, m_Mod, m_Value);
m_PrimResAmount = Imbuing.GetPrimaryAmount(m_Item, m_Mod, m_Value);
m_SpecResAmount = Imbuing.GetSpecialAmount(m_Item, m_Mod, m_Value);
// ------------------------------ Gump Menu -------------------------------------------------------------
AddPage(0);
AddBackground(0, 0, 540, 450, 5054);
AddImageTiled(10, 10, 520, 430, 2624);
AddImageTiled(10, 35, 520, 10, 5058);
AddImageTiled(260, 45, 15, 290, 5058);
AddImageTiled(10, 185, 520, 10, 5058);
AddImageTiled(10, 335, 520, 10, 5058);
AddImageTiled(10, 405, 520, 10, 5058);
AddAlphaRegion(10, 10, 520, 430);
AddHtmlLocalized(10, 13, 520, 18, 1079717, LabelColor, false, false); //<CENTER>IMBUING CONFIRMATION</CENTER>
AddHtmlLocalized(57, 49, 200, 18, 1114269, LabelColor, false, false); //PROPERTY INFORMATION
// - Attribute to Imbue
AddHtmlLocalized(30, 80, 80, 17, 1114270, LabelColor, false, false); //Property:
AddHtmlLocalized(100, 80, 150, 17, m_Definition.AttributeName, LabelColor, false, false);
// - Weight Modifier
AddHtmlLocalized(30, 120, 80, 17, 1114272, 0xFFFFFF, false, false); //Weight:
double w = (double)m_Definition.Weight / 100.0;
AddHtml(90, 120, 80, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}x", w), false, false);
AddHtmlLocalized(30, 140, 80, 17, 1114273, LabelColor, false, false); //Intensity:
AddHtml(90, 140, 80, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}%", currentIntensity), false, false);
// - Materials needed
AddHtmlLocalized(10, 199, 255, 18, 1044055, LabelColor, false, false); //<CENTER>MATERIALS</CENTER>
AddHtmlLocalized(40, 230, 180, 17, m_Definition.PrimaryName, LabelColor, false, false);
AddHtml(210, 230, 40, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}", m_PrimResAmount.ToString()), false, false);
AddHtmlLocalized(40, 255, 180, 17, m_Definition.GemName, LabelColor, false, false);
AddHtml(210, 255, 40, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}", m_GemAmount.ToString()), false, false);
if (m_SpecResAmount > 0)
{
AddHtmlLocalized(40, 280, 180, 17, m_Definition.SpecialName, LabelColor, false, false);
AddHtml(210, 280, 40, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}", m_SpecResAmount.ToString()), false, false);
}
// - Mod Description
AddHtmlLocalized(290, 65, 215, 110, m_Definition.Description, LabelColor, false, false);
AddHtmlLocalized(365, 199, 150, 18, 1113650, LabelColor, false, false); //RESULTS
AddHtmlLocalized(288, 220, 150, 17, 1113645, LabelColor, false, false); //Properties:
AddHtml(443, 220, 80, 17, String.Format("<BASEFONT COLOR=#CCFFCC> {0}/5", m_TotalProps + 1), false, false);
AddHtmlLocalized(288, 240, 150, 17, 1113646, LabelColor, false, false); //Total Property Weight:
AddHtml(443, 240, 80, 17, String.Format("<BASEFONT COLOR=#CCFFCC> {0}/{1}", m_TotalItemWeight + (int)m_PropWeight, m_MaxWeight), false, false);
// - Times Imbued
AddHtmlLocalized(288, 260, 150, 17, 1113647, LabelColor, false, false); //Times Imbued:
AddHtml(443, 260, 80, 17, String.Format("<BASEFONT COLOR=#CCFFCC> {0}/20", timesImbued + 1), false, false);
// - Name of Attribute to be Replaced
int replace = WhatReplacesWhat(m_Mod, m_Item);
AddHtmlLocalized(30, 100, 80, 17, 1114271, LabelColor, false, false);
if (replace <= 0)
replace = m_Definition.AttributeName;
AddHtmlLocalized(100, 100, 150, 17, replace, LabelColor, false, false);
// ===== CALCULATE DIFFICULTY =====
double dif;
double suc = Imbuing.GetSuccessChance(from, item, m_TotalItemWeight, m_PropWeight, out dif);
int Succ = Convert.ToInt32(suc);
string color;
// = Imbuing Success Chance %
AddHtmlLocalized(305, 300, 150, 17, 1044057, 0xFFFFFF, false, false);
if (Succ <= 1) color = "#FF5511";
else if (Succ > 1 && Succ < 10) color = "#EE6611";
else if (Succ >= 10 && Succ < 20) color = "#DD7711";
else if (Succ >= 20 && Succ < 30) color = "#CC8811";
else if (Succ >= 30 && Succ < 40) color = "#BB9911";
else if (Succ >= 40 && Succ < 50) color = "#AAAA11";
else if (Succ >= 50 && Succ < 60) color = "#99BB11";
else if (Succ >= 60 && Succ < 70) color = "#88CC11";
else if (Succ >= 70 && Succ < 80) color = "#77DD11";
else if (Succ >= 80 && Succ < 90) color = "#66EE11";
else if (Succ >= 90 && Succ < 100) color = "#55FF11";
else if (Succ >= 100) color = "#01FF01";
else color = "#FFFFFF";
if (suc > 100) suc = 100;
if (suc < 0) suc = 0;
AddHtml(430, 300, 80, 17, String.Format("<BASEFONT COLOR={0}>\t{1}%", color, suc), false, false);
// - Attribute Level
int ModValue_plus = 0;
if (maxInt > 1)
{
// - Set Intesity to Minimum
if (m_Value <= 0)
m_Value = 1;
// = New Value:
AddHtmlLocalized(245, 350, 100, 17, 1062300, LabelColor, false, false);
// - Mage Weapon Value ( i.e [Mage Weapon -25] )
if (m_Mod == 41)
AddHtml(254, 374, 50, 17, String.Format("<BASEFONT COLOR=#CCCCFF> -{0}", (30 - m_Value)), false, false);
// - Show Property Value as % ( i.e [Hit Fireball 25%] )
else if (maxInt <= 8 || m_Mod == 21 || m_Mod == 17)
AddHtml(254, 374, 50, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}", (m_Value + ModValue_plus)), false, false);
// - Show Property Value as just Number ( i.e [Mana Regen 2] )
else
AddHtml(254, 374, 50, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}%", (m_Value + ModValue_plus)), false, false);
// == Buttons ==
//0x1467???
AddButton(192, 376, 5230, 5230, 10053, GumpButtonType.Reply, 0); // To Minimum Value
AddButton(211, 376, 5230, 5230, 10052, GumpButtonType.Reply, 0); // Dec Value by %
AddButton(230, 376, 5230, 5230, 10051, GumpButtonType.Reply, 0); // dec value by 1
AddButton(331, 376, 5230, 5230, 10056, GumpButtonType.Reply, 0); //To Maximum Value
AddButton(312, 376, 5230, 5230, 10055, GumpButtonType.Reply, 0); // Inc Value by %
AddButton(293, 376, 5230, 5230, 10054, GumpButtonType.Reply, 0); // inc Value by 1
AddLabel(341, 374, 0, ">");
AddLabel(337, 374, 0, ">");
AddLabel(333, 374, 0, ">");
AddLabel(320, 374, 0, ">");
AddLabel(316, 374, 0, ">");
AddLabel(298, 374, 0, ">");
AddLabel(235, 374, 0, "<");
AddLabel(216, 374, 0, "<");
AddLabel(212, 374, 0, "<");
AddLabel(199, 374, 0, "<");
AddLabel(195, 374, 0, "<");
AddLabel(191, 374, 0, "<");
}
AddButton(19, 416, 4005, 4007, 10099, GumpButtonType.Reply, 0);
AddHtmlLocalized(58, 417, 100, 18, 1114268, LabelColor, false, false); //Back
AddButton(400, 416, 4005, 4007, 10100, GumpButtonType.Reply, 0);
AddHtmlLocalized(439, 417, 120, 18, 1114267, LabelColor, false, false); //Imbue Item
}
public override void OnResponse(NetState state, RelayInfo info)
{
Mobile from = state.Mobile;
PlayerMobile pm = from as PlayerMobile;
ImbuingContext context = Imbuing.GetContext(pm);
int buttonNum = 0;
if (info.ButtonID > 0 && info.ButtonID < 10000)
buttonNum = 0;
else if (info.ButtonID > 20004)
buttonNum = 30000;
else
buttonNum = info.ButtonID;
switch (buttonNum)
{
case 0:
{
//Close
break;
}
case 10051: // = Decrease Mod Value [<]
{
if (context.Imbue_ModInt > m_Definition.IncAmount)
context.Imbue_ModInt -= m_Definition.IncAmount;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, m_Item, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10052:// = Decrease Mod Value [<<]
{
if ((m_Mod == 42 || m_Mod == 24) && context.Imbue_ModInt > 20)
context.Imbue_ModInt -= 20;
if ((m_Mod == 13 || m_Mod == 20 || m_Mod == 21) && context.Imbue_ModInt > 10)
context.Imbue_ModInt -= 10;
else if (context.Imbue_ModInt > 5)
context.Imbue_ModInt -= 5;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10053:// = Minimum Mod Value [<<<]
{
//context.Imbue_ModInt = 0;
context.Imbue_ModInt = 1;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10054: // = Increase Mod Value [>]
{
int max = m_Definition.MaxIntensity;
if(m_Mod == 12 && context.LastImbued is BaseJewel)
max = m_Definition.MaxIntensity / 2;
if (context.Imbue_ModInt + m_Definition.IncAmount <= max)
context.Imbue_ModInt += m_Definition.IncAmount;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10055: // = Increase Mod Value [>>]
{
int max = m_Definition.MaxIntensity;
if (m_Mod == 12 && context.LastImbued is BaseJewel)
max = m_Definition.MaxIntensity / 2;
if (m_Mod == 42 || m_Mod == 24)
{
if (context.Imbue_ModInt + 20 <= max)
context.Imbue_ModInt += 20;
else
context.Imbue_ModInt = max;
}
if (m_Mod == 13 || m_Mod == 20 || m_Mod == 21)
{
if (context.Imbue_ModInt + 10 <= max)
context.Imbue_ModInt += 10;
else
context.Imbue_ModInt = max;
}
else if (context.Imbue_ModInt + 5 <= max)
context.Imbue_ModInt += 5;
else
context.Imbue_ModInt = m_Definition.MaxIntensity;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10056: // = Maximum Mod Value [>>>]
{
int max = m_Definition.MaxIntensity;
if (m_Mod == 12 && context.LastImbued is BaseJewel)
max = m_Definition.MaxIntensity / 2;
context.Imbue_ModInt = max;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10099: // - Back
{
from.SendGump(new ImbuingGumpB(from, context.LastImbued));
break;
}
case 10100: // = Imbue the Item
{
context.Imbue_IWmax = m_MaxWeight;
if (Imbuing.OnBeforeImbue(from, m_Item, m_Mod, m_Value, m_TotalProps, MaxProps, m_TotalItemWeight, m_MaxWeight))
{
from.CloseGump(typeof(ImbuingGumpC));
Imbuing.ImbueItem(from, m_Item, m_Mod, m_Value);
SendGumpDelayed(from);
}
break;
}
}
}
public void SendGumpDelayed(Mobile from)
{
Timer.DelayCall(TimeSpan.FromSeconds(1.5), new TimerStateCallback(SendGump_Callback), from);
}
public void SendGump_Callback(object o)
{
Mobile from = o as Mobile;
if (from != null)
from.SendGump(new ImbuingGump(from));
}
// =========== Check if Choosen Attribute Replaces Another =================
public static int WhatReplacesWhat(int mod, Item item)
{
if (item is BaseWeapon)
{
BaseWeapon i = item as BaseWeapon;
// Slayers replace Slayers
if (mod >= 101 && mod <= 126)
{
if (i.Slayer != SlayerName.None)
return GetNameForAttribute(i.Slayer);
if (i.Slayer2 != SlayerName.None)
return GetNameForAttribute(i.Slayer2);
}
// OnHitEffect replace OnHitEffect
if (mod >= 35 && mod <= 39)
{
if (i.WeaponAttributes.HitMagicArrow > 0)
return GetNameForAttribute(AosWeaponAttribute.HitMagicArrow);
else if (i.WeaponAttributes.HitHarm > 0)
return GetNameForAttribute(AosWeaponAttribute.HitHarm);
else if (i.WeaponAttributes.HitFireball > 0)
return GetNameForAttribute(AosWeaponAttribute.HitFireball);
else if (i.WeaponAttributes.HitLightning > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLightning);
else if (i.WeaponAttributes.HitDispel > 0)
return GetNameForAttribute(AosWeaponAttribute.HitDispel);
}
// OnHitArea replace OnHitArea
if (mod >= 30 && mod <= 34)
{
if (i.WeaponAttributes.HitPhysicalArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitPhysicalArea);
else if (i.WeaponAttributes.HitColdArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitFireArea);
else if (i.WeaponAttributes.HitFireArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitColdArea);
else if (i.WeaponAttributes.HitPoisonArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitPoisonArea);
else if (i.WeaponAttributes.HitEnergyArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitEnergyArea);
}
// OnHitLeech replace OnHitLeech
/*if (mod >= 25 && mod <= 27)
{
if (i.WeaponAttributes.HitLeechHits > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLeechHits);
else if (i.WeaponAttributes.HitLeechStam > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLeechStam);
else if (i.WeaponAttributes.HitLeechMana > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLeechMana);
}
// HitLower replace HitLower
if (mod >= 28 && mod <= 29)
{
if (i.WeaponAttributes.HitLowerAttack > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLowerAttack);
else if (i.WeaponAttributes.HitLowerDefend > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLowerDefend);
}*/
}
if (item is BaseJewel)
{
BaseJewel i = item as BaseJewel;
// SkillGroup1 replace SkillGroup1
if (mod >= 151 && mod <= 155)
{
if (i.SkillBonuses.GetBonus(0) > 0)
{
foreach (SkillName sk in Imbuing.PossibleSkills)
{
if(i.SkillBonuses.GetSkill(0) == sk)
return GetNameForAttribute(sk);
}
}
}
// SkillGroup2 replace SkillGroup2
|
[
" if (mod >= 156 && mod <= 160)"
] | 1,845
|
lcc
|
csharp
| null |
9d639220f2ae9cbb3b86c56287371346450159efa5afc251
| 27
|
Your task is code completion.
using System;
using Server;
using Server.Targeting;
using Server.Mobiles;
using Server.Network;
using Server.Items;
using Server.Gumps;
using System.Collections;
using System.Collections.Generic;
using Server.ContextMenus;
using Server.SkillHandlers;
namespace Server.Gumps
{
public class ImbuingGumpC : Gump
{
private const int LabelHue = 0x480;
private const int LabelColor = 0x7FFF; //Localized
private const int FontColor = 0xFFFFFF; //string
private const int ValueColor = 0xCCCCFF;
public const int MaxProps = 5;
private int m_Mod, m_Value;
private Item m_Item;
private int m_GemAmount = 0, m_PrimResAmount = 0, m_SpecResAmount = 0;
private int m_TotalItemWeight;
private int m_TotalProps;
private int m_PropWeight;
private int m_MaxWeight;
private ImbuingDefinition m_Definition;
public ImbuingGumpC(Mobile from, Item item, int mod, int value) : base(520, 340)
{
PlayerMobile m = from as PlayerMobile;
from.CloseGump(typeof(ImbuingGump));
from.CloseGump(typeof(ImbuingGumpB));
// SoulForge Check
if (!Imbuing.CheckSoulForge(from, 1))
return;
ImbuingContext context = Imbuing.GetContext(m);
m_Item = item;
m_Mod = mod;
m_Value = value;
// = Check Type of Ingredients Needed
if (!Imbuing.Table.ContainsKey(m_Mod))
return;
m_Definition = Imbuing.Table[m_Mod];
int maxInt = m_Definition.MaxIntensity;
int inc = m_Definition.IncAmount;
int weight = m_Definition.Weight;
if (m_Item is BaseJewel && m_Mod == 12)
maxInt /= 2;
if (m_Value < inc)
m_Value = inc;
if (m_Value > maxInt)
m_Value = maxInt;
if (m_Value <= 0)
m_Value = 1;
//double currentIntensity = ((double)m_Value / (double)maxInt) * 100.0;
//currentIntensity = Math.Round(currentIntensity, 1);
double currentIntensity = ((double)weight / (double)maxInt * m_Value);
currentIntensity = Math.Floor(currentIntensity);
//Set context
context.LastImbued = item;
context.Imbue_Mod = mod;
context.Imbue_ModVal = weight;
context.ImbMenu_ModInc = inc;
context.Imbue_ModInt = value;
// - Current Mod Weight
m_TotalItemWeight = Imbuing.GetTotalWeight(m_Item, m_Mod);
m_TotalProps = Imbuing.GetTotalMods(m_Item, m_Mod);
if (maxInt <= 1)
currentIntensity= 100;
double propweight = ((double)weight / (double)maxInt) * m_Value;
//propweight = Math.Round(propweight);
propweight = Math.Floor(propweight);
m_PropWeight = Convert.ToInt32(propweight);
// - Maximum allowed Property Weight & Item Mod Count
m_MaxWeight = Imbuing.GetMaxWeight(m_Item);
// = Times Item has been Imbued
int timesImbued = 0;
if (m_Item is BaseWeapon)
timesImbued = ((BaseWeapon)m_Item).TimesImbued;
if (m_Item is BaseArmor)
timesImbued = ((BaseArmor)m_Item).TimesImbued;
if (m_Item is BaseJewel)
timesImbued = ((BaseJewel)m_Item).TimesImbued;
if (m_Item is BaseHat)
timesImbued = ((BaseHat)m_Item).TimesImbued;
// = Check Ingredients needed at the current Intensity
m_GemAmount = Imbuing.GetGemAmount(m_Item, m_Mod, m_Value);
m_PrimResAmount = Imbuing.GetPrimaryAmount(m_Item, m_Mod, m_Value);
m_SpecResAmount = Imbuing.GetSpecialAmount(m_Item, m_Mod, m_Value);
// ------------------------------ Gump Menu -------------------------------------------------------------
AddPage(0);
AddBackground(0, 0, 540, 450, 5054);
AddImageTiled(10, 10, 520, 430, 2624);
AddImageTiled(10, 35, 520, 10, 5058);
AddImageTiled(260, 45, 15, 290, 5058);
AddImageTiled(10, 185, 520, 10, 5058);
AddImageTiled(10, 335, 520, 10, 5058);
AddImageTiled(10, 405, 520, 10, 5058);
AddAlphaRegion(10, 10, 520, 430);
AddHtmlLocalized(10, 13, 520, 18, 1079717, LabelColor, false, false); //<CENTER>IMBUING CONFIRMATION</CENTER>
AddHtmlLocalized(57, 49, 200, 18, 1114269, LabelColor, false, false); //PROPERTY INFORMATION
// - Attribute to Imbue
AddHtmlLocalized(30, 80, 80, 17, 1114270, LabelColor, false, false); //Property:
AddHtmlLocalized(100, 80, 150, 17, m_Definition.AttributeName, LabelColor, false, false);
// - Weight Modifier
AddHtmlLocalized(30, 120, 80, 17, 1114272, 0xFFFFFF, false, false); //Weight:
double w = (double)m_Definition.Weight / 100.0;
AddHtml(90, 120, 80, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}x", w), false, false);
AddHtmlLocalized(30, 140, 80, 17, 1114273, LabelColor, false, false); //Intensity:
AddHtml(90, 140, 80, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}%", currentIntensity), false, false);
// - Materials needed
AddHtmlLocalized(10, 199, 255, 18, 1044055, LabelColor, false, false); //<CENTER>MATERIALS</CENTER>
AddHtmlLocalized(40, 230, 180, 17, m_Definition.PrimaryName, LabelColor, false, false);
AddHtml(210, 230, 40, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}", m_PrimResAmount.ToString()), false, false);
AddHtmlLocalized(40, 255, 180, 17, m_Definition.GemName, LabelColor, false, false);
AddHtml(210, 255, 40, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}", m_GemAmount.ToString()), false, false);
if (m_SpecResAmount > 0)
{
AddHtmlLocalized(40, 280, 180, 17, m_Definition.SpecialName, LabelColor, false, false);
AddHtml(210, 280, 40, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}", m_SpecResAmount.ToString()), false, false);
}
// - Mod Description
AddHtmlLocalized(290, 65, 215, 110, m_Definition.Description, LabelColor, false, false);
AddHtmlLocalized(365, 199, 150, 18, 1113650, LabelColor, false, false); //RESULTS
AddHtmlLocalized(288, 220, 150, 17, 1113645, LabelColor, false, false); //Properties:
AddHtml(443, 220, 80, 17, String.Format("<BASEFONT COLOR=#CCFFCC> {0}/5", m_TotalProps + 1), false, false);
AddHtmlLocalized(288, 240, 150, 17, 1113646, LabelColor, false, false); //Total Property Weight:
AddHtml(443, 240, 80, 17, String.Format("<BASEFONT COLOR=#CCFFCC> {0}/{1}", m_TotalItemWeight + (int)m_PropWeight, m_MaxWeight), false, false);
// - Times Imbued
AddHtmlLocalized(288, 260, 150, 17, 1113647, LabelColor, false, false); //Times Imbued:
AddHtml(443, 260, 80, 17, String.Format("<BASEFONT COLOR=#CCFFCC> {0}/20", timesImbued + 1), false, false);
// - Name of Attribute to be Replaced
int replace = WhatReplacesWhat(m_Mod, m_Item);
AddHtmlLocalized(30, 100, 80, 17, 1114271, LabelColor, false, false);
if (replace <= 0)
replace = m_Definition.AttributeName;
AddHtmlLocalized(100, 100, 150, 17, replace, LabelColor, false, false);
// ===== CALCULATE DIFFICULTY =====
double dif;
double suc = Imbuing.GetSuccessChance(from, item, m_TotalItemWeight, m_PropWeight, out dif);
int Succ = Convert.ToInt32(suc);
string color;
// = Imbuing Success Chance %
AddHtmlLocalized(305, 300, 150, 17, 1044057, 0xFFFFFF, false, false);
if (Succ <= 1) color = "#FF5511";
else if (Succ > 1 && Succ < 10) color = "#EE6611";
else if (Succ >= 10 && Succ < 20) color = "#DD7711";
else if (Succ >= 20 && Succ < 30) color = "#CC8811";
else if (Succ >= 30 && Succ < 40) color = "#BB9911";
else if (Succ >= 40 && Succ < 50) color = "#AAAA11";
else if (Succ >= 50 && Succ < 60) color = "#99BB11";
else if (Succ >= 60 && Succ < 70) color = "#88CC11";
else if (Succ >= 70 && Succ < 80) color = "#77DD11";
else if (Succ >= 80 && Succ < 90) color = "#66EE11";
else if (Succ >= 90 && Succ < 100) color = "#55FF11";
else if (Succ >= 100) color = "#01FF01";
else color = "#FFFFFF";
if (suc > 100) suc = 100;
if (suc < 0) suc = 0;
AddHtml(430, 300, 80, 17, String.Format("<BASEFONT COLOR={0}>\t{1}%", color, suc), false, false);
// - Attribute Level
int ModValue_plus = 0;
if (maxInt > 1)
{
// - Set Intesity to Minimum
if (m_Value <= 0)
m_Value = 1;
// = New Value:
AddHtmlLocalized(245, 350, 100, 17, 1062300, LabelColor, false, false);
// - Mage Weapon Value ( i.e [Mage Weapon -25] )
if (m_Mod == 41)
AddHtml(254, 374, 50, 17, String.Format("<BASEFONT COLOR=#CCCCFF> -{0}", (30 - m_Value)), false, false);
// - Show Property Value as % ( i.e [Hit Fireball 25%] )
else if (maxInt <= 8 || m_Mod == 21 || m_Mod == 17)
AddHtml(254, 374, 50, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}", (m_Value + ModValue_plus)), false, false);
// - Show Property Value as just Number ( i.e [Mana Regen 2] )
else
AddHtml(254, 374, 50, 17, String.Format("<BASEFONT COLOR=#CCCCFF> {0}%", (m_Value + ModValue_plus)), false, false);
// == Buttons ==
//0x1467???
AddButton(192, 376, 5230, 5230, 10053, GumpButtonType.Reply, 0); // To Minimum Value
AddButton(211, 376, 5230, 5230, 10052, GumpButtonType.Reply, 0); // Dec Value by %
AddButton(230, 376, 5230, 5230, 10051, GumpButtonType.Reply, 0); // dec value by 1
AddButton(331, 376, 5230, 5230, 10056, GumpButtonType.Reply, 0); //To Maximum Value
AddButton(312, 376, 5230, 5230, 10055, GumpButtonType.Reply, 0); // Inc Value by %
AddButton(293, 376, 5230, 5230, 10054, GumpButtonType.Reply, 0); // inc Value by 1
AddLabel(341, 374, 0, ">");
AddLabel(337, 374, 0, ">");
AddLabel(333, 374, 0, ">");
AddLabel(320, 374, 0, ">");
AddLabel(316, 374, 0, ">");
AddLabel(298, 374, 0, ">");
AddLabel(235, 374, 0, "<");
AddLabel(216, 374, 0, "<");
AddLabel(212, 374, 0, "<");
AddLabel(199, 374, 0, "<");
AddLabel(195, 374, 0, "<");
AddLabel(191, 374, 0, "<");
}
AddButton(19, 416, 4005, 4007, 10099, GumpButtonType.Reply, 0);
AddHtmlLocalized(58, 417, 100, 18, 1114268, LabelColor, false, false); //Back
AddButton(400, 416, 4005, 4007, 10100, GumpButtonType.Reply, 0);
AddHtmlLocalized(439, 417, 120, 18, 1114267, LabelColor, false, false); //Imbue Item
}
public override void OnResponse(NetState state, RelayInfo info)
{
Mobile from = state.Mobile;
PlayerMobile pm = from as PlayerMobile;
ImbuingContext context = Imbuing.GetContext(pm);
int buttonNum = 0;
if (info.ButtonID > 0 && info.ButtonID < 10000)
buttonNum = 0;
else if (info.ButtonID > 20004)
buttonNum = 30000;
else
buttonNum = info.ButtonID;
switch (buttonNum)
{
case 0:
{
//Close
break;
}
case 10051: // = Decrease Mod Value [<]
{
if (context.Imbue_ModInt > m_Definition.IncAmount)
context.Imbue_ModInt -= m_Definition.IncAmount;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, m_Item, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10052:// = Decrease Mod Value [<<]
{
if ((m_Mod == 42 || m_Mod == 24) && context.Imbue_ModInt > 20)
context.Imbue_ModInt -= 20;
if ((m_Mod == 13 || m_Mod == 20 || m_Mod == 21) && context.Imbue_ModInt > 10)
context.Imbue_ModInt -= 10;
else if (context.Imbue_ModInt > 5)
context.Imbue_ModInt -= 5;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10053:// = Minimum Mod Value [<<<]
{
//context.Imbue_ModInt = 0;
context.Imbue_ModInt = 1;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10054: // = Increase Mod Value [>]
{
int max = m_Definition.MaxIntensity;
if(m_Mod == 12 && context.LastImbued is BaseJewel)
max = m_Definition.MaxIntensity / 2;
if (context.Imbue_ModInt + m_Definition.IncAmount <= max)
context.Imbue_ModInt += m_Definition.IncAmount;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10055: // = Increase Mod Value [>>]
{
int max = m_Definition.MaxIntensity;
if (m_Mod == 12 && context.LastImbued is BaseJewel)
max = m_Definition.MaxIntensity / 2;
if (m_Mod == 42 || m_Mod == 24)
{
if (context.Imbue_ModInt + 20 <= max)
context.Imbue_ModInt += 20;
else
context.Imbue_ModInt = max;
}
if (m_Mod == 13 || m_Mod == 20 || m_Mod == 21)
{
if (context.Imbue_ModInt + 10 <= max)
context.Imbue_ModInt += 10;
else
context.Imbue_ModInt = max;
}
else if (context.Imbue_ModInt + 5 <= max)
context.Imbue_ModInt += 5;
else
context.Imbue_ModInt = m_Definition.MaxIntensity;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10056: // = Maximum Mod Value [>>>]
{
int max = m_Definition.MaxIntensity;
if (m_Mod == 12 && context.LastImbued is BaseJewel)
max = m_Definition.MaxIntensity / 2;
context.Imbue_ModInt = max;
from.CloseGump(typeof(ImbuingGumpC));
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10099: // - Back
{
from.SendGump(new ImbuingGumpB(from, context.LastImbued));
break;
}
case 10100: // = Imbue the Item
{
context.Imbue_IWmax = m_MaxWeight;
if (Imbuing.OnBeforeImbue(from, m_Item, m_Mod, m_Value, m_TotalProps, MaxProps, m_TotalItemWeight, m_MaxWeight))
{
from.CloseGump(typeof(ImbuingGumpC));
Imbuing.ImbueItem(from, m_Item, m_Mod, m_Value);
SendGumpDelayed(from);
}
break;
}
}
}
public void SendGumpDelayed(Mobile from)
{
Timer.DelayCall(TimeSpan.FromSeconds(1.5), new TimerStateCallback(SendGump_Callback), from);
}
public void SendGump_Callback(object o)
{
Mobile from = o as Mobile;
if (from != null)
from.SendGump(new ImbuingGump(from));
}
// =========== Check if Choosen Attribute Replaces Another =================
public static int WhatReplacesWhat(int mod, Item item)
{
if (item is BaseWeapon)
{
BaseWeapon i = item as BaseWeapon;
// Slayers replace Slayers
if (mod >= 101 && mod <= 126)
{
if (i.Slayer != SlayerName.None)
return GetNameForAttribute(i.Slayer);
if (i.Slayer2 != SlayerName.None)
return GetNameForAttribute(i.Slayer2);
}
// OnHitEffect replace OnHitEffect
if (mod >= 35 && mod <= 39)
{
if (i.WeaponAttributes.HitMagicArrow > 0)
return GetNameForAttribute(AosWeaponAttribute.HitMagicArrow);
else if (i.WeaponAttributes.HitHarm > 0)
return GetNameForAttribute(AosWeaponAttribute.HitHarm);
else if (i.WeaponAttributes.HitFireball > 0)
return GetNameForAttribute(AosWeaponAttribute.HitFireball);
else if (i.WeaponAttributes.HitLightning > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLightning);
else if (i.WeaponAttributes.HitDispel > 0)
return GetNameForAttribute(AosWeaponAttribute.HitDispel);
}
// OnHitArea replace OnHitArea
if (mod >= 30 && mod <= 34)
{
if (i.WeaponAttributes.HitPhysicalArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitPhysicalArea);
else if (i.WeaponAttributes.HitColdArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitFireArea);
else if (i.WeaponAttributes.HitFireArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitColdArea);
else if (i.WeaponAttributes.HitPoisonArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitPoisonArea);
else if (i.WeaponAttributes.HitEnergyArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitEnergyArea);
}
// OnHitLeech replace OnHitLeech
/*if (mod >= 25 && mod <= 27)
{
if (i.WeaponAttributes.HitLeechHits > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLeechHits);
else if (i.WeaponAttributes.HitLeechStam > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLeechStam);
else if (i.WeaponAttributes.HitLeechMana > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLeechMana);
}
// HitLower replace HitLower
if (mod >= 28 && mod <= 29)
{
if (i.WeaponAttributes.HitLowerAttack > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLowerAttack);
else if (i.WeaponAttributes.HitLowerDefend > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLowerDefend);
}*/
}
if (item is BaseJewel)
{
BaseJewel i = item as BaseJewel;
// SkillGroup1 replace SkillGroup1
if (mod >= 151 && mod <= 155)
{
if (i.SkillBonuses.GetBonus(0) > 0)
{
foreach (SkillName sk in Imbuing.PossibleSkills)
{
if(i.SkillBonuses.GetSkill(0) == sk)
return GetNameForAttribute(sk);
}
}
}
// SkillGroup2 replace SkillGroup2
|
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]
public class ImbuingGumpC : Gump
{
// ... (many lines of code)
public override void OnResponse(NetState state, RelayInfo info)
{
// ... (many lines of code)
switch (buttonNum)
{
// ... (many lines of code)
case 10100: // = Imbue the Item
{
context.Imbue_IWmax = m_MaxWeight;
if (Imbuing.OnBeforeImbue(from, m_Item, m_Mod, m_Value, m_TotalProps, MaxProps, m_TotalItemWeight, m_MaxWeight))
{
from.CloseGump(typeof(ImbuingGumpC));
Imbuing.ImbueItem(from, m_Item, m_Mod, m_Value);
SendGumpDelayed(from);
}
break;
}
}
}
public void SendGumpDelayed(Mobile from)
{
Timer.DelayCall(TimeSpan.FromSeconds(1.5), new TimerStateCallback(SendGump_Callback), from);
}
public void SendGump_Callback(object o)
{
Mobile from = o as Mobile;
if (from != null)
from.SendGump(new ImbuingGump(from));
}
// ... (many lines of code)
}
Cheatsheet (for next line):
- We are in the case 10100 block, which handles the "Imbue the Item" button click.
- The code calls Imbuing.OnBeforeImbue() and Imbuing.ImbueItem() methods.
- The SendGumpDelayed() method is called to send a new gump after a delay.
- The SendGump_Callback() method is used to send a new gump when the delay is over.
- The context and m_Item variables are used to store the imbuing context and the item being imbued.
- The m_Mod, m_Value, m_TotalProps, MaxProps, and m_TotalItemWeight variables are used to store the imbuing parameters.
- The m_MaxWeight variable is used to store the maximum weight of the item.
Next line will likely be:
- The code should close the current gump and send a new gump to the player after a delay, but it seems like the new gump is already being sent in the SendGump_Callback() method. However, the current code does not handle the case when the imbuing is successful or failed. It would be better to add a message to the player to confirm the imbuing result.
However, if we assume that the code is correct and we just need to complete it, the next line could be:
```csharp
// No code is needed here, the SendGump_Callback() method will handle the sending of the new gump.
```
But if we want to add a message to the player to confirm the imbuing result, the next line could be:
```csharp
// Add a message to the player to confirm the imbuing result
from.SendGump(new ImbuingGump(from, Imbuing.GetImbuingResult(from, m_Item, m_Mod, m_Value)));
```
Please note that the Imbuing.GetImbuingResult() method is not defined in the given code, so it should be implemented separately.
|
|
Please complete the code given below.
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Download buttons. Let's get some terminology straight. Here is a list
of terms and example values for them:
* product: 'firefox' or 'thunderbird'
* version: 7.0, 8.0b3, 9.0a2
* build: 'beta', 'aurora', or None (for latest)
* platform: 'os_windows', 'os_linux', 'os_linux64', or 'os_osx'
* locale: a string in the form of 'en-US'
"""
from django.conf import settings
import jingo
import jinja2
from bedrock.firefox.firefox_details import firefox_details, mobile_details
from lib.l10n_utils import get_locale
nightly_desktop = ('https://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/'
'latest-mozilla-aurora')
nightly_android = ('https://ftp.mozilla.org/pub/mozilla.org/mobile/nightly/'
'latest-mozilla-aurora-android')
download_urls = {
'transition': '/firefox/new/?scene=2#download-fx',
'direct': 'https://download.mozilla.org/',
'aurora': nightly_desktop,
'aurora-l10n': nightly_desktop + '-l10n',
'aurora-android-api-9': nightly_android + (
'-api-9/fennec-%s.multi.android-arm.apk'),
'aurora-android-api-11': nightly_android + (
'-api-11/fennec-%s.multi.android-arm.apk'),
'aurora-android-x86': nightly_android + (
'-x86/fennec-%s.multi.android-i386.apk'),
}
def latest_version(locale, channel='release'):
"""Return build info for a locale and channel.
:param locale: locale string of the build
:param channel: channel of the build: release, beta, or aurora
:return: dict or None
"""
all_builds = (firefox_details.firefox_primary_builds,
firefox_details.firefox_beta_builds)
version = firefox_details.latest_version(channel)
for builds in all_builds:
if locale in builds and version in builds[locale]:
_builds = builds[locale][version]
# Append Linux 64-bit build
if 'Linux' in _builds:
_builds['Linux 64'] = _builds['Linux']
return version, _builds
def make_aurora_link(product, version, platform, locale,
force_full_installer=False):
# Download links are different for localized versions
if locale.lower() == 'en-us':
if platform == 'os_windows':
product = 'firefox-aurora-stub'
else:
product = 'firefox-aurora-latest-ssl'
else:
product = 'firefox-aurora-latest-l10n'
tmpl = '?'.join([download_urls['direct'],
'product={prod}&os={plat}&lang={locale}'])
return tmpl.format(
prod=product, locale=locale,
plat=platform.replace('os_', '').replace('windows', 'win'))
def make_download_link(product, build, version, platform, locale,
force_direct=False, force_full_installer=False,
force_funnelcake=False, funnelcake_id=None):
# Aurora has a special download link format
if build == 'aurora':
return make_aurora_link(product, version, platform, locale,
force_full_installer=force_full_installer)
# The downloaders expect the platform in a certain format
platform = {
'os_windows': 'win',
'os_linux': 'linux',
'os_linux64': 'linux64',
'os_osx': 'osx'
}[platform]
# stub installer exceptions
# TODO: NUKE FROM ORBIT!
stub_langs = settings.STUB_INSTALLER_LOCALES.get(platform, [])
if stub_langs and (stub_langs == settings.STUB_INSTALLER_ALL or
locale.lower() in stub_langs):
suffix = 'stub'
if force_funnelcake or force_full_installer:
suffix = 'latest'
version = ('beta-' if build == 'beta' else '') + suffix
elif not funnelcake_id:
# Force download via SSL. Stub installers are always downloaded via SSL.
# Funnelcakes may not be ready for SSL download
version += '-SSL'
# append funnelcake id to version if we have one
if funnelcake_id:
version = '{vers}-f{fc}'.format(vers=version, fc=funnelcake_id)
# Check if direct download link has been requested
# (bypassing the transition page)
if force_direct:
# build a direct download link
tmpl = '?'.join([download_urls['direct'],
'product={prod}-{vers}&os={plat}&lang={locale}'])
return tmpl.format(prod=product, vers=version,
plat=platform, locale=locale)
else:
# build a link to the transition page
return download_urls['transition']
def android_builds(build, builds=None):
builds = builds or []
android_link = settings.GOOGLE_PLAY_FIREFOX_LINK
variations = {
'api-9': 'Gingerbread',
'api-11': 'Honeycomb+ ARMv7',
'x86': 'x86',
}
if build.lower() == 'beta':
android_link = android_link.replace('org.mozilla.firefox',
'org.mozilla.firefox_beta')
if build == 'aurora':
for type, arch_pretty in variations.items():
link = (download_urls['aurora-android-%s' % type] %
mobile_details.latest_version('aurora'))
builds.append({'os': 'os_android',
'os_pretty': 'Android',
'os_arch_pretty': 'Android %s' % arch_pretty,
'arch': 'x86' if type == 'x86' else 'armv7 %s' % type,
'arch_pretty': arch_pretty,
'download_link': link})
if build != 'aurora':
builds.append({'os': 'os_android',
'os_pretty': 'Android',
'download_link': android_link})
return builds
@jingo.register.function
@jinja2.contextfunction
def download_firefox(ctx, build='release', small=False, icon=True,
mobile=None, dom_id=None, locale=None, simple=False,
force_direct=False, force_full_installer=False,
force_funnelcake=False, check_old_fx=False):
""" Output a "download firefox" button.
:param ctx: context from calling template.
:param build: name of build: 'release', 'beta' or 'aurora'.
:param small: Display the small button if True.
:param icon: Display the Fx icon on the button if True.
:param mobile: Display the android download button if True, the desktop
button only if False, and by default (None) show whichever
is appropriate for the user's system.
:param dom_id: Use this string as the id attr on the element.
:param locale: The locale of the download. Default to locale of request.
:param simple: Display button with text only if True. Will not display
icon or privacy/what's new/systems & languages links. Can be used
in conjunction with 'small'.
:param force_direct: Force the download URL to be direct.
:param force_full_installer: Force the installer download to not be
the stub installer (for aurora).
:param force_funnelcake: Force the download version for en-US Windows to be
'latest', which bouncer will translate to the funnelcake build.
:param check_old_fx: Checks to see if the user is on an old version of
Firefox and, if true, changes the button text from 'Free Download'
to 'Update your Firefox'. Must be used in conjunction with
'simple' param being true.
:return: The button html.
"""
alt_build = '' if build == 'release' else build
platform = 'mobile' if mobile else 'desktop'
locale = locale or get_locale(ctx['request'])
funnelcake_id = ctx.get('funnelcake_id', False)
dom_id = dom_id or 'download-button-%s-%s' % (platform, build)
l_version = latest_version(locale, build)
if l_version:
version, platforms = l_version
else:
locale = 'en-US'
version, platforms = latest_version('en-US', build)
# Gather data about the build for each platform
builds = []
if not mobile:
|
[
" for plat_os in ['Windows', 'Linux', 'Linux 64', 'OS X']:"
] | 816
|
lcc
|
python
| null |
03873ecbb96288a84c3d9ea1f5a2a718188d2c8a0c5920ab
| 28
|
Your task is code completion.
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Download buttons. Let's get some terminology straight. Here is a list
of terms and example values for them:
* product: 'firefox' or 'thunderbird'
* version: 7.0, 8.0b3, 9.0a2
* build: 'beta', 'aurora', or None (for latest)
* platform: 'os_windows', 'os_linux', 'os_linux64', or 'os_osx'
* locale: a string in the form of 'en-US'
"""
from django.conf import settings
import jingo
import jinja2
from bedrock.firefox.firefox_details import firefox_details, mobile_details
from lib.l10n_utils import get_locale
nightly_desktop = ('https://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/'
'latest-mozilla-aurora')
nightly_android = ('https://ftp.mozilla.org/pub/mozilla.org/mobile/nightly/'
'latest-mozilla-aurora-android')
download_urls = {
'transition': '/firefox/new/?scene=2#download-fx',
'direct': 'https://download.mozilla.org/',
'aurora': nightly_desktop,
'aurora-l10n': nightly_desktop + '-l10n',
'aurora-android-api-9': nightly_android + (
'-api-9/fennec-%s.multi.android-arm.apk'),
'aurora-android-api-11': nightly_android + (
'-api-11/fennec-%s.multi.android-arm.apk'),
'aurora-android-x86': nightly_android + (
'-x86/fennec-%s.multi.android-i386.apk'),
}
def latest_version(locale, channel='release'):
"""Return build info for a locale and channel.
:param locale: locale string of the build
:param channel: channel of the build: release, beta, or aurora
:return: dict or None
"""
all_builds = (firefox_details.firefox_primary_builds,
firefox_details.firefox_beta_builds)
version = firefox_details.latest_version(channel)
for builds in all_builds:
if locale in builds and version in builds[locale]:
_builds = builds[locale][version]
# Append Linux 64-bit build
if 'Linux' in _builds:
_builds['Linux 64'] = _builds['Linux']
return version, _builds
def make_aurora_link(product, version, platform, locale,
force_full_installer=False):
# Download links are different for localized versions
if locale.lower() == 'en-us':
if platform == 'os_windows':
product = 'firefox-aurora-stub'
else:
product = 'firefox-aurora-latest-ssl'
else:
product = 'firefox-aurora-latest-l10n'
tmpl = '?'.join([download_urls['direct'],
'product={prod}&os={plat}&lang={locale}'])
return tmpl.format(
prod=product, locale=locale,
plat=platform.replace('os_', '').replace('windows', 'win'))
def make_download_link(product, build, version, platform, locale,
force_direct=False, force_full_installer=False,
force_funnelcake=False, funnelcake_id=None):
# Aurora has a special download link format
if build == 'aurora':
return make_aurora_link(product, version, platform, locale,
force_full_installer=force_full_installer)
# The downloaders expect the platform in a certain format
platform = {
'os_windows': 'win',
'os_linux': 'linux',
'os_linux64': 'linux64',
'os_osx': 'osx'
}[platform]
# stub installer exceptions
# TODO: NUKE FROM ORBIT!
stub_langs = settings.STUB_INSTALLER_LOCALES.get(platform, [])
if stub_langs and (stub_langs == settings.STUB_INSTALLER_ALL or
locale.lower() in stub_langs):
suffix = 'stub'
if force_funnelcake or force_full_installer:
suffix = 'latest'
version = ('beta-' if build == 'beta' else '') + suffix
elif not funnelcake_id:
# Force download via SSL. Stub installers are always downloaded via SSL.
# Funnelcakes may not be ready for SSL download
version += '-SSL'
# append funnelcake id to version if we have one
if funnelcake_id:
version = '{vers}-f{fc}'.format(vers=version, fc=funnelcake_id)
# Check if direct download link has been requested
# (bypassing the transition page)
if force_direct:
# build a direct download link
tmpl = '?'.join([download_urls['direct'],
'product={prod}-{vers}&os={plat}&lang={locale}'])
return tmpl.format(prod=product, vers=version,
plat=platform, locale=locale)
else:
# build a link to the transition page
return download_urls['transition']
def android_builds(build, builds=None):
builds = builds or []
android_link = settings.GOOGLE_PLAY_FIREFOX_LINK
variations = {
'api-9': 'Gingerbread',
'api-11': 'Honeycomb+ ARMv7',
'x86': 'x86',
}
if build.lower() == 'beta':
android_link = android_link.replace('org.mozilla.firefox',
'org.mozilla.firefox_beta')
if build == 'aurora':
for type, arch_pretty in variations.items():
link = (download_urls['aurora-android-%s' % type] %
mobile_details.latest_version('aurora'))
builds.append({'os': 'os_android',
'os_pretty': 'Android',
'os_arch_pretty': 'Android %s' % arch_pretty,
'arch': 'x86' if type == 'x86' else 'armv7 %s' % type,
'arch_pretty': arch_pretty,
'download_link': link})
if build != 'aurora':
builds.append({'os': 'os_android',
'os_pretty': 'Android',
'download_link': android_link})
return builds
@jingo.register.function
@jinja2.contextfunction
def download_firefox(ctx, build='release', small=False, icon=True,
mobile=None, dom_id=None, locale=None, simple=False,
force_direct=False, force_full_installer=False,
force_funnelcake=False, check_old_fx=False):
""" Output a "download firefox" button.
:param ctx: context from calling template.
:param build: name of build: 'release', 'beta' or 'aurora'.
:param small: Display the small button if True.
:param icon: Display the Fx icon on the button if True.
:param mobile: Display the android download button if True, the desktop
button only if False, and by default (None) show whichever
is appropriate for the user's system.
:param dom_id: Use this string as the id attr on the element.
:param locale: The locale of the download. Default to locale of request.
:param simple: Display button with text only if True. Will not display
icon or privacy/what's new/systems & languages links. Can be used
in conjunction with 'small'.
:param force_direct: Force the download URL to be direct.
:param force_full_installer: Force the installer download to not be
the stub installer (for aurora).
:param force_funnelcake: Force the download version for en-US Windows to be
'latest', which bouncer will translate to the funnelcake build.
:param check_old_fx: Checks to see if the user is on an old version of
Firefox and, if true, changes the button text from 'Free Download'
to 'Update your Firefox'. Must be used in conjunction with
'simple' param being true.
:return: The button html.
"""
alt_build = '' if build == 'release' else build
platform = 'mobile' if mobile else 'desktop'
locale = locale or get_locale(ctx['request'])
funnelcake_id = ctx.get('funnelcake_id', False)
dom_id = dom_id or 'download-button-%s-%s' % (platform, build)
l_version = latest_version(locale, build)
if l_version:
version, platforms = l_version
else:
locale = 'en-US'
version, platforms = latest_version('en-US', build)
# Gather data about the build for each platform
builds = []
if not mobile:
|
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]
@jingo.register.function
@jinja2.contextfunction
def download_firefox(ctx, build='release', small=False, icon=True,
mobile=None, dom_id=None, locale=None, simple=False,
force_direct=False, force_full_installer=False,
force_funnelcake=False, check_old_fx=False):
""" Output a "download firefox" button.
:param ctx: context from calling template.
:param build: name of build: 'release', 'beta' or 'aurora'.
:param small: Display the small button if True.
:param icon: Display the Fx icon on the button if True.
:param mobile: Display the android download button if True, the desktop
button only if False, and by default (None) show whichever
is appropriate for the user's system.
:param dom_id: Use this string as the id attr on the element.
:param locale: The locale of the download. Default to locale of request.
:param simple: Display button with text only if True. Will not display
icon or privacy/what's new/systems & languages links. Can be used
in conjunction with 'small'.
:param force_direct: Force the download URL to be direct.
:param force_full_installer: Force the installer download to not be
the stub installer (for aurora).
:param force_funnelcake: Force the download version for en-US Windows to be
'latest', which bouncer will translate to the funnelcake build.
:param check_old_fx: Checks to see if the user is on an old version of
Firefox and, if true, changes the button text from 'Free Download'
to 'Update your Firefox'. Must be used in conjunction with
'simple' param being true.
:return: The button html.
"""
alt_build = '' if build == 'release' else build
platform = 'mobile' if mobile else 'desktop'
locale = locale or get_locale(ctx['request'])
funnelcake_id = ctx.get('funnelcake_id', False)
dom_id = dom_id or 'download-button-%s-%s' % (platform, build)
l_version = latest_version(locale, build)
if l_version:
version, platforms = l_version
else:
locale = 'en-US'
version, platforms = latest_version('en-US', build)
# Gather data about the build for each platform
builds = []
if not mobile:
Cheatsheet (for next line):
- We are in the if not mobile block.
- The task is to gather data about the build for each platform.
- The builds list is initialized but empty.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value.
- The l_version is the latest version and platforms for the given locale and build.
- The version and platforms are either the latest version and platforms or the latest version and platforms for 'en-US' if l_version is None.
- The builds list is used to store the data about the build for each platform.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value.
- The l_version is the latest version and platforms for the given locale and build.
- The version and platforms are either the latest version and platforms or the latest version and platforms for 'en-US' if l_version is None.
- The builds list is used to store the data about the build for each platform.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value.
- The l_version is the latest version and platforms for the given locale and build.
- The version and platforms are either the latest version and platforms or the latest version and platforms for 'en-US' if l_version is None.
- The builds list is used to store the data about the build for each platform.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value.
- The l_version is the latest version and platforms for the given locale and build.
- The version and platforms are either the latest version and platforms or the latest version and platforms for 'en-US' if l_version is None.
- The builds list is used to store the data about the build for each platform.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value.
- The l_version is the latest version and platforms for the given locale and build.
- The version and platforms are either the latest version and platforms or the latest version and platforms for 'en-US' if l_version is None.
- The builds list is used to store the data about the build for each platform.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value.
- The l_version is the latest version and platforms for the given locale and build.
- The version and platforms are either the latest version and platforms or the latest version and platforms for 'en-US' if l_version is None.
- The builds list is used to store the data about the build for each platform.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value.
- The l_version is the latest version and platforms for the given locale and build.
- The version and platforms are either the latest version and platforms or the latest version and platforms for 'en-US' if l_version is None.
- The builds list is used to store the data about the build for each platform.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value.
- The l_version is the latest version and platforms for the given locale and build.
- The version and platforms are either the latest version and platforms or the latest version and platforms for 'en-US' if l_version is None.
- The builds list is used to store the data about the build for each platform.
- The android_builds() function is used to gather data for Android builds.
- The latest_version() function is used to get the latest version and platforms.
- The platform is either 'mobile' or 'desktop'.
- The build is either 'release', 'beta', or 'aurora'.
- The locale is either the provided locale or the locale of the request.
- The funnelcake_id is either the provided funnelcake_id or False.
- The dom_id is either the provided dom_id or a default value
|
|
Please complete the code given below.
/**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Id:$ */
package com.aurel.track.fieldType.runtime.system.select;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.aurel.track.admin.customize.lists.systemOption.StatusBL;
import com.aurel.track.admin.customize.projectType.ProjectTypesBL;
import com.aurel.track.beans.IBeanID;
import com.aurel.track.beans.ILabelBean;
import com.aurel.track.beans.ISerializableLabelBean;
import com.aurel.track.beans.TPersonBean;
import com.aurel.track.beans.TProjectBean;
import com.aurel.track.beans.TStateBean;
import com.aurel.track.beans.TWorkItemBean;
import com.aurel.track.exchange.track.NameMappingBL;
import com.aurel.track.fieldType.bulkSetters.IBulkSetter;
import com.aurel.track.fieldType.constants.SystemFields;
import com.aurel.track.fieldType.fieldChange.FieldChangeValue;
import com.aurel.track.fieldType.runtime.base.LookupContainer;
import com.aurel.track.fieldType.runtime.base.SelectContext;
import com.aurel.track.fieldType.runtime.base.SerializableBeanAllowedContext;
import com.aurel.track.fieldType.runtime.matchers.design.IMatcherValue;
import com.aurel.track.fieldType.runtime.matchers.design.MatcherDatasourceContext;
import com.aurel.track.fieldType.runtime.matchers.run.MatcherContext;
import com.aurel.track.item.massOperation.MassOperationContext;
import com.aurel.track.item.massOperation.MassOperationValue;
import com.aurel.track.item.workflow.execute.StatusWorkflow;
import com.aurel.track.item.workflow.execute.WorkflowContext;
import com.aurel.track.lucene.LuceneUtil;
import com.aurel.track.resources.LocalizeUtil;
import com.aurel.track.util.GeneralUtils;
public class SystemStateRT extends SystemSelectBaseLocalizedRT{
/**
* In case of a custom picker or system selects select the list type
* Used by saving custom pickers and
* explicit history for both system and custom fields
* @return
*/
@Override
public Integer getSystemOptionType() {
return SystemFields.INTEGER_STATE;
}
/**
* Loads the edit data source for state list
* @param selectContext
* @return
*/
@Override
public List loadEditDataSource(SelectContext selectContext) {
TWorkItemBean workItemBean = selectContext.getWorkItemBean();
Integer person = selectContext.getPersonID();
List<TStateBean> dataSource;
if (workItemBean.isAccessLevelFlag()) {
//for private issue do not make workflow limitations
dataSource = StatusBL.getByProjectTypeIssueTypeAssignments(workItemBean.getProjectID(),
workItemBean.getListTypeID(), workItemBean.getStateID());
} else {
dataSource = StatusWorkflow.loadStatesTo(workItemBean.getProjectID(),
workItemBean.getListTypeID(), workItemBean.getStateID(), person, workItemBean, null);
}
return LocalizeUtil.localizeDropDownList(dataSource, selectContext.getLocale());
}
/**
* Loads the create data source for state list
* The list should contain a single value,
* consequently the initial entry can't be changed
* even if it will be (accidentally) shown in the create issue screen
* @param selectContext
* @return
*/
@Override
public List loadCreateDataSource(SelectContext selectContext) {
TWorkItemBean workItemBean = selectContext.getWorkItemBean();
List<TStateBean> dataSource = StatusWorkflow.loadInitialStates(workItemBean.getProjectID(),
workItemBean.getListTypeID(), workItemBean, selectContext.getPersonID(), null);
return LocalizeUtil.localizeDropDownList(dataSource, selectContext.getLocale());
}
/**
* Loads the datasource for the matcher
* used by select fields to get the possible values
* It will be called from both field expressions and upper selects
* The value can be a list for simple select or a map of lists for composite selects or a tree
* @param matcherValue
* @param matcherDatasourceContext the data source may be project dependent.
* @param parameterCode for composite selects
* @return the datasource (list or tree)
*/
@Override
public Object getMatcherDataSource(IMatcherValue matcherValue, MatcherDatasourceContext matcherDatasourceContext, Integer parameterCode) {
List<TStateBean> datasource;
Integer[] projectTypeIDs = ProjectTypesBL.getProjectTypeIDsForProjectIDs(matcherDatasourceContext.getProjectIDs());
if (projectTypeIDs == null || projectTypeIDs.length==0) {
datasource = (List)StatusBL.loadAll();
} else {
datasource =(List)StatusBL.loadAllowedByProjectTypesAndIssueTypes(projectTypeIDs, matcherDatasourceContext.getItemTypeIDs());
}
Locale locale = matcherDatasourceContext.getLocale();
LocalizeUtil.localizeDropDownList(datasource, locale);
if (matcherDatasourceContext.isWithParameter()) {
datasource.add((TStateBean)getLabelBean(MatcherContext.PARAMETER, locale));
}
if (matcherValue!=null) {
if (matcherDatasourceContext.isInitValueIfNull()) {
//from field expression
Object value = matcherValue.getValue();
if (value==null && datasource!=null && !datasource.isEmpty()) {
matcherValue.setValue(new Integer[] {datasource.get(0).getObjectID()});
}
} else {
//from upper select
if (matcherDatasourceContext.isFirstLoad()) {
//select the not closed states
List<Integer> notClosedStates = new ArrayList<Integer>();
for ( int i = 0; i < datasource.size(); i++) {
TStateBean stateBean = datasource.get(i);
Integer stateFlag = stateBean.getStateflag();
//stateflag null for $Parameter
if (stateFlag!=null && TStateBean.STATEFLAGS.CLOSED!=stateFlag.intValue() ) {
notClosedStates.add(stateBean.getObjectID());
}
}
Integer[] selectedStates = GeneralUtils.createIntegerArrFromCollection(notClosedStates);
matcherValue.setValue(selectedStates);
}
}
}
return datasource;
}
/**
* Loads the IBulkSetter object for configuring the bulk operation
* @param fieldID
*/
@Override
public IBulkSetter getBulkSetterDT(Integer fieldID) {
IBulkSetter bulkSetter = super.getBulkSetterDT(fieldID);
//should be verified against project types and workflow
bulkSetter.setSelectValueSurelyAllowed(false);
return bulkSetter;
}
/**
* Loads the datasource for the mass operation
* used mainly by select fields to get
* the all possible options for a field (system or custom select)
* It also sets a value if not yet selected
* The value can be a List for simple select or a Map of lists for composite selects
* @param massOperationContext
* @param massOperationValue
* @param parameterCode
* @param personBean
* @param locale
* @return
*/
@Override
public void loadBulkOperationDataSource(MassOperationContext massOperationContext,
MassOperationValue massOperationValue,
Integer parameterCode, TPersonBean personBean, Locale locale) {
List<IBeanID> datasource = (List)StatusBL.loadAll(locale);
massOperationValue.setPossibleValues(datasource);
massOperationValue.setValue(getBulkSelectValue(massOperationContext,
massOperationValue.getFieldID(), null,
(Integer)massOperationValue.getValue(),
(List<IBeanID>)massOperationValue.getPossibleValues()));
}
/**
* Loads the datasource and value for configuring the field change
* @param workflowContext
* @param fieldChangeValue
* @param parameterCode
* @param personBean
* @param locale
*/
@Override
public void loadFieldChangeDatasourceAndValue(WorkflowContext workflowContext,
FieldChangeValue fieldChangeValue,
Integer parameterCode, TPersonBean personBean, Locale locale) {
List<TStateBean> datasource = null;
Integer itemTypeID = workflowContext.getItemTypeID();
Integer projectID = workflowContext.getProjectID();
Integer projectTypeID = workflowContext.getProjectTypeID();
if (projectTypeID==null && projectID!=null) {
TProjectBean projectBean = LookupContainer.getProjectBean(projectID);
if (projectBean!=null) {
projectTypeID = projectBean.getProjectType();
}
}
if (projectTypeID==null || itemTypeID==null) {
datasource = StatusBL.loadAll();
} else {
datasource = StatusBL.getByProjectTypeIssueTypeAssignments(projectTypeID, itemTypeID, (Integer)fieldChangeValue.getValue());
}
fieldChangeValue.setPossibleValues(LocalizeUtil.localizeDropDownList(datasource, locale));
fieldChangeValue.setValue(getBulkSelectValue(null,
fieldChangeValue.getFieldID(), null,
(Integer)fieldChangeValue.getValue(),
(List<IBeanID>)fieldChangeValue.getPossibleValues()));
}
/**
* Get the ILabelBean by primary key
* @return
*/
@Override
public ILabelBean getLabelBean(Integer optionID, Locale locale) {
if (optionID!=null &&
optionID.equals(MatcherContext.PARAMETER)) {
TStateBean stateBean = new TStateBean();
stateBean.setLabel(MatcherContext.getLocalizedParameter(locale));
stateBean.setObjectID(optionID);
return stateBean;
}
return StatusBL.loadByPrimaryKey(optionID);
}
/**
* Returns the lookup entity type related to the fieldType
* @return
*/
@Override
public int getLookupEntityType() {
return LuceneUtil.LOOKUPENTITYTYPES.STATE;
}
/**
* Creates a new empty serializableLabelBean
* @return
*/
@Override
public ISerializableLabelBean getNewSerializableLabelBean() {
return new TStateBean();
}
/**
* Gets the ID by the label
* @param fieldID
* @param projectID
* @param issueTypeID
* @param locale
* @param label
* @param lookupBeansMap
* @param componentPartsMap
* @return
*/
@Override
public Integer getLookupIDByLabel(Integer fieldID,
Integer projectID, Integer issueTypeID,
Locale locale, String label,
Map<String, ILabelBean> lookupBeansMap, Map<Integer, Integer> componentPartsMap) {
Integer objectID = NameMappingBL.getExactMatch(label, lookupBeansMap);
if (objectID!=null) {
return objectID;
}
TStateBean stateBean = null;
Integer primaryKey = LocalizeUtil.getDropDownPrimaryKeyFromLocalizedText(
new TStateBean().getKeyPrefix(), label, locale);
if (primaryKey!=null) {
stateBean = LookupContainer.getStatusBean(primaryKey);
if (stateBean!=null) {
return primaryKey;
}
}
List<TStateBean> stateBeans = StatusBL.loadByLabel(label);
if (stateBeans!=null && !stateBeans.isEmpty()) {
stateBean = stateBeans.get(0);
}
if (stateBean!=null) {
return stateBean.getObjectID();
}
return null;
}
/**
* Whether the lookupID found by label is allowed in
* the context of serializableBeanAllowedContext
* In excel the lookup entries are not limited by the user interface controls
* This method should return false if the lookupID
* is not allowed (for ex. a person without manager role was set as manager)
* @param objectID
* @param serializableBeanAllowedContext
* @return
*/
@Override
public boolean lookupBeanAllowed(Integer objectID,
SerializableBeanAllowedContext serializableBeanAllowedContext) {
List<TStateBean> stateBeansList=null;
Integer projectID = serializableBeanAllowedContext.getProjectID();
Integer issueTypeID = serializableBeanAllowedContext.getIssueTypeID();
|
[
"\t\tif (projectID==null || issueTypeID==null) {"
] | 1,101
|
lcc
|
java
| null |
63fdad7f1feacdf8cca4aaf57dae737d83c351d9ab66db8b
| 29
|
Your task is code completion.
/**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Id:$ */
package com.aurel.track.fieldType.runtime.system.select;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.aurel.track.admin.customize.lists.systemOption.StatusBL;
import com.aurel.track.admin.customize.projectType.ProjectTypesBL;
import com.aurel.track.beans.IBeanID;
import com.aurel.track.beans.ILabelBean;
import com.aurel.track.beans.ISerializableLabelBean;
import com.aurel.track.beans.TPersonBean;
import com.aurel.track.beans.TProjectBean;
import com.aurel.track.beans.TStateBean;
import com.aurel.track.beans.TWorkItemBean;
import com.aurel.track.exchange.track.NameMappingBL;
import com.aurel.track.fieldType.bulkSetters.IBulkSetter;
import com.aurel.track.fieldType.constants.SystemFields;
import com.aurel.track.fieldType.fieldChange.FieldChangeValue;
import com.aurel.track.fieldType.runtime.base.LookupContainer;
import com.aurel.track.fieldType.runtime.base.SelectContext;
import com.aurel.track.fieldType.runtime.base.SerializableBeanAllowedContext;
import com.aurel.track.fieldType.runtime.matchers.design.IMatcherValue;
import com.aurel.track.fieldType.runtime.matchers.design.MatcherDatasourceContext;
import com.aurel.track.fieldType.runtime.matchers.run.MatcherContext;
import com.aurel.track.item.massOperation.MassOperationContext;
import com.aurel.track.item.massOperation.MassOperationValue;
import com.aurel.track.item.workflow.execute.StatusWorkflow;
import com.aurel.track.item.workflow.execute.WorkflowContext;
import com.aurel.track.lucene.LuceneUtil;
import com.aurel.track.resources.LocalizeUtil;
import com.aurel.track.util.GeneralUtils;
public class SystemStateRT extends SystemSelectBaseLocalizedRT{
/**
* In case of a custom picker or system selects select the list type
* Used by saving custom pickers and
* explicit history for both system and custom fields
* @return
*/
@Override
public Integer getSystemOptionType() {
return SystemFields.INTEGER_STATE;
}
/**
* Loads the edit data source for state list
* @param selectContext
* @return
*/
@Override
public List loadEditDataSource(SelectContext selectContext) {
TWorkItemBean workItemBean = selectContext.getWorkItemBean();
Integer person = selectContext.getPersonID();
List<TStateBean> dataSource;
if (workItemBean.isAccessLevelFlag()) {
//for private issue do not make workflow limitations
dataSource = StatusBL.getByProjectTypeIssueTypeAssignments(workItemBean.getProjectID(),
workItemBean.getListTypeID(), workItemBean.getStateID());
} else {
dataSource = StatusWorkflow.loadStatesTo(workItemBean.getProjectID(),
workItemBean.getListTypeID(), workItemBean.getStateID(), person, workItemBean, null);
}
return LocalizeUtil.localizeDropDownList(dataSource, selectContext.getLocale());
}
/**
* Loads the create data source for state list
* The list should contain a single value,
* consequently the initial entry can't be changed
* even if it will be (accidentally) shown in the create issue screen
* @param selectContext
* @return
*/
@Override
public List loadCreateDataSource(SelectContext selectContext) {
TWorkItemBean workItemBean = selectContext.getWorkItemBean();
List<TStateBean> dataSource = StatusWorkflow.loadInitialStates(workItemBean.getProjectID(),
workItemBean.getListTypeID(), workItemBean, selectContext.getPersonID(), null);
return LocalizeUtil.localizeDropDownList(dataSource, selectContext.getLocale());
}
/**
* Loads the datasource for the matcher
* used by select fields to get the possible values
* It will be called from both field expressions and upper selects
* The value can be a list for simple select or a map of lists for composite selects or a tree
* @param matcherValue
* @param matcherDatasourceContext the data source may be project dependent.
* @param parameterCode for composite selects
* @return the datasource (list or tree)
*/
@Override
public Object getMatcherDataSource(IMatcherValue matcherValue, MatcherDatasourceContext matcherDatasourceContext, Integer parameterCode) {
List<TStateBean> datasource;
Integer[] projectTypeIDs = ProjectTypesBL.getProjectTypeIDsForProjectIDs(matcherDatasourceContext.getProjectIDs());
if (projectTypeIDs == null || projectTypeIDs.length==0) {
datasource = (List)StatusBL.loadAll();
} else {
datasource =(List)StatusBL.loadAllowedByProjectTypesAndIssueTypes(projectTypeIDs, matcherDatasourceContext.getItemTypeIDs());
}
Locale locale = matcherDatasourceContext.getLocale();
LocalizeUtil.localizeDropDownList(datasource, locale);
if (matcherDatasourceContext.isWithParameter()) {
datasource.add((TStateBean)getLabelBean(MatcherContext.PARAMETER, locale));
}
if (matcherValue!=null) {
if (matcherDatasourceContext.isInitValueIfNull()) {
//from field expression
Object value = matcherValue.getValue();
if (value==null && datasource!=null && !datasource.isEmpty()) {
matcherValue.setValue(new Integer[] {datasource.get(0).getObjectID()});
}
} else {
//from upper select
if (matcherDatasourceContext.isFirstLoad()) {
//select the not closed states
List<Integer> notClosedStates = new ArrayList<Integer>();
for ( int i = 0; i < datasource.size(); i++) {
TStateBean stateBean = datasource.get(i);
Integer stateFlag = stateBean.getStateflag();
//stateflag null for $Parameter
if (stateFlag!=null && TStateBean.STATEFLAGS.CLOSED!=stateFlag.intValue() ) {
notClosedStates.add(stateBean.getObjectID());
}
}
Integer[] selectedStates = GeneralUtils.createIntegerArrFromCollection(notClosedStates);
matcherValue.setValue(selectedStates);
}
}
}
return datasource;
}
/**
* Loads the IBulkSetter object for configuring the bulk operation
* @param fieldID
*/
@Override
public IBulkSetter getBulkSetterDT(Integer fieldID) {
IBulkSetter bulkSetter = super.getBulkSetterDT(fieldID);
//should be verified against project types and workflow
bulkSetter.setSelectValueSurelyAllowed(false);
return bulkSetter;
}
/**
* Loads the datasource for the mass operation
* used mainly by select fields to get
* the all possible options for a field (system or custom select)
* It also sets a value if not yet selected
* The value can be a List for simple select or a Map of lists for composite selects
* @param massOperationContext
* @param massOperationValue
* @param parameterCode
* @param personBean
* @param locale
* @return
*/
@Override
public void loadBulkOperationDataSource(MassOperationContext massOperationContext,
MassOperationValue massOperationValue,
Integer parameterCode, TPersonBean personBean, Locale locale) {
List<IBeanID> datasource = (List)StatusBL.loadAll(locale);
massOperationValue.setPossibleValues(datasource);
massOperationValue.setValue(getBulkSelectValue(massOperationContext,
massOperationValue.getFieldID(), null,
(Integer)massOperationValue.getValue(),
(List<IBeanID>)massOperationValue.getPossibleValues()));
}
/**
* Loads the datasource and value for configuring the field change
* @param workflowContext
* @param fieldChangeValue
* @param parameterCode
* @param personBean
* @param locale
*/
@Override
public void loadFieldChangeDatasourceAndValue(WorkflowContext workflowContext,
FieldChangeValue fieldChangeValue,
Integer parameterCode, TPersonBean personBean, Locale locale) {
List<TStateBean> datasource = null;
Integer itemTypeID = workflowContext.getItemTypeID();
Integer projectID = workflowContext.getProjectID();
Integer projectTypeID = workflowContext.getProjectTypeID();
if (projectTypeID==null && projectID!=null) {
TProjectBean projectBean = LookupContainer.getProjectBean(projectID);
if (projectBean!=null) {
projectTypeID = projectBean.getProjectType();
}
}
if (projectTypeID==null || itemTypeID==null) {
datasource = StatusBL.loadAll();
} else {
datasource = StatusBL.getByProjectTypeIssueTypeAssignments(projectTypeID, itemTypeID, (Integer)fieldChangeValue.getValue());
}
fieldChangeValue.setPossibleValues(LocalizeUtil.localizeDropDownList(datasource, locale));
fieldChangeValue.setValue(getBulkSelectValue(null,
fieldChangeValue.getFieldID(), null,
(Integer)fieldChangeValue.getValue(),
(List<IBeanID>)fieldChangeValue.getPossibleValues()));
}
/**
* Get the ILabelBean by primary key
* @return
*/
@Override
public ILabelBean getLabelBean(Integer optionID, Locale locale) {
if (optionID!=null &&
optionID.equals(MatcherContext.PARAMETER)) {
TStateBean stateBean = new TStateBean();
stateBean.setLabel(MatcherContext.getLocalizedParameter(locale));
stateBean.setObjectID(optionID);
return stateBean;
}
return StatusBL.loadByPrimaryKey(optionID);
}
/**
* Returns the lookup entity type related to the fieldType
* @return
*/
@Override
public int getLookupEntityType() {
return LuceneUtil.LOOKUPENTITYTYPES.STATE;
}
/**
* Creates a new empty serializableLabelBean
* @return
*/
@Override
public ISerializableLabelBean getNewSerializableLabelBean() {
return new TStateBean();
}
/**
* Gets the ID by the label
* @param fieldID
* @param projectID
* @param issueTypeID
* @param locale
* @param label
* @param lookupBeansMap
* @param componentPartsMap
* @return
*/
@Override
public Integer getLookupIDByLabel(Integer fieldID,
Integer projectID, Integer issueTypeID,
Locale locale, String label,
Map<String, ILabelBean> lookupBeansMap, Map<Integer, Integer> componentPartsMap) {
Integer objectID = NameMappingBL.getExactMatch(label, lookupBeansMap);
if (objectID!=null) {
return objectID;
}
TStateBean stateBean = null;
Integer primaryKey = LocalizeUtil.getDropDownPrimaryKeyFromLocalizedText(
new TStateBean().getKeyPrefix(), label, locale);
if (primaryKey!=null) {
stateBean = LookupContainer.getStatusBean(primaryKey);
if (stateBean!=null) {
return primaryKey;
}
}
List<TStateBean> stateBeans = StatusBL.loadByLabel(label);
if (stateBeans!=null && !stateBeans.isEmpty()) {
stateBean = stateBeans.get(0);
}
if (stateBean!=null) {
return stateBean.getObjectID();
}
return null;
}
/**
* Whether the lookupID found by label is allowed in
* the context of serializableBeanAllowedContext
* In excel the lookup entries are not limited by the user interface controls
* This method should return false if the lookupID
* is not allowed (for ex. a person without manager role was set as manager)
* @param objectID
* @param serializableBeanAllowedContext
* @return
*/
@Override
public boolean lookupBeanAllowed(Integer objectID,
SerializableBeanAllowedContext serializableBeanAllowedContext) {
List<TStateBean> stateBeansList=null;
Integer projectID = serializableBeanAllowedContext.getProjectID();
Integer issueTypeID = serializableBeanAllowedContext.getIssueTypeID();
|
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 SystemStateRT extends SystemSelectBaseLocalizedRT {
// ... (many methods and variables)
public boolean lookupBeanAllowed(Integer objectID,
SerializableBeanAllowedContext serializableBeanAllowedContext) {
List<TStateBean> stateBeansList=null;
Integer projectID = serializableBeanAllowedContext.getProjectID();
Integer issueTypeID = serializableBeanAllowedContext.getIssueTypeID();
// ... (rest of the method)
Cheatsheet (for next line):
- We are in the lookupBeanAllowed() method, which checks if a lookup ID is allowed in the context of a serializable bean.
- objectID is the ID of the lookup bean to check.
- serializableBeanAllowedContext contains information about the project and issue type.
- The method should return true if the lookup ID is allowed, false otherwise.
- The method is checking if the lookup ID is allowed based on the project and issue type.
- [Relevant lines: method header, projectID and issueTypeID variables]
Next line will likely be: return StatusBL.isAllowed(objectID, projectID, issueTypeID);
|
|
Please complete the code given below.
using System.Collections.Generic;
using System.Linq;
using AutoJIT.Contrib;
using AutoJIT.CSharpConverter.ConversionModule.Helper;
using AutoJIT.CSharpConverter.ConversionModule.StatementConverter.Interface;
using AutoJIT.Parser;
using AutoJIT.Parser.AST;
using AutoJIT.Parser.AST.Statements;
using AutoJIT.Parser.AST.Statements.Interface;
using AutoJIT.Parser.AST.Visitor;
using AutoJIT.Parser.Extensions;
using AutoJITRuntime;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace AutoJIT.CSharpConverter.ConversionModule.Visitor
{
public class ConversionVisitor : SyntaxVisitorBase<IEnumerable<CSharpSyntaxNode>>
{
private readonly ICSharpSkeletonFactory _cSharpSkeletonFactory;
private readonly IInjectionService _injectionService;
protected IContextService ContextService;
public ConversionVisitor( IInjectionService injectionService, IContextService contextService, ICSharpSkeletonFactory cSharpSkeletonFactory ) {
_injectionService = injectionService;
ContextService = contextService;
_cSharpSkeletonFactory = cSharpSkeletonFactory;
}
public void InitializeContext( IContext context ) {
ContextService.Initialize( context );
}
public override IEnumerable<CSharpSyntaxNode> VisitAssignStatement( AssignStatement node ) {
return GetConverter<AssignStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitContinueCaseStatement( ContinueCaseStatement node ) {
return GetConverter<ContinueCaseStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitContinueLoopStatement( ContinueLoopStatement node ) {
return GetConverter<ContinueLoopStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitDimStatement( DimStatement node ) {
return GetConverter<DimStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitDoUntilStatement( DoUntilStatement node ) {
return GetConverter<DoUntilStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitExitloopStatement( ExitloopStatement node ) {
return GetConverter<ExitloopStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitExitStatement( ExitStatement node ) {
return GetConverter<ExitStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitForInStatement( ForInStatement node ) {
return GetConverter<ForInStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitForToNextStatement( ForToNextStatement node ) {
return GetConverter<ForToNextStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitFunctionCallStatement( FunctionCallStatement node ) {
return GetConverter<FunctionCallStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitGlobalDeclarationStatement( GlobalDeclarationStatement node ) {
return GetConverter<GlobalDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitIfElseStatement( IfElseStatement node ) {
return GetConverter<IfElseStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitInitDefaultParameterStatement( InitDefaultParameterStatement node ) {
return GetConverter<InitDefaultParameterStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitLocalDeclarationStatement( LocalDeclarationStatement node ) {
return GetConverter<LocalDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitStaticDeclarationStatement( StaticDeclarationStatement node ) {
return GetConverter<StaticDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitGlobalEnumDeclarationStatement( GlobalEnumDeclarationStatement node ) {
return GetConverter<GlobalEnumDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitLocalEnumDeclarationStatement( LocalEnumDeclarationStatement node ) {
return GetConverter<LocalEnumDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitReDimStatement( ReDimStatement node ) {
return GetConverter<ReDimStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitReturnStatement( ReturnStatement node ) {
return GetConverter<ReturnStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitSelectCaseStatement( SelectCaseStatement node ) {
return GetConverter<SelectCaseStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitSwitchCaseStatement( SwitchCaseStatement node ) {
return GetConverter<SwitchCaseStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitWhileStatement( WhileStatement node ) {
return GetConverter<WhileStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitVariableFunctionCallStatement( VariableFunctionCallStatement node ) {
return GetConverter<VariableFunctionCallStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitFunction( Function node ) {
return Convert( node, ContextService ).ToEnumerable();
}
public override IEnumerable<CSharpSyntaxNode> VisitBlockStatement( BlockStatement node ) {
return GetConverter<BlockStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitAutoitScriptRoot( AutoitScriptRoot node ) {
var memberList = new SyntaxList<MemberDeclarationSyntax>();
ContextService.SetGlobalContext( true );
var blockSyntax = (BlockSyntax) node.MainFunction.Accept( this ).Single();
blockSyntax = blockSyntax.AddStatements(
SyntaxFactory.ReturnStatement( SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal( "0", 0 ) ) ) );
var main = SyntaxFactory.MethodDeclaration(SyntaxFactory.IdentifierName(typeof(Variant).Name), "Main").AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)).WithBody(blockSyntax);
memberList = memberList.Add(main);
ContextService.SetGlobalContext( false );
memberList = memberList.AddRange( ContextService.PopGlobalVariables() );
ContextService.ResetFunctionContext();
foreach (Function function in node.Functions) {
memberList = memberList.Add( (MemberDeclarationSyntax) function.Accept( this ).Single() );
memberList = memberList.AddRange( ContextService.PopGlobalVariables() );
ContextService.ResetFunctionContext();
}
NamespaceDeclarationSyntax finalScript = _cSharpSkeletonFactory.EmbedInClassTemplate( new List<MemberDeclarationSyntax>( memberList ), ContextService.GetRuntimeInstanceName(), "AutoJITScriptClass", ContextService.GetContextInstanceName() );
finalScript = RemoveEmptyStatements( finalScript );
finalScript = FixByReferenceCalls( finalScript, memberList );
return finalScript.ToEnumerable();
}
protected MemberDeclarationSyntax Convert( Function function, IContextService context ) {
IList<IStatementNode> statementNodes = function.Statements.Block;
statementNodes = DeclareParameter( statementNodes, function.Parameter, context );
List<StatementSyntax> dotNetStatements = ConvertStatements( statementNodes );
dotNetStatements = OrderDeclarations( dotNetStatements );
if ( !( dotNetStatements.Last() is ReturnStatementSyntax ) ) {
dotNetStatements.Add( SyntaxFactory.ReturnStatement( SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal( "0", 0 ) ) ) );
}
BlockSyntax body = dotNetStatements.ToBlock();
return SyntaxFactory.MethodDeclaration( SyntaxFactory.IdentifierName( typeof (Variant).Name ), function.Name.Token.Value.StringValue ).AddModifiers( SyntaxFactory.Token( SyntaxKind.PublicKeyword ) ).WithParameterList( SyntaxFactory.ParameterList( CreaterParameter( function.Parameter, context ).ToSeparatedSyntaxList() ) ).WithBody( body );
}
private IList<IStatementNode> DeclareParameter( IList<IStatementNode> statementNodes, IEnumerable<AutoitParameter> parameter, IContextService context ) {
foreach (AutoitParameter parameterInfo in parameter) {
context.RegisterLocal( parameterInfo.ParameterName.Token.Value.StringValue );
if ( parameterInfo.DefaultValue != null ) {
var statement = new InitDefaultParameterStatement( context.GetVariableName( parameterInfo.ParameterName.Token.Value.StringValue ), parameterInfo.DefaultValue );
statement.Initialize();
statementNodes.Insert( 0, statement );
}
}
return statementNodes;
}
private static List<StatementSyntax> OrderDeclarations( List<StatementSyntax> cSharpStatements ) {
List<LocalDeclarationStatementSyntax> allDeclarations = cSharpStatements.SelectMany( s => s.DescendantNodesAndSelf().OfType<LocalDeclarationStatementSyntax>() ).ToList();
for ( int index = 0; index < cSharpStatements.Count; index++ ) {
cSharpStatements[index] = cSharpStatements[index].ReplaceNodes( allDeclarations, ( node, syntaxNode ) => SyntaxFactory.EmptyStatement() );
}
cSharpStatements.InsertRange( 0, allDeclarations );
return cSharpStatements;
}
private List<StatementSyntax> ConvertStatements( IEnumerable<IStatementNode> statements ) {
List<CSharpSyntaxNode> nodes = statements.SelectMany( x => x.Accept( this ) ).ToList();
return nodes.OfType<StatementSyntax>().ToList();
}
private IEnumerable<ParameterSyntax> CreaterParameter( IEnumerable<AutoitParameter> parameters, IContextService context ) {
return parameters.Select(
p => {
ParameterSyntax parameter = SyntaxFactory.Parameter( SyntaxFactory.Identifier( context.GetVariableName( p.ParameterName.Token.Value.StringValue ) ) ).WithType( SyntaxFactory.IdentifierName( typeof (Variant).Name ) );
if ( p.DefaultValue != null ) {
parameter = parameter.WithDefault( SyntaxFactory.EqualsValueClause( SyntaxFactory.LiteralExpression( SyntaxKind.NullLiteralExpression ) ) );
}
if ( p.IsByRef ) {
parameter = parameter.WithModifiers( new SyntaxTokenList().Add( SyntaxFactory.Token( SyntaxKind.RefKeyword ) ) );
}
return parameter;
} );
}
private IAutoitStatementConverter<T, StatementSyntax> GetConverter<T>() where T : IStatementNode {
var converter = _injectionService.Inject<IAutoitStatementConverter<T, StatementSyntax>>();
return converter;
}
private static NamespaceDeclarationSyntax RemoveEmptyStatements( NamespaceDeclarationSyntax finalScript ) {
List<EmptyStatementSyntax> emptyStatements = finalScript.DescendantNodes().OfType<EmptyStatementSyntax>().Where( x => x.Parent.GetType() != typeof (LabeledStatementSyntax) ).ToList();
finalScript = finalScript.RemoveNodes( emptyStatements, SyntaxRemoveOptions.KeepEndOfLine );
return finalScript;
}
private static NamespaceDeclarationSyntax FixByReferenceCalls( NamespaceDeclarationSyntax finalScript, SyntaxList<MemberDeclarationSyntax> memberList ) {
var toReplace = new Dictionary<ArgumentSyntax, ArgumentSyntax>();
IEnumerable<ArgumentSyntax> argumentSyntaxs = finalScript.DescendantNodes().OfType<ArgumentSyntax>();
|
[
" foreach (ArgumentSyntax argumentSyntax in argumentSyntaxs) {"
] | 861
|
lcc
|
csharp
| null |
a2ce4aeed86faf7c78539925675910ecdf08f4ca9f5603ee
| 30
|
Your task is code completion.
using System.Collections.Generic;
using System.Linq;
using AutoJIT.Contrib;
using AutoJIT.CSharpConverter.ConversionModule.Helper;
using AutoJIT.CSharpConverter.ConversionModule.StatementConverter.Interface;
using AutoJIT.Parser;
using AutoJIT.Parser.AST;
using AutoJIT.Parser.AST.Statements;
using AutoJIT.Parser.AST.Statements.Interface;
using AutoJIT.Parser.AST.Visitor;
using AutoJIT.Parser.Extensions;
using AutoJITRuntime;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace AutoJIT.CSharpConverter.ConversionModule.Visitor
{
public class ConversionVisitor : SyntaxVisitorBase<IEnumerable<CSharpSyntaxNode>>
{
private readonly ICSharpSkeletonFactory _cSharpSkeletonFactory;
private readonly IInjectionService _injectionService;
protected IContextService ContextService;
public ConversionVisitor( IInjectionService injectionService, IContextService contextService, ICSharpSkeletonFactory cSharpSkeletonFactory ) {
_injectionService = injectionService;
ContextService = contextService;
_cSharpSkeletonFactory = cSharpSkeletonFactory;
}
public void InitializeContext( IContext context ) {
ContextService.Initialize( context );
}
public override IEnumerable<CSharpSyntaxNode> VisitAssignStatement( AssignStatement node ) {
return GetConverter<AssignStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitContinueCaseStatement( ContinueCaseStatement node ) {
return GetConverter<ContinueCaseStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitContinueLoopStatement( ContinueLoopStatement node ) {
return GetConverter<ContinueLoopStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitDimStatement( DimStatement node ) {
return GetConverter<DimStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitDoUntilStatement( DoUntilStatement node ) {
return GetConverter<DoUntilStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitExitloopStatement( ExitloopStatement node ) {
return GetConverter<ExitloopStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitExitStatement( ExitStatement node ) {
return GetConverter<ExitStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitForInStatement( ForInStatement node ) {
return GetConverter<ForInStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitForToNextStatement( ForToNextStatement node ) {
return GetConverter<ForToNextStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitFunctionCallStatement( FunctionCallStatement node ) {
return GetConverter<FunctionCallStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitGlobalDeclarationStatement( GlobalDeclarationStatement node ) {
return GetConverter<GlobalDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitIfElseStatement( IfElseStatement node ) {
return GetConverter<IfElseStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitInitDefaultParameterStatement( InitDefaultParameterStatement node ) {
return GetConverter<InitDefaultParameterStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitLocalDeclarationStatement( LocalDeclarationStatement node ) {
return GetConverter<LocalDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitStaticDeclarationStatement( StaticDeclarationStatement node ) {
return GetConverter<StaticDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitGlobalEnumDeclarationStatement( GlobalEnumDeclarationStatement node ) {
return GetConverter<GlobalEnumDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitLocalEnumDeclarationStatement( LocalEnumDeclarationStatement node ) {
return GetConverter<LocalEnumDeclarationStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitReDimStatement( ReDimStatement node ) {
return GetConverter<ReDimStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitReturnStatement( ReturnStatement node ) {
return GetConverter<ReturnStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitSelectCaseStatement( SelectCaseStatement node ) {
return GetConverter<SelectCaseStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitSwitchCaseStatement( SwitchCaseStatement node ) {
return GetConverter<SwitchCaseStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitWhileStatement( WhileStatement node ) {
return GetConverter<WhileStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitVariableFunctionCallStatement( VariableFunctionCallStatement node ) {
return GetConverter<VariableFunctionCallStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitFunction( Function node ) {
return Convert( node, ContextService ).ToEnumerable();
}
public override IEnumerable<CSharpSyntaxNode> VisitBlockStatement( BlockStatement node ) {
return GetConverter<BlockStatement>().Convert( node, ContextService );
}
public override IEnumerable<CSharpSyntaxNode> VisitAutoitScriptRoot( AutoitScriptRoot node ) {
var memberList = new SyntaxList<MemberDeclarationSyntax>();
ContextService.SetGlobalContext( true );
var blockSyntax = (BlockSyntax) node.MainFunction.Accept( this ).Single();
blockSyntax = blockSyntax.AddStatements(
SyntaxFactory.ReturnStatement( SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal( "0", 0 ) ) ) );
var main = SyntaxFactory.MethodDeclaration(SyntaxFactory.IdentifierName(typeof(Variant).Name), "Main").AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)).WithBody(blockSyntax);
memberList = memberList.Add(main);
ContextService.SetGlobalContext( false );
memberList = memberList.AddRange( ContextService.PopGlobalVariables() );
ContextService.ResetFunctionContext();
foreach (Function function in node.Functions) {
memberList = memberList.Add( (MemberDeclarationSyntax) function.Accept( this ).Single() );
memberList = memberList.AddRange( ContextService.PopGlobalVariables() );
ContextService.ResetFunctionContext();
}
NamespaceDeclarationSyntax finalScript = _cSharpSkeletonFactory.EmbedInClassTemplate( new List<MemberDeclarationSyntax>( memberList ), ContextService.GetRuntimeInstanceName(), "AutoJITScriptClass", ContextService.GetContextInstanceName() );
finalScript = RemoveEmptyStatements( finalScript );
finalScript = FixByReferenceCalls( finalScript, memberList );
return finalScript.ToEnumerable();
}
protected MemberDeclarationSyntax Convert( Function function, IContextService context ) {
IList<IStatementNode> statementNodes = function.Statements.Block;
statementNodes = DeclareParameter( statementNodes, function.Parameter, context );
List<StatementSyntax> dotNetStatements = ConvertStatements( statementNodes );
dotNetStatements = OrderDeclarations( dotNetStatements );
if ( !( dotNetStatements.Last() is ReturnStatementSyntax ) ) {
dotNetStatements.Add( SyntaxFactory.ReturnStatement( SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal( "0", 0 ) ) ) );
}
BlockSyntax body = dotNetStatements.ToBlock();
return SyntaxFactory.MethodDeclaration( SyntaxFactory.IdentifierName( typeof (Variant).Name ), function.Name.Token.Value.StringValue ).AddModifiers( SyntaxFactory.Token( SyntaxKind.PublicKeyword ) ).WithParameterList( SyntaxFactory.ParameterList( CreaterParameter( function.Parameter, context ).ToSeparatedSyntaxList() ) ).WithBody( body );
}
private IList<IStatementNode> DeclareParameter( IList<IStatementNode> statementNodes, IEnumerable<AutoitParameter> parameter, IContextService context ) {
foreach (AutoitParameter parameterInfo in parameter) {
context.RegisterLocal( parameterInfo.ParameterName.Token.Value.StringValue );
if ( parameterInfo.DefaultValue != null ) {
var statement = new InitDefaultParameterStatement( context.GetVariableName( parameterInfo.ParameterName.Token.Value.StringValue ), parameterInfo.DefaultValue );
statement.Initialize();
statementNodes.Insert( 0, statement );
}
}
return statementNodes;
}
private static List<StatementSyntax> OrderDeclarations( List<StatementSyntax> cSharpStatements ) {
List<LocalDeclarationStatementSyntax> allDeclarations = cSharpStatements.SelectMany( s => s.DescendantNodesAndSelf().OfType<LocalDeclarationStatementSyntax>() ).ToList();
for ( int index = 0; index < cSharpStatements.Count; index++ ) {
cSharpStatements[index] = cSharpStatements[index].ReplaceNodes( allDeclarations, ( node, syntaxNode ) => SyntaxFactory.EmptyStatement() );
}
cSharpStatements.InsertRange( 0, allDeclarations );
return cSharpStatements;
}
private List<StatementSyntax> ConvertStatements( IEnumerable<IStatementNode> statements ) {
List<CSharpSyntaxNode> nodes = statements.SelectMany( x => x.Accept( this ) ).ToList();
return nodes.OfType<StatementSyntax>().ToList();
}
private IEnumerable<ParameterSyntax> CreaterParameter( IEnumerable<AutoitParameter> parameters, IContextService context ) {
return parameters.Select(
p => {
ParameterSyntax parameter = SyntaxFactory.Parameter( SyntaxFactory.Identifier( context.GetVariableName( p.ParameterName.Token.Value.StringValue ) ) ).WithType( SyntaxFactory.IdentifierName( typeof (Variant).Name ) );
if ( p.DefaultValue != null ) {
parameter = parameter.WithDefault( SyntaxFactory.EqualsValueClause( SyntaxFactory.LiteralExpression( SyntaxKind.NullLiteralExpression ) ) );
}
if ( p.IsByRef ) {
parameter = parameter.WithModifiers( new SyntaxTokenList().Add( SyntaxFactory.Token( SyntaxKind.RefKeyword ) ) );
}
return parameter;
} );
}
private IAutoitStatementConverter<T, StatementSyntax> GetConverter<T>() where T : IStatementNode {
var converter = _injectionService.Inject<IAutoitStatementConverter<T, StatementSyntax>>();
return converter;
}
private static NamespaceDeclarationSyntax RemoveEmptyStatements( NamespaceDeclarationSyntax finalScript ) {
List<EmptyStatementSyntax> emptyStatements = finalScript.DescendantNodes().OfType<EmptyStatementSyntax>().Where( x => x.Parent.GetType() != typeof (LabeledStatementSyntax) ).ToList();
finalScript = finalScript.RemoveNodes( emptyStatements, SyntaxRemoveOptions.KeepEndOfLine );
return finalScript;
}
private static NamespaceDeclarationSyntax FixByReferenceCalls( NamespaceDeclarationSyntax finalScript, SyntaxList<MemberDeclarationSyntax> memberList ) {
var toReplace = new Dictionary<ArgumentSyntax, ArgumentSyntax>();
IEnumerable<ArgumentSyntax> argumentSyntaxs = finalScript.DescendantNodes().OfType<ArgumentSyntax>();
|
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
|
Based on the provided code, I will create a cheat sheet to help with code completion.
**Cheat Sheet:**
**Context:** The code is part of the `ConversionVisitor` class, specifically in the `Convert` method, which is used to convert an `AutoitFunction` to a C# method.
**Relevant Variables and Methods:**
* `function`: The `AutoitFunction` being converted.
* `context`: The `IContextService` instance used for conversion.
* `statementNodes`: The list of `IStatementNode` objects representing the statements in the function.
* `dotNetStatements`: The list of `StatementSyntax` objects representing the converted C# statements.
* `body`: The `BlockSyntax` object representing the method body.
**Relevant Lines:**
* `return GetConverter<Function>().Convert( node, ContextService );` (line 34)
* `return SyntaxFactory.MethodDeclaration( SyntaxFactory.IdentifierName( typeof (Variant).Name ), function.Name.Token.Value.StringValue ).AddModifiers( SyntaxFactory.Token( SyntaxKind.PublicKeyword ) ).WithParameterList( SyntaxFactory.ParameterList( CreaterParameter( function.Parameter, context ).ToSeparatedSyntaxList() ) ).WithBody( body );` (line 63)
**Task:** The next line of code should convert the `statementNodes` list to a list of `StatementSyntax` objects.
**Expected Outcome:** A list of `StatementSyntax` objects representing the converted C# statements.
**Possible Next Line(s) of Code:**
* `List<StatementSyntax> dotNetStatements = ConvertStatements( statementNodes );`
* `dotNetStatements = ConvertStatements( statementNodes ).ToList();`
The `ConvertStatements` method is already implemented in the code, so the next line of code should call this method and assign the result to the `dotNetStatements` variable.
|
|
Please complete the code given below.
"""Tests for items views."""
import json
from datetime import datetime
import ddt
from mock import patch
from pytz import UTC
from webob import Response
from django.http import Http404
from django.test import TestCase
from django.test.client import RequestFactory
from django.core.urlresolvers import reverse
from contentstore.utils import reverse_usage_url
from contentstore.views.preview import StudioUserService
from contentstore.views.component import (
component_handler, get_component_templates
)
from contentstore.tests.utils import CourseTestCase
from student.tests.factories import UserFactory
from xmodule.capa_module import CapaDescriptor
from xmodule.modulestore import PublishState
from xmodule.x_module import STUDIO_VIEW, STUDENT_VIEW
from xblock.exceptions import NoSuchHandlerError
from opaque_keys.edx.keys import UsageKey, CourseKey
from opaque_keys.edx.locations import Location
from xmodule.partitions.partitions import Group, UserPartition
class ItemTest(CourseTestCase):
""" Base test class for create, save, and delete """
def setUp(self):
super(ItemTest, self).setUp()
self.course_key = self.course.id
self.usage_key = self.course.location
def get_item_from_modulestore(self, usage_key, verify_is_draft=False):
"""
Get the item referenced by the UsageKey from the modulestore
"""
item = self.store.get_item(usage_key)
if verify_is_draft:
self.assertTrue(getattr(item, 'is_draft', False))
return item
def response_usage_key(self, response):
"""
Get the UsageKey from the response payload and verify that the status_code was 200.
:param response:
"""
parsed = json.loads(response.content)
self.assertEqual(response.status_code, 200)
key = UsageKey.from_string(parsed['locator'])
if key.course_key.run is None:
key = key.map_into_course(CourseKey.from_string(parsed['courseKey']))
return key
def create_xblock(self, parent_usage_key=None, display_name=None, category=None, boilerplate=None):
data = {
'parent_locator': unicode(self.usage_key) if parent_usage_key is None else unicode(parent_usage_key),
'category': category
}
if display_name is not None:
data['display_name'] = display_name
if boilerplate is not None:
data['boilerplate'] = boilerplate
return self.client.ajax_post(reverse('contentstore.views.xblock_handler'), json.dumps(data))
def _create_vertical(self, parent_usage_key=None):
"""
Creates a vertical, returning its UsageKey.
"""
resp = self.create_xblock(category='vertical', parent_usage_key=parent_usage_key)
self.assertEqual(resp.status_code, 200)
return self.response_usage_key(resp)
class GetItem(ItemTest):
"""Tests for '/xblock' GET url."""
def _get_container_preview(self, usage_key):
"""
Returns the HTML and resources required for the xblock at the specified UsageKey
"""
preview_url = reverse_usage_url("xblock_view_handler", usage_key, {'view_name': 'container_preview'})
resp = self.client.get(preview_url, HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, 200)
resp_content = json.loads(resp.content)
html = resp_content['html']
self.assertTrue(html)
resources = resp_content['resources']
self.assertIsNotNone(resources)
return html, resources
def test_get_vertical(self):
# Add a vertical
resp = self.create_xblock(category='vertical')
usage_key = self.response_usage_key(resp)
# Retrieve it
resp = self.client.get(reverse_usage_url('xblock_handler', usage_key))
self.assertEqual(resp.status_code, 200)
def test_get_empty_container_fragment(self):
root_usage_key = self._create_vertical()
html, __ = self._get_container_preview(root_usage_key)
# Verify that the Studio wrapper is not added
self.assertNotIn('wrapper-xblock', html)
# Verify that the header and article tags are still added
self.assertIn('<header class="xblock-header xblock-header-vertical">', html)
self.assertIn('<article class="xblock-render">', html)
def test_get_container_fragment(self):
root_usage_key = self._create_vertical()
# Add a problem beneath a child vertical
child_vertical_usage_key = self._create_vertical(parent_usage_key=root_usage_key)
resp = self.create_xblock(parent_usage_key=child_vertical_usage_key, category='problem', boilerplate='multiplechoice.yaml')
self.assertEqual(resp.status_code, 200)
# Get the preview HTML
html, __ = self._get_container_preview(root_usage_key)
# Verify that the Studio nesting wrapper has been added
self.assertIn('level-nesting', html)
self.assertIn('<header class="xblock-header xblock-header-vertical">', html)
self.assertIn('<article class="xblock-render">', html)
# Verify that the Studio element wrapper has been added
self.assertIn('level-element', html)
def test_get_container_nested_container_fragment(self):
"""
Test the case of the container page containing a link to another container page.
"""
# Add a wrapper with child beneath a child vertical
root_usage_key = self._create_vertical()
resp = self.create_xblock(parent_usage_key=root_usage_key, category="wrapper")
self.assertEqual(resp.status_code, 200)
wrapper_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=wrapper_usage_key, category='problem', boilerplate='multiplechoice.yaml')
self.assertEqual(resp.status_code, 200)
# Get the preview HTML and verify the View -> link is present.
html, __ = self._get_container_preview(root_usage_key)
self.assertIn('wrapper-xblock', html)
self.assertRegexpMatches(
html,
# The instance of the wrapper class will have an auto-generated ID. Allow any
# characters after wrapper.
(r'"/container/i4x://MITx/999/wrapper/\w+" class="action-button">\s*'
'<span class="action-button-text">View</span>')
)
def test_split_test(self):
"""
Test that a split_test module renders all of its children in Studio.
"""
root_usage_key = self._create_vertical()
resp = self.create_xblock(category='split_test', parent_usage_key=root_usage_key)
split_test_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=split_test_usage_key, category='html', boilerplate='announcement.yaml')
self.assertEqual(resp.status_code, 200)
resp = self.create_xblock(parent_usage_key=split_test_usage_key, category='html', boilerplate='zooming_image.yaml')
self.assertEqual(resp.status_code, 200)
html, __ = self._get_container_preview(split_test_usage_key)
self.assertIn('Announcement', html)
self.assertIn('Zooming', html)
class DeleteItem(ItemTest):
"""Tests for '/xblock' DELETE url."""
def test_delete_static_page(self):
# Add static tab
resp = self.create_xblock(category='static_tab')
usage_key = self.response_usage_key(resp)
# Now delete it. There was a bug that the delete was failing (static tabs do not exist in draft modulestore).
resp = self.client.delete(reverse_usage_url('xblock_handler', usage_key))
self.assertEqual(resp.status_code, 204)
class TestCreateItem(ItemTest):
"""
Test the create_item handler thoroughly
"""
def test_create_nicely(self):
"""
Try the straightforward use cases
"""
# create a chapter
display_name = 'Nicely created'
resp = self.create_xblock(display_name=display_name, category='chapter')
# get the new item and check its category and display_name
chap_usage_key = self.response_usage_key(resp)
new_obj = self.get_item_from_modulestore(chap_usage_key)
self.assertEqual(new_obj.scope_ids.block_type, 'chapter')
self.assertEqual(new_obj.display_name, display_name)
self.assertEqual(new_obj.location.org, self.course.location.org)
self.assertEqual(new_obj.location.course, self.course.location.course)
# get the course and ensure it now points to this one
course = self.get_item_from_modulestore(self.usage_key)
self.assertIn(chap_usage_key, course.children)
# use default display name
resp = self.create_xblock(parent_usage_key=chap_usage_key, category='vertical')
vert_usage_key = self.response_usage_key(resp)
# create problem w/ boilerplate
template_id = 'multiplechoice.yaml'
resp = self.create_xblock(
parent_usage_key=vert_usage_key,
category='problem',
boilerplate=template_id
)
prob_usage_key = self.response_usage_key(resp)
problem = self.get_item_from_modulestore(prob_usage_key, verify_is_draft=True)
# check against the template
template = CapaDescriptor.get_template(template_id)
self.assertEqual(problem.data, template['data'])
self.assertEqual(problem.display_name, template['metadata']['display_name'])
self.assertEqual(problem.markdown, template['metadata']['markdown'])
def test_create_item_negative(self):
"""
Negative tests for create_item
"""
# non-existent boilerplate: creates a default
resp = self.create_xblock(category='problem', boilerplate='nosuchboilerplate.yaml')
self.assertEqual(resp.status_code, 200)
def test_create_with_future_date(self):
self.assertEqual(self.course.start, datetime(2030, 1, 1, tzinfo=UTC))
resp = self.create_xblock(category='chapter')
usage_key = self.response_usage_key(resp)
obj = self.get_item_from_modulestore(usage_key)
self.assertEqual(obj.start, datetime(2030, 1, 1, tzinfo=UTC))
def test_static_tabs_initialization(self):
"""
Test that static tab display names are not being initialized as None.
"""
# Add a new static tab with no explicit name
resp = self.create_xblock(category='static_tab')
usage_key = self.response_usage_key(resp)
# Check that its name is not None
new_tab = self.get_item_from_modulestore(usage_key)
self.assertEquals(new_tab.display_name, 'Empty')
class TestDuplicateItem(ItemTest):
"""
Test the duplicate method.
"""
def setUp(self):
""" Creates the test course structure and a few components to 'duplicate'. """
super(TestDuplicateItem, self).setUp()
# Create a parent chapter (for testing children of children).
resp = self.create_xblock(parent_usage_key=self.usage_key, category='chapter')
self.chapter_usage_key = self.response_usage_key(resp)
# create a sequential containing a problem and an html component
resp = self.create_xblock(parent_usage_key=self.chapter_usage_key, category='sequential')
self.seq_usage_key = self.response_usage_key(resp)
# create problem and an html component
resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='problem', boilerplate='multiplechoice.yaml')
self.problem_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='html')
self.html_usage_key = self.response_usage_key(resp)
# Create a second sequential just (testing children of children)
self.create_xblock(parent_usage_key=self.chapter_usage_key, category='sequential2')
def test_duplicate_equality(self):
"""
Tests that a duplicated xblock is identical to the original,
except for location and display name.
"""
def duplicate_and_verify(source_usage_key, parent_usage_key):
usage_key = self._duplicate_item(parent_usage_key, source_usage_key)
self.assertTrue(check_equality(source_usage_key, usage_key), "Duplicated item differs from original")
def check_equality(source_usage_key, duplicate_usage_key):
original_item = self.get_item_from_modulestore(source_usage_key)
duplicated_item = self.get_item_from_modulestore(duplicate_usage_key)
self.assertNotEqual(
original_item.location,
duplicated_item.location,
"Location of duplicate should be different from original"
)
# Set the location and display name to be the same so we can make sure the rest of the duplicate is equal.
duplicated_item.location = original_item.location
duplicated_item.display_name = original_item.display_name
# Children will also be duplicated, so for the purposes of testing equality, we will set
# the children to the original after recursively checking the children.
if original_item.has_children:
self.assertEqual(
len(original_item.children),
len(duplicated_item.children),
"Duplicated item differs in number of children"
)
for i in xrange(len(original_item.children)):
if not check_equality(original_item.children[i], duplicated_item.children[i]):
return False
duplicated_item.children = original_item.children
return original_item == duplicated_item
duplicate_and_verify(self.problem_usage_key, self.seq_usage_key)
duplicate_and_verify(self.html_usage_key, self.seq_usage_key)
duplicate_and_verify(self.seq_usage_key, self.chapter_usage_key)
duplicate_and_verify(self.chapter_usage_key, self.usage_key)
def test_ordering(self):
"""
Tests the a duplicated xblock appears immediately after its source
(if duplicate and source share the same parent), else at the
end of the children of the parent.
"""
def verify_order(source_usage_key, parent_usage_key, source_position=None):
usage_key = self._duplicate_item(parent_usage_key, source_usage_key)
parent = self.get_item_from_modulestore(parent_usage_key)
children = parent.children
if source_position is None:
self.assertFalse(source_usage_key in children, 'source item not expected in children array')
self.assertEqual(
children[len(children) - 1],
usage_key,
"duplicated item not at end"
)
else:
self.assertEqual(
children[source_position],
source_usage_key,
"source item at wrong position"
)
self.assertEqual(
children[source_position + 1],
usage_key,
"duplicated item not ordered after source item"
)
verify_order(self.problem_usage_key, self.seq_usage_key, 0)
# 2 because duplicate of problem should be located before.
verify_order(self.html_usage_key, self.seq_usage_key, 2)
verify_order(self.seq_usage_key, self.chapter_usage_key, 0)
# Test duplicating something into a location that is not the parent of the original item.
# Duplicated item should appear at the end.
verify_order(self.html_usage_key, self.usage_key)
def test_display_name(self):
"""
Tests the expected display name for the duplicated xblock.
"""
def verify_name(source_usage_key, parent_usage_key, expected_name, display_name=None):
usage_key = self._duplicate_item(parent_usage_key, source_usage_key, display_name)
duplicated_item = self.get_item_from_modulestore(usage_key)
self.assertEqual(duplicated_item.display_name, expected_name)
return usage_key
# Display name comes from template.
dupe_usage_key = verify_name(self.problem_usage_key, self.seq_usage_key, "Duplicate of 'Multiple Choice'")
# Test dupe of dupe.
verify_name(dupe_usage_key, self.seq_usage_key, "Duplicate of 'Duplicate of 'Multiple Choice''")
# Uses default display_name of 'Text' from HTML component.
verify_name(self.html_usage_key, self.seq_usage_key, "Duplicate of 'Text'")
# The sequence does not have a display_name set, so category is shown.
verify_name(self.seq_usage_key, self.chapter_usage_key, "Duplicate of sequential")
# Now send a custom display name for the duplicate.
verify_name(self.seq_usage_key, self.chapter_usage_key, "customized name", display_name="customized name")
def _duplicate_item(self, parent_usage_key, source_usage_key, display_name=None):
data = {
'parent_locator': unicode(parent_usage_key),
'duplicate_source_locator': unicode(source_usage_key)
}
if display_name is not None:
data['display_name'] = display_name
resp = self.client.ajax_post(reverse('contentstore.views.xblock_handler'), json.dumps(data))
return self.response_usage_key(resp)
class TestEditItem(ItemTest):
"""
Test xblock update.
"""
def setUp(self):
""" Creates the test course structure and a couple problems to 'edit'. """
super(TestEditItem, self).setUp()
# create a chapter
display_name = 'chapter created'
resp = self.create_xblock(display_name=display_name, category='chapter')
chap_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=chap_usage_key, category='sequential')
self.seq_usage_key = self.response_usage_key(resp)
self.seq_update_url = reverse_usage_url("xblock_handler", self.seq_usage_key)
# create problem w/ boilerplate
template_id = 'multiplechoice.yaml'
resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='problem', boilerplate=template_id)
self.problem_usage_key = self.response_usage_key(resp)
self.problem_update_url = reverse_usage_url("xblock_handler", self.problem_usage_key)
self.course_update_url = reverse_usage_url("xblock_handler", self.usage_key)
def verify_publish_state(self, usage_key, expected_publish_state):
"""
Helper method that gets the item from the module store and verifies that the publish state is as expected.
Returns the item corresponding to the given usage_key.
"""
item = self.get_item_from_modulestore(
usage_key,
(expected_publish_state == PublishState.private) or (expected_publish_state == PublishState.draft)
)
self.assertEqual(expected_publish_state, self.store.compute_publish_state(item))
return item
def test_delete_field(self):
"""
Sending null in for a field 'deletes' it
"""
self.client.ajax_post(
self.problem_update_url,
data={'metadata': {'rerandomize': 'onreset'}}
)
problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertEqual(problem.rerandomize, 'onreset')
self.client.ajax_post(
self.problem_update_url,
data={'metadata': {'rerandomize': None}}
)
problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertEqual(problem.rerandomize, 'never')
def test_null_field(self):
"""
Sending null in for a field 'deletes' it
"""
problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertIsNotNone(problem.markdown)
self.client.ajax_post(
self.problem_update_url,
data={'nullout': ['markdown']}
)
problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertIsNone(problem.markdown)
def test_date_fields(self):
"""
Test setting due & start dates on sequential
"""
sequential = self.get_item_from_modulestore(self.seq_usage_key)
self.assertIsNone(sequential.due)
self.client.ajax_post(
self.seq_update_url,
data={'metadata': {'due': '2010-11-22T04:00Z'}}
)
sequential = self.get_item_from_modulestore(self.seq_usage_key)
self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC))
self.client.ajax_post(
self.seq_update_url,
data={'metadata': {'start': '2010-09-12T14:00Z'}}
)
sequential = self.get_item_from_modulestore(self.seq_usage_key)
self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC))
self.assertEqual(sequential.start, datetime(2010, 9, 12, 14, 0, tzinfo=UTC))
def test_delete_child(self):
"""
Test deleting a child.
"""
# Create 2 children of main course.
resp_1 = self.create_xblock(display_name='child 1', category='chapter')
resp_2 = self.create_xblock(display_name='child 2', category='chapter')
chapter1_usage_key = self.response_usage_key(resp_1)
chapter2_usage_key = self.response_usage_key(resp_2)
course = self.get_item_from_modulestore(self.usage_key)
self.assertIn(chapter1_usage_key, course.children)
self.assertIn(chapter2_usage_key, course.children)
# Remove one child from the course.
resp = self.client.ajax_post(
self.course_update_url,
data={'children': [unicode(chapter2_usage_key)]}
)
self.assertEqual(resp.status_code, 200)
# Verify that the child is removed.
course = self.get_item_from_modulestore(self.usage_key)
self.assertNotIn(chapter1_usage_key, course.children)
self.assertIn(chapter2_usage_key, course.children)
def test_reorder_children(self):
"""
Test reordering children that can be in the draft store.
"""
# Create 2 child units and re-order them. There was a bug about @draft getting added
# to the IDs.
unit_1_resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='vertical')
unit_2_resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='vertical')
unit1_usage_key = self.response_usage_key(unit_1_resp)
unit2_usage_key = self.response_usage_key(unit_2_resp)
# The sequential already has a child defined in the setUp (a problem).
# Children must be on the sequential to reproduce the original bug,
# as it is important that the parent (sequential) NOT be in the draft store.
children = self.get_item_from_modulestore(self.seq_usage_key).children
self.assertEqual(unit1_usage_key, children[1])
self.assertEqual(unit2_usage_key, children[2])
resp = self.client.ajax_post(
self.seq_update_url,
data={'children': [unicode(self.problem_usage_key), unicode(unit2_usage_key), unicode(unit1_usage_key)]}
)
self.assertEqual(resp.status_code, 200)
children = self.get_item_from_modulestore(self.seq_usage_key).children
self.assertEqual(self.problem_usage_key, children[0])
self.assertEqual(unit1_usage_key, children[2])
self.assertEqual(unit2_usage_key, children[1])
def test_make_public(self):
""" Test making a private problem public (publishing it). """
# When the problem is first created, it is only in draft (because of its category).
self.verify_publish_state(self.problem_usage_key, PublishState.private)
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.public)
def test_make_private(self):
""" Test making a public problem private (un-publishing it). """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make it private
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_private'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.private)
def test_make_draft(self):
""" Test creating a draft version of a public problem. """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
published = self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make it draft, which means both versions will exist.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'create_draft'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.draft)
# Update the draft version and check that published is different.
self.client.ajax_post(
self.problem_update_url,
data={'metadata': {'due': '2077-10-10T04:00Z'}}
)
updated_draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertEqual(updated_draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC))
self.assertIsNone(published.due)
def test_make_public_with_update(self):
""" Update a problem and make it public at the same time. """
self.client.ajax_post(
self.problem_update_url,
data={
'metadata': {'due': '2077-10-10T04:00Z'},
'publish': 'make_public'
}
)
published = self.get_item_from_modulestore(self.problem_usage_key)
self.assertEqual(published.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC))
def test_make_private_with_update(self):
""" Make a problem private and update it at the same time. """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Make problem private and update.
self.client.ajax_post(
self.problem_update_url,
data={
'metadata': {'due': '2077-10-10T04:00Z'},
'publish': 'make_private'
}
)
draft = self.verify_publish_state(self.problem_usage_key, PublishState.private)
self.assertEqual(draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC))
def test_create_draft_with_update(self):
""" Create a draft and update it at the same time. """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
published = self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make it draft, which means both versions will exist.
self.client.ajax_post(
self.problem_update_url,
data={
'metadata': {'due': '2077-10-10T04:00Z'},
'publish': 'create_draft'
}
)
draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertEqual(draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC))
self.assertIsNone(published.due)
def test_create_draft_with_multiple_requests(self):
"""
Create a draft request returns already created version if it exists.
"""
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make it draft, which means both versions will exist.
self.client.ajax_post(
self.problem_update_url,
data={
'publish': 'create_draft'
}
)
draft_1 = self.verify_publish_state(self.problem_usage_key, PublishState.draft)
# Now check that when a user sends request to create a draft when there is already a draft version then
# user gets that already created draft instead of getting 'DuplicateItemError' exception.
self.client.ajax_post(
self.problem_update_url,
data={
'publish': 'create_draft'
}
)
draft_2 = self.verify_publish_state(self.problem_usage_key, PublishState.draft)
self.assertIsNotNone(draft_2)
self.assertEqual(draft_1, draft_2)
def test_make_private_with_multiple_requests(self):
"""
Make private requests gets proper response even if xmodule is already made private.
"""
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.assertIsNotNone(self.get_item_from_modulestore(self.problem_usage_key))
# Now make it private, and check that its version is private
resp = self.client.ajax_post(
self.problem_update_url,
data={
'publish': 'make_private'
}
)
self.assertEqual(resp.status_code, 200)
draft_1 = self.verify_publish_state(self.problem_usage_key, PublishState.private)
# Now check that when a user sends request to make it private when it already is private then
# user gets that private version instead of getting 'ItemNotFoundError' exception.
self.client.ajax_post(
self.problem_update_url,
data={
'publish': 'make_private'
}
)
self.assertEqual(resp.status_code, 200)
draft_2 = self.verify_publish_state(self.problem_usage_key, PublishState.private)
self.assertEqual(draft_1, draft_2)
def test_published_and_draft_contents_with_update(self):
""" Create a draft and publish it then modify the draft and check that published content is not modified """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
published = self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make a draft
self.client.ajax_post(
self.problem_update_url,
data={
'id': unicode(self.problem_usage_key),
'metadata': {},
'data': "<p>Problem content draft.</p>",
'publish': 'create_draft'
}
)
# Both published and draft content should be different
draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertNotEqual(draft.data, published.data)
# Get problem by 'xblock_handler'
view_url = reverse_usage_url("xblock_view_handler", self.problem_usage_key, {"view_name": STUDENT_VIEW})
resp = self.client.get(view_url, HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, 200)
# Activate the editing view
view_url = reverse_usage_url("xblock_view_handler", self.problem_usage_key, {"view_name": STUDIO_VIEW})
resp = self.client.get(view_url, HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, 200)
# Both published and draft content should still be different
draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertNotEqual(draft.data, published.data)
def test_publish_states_of_nested_xblocks(self):
""" Test publishing of a unit page containing a nested xblock """
resp = self.create_xblock(parent_usage_key=self.seq_usage_key, display_name='Test Unit', category='vertical')
unit_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=unit_usage_key, category='wrapper')
wrapper_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=wrapper_usage_key, category='html')
html_usage_key = self.response_usage_key(resp)
# The unit and its children should be private initially
unit_update_url = reverse_usage_url('xblock_handler', unit_usage_key)
self.verify_publish_state(unit_usage_key, PublishState.private)
self.verify_publish_state(html_usage_key, PublishState.private)
# Make the unit public and verify that the problem is also made public
resp = self.client.ajax_post(
unit_update_url,
data={'publish': 'make_public'}
)
self.assertEqual(resp.status_code, 200)
self.verify_publish_state(unit_usage_key, PublishState.public)
self.verify_publish_state(html_usage_key, PublishState.public)
# Make a draft for the unit and verify that the problem also has a draft
resp = self.client.ajax_post(
unit_update_url,
data={
'id': unicode(unit_usage_key),
'metadata': {},
'publish': 'create_draft'
}
)
self.assertEqual(resp.status_code, 200)
self.verify_publish_state(unit_usage_key, PublishState.draft)
self.verify_publish_state(html_usage_key, PublishState.draft)
class TestEditSplitModule(ItemTest):
"""
Tests around editing instances of the split_test module.
"""
def setUp(self):
super(TestEditSplitModule, self).setUp()
self.course.user_partitions = [
UserPartition(
0, 'first_partition', 'First Partition',
[Group("0", 'alpha'), Group("1", 'beta')]
),
UserPartition(
1, 'second_partition', 'Second Partition',
[Group("0", 'Group 0'), Group("1", 'Group 1'), Group("2", 'Group 2')]
)
]
self.store.update_item(self.course, self.user.id)
root_usage_key = self._create_vertical()
resp = self.create_xblock(category='split_test', parent_usage_key=root_usage_key)
self.split_test_usage_key = self.response_usage_key(resp)
self.split_test_update_url = reverse_usage_url("xblock_handler", self.split_test_usage_key)
self.request_factory = RequestFactory()
self.request = self.request_factory.get('/dummy-url')
self.request.user = self.user
def _update_partition_id(self, partition_id):
"""
Helper method that sets the user_partition_id to the supplied value.
The updated split_test instance is returned.
"""
self.client.ajax_post(
self.split_test_update_url,
# Even though user_partition_id is Scope.content, it will get saved by the Studio editor as
# metadata. The code in item.py will update the field correctly, even though it is not the
# expected scope.
data={'metadata': {'user_partition_id': str(partition_id)}}
)
# Verify the partition_id was saved.
split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True)
self.assertEqual(partition_id, split_test.user_partition_id)
return split_test
def _assert_children(self, expected_number):
"""
Verifies the number of children of the split_test instance.
"""
split_test = self.get_item_from_modulestore(self.split_test_usage_key, True)
self.assertEqual(expected_number, len(split_test.children))
return split_test
def test_create_groups(self):
"""
Test that verticals are created for the configuration groups when
a spit test module is edited.
"""
split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True)
# Initially, no user_partition_id is set, and the split_test has no children.
self.assertEqual(-1, split_test.user_partition_id)
self.assertEqual(0, len(split_test.children))
# Set the user_partition_id to 0.
split_test = self._update_partition_id(0)
# Verify that child verticals have been set to match the groups
self.assertEqual(2, len(split_test.children))
vertical_0 = self.get_item_from_modulestore(split_test.children[0], verify_is_draft=True)
vertical_1 = self.get_item_from_modulestore(split_test.children[1], verify_is_draft=True)
self.assertEqual("vertical", vertical_0.category)
self.assertEqual("vertical", vertical_1.category)
self.assertEqual("alpha", vertical_0.display_name)
self.assertEqual("beta", vertical_1.display_name)
# Verify that the group_id_to_child mapping is correct.
self.assertEqual(2, len(split_test.group_id_to_child))
self.assertEqual(vertical_0.location, split_test.group_id_to_child['0'])
self.assertEqual(vertical_1.location, split_test.group_id_to_child['1'])
def test_change_user_partition_id(self):
"""
Test what happens when the user_partition_id is changed to a different groups
group configuration.
"""
# Set to first group configuration.
|
[
" split_test = self._update_partition_id(0)"
] | 2,752
|
lcc
|
python
| null |
b55c3cd64c946848d39da7e77c7364582b5e7ab71a545f58
| 31
|
Your task is code completion.
"""Tests for items views."""
import json
from datetime import datetime
import ddt
from mock import patch
from pytz import UTC
from webob import Response
from django.http import Http404
from django.test import TestCase
from django.test.client import RequestFactory
from django.core.urlresolvers import reverse
from contentstore.utils import reverse_usage_url
from contentstore.views.preview import StudioUserService
from contentstore.views.component import (
component_handler, get_component_templates
)
from contentstore.tests.utils import CourseTestCase
from student.tests.factories import UserFactory
from xmodule.capa_module import CapaDescriptor
from xmodule.modulestore import PublishState
from xmodule.x_module import STUDIO_VIEW, STUDENT_VIEW
from xblock.exceptions import NoSuchHandlerError
from opaque_keys.edx.keys import UsageKey, CourseKey
from opaque_keys.edx.locations import Location
from xmodule.partitions.partitions import Group, UserPartition
class ItemTest(CourseTestCase):
""" Base test class for create, save, and delete """
def setUp(self):
super(ItemTest, self).setUp()
self.course_key = self.course.id
self.usage_key = self.course.location
def get_item_from_modulestore(self, usage_key, verify_is_draft=False):
"""
Get the item referenced by the UsageKey from the modulestore
"""
item = self.store.get_item(usage_key)
if verify_is_draft:
self.assertTrue(getattr(item, 'is_draft', False))
return item
def response_usage_key(self, response):
"""
Get the UsageKey from the response payload and verify that the status_code was 200.
:param response:
"""
parsed = json.loads(response.content)
self.assertEqual(response.status_code, 200)
key = UsageKey.from_string(parsed['locator'])
if key.course_key.run is None:
key = key.map_into_course(CourseKey.from_string(parsed['courseKey']))
return key
def create_xblock(self, parent_usage_key=None, display_name=None, category=None, boilerplate=None):
data = {
'parent_locator': unicode(self.usage_key) if parent_usage_key is None else unicode(parent_usage_key),
'category': category
}
if display_name is not None:
data['display_name'] = display_name
if boilerplate is not None:
data['boilerplate'] = boilerplate
return self.client.ajax_post(reverse('contentstore.views.xblock_handler'), json.dumps(data))
def _create_vertical(self, parent_usage_key=None):
"""
Creates a vertical, returning its UsageKey.
"""
resp = self.create_xblock(category='vertical', parent_usage_key=parent_usage_key)
self.assertEqual(resp.status_code, 200)
return self.response_usage_key(resp)
class GetItem(ItemTest):
"""Tests for '/xblock' GET url."""
def _get_container_preview(self, usage_key):
"""
Returns the HTML and resources required for the xblock at the specified UsageKey
"""
preview_url = reverse_usage_url("xblock_view_handler", usage_key, {'view_name': 'container_preview'})
resp = self.client.get(preview_url, HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, 200)
resp_content = json.loads(resp.content)
html = resp_content['html']
self.assertTrue(html)
resources = resp_content['resources']
self.assertIsNotNone(resources)
return html, resources
def test_get_vertical(self):
# Add a vertical
resp = self.create_xblock(category='vertical')
usage_key = self.response_usage_key(resp)
# Retrieve it
resp = self.client.get(reverse_usage_url('xblock_handler', usage_key))
self.assertEqual(resp.status_code, 200)
def test_get_empty_container_fragment(self):
root_usage_key = self._create_vertical()
html, __ = self._get_container_preview(root_usage_key)
# Verify that the Studio wrapper is not added
self.assertNotIn('wrapper-xblock', html)
# Verify that the header and article tags are still added
self.assertIn('<header class="xblock-header xblock-header-vertical">', html)
self.assertIn('<article class="xblock-render">', html)
def test_get_container_fragment(self):
root_usage_key = self._create_vertical()
# Add a problem beneath a child vertical
child_vertical_usage_key = self._create_vertical(parent_usage_key=root_usage_key)
resp = self.create_xblock(parent_usage_key=child_vertical_usage_key, category='problem', boilerplate='multiplechoice.yaml')
self.assertEqual(resp.status_code, 200)
# Get the preview HTML
html, __ = self._get_container_preview(root_usage_key)
# Verify that the Studio nesting wrapper has been added
self.assertIn('level-nesting', html)
self.assertIn('<header class="xblock-header xblock-header-vertical">', html)
self.assertIn('<article class="xblock-render">', html)
# Verify that the Studio element wrapper has been added
self.assertIn('level-element', html)
def test_get_container_nested_container_fragment(self):
"""
Test the case of the container page containing a link to another container page.
"""
# Add a wrapper with child beneath a child vertical
root_usage_key = self._create_vertical()
resp = self.create_xblock(parent_usage_key=root_usage_key, category="wrapper")
self.assertEqual(resp.status_code, 200)
wrapper_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=wrapper_usage_key, category='problem', boilerplate='multiplechoice.yaml')
self.assertEqual(resp.status_code, 200)
# Get the preview HTML and verify the View -> link is present.
html, __ = self._get_container_preview(root_usage_key)
self.assertIn('wrapper-xblock', html)
self.assertRegexpMatches(
html,
# The instance of the wrapper class will have an auto-generated ID. Allow any
# characters after wrapper.
(r'"/container/i4x://MITx/999/wrapper/\w+" class="action-button">\s*'
'<span class="action-button-text">View</span>')
)
def test_split_test(self):
"""
Test that a split_test module renders all of its children in Studio.
"""
root_usage_key = self._create_vertical()
resp = self.create_xblock(category='split_test', parent_usage_key=root_usage_key)
split_test_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=split_test_usage_key, category='html', boilerplate='announcement.yaml')
self.assertEqual(resp.status_code, 200)
resp = self.create_xblock(parent_usage_key=split_test_usage_key, category='html', boilerplate='zooming_image.yaml')
self.assertEqual(resp.status_code, 200)
html, __ = self._get_container_preview(split_test_usage_key)
self.assertIn('Announcement', html)
self.assertIn('Zooming', html)
class DeleteItem(ItemTest):
"""Tests for '/xblock' DELETE url."""
def test_delete_static_page(self):
# Add static tab
resp = self.create_xblock(category='static_tab')
usage_key = self.response_usage_key(resp)
# Now delete it. There was a bug that the delete was failing (static tabs do not exist in draft modulestore).
resp = self.client.delete(reverse_usage_url('xblock_handler', usage_key))
self.assertEqual(resp.status_code, 204)
class TestCreateItem(ItemTest):
"""
Test the create_item handler thoroughly
"""
def test_create_nicely(self):
"""
Try the straightforward use cases
"""
# create a chapter
display_name = 'Nicely created'
resp = self.create_xblock(display_name=display_name, category='chapter')
# get the new item and check its category and display_name
chap_usage_key = self.response_usage_key(resp)
new_obj = self.get_item_from_modulestore(chap_usage_key)
self.assertEqual(new_obj.scope_ids.block_type, 'chapter')
self.assertEqual(new_obj.display_name, display_name)
self.assertEqual(new_obj.location.org, self.course.location.org)
self.assertEqual(new_obj.location.course, self.course.location.course)
# get the course and ensure it now points to this one
course = self.get_item_from_modulestore(self.usage_key)
self.assertIn(chap_usage_key, course.children)
# use default display name
resp = self.create_xblock(parent_usage_key=chap_usage_key, category='vertical')
vert_usage_key = self.response_usage_key(resp)
# create problem w/ boilerplate
template_id = 'multiplechoice.yaml'
resp = self.create_xblock(
parent_usage_key=vert_usage_key,
category='problem',
boilerplate=template_id
)
prob_usage_key = self.response_usage_key(resp)
problem = self.get_item_from_modulestore(prob_usage_key, verify_is_draft=True)
# check against the template
template = CapaDescriptor.get_template(template_id)
self.assertEqual(problem.data, template['data'])
self.assertEqual(problem.display_name, template['metadata']['display_name'])
self.assertEqual(problem.markdown, template['metadata']['markdown'])
def test_create_item_negative(self):
"""
Negative tests for create_item
"""
# non-existent boilerplate: creates a default
resp = self.create_xblock(category='problem', boilerplate='nosuchboilerplate.yaml')
self.assertEqual(resp.status_code, 200)
def test_create_with_future_date(self):
self.assertEqual(self.course.start, datetime(2030, 1, 1, tzinfo=UTC))
resp = self.create_xblock(category='chapter')
usage_key = self.response_usage_key(resp)
obj = self.get_item_from_modulestore(usage_key)
self.assertEqual(obj.start, datetime(2030, 1, 1, tzinfo=UTC))
def test_static_tabs_initialization(self):
"""
Test that static tab display names are not being initialized as None.
"""
# Add a new static tab with no explicit name
resp = self.create_xblock(category='static_tab')
usage_key = self.response_usage_key(resp)
# Check that its name is not None
new_tab = self.get_item_from_modulestore(usage_key)
self.assertEquals(new_tab.display_name, 'Empty')
class TestDuplicateItem(ItemTest):
"""
Test the duplicate method.
"""
def setUp(self):
""" Creates the test course structure and a few components to 'duplicate'. """
super(TestDuplicateItem, self).setUp()
# Create a parent chapter (for testing children of children).
resp = self.create_xblock(parent_usage_key=self.usage_key, category='chapter')
self.chapter_usage_key = self.response_usage_key(resp)
# create a sequential containing a problem and an html component
resp = self.create_xblock(parent_usage_key=self.chapter_usage_key, category='sequential')
self.seq_usage_key = self.response_usage_key(resp)
# create problem and an html component
resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='problem', boilerplate='multiplechoice.yaml')
self.problem_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='html')
self.html_usage_key = self.response_usage_key(resp)
# Create a second sequential just (testing children of children)
self.create_xblock(parent_usage_key=self.chapter_usage_key, category='sequential2')
def test_duplicate_equality(self):
"""
Tests that a duplicated xblock is identical to the original,
except for location and display name.
"""
def duplicate_and_verify(source_usage_key, parent_usage_key):
usage_key = self._duplicate_item(parent_usage_key, source_usage_key)
self.assertTrue(check_equality(source_usage_key, usage_key), "Duplicated item differs from original")
def check_equality(source_usage_key, duplicate_usage_key):
original_item = self.get_item_from_modulestore(source_usage_key)
duplicated_item = self.get_item_from_modulestore(duplicate_usage_key)
self.assertNotEqual(
original_item.location,
duplicated_item.location,
"Location of duplicate should be different from original"
)
# Set the location and display name to be the same so we can make sure the rest of the duplicate is equal.
duplicated_item.location = original_item.location
duplicated_item.display_name = original_item.display_name
# Children will also be duplicated, so for the purposes of testing equality, we will set
# the children to the original after recursively checking the children.
if original_item.has_children:
self.assertEqual(
len(original_item.children),
len(duplicated_item.children),
"Duplicated item differs in number of children"
)
for i in xrange(len(original_item.children)):
if not check_equality(original_item.children[i], duplicated_item.children[i]):
return False
duplicated_item.children = original_item.children
return original_item == duplicated_item
duplicate_and_verify(self.problem_usage_key, self.seq_usage_key)
duplicate_and_verify(self.html_usage_key, self.seq_usage_key)
duplicate_and_verify(self.seq_usage_key, self.chapter_usage_key)
duplicate_and_verify(self.chapter_usage_key, self.usage_key)
def test_ordering(self):
"""
Tests the a duplicated xblock appears immediately after its source
(if duplicate and source share the same parent), else at the
end of the children of the parent.
"""
def verify_order(source_usage_key, parent_usage_key, source_position=None):
usage_key = self._duplicate_item(parent_usage_key, source_usage_key)
parent = self.get_item_from_modulestore(parent_usage_key)
children = parent.children
if source_position is None:
self.assertFalse(source_usage_key in children, 'source item not expected in children array')
self.assertEqual(
children[len(children) - 1],
usage_key,
"duplicated item not at end"
)
else:
self.assertEqual(
children[source_position],
source_usage_key,
"source item at wrong position"
)
self.assertEqual(
children[source_position + 1],
usage_key,
"duplicated item not ordered after source item"
)
verify_order(self.problem_usage_key, self.seq_usage_key, 0)
# 2 because duplicate of problem should be located before.
verify_order(self.html_usage_key, self.seq_usage_key, 2)
verify_order(self.seq_usage_key, self.chapter_usage_key, 0)
# Test duplicating something into a location that is not the parent of the original item.
# Duplicated item should appear at the end.
verify_order(self.html_usage_key, self.usage_key)
def test_display_name(self):
"""
Tests the expected display name for the duplicated xblock.
"""
def verify_name(source_usage_key, parent_usage_key, expected_name, display_name=None):
usage_key = self._duplicate_item(parent_usage_key, source_usage_key, display_name)
duplicated_item = self.get_item_from_modulestore(usage_key)
self.assertEqual(duplicated_item.display_name, expected_name)
return usage_key
# Display name comes from template.
dupe_usage_key = verify_name(self.problem_usage_key, self.seq_usage_key, "Duplicate of 'Multiple Choice'")
# Test dupe of dupe.
verify_name(dupe_usage_key, self.seq_usage_key, "Duplicate of 'Duplicate of 'Multiple Choice''")
# Uses default display_name of 'Text' from HTML component.
verify_name(self.html_usage_key, self.seq_usage_key, "Duplicate of 'Text'")
# The sequence does not have a display_name set, so category is shown.
verify_name(self.seq_usage_key, self.chapter_usage_key, "Duplicate of sequential")
# Now send a custom display name for the duplicate.
verify_name(self.seq_usage_key, self.chapter_usage_key, "customized name", display_name="customized name")
def _duplicate_item(self, parent_usage_key, source_usage_key, display_name=None):
data = {
'parent_locator': unicode(parent_usage_key),
'duplicate_source_locator': unicode(source_usage_key)
}
if display_name is not None:
data['display_name'] = display_name
resp = self.client.ajax_post(reverse('contentstore.views.xblock_handler'), json.dumps(data))
return self.response_usage_key(resp)
class TestEditItem(ItemTest):
"""
Test xblock update.
"""
def setUp(self):
""" Creates the test course structure and a couple problems to 'edit'. """
super(TestEditItem, self).setUp()
# create a chapter
display_name = 'chapter created'
resp = self.create_xblock(display_name=display_name, category='chapter')
chap_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=chap_usage_key, category='sequential')
self.seq_usage_key = self.response_usage_key(resp)
self.seq_update_url = reverse_usage_url("xblock_handler", self.seq_usage_key)
# create problem w/ boilerplate
template_id = 'multiplechoice.yaml'
resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='problem', boilerplate=template_id)
self.problem_usage_key = self.response_usage_key(resp)
self.problem_update_url = reverse_usage_url("xblock_handler", self.problem_usage_key)
self.course_update_url = reverse_usage_url("xblock_handler", self.usage_key)
def verify_publish_state(self, usage_key, expected_publish_state):
"""
Helper method that gets the item from the module store and verifies that the publish state is as expected.
Returns the item corresponding to the given usage_key.
"""
item = self.get_item_from_modulestore(
usage_key,
(expected_publish_state == PublishState.private) or (expected_publish_state == PublishState.draft)
)
self.assertEqual(expected_publish_state, self.store.compute_publish_state(item))
return item
def test_delete_field(self):
"""
Sending null in for a field 'deletes' it
"""
self.client.ajax_post(
self.problem_update_url,
data={'metadata': {'rerandomize': 'onreset'}}
)
problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertEqual(problem.rerandomize, 'onreset')
self.client.ajax_post(
self.problem_update_url,
data={'metadata': {'rerandomize': None}}
)
problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertEqual(problem.rerandomize, 'never')
def test_null_field(self):
"""
Sending null in for a field 'deletes' it
"""
problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertIsNotNone(problem.markdown)
self.client.ajax_post(
self.problem_update_url,
data={'nullout': ['markdown']}
)
problem = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertIsNone(problem.markdown)
def test_date_fields(self):
"""
Test setting due & start dates on sequential
"""
sequential = self.get_item_from_modulestore(self.seq_usage_key)
self.assertIsNone(sequential.due)
self.client.ajax_post(
self.seq_update_url,
data={'metadata': {'due': '2010-11-22T04:00Z'}}
)
sequential = self.get_item_from_modulestore(self.seq_usage_key)
self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC))
self.client.ajax_post(
self.seq_update_url,
data={'metadata': {'start': '2010-09-12T14:00Z'}}
)
sequential = self.get_item_from_modulestore(self.seq_usage_key)
self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC))
self.assertEqual(sequential.start, datetime(2010, 9, 12, 14, 0, tzinfo=UTC))
def test_delete_child(self):
"""
Test deleting a child.
"""
# Create 2 children of main course.
resp_1 = self.create_xblock(display_name='child 1', category='chapter')
resp_2 = self.create_xblock(display_name='child 2', category='chapter')
chapter1_usage_key = self.response_usage_key(resp_1)
chapter2_usage_key = self.response_usage_key(resp_2)
course = self.get_item_from_modulestore(self.usage_key)
self.assertIn(chapter1_usage_key, course.children)
self.assertIn(chapter2_usage_key, course.children)
# Remove one child from the course.
resp = self.client.ajax_post(
self.course_update_url,
data={'children': [unicode(chapter2_usage_key)]}
)
self.assertEqual(resp.status_code, 200)
# Verify that the child is removed.
course = self.get_item_from_modulestore(self.usage_key)
self.assertNotIn(chapter1_usage_key, course.children)
self.assertIn(chapter2_usage_key, course.children)
def test_reorder_children(self):
"""
Test reordering children that can be in the draft store.
"""
# Create 2 child units and re-order them. There was a bug about @draft getting added
# to the IDs.
unit_1_resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='vertical')
unit_2_resp = self.create_xblock(parent_usage_key=self.seq_usage_key, category='vertical')
unit1_usage_key = self.response_usage_key(unit_1_resp)
unit2_usage_key = self.response_usage_key(unit_2_resp)
# The sequential already has a child defined in the setUp (a problem).
# Children must be on the sequential to reproduce the original bug,
# as it is important that the parent (sequential) NOT be in the draft store.
children = self.get_item_from_modulestore(self.seq_usage_key).children
self.assertEqual(unit1_usage_key, children[1])
self.assertEqual(unit2_usage_key, children[2])
resp = self.client.ajax_post(
self.seq_update_url,
data={'children': [unicode(self.problem_usage_key), unicode(unit2_usage_key), unicode(unit1_usage_key)]}
)
self.assertEqual(resp.status_code, 200)
children = self.get_item_from_modulestore(self.seq_usage_key).children
self.assertEqual(self.problem_usage_key, children[0])
self.assertEqual(unit1_usage_key, children[2])
self.assertEqual(unit2_usage_key, children[1])
def test_make_public(self):
""" Test making a private problem public (publishing it). """
# When the problem is first created, it is only in draft (because of its category).
self.verify_publish_state(self.problem_usage_key, PublishState.private)
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.public)
def test_make_private(self):
""" Test making a public problem private (un-publishing it). """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make it private
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_private'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.private)
def test_make_draft(self):
""" Test creating a draft version of a public problem. """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
published = self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make it draft, which means both versions will exist.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'create_draft'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.draft)
# Update the draft version and check that published is different.
self.client.ajax_post(
self.problem_update_url,
data={'metadata': {'due': '2077-10-10T04:00Z'}}
)
updated_draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertEqual(updated_draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC))
self.assertIsNone(published.due)
def test_make_public_with_update(self):
""" Update a problem and make it public at the same time. """
self.client.ajax_post(
self.problem_update_url,
data={
'metadata': {'due': '2077-10-10T04:00Z'},
'publish': 'make_public'
}
)
published = self.get_item_from_modulestore(self.problem_usage_key)
self.assertEqual(published.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC))
def test_make_private_with_update(self):
""" Make a problem private and update it at the same time. """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Make problem private and update.
self.client.ajax_post(
self.problem_update_url,
data={
'metadata': {'due': '2077-10-10T04:00Z'},
'publish': 'make_private'
}
)
draft = self.verify_publish_state(self.problem_usage_key, PublishState.private)
self.assertEqual(draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC))
def test_create_draft_with_update(self):
""" Create a draft and update it at the same time. """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
published = self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make it draft, which means both versions will exist.
self.client.ajax_post(
self.problem_update_url,
data={
'metadata': {'due': '2077-10-10T04:00Z'},
'publish': 'create_draft'
}
)
draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertEqual(draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC))
self.assertIsNone(published.due)
def test_create_draft_with_multiple_requests(self):
"""
Create a draft request returns already created version if it exists.
"""
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make it draft, which means both versions will exist.
self.client.ajax_post(
self.problem_update_url,
data={
'publish': 'create_draft'
}
)
draft_1 = self.verify_publish_state(self.problem_usage_key, PublishState.draft)
# Now check that when a user sends request to create a draft when there is already a draft version then
# user gets that already created draft instead of getting 'DuplicateItemError' exception.
self.client.ajax_post(
self.problem_update_url,
data={
'publish': 'create_draft'
}
)
draft_2 = self.verify_publish_state(self.problem_usage_key, PublishState.draft)
self.assertIsNotNone(draft_2)
self.assertEqual(draft_1, draft_2)
def test_make_private_with_multiple_requests(self):
"""
Make private requests gets proper response even if xmodule is already made private.
"""
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
self.assertIsNotNone(self.get_item_from_modulestore(self.problem_usage_key))
# Now make it private, and check that its version is private
resp = self.client.ajax_post(
self.problem_update_url,
data={
'publish': 'make_private'
}
)
self.assertEqual(resp.status_code, 200)
draft_1 = self.verify_publish_state(self.problem_usage_key, PublishState.private)
# Now check that when a user sends request to make it private when it already is private then
# user gets that private version instead of getting 'ItemNotFoundError' exception.
self.client.ajax_post(
self.problem_update_url,
data={
'publish': 'make_private'
}
)
self.assertEqual(resp.status_code, 200)
draft_2 = self.verify_publish_state(self.problem_usage_key, PublishState.private)
self.assertEqual(draft_1, draft_2)
def test_published_and_draft_contents_with_update(self):
""" Create a draft and publish it then modify the draft and check that published content is not modified """
# Make problem public.
self.client.ajax_post(
self.problem_update_url,
data={'publish': 'make_public'}
)
published = self.verify_publish_state(self.problem_usage_key, PublishState.public)
# Now make a draft
self.client.ajax_post(
self.problem_update_url,
data={
'id': unicode(self.problem_usage_key),
'metadata': {},
'data': "<p>Problem content draft.</p>",
'publish': 'create_draft'
}
)
# Both published and draft content should be different
draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertNotEqual(draft.data, published.data)
# Get problem by 'xblock_handler'
view_url = reverse_usage_url("xblock_view_handler", self.problem_usage_key, {"view_name": STUDENT_VIEW})
resp = self.client.get(view_url, HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, 200)
# Activate the editing view
view_url = reverse_usage_url("xblock_view_handler", self.problem_usage_key, {"view_name": STUDIO_VIEW})
resp = self.client.get(view_url, HTTP_ACCEPT='application/json')
self.assertEqual(resp.status_code, 200)
# Both published and draft content should still be different
draft = self.get_item_from_modulestore(self.problem_usage_key, verify_is_draft=True)
self.assertNotEqual(draft.data, published.data)
def test_publish_states_of_nested_xblocks(self):
""" Test publishing of a unit page containing a nested xblock """
resp = self.create_xblock(parent_usage_key=self.seq_usage_key, display_name='Test Unit', category='vertical')
unit_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=unit_usage_key, category='wrapper')
wrapper_usage_key = self.response_usage_key(resp)
resp = self.create_xblock(parent_usage_key=wrapper_usage_key, category='html')
html_usage_key = self.response_usage_key(resp)
# The unit and its children should be private initially
unit_update_url = reverse_usage_url('xblock_handler', unit_usage_key)
self.verify_publish_state(unit_usage_key, PublishState.private)
self.verify_publish_state(html_usage_key, PublishState.private)
# Make the unit public and verify that the problem is also made public
resp = self.client.ajax_post(
unit_update_url,
data={'publish': 'make_public'}
)
self.assertEqual(resp.status_code, 200)
self.verify_publish_state(unit_usage_key, PublishState.public)
self.verify_publish_state(html_usage_key, PublishState.public)
# Make a draft for the unit and verify that the problem also has a draft
resp = self.client.ajax_post(
unit_update_url,
data={
'id': unicode(unit_usage_key),
'metadata': {},
'publish': 'create_draft'
}
)
self.assertEqual(resp.status_code, 200)
self.verify_publish_state(unit_usage_key, PublishState.draft)
self.verify_publish_state(html_usage_key, PublishState.draft)
class TestEditSplitModule(ItemTest):
"""
Tests around editing instances of the split_test module.
"""
def setUp(self):
super(TestEditSplitModule, self).setUp()
self.course.user_partitions = [
UserPartition(
0, 'first_partition', 'First Partition',
[Group("0", 'alpha'), Group("1", 'beta')]
),
UserPartition(
1, 'second_partition', 'Second Partition',
[Group("0", 'Group 0'), Group("1", 'Group 1'), Group("2", 'Group 2')]
)
]
self.store.update_item(self.course, self.user.id)
root_usage_key = self._create_vertical()
resp = self.create_xblock(category='split_test', parent_usage_key=root_usage_key)
self.split_test_usage_key = self.response_usage_key(resp)
self.split_test_update_url = reverse_usage_url("xblock_handler", self.split_test_usage_key)
self.request_factory = RequestFactory()
self.request = self.request_factory.get('/dummy-url')
self.request.user = self.user
def _update_partition_id(self, partition_id):
"""
Helper method that sets the user_partition_id to the supplied value.
The updated split_test instance is returned.
"""
self.client.ajax_post(
self.split_test_update_url,
# Even though user_partition_id is Scope.content, it will get saved by the Studio editor as
# metadata. The code in item.py will update the field correctly, even though it is not the
# expected scope.
data={'metadata': {'user_partition_id': str(partition_id)}}
)
# Verify the partition_id was saved.
split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True)
self.assertEqual(partition_id, split_test.user_partition_id)
return split_test
def _assert_children(self, expected_number):
"""
Verifies the number of children of the split_test instance.
"""
split_test = self.get_item_from_modulestore(self.split_test_usage_key, True)
self.assertEqual(expected_number, len(split_test.children))
return split_test
def test_create_groups(self):
"""
Test that verticals are created for the configuration groups when
a spit test module is edited.
"""
split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True)
# Initially, no user_partition_id is set, and the split_test has no children.
self.assertEqual(-1, split_test.user_partition_id)
self.assertEqual(0, len(split_test.children))
# Set the user_partition_id to 0.
split_test = self._update_partition_id(0)
# Verify that child verticals have been set to match the groups
self.assertEqual(2, len(split_test.children))
vertical_0 = self.get_item_from_modulestore(split_test.children[0], verify_is_draft=True)
vertical_1 = self.get_item_from_modulestore(split_test.children[1], verify_is_draft=True)
self.assertEqual("vertical", vertical_0.category)
self.assertEqual("vertical", vertical_1.category)
self.assertEqual("alpha", vertical_0.display_name)
self.assertEqual("beta", vertical_1.display_name)
# Verify that the group_id_to_child mapping is correct.
self.assertEqual(2, len(split_test.group_id_to_child))
self.assertEqual(vertical_0.location, split_test.group_id_to_child['0'])
self.assertEqual(vertical_1.location, split_test.group_id_to_child['1'])
def test_change_user_partition_id(self):
"""
Test what happens when the user_partition_id is changed to a different groups
group configuration.
"""
# Set to first group configuration.
|
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
|
Context:
[Previous code... ~10,000 lines omitted for brevity]
class TestEditSplitModule(ItemTest):
"""
Tests around editing instances of the split_test module.
"""
def setUp(self):
super(TestEditSplitModule, self).setUp()
self.course.user_partitions = [
UserPartition(
0, 'first_partition', 'First Partition',
[Group("0", 'alpha'), Group("1", 'beta')]
),
UserPartition(
1, 'second_partition', 'Second Partition',
[Group("0", 'Group 0'), Group("1", 'Group 1'), Group("2", 'Group 2')]
)
]
self.store.update_item(self.course, self.user.id)
root_usage_key = self._create_vertical()
resp = self.create_xblock(category='split_test', parent_usage_key=root_usage_key)
self.split_test_usage_key = self.response_usage_key(resp)
self.split_test_update_url = reverse_usage_url("xblock_handler", self.split_test_usage_key)
self.request_factory = RequestFactory()
self.request = self.request_factory.get('/dummy-url')
self.request.user = self.user
def _update_partition_id(self, partition_id):
"""
Helper method that sets the user_partition_id to the supplied value.
The updated split_test instance is returned.
"""
self.client.ajax_post(
self.split_test_update_url,
# Even though user_partition_id is Scope.content, it will get saved by the Studio editor as
# metadata. The code in item.py will update the field correctly, even though it is not the
# expected scope.
data={'metadata': {'user_partition_id': str(partition_id)}}
)
# Verify the partition_id was saved.
split_test = self.get_item_from_modulestore(self.split_test_usage_key, verify_is_draft=True)
self.assertEqual(partition_id, split_test.user_partition_id)
return split_test
def _assert_children(self, expected_number):
"""
Verifies the number of children of the split_test instance.
"""
split_test = self.get_item_from_modulestore(self.split_test_usage_key, True)
self.assertEqual(expected_number, len(split_test.children))
return split_test
def test_change_user_partition_id(self):
"""
Test what happens when the user_partition_id is changed to a different groups
group configuration.
"""
# Set to first group configuration.
split_test = self._update_partition_id(0)
# Verify that child verticals have been set to match the groups
self.assertEqual(2, len(split_test.children))
vertical_0 = self.get_item_from_modulestore(split_test.children[0], verify_is_draft=True)
vertical_1 = self.get_item_from_modulestore(split_test.children[1], verify_is_draft=True)
self.assertEqual("vertical", vertical_0.category)
self.assertEqual("vertical", vertical_1.category)
self.assertEqual("alpha", vertical_0.display_name)
self.assertEqual("beta", vertical_1.display_name)
# Verify that the group_id_to_child mapping is correct.
self.assertEqual(2, len(split_test.group_id_to_child))
self.assertEqual(vertical_0.location, split_test.group_id_to_child['0'])
self.assertEqual(vertical_1.location, split_test.group_id_to_child['1'])
# Now change to second group configuration.
split_test = self._update_partition_id(1)
# Verify that child verticals have been set to match the groups
self.assertEqual(3, len(split_test.children))
vertical_0 = self.get_item_from_modulestore(split_test.children[0], verify_is_draft=True)
vertical_1 = self.get_item_from_modulestore(split_test.children[1], verify_is_draft=True)
vertical_2 = self.get_item_from_modulestore(split_test.children[2], verify_is_draft=True)
self.assertEqual("vertical", vertical_0.category)
self.assertEqual("vertical", vertical_1.category)
self.assertEqual("vertical", vertical_2.category)
self.assertEqual("Group 0", vertical_0.display_name)
self.assertEqual("Group 1", vertical_1.display_name)
self.assertEqual("Group 2", vertical_2.display_name)
# Verify that the group_id_to_child mapping is correct.
self.assertEqual(3, len(split_test.group_id_to_child))
self.assertEqual(vertical_0.location, split_test.group_id_to_child['0'])
self.assertEqual(vertical_1.location, split_test.group_id_to_child['1'])
self.assertEqual(vertical_2.location, split_test.group_id_to_child['2'])
Cheatsheet (for next line):
- We are in test_change_user_partition_id(), which is testing the behavior of changing the user_partition_id.
- The user_partition_id is changed to 1, which corresponds to the second group configuration.
- The test verifies that the child verticals are updated correctly.
- The group_id_to_child mapping is also verified to be correct.
- [Relevant lines: previous test cases, group configuration, split_test instance]
Next line will likely be: self.assertEqual(3, len(split_test.children));
|
|
Please complete the code given below.
using System;
using System.IO;
using System.Text;
using System.Collections;
/*
* $Id: TrueTypeFontUnicode.cs,v 1.7 2006/09/17 16:03:37 psoares33 Exp $
* $Name: $
*
* Copyright 2001, 2002 Paulo Soares
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
namespace iTextSharp.text.pdf {
/** Represents a True Type font with Unicode encoding. All the character
* in the font can be used directly by using the encoding Identity-H or
* Identity-V. This is the only way to represent some character sets such
* as Thai.
* @author Paulo Soares (psoares@consiste.pt)
*/
internal class TrueTypeFontUnicode : TrueTypeFont, IComparer {
/** <CODE>true</CODE> if the encoding is vertical.
*/
bool vertical = false;
/** Creates a new TrueType font addressed by Unicode characters. The font
* will always be embedded.
* @param ttFile the location of the font on file. The file must end in '.ttf'.
* The modifiers after the name are ignored.
* @param enc the encoding to be applied to this font
* @param emb true if the font is to be embedded in the PDF
* @param ttfAfm the font as a <CODE>byte</CODE> array
* @throws DocumentException the font is invalid
* @throws IOException the font file could not be read
*/
internal TrueTypeFontUnicode(string ttFile, string enc, bool emb, byte[] ttfAfm) {
string nameBase = GetBaseName(ttFile);
string ttcName = GetTTCName(nameBase);
if (nameBase.Length < ttFile.Length) {
style = ttFile.Substring(nameBase.Length);
}
encoding = enc;
embedded = emb;
fileName = ttcName;
ttcIndex = "";
if (ttcName.Length < nameBase.Length)
ttcIndex = nameBase.Substring(ttcName.Length + 1);
FontType = FONT_TYPE_TTUNI;
if ((fileName.ToLower().EndsWith(".ttf") || fileName.ToLower().EndsWith(".otf") || fileName.ToLower().EndsWith(".ttc")) && ((enc.Equals(IDENTITY_H) || enc.Equals(IDENTITY_V)) && emb)) {
Process(ttfAfm);
if (os_2.fsType == 2)
throw new DocumentException(fileName + style + " cannot be embedded due to licensing restrictions.");
// Sivan
if ((cmap31 == null && !fontSpecific) || (cmap10 == null && fontSpecific))
directTextToByte=true;
//throw new DocumentException(fileName + " " + style + " does not contain an usable cmap.");
if (fontSpecific) {
fontSpecific = false;
String tempEncoding = encoding;
encoding = "";
CreateEncoding();
encoding = tempEncoding;
fontSpecific = true;
}
}
else
throw new DocumentException(fileName + " " + style + " is not a TTF font file.");
vertical = enc.EndsWith("V");
}
/**
* Gets the width of a <CODE>string</CODE> in normalized 1000 units.
* @param text the <CODE>string</CODE> to get the witdth of
* @return the width in normalized 1000 units
*/
public override int GetWidth(string text) {
if (vertical)
return text.Length * 1000;
int total = 0;
if (fontSpecific) {
char[] cc = text.ToCharArray();
int len = cc.Length;
for (int k = 0; k < len; ++k) {
char c = cc[k];
if ((c & 0xff00) == 0 || (c & 0xff00) == 0xf000)
total += GetRawWidth(c & 0xff, null);
}
}
else {
int len = text.Length;
for (int k = 0; k < len; ++k)
total += GetRawWidth(text[k], encoding);
}
return total;
}
/** Creates a ToUnicode CMap to allow copy and paste from Acrobat.
* @param metrics metrics[0] contains the glyph index and metrics[2]
* contains the Unicode code
* @throws DocumentException on error
* @return the stream representing this CMap or <CODE>null</CODE>
*/
private PdfStream GetToUnicode(Object[] metrics) {
if (metrics.Length == 0)
return null;
StringBuilder buf = new StringBuilder(
"/CIDInit /ProcSet findresource begin\n" +
"12 dict begin\n" +
"begincmap\n" +
"/CIDSystemInfo\n" +
"<< /Registry (Adobe)\n" +
"/Ordering (UCS)\n" +
"/Supplement 0\n" +
">> def\n" +
"/CMapName /Adobe-Identity-UCS def\n" +
"/CMapType 2 def\n" +
"1 begincodespacerange\n" +
"<0000><FFFF>\n" +
"endcodespacerange\n");
int size = 0;
for (int k = 0; k < metrics.Length; ++k) {
if (size == 0) {
if (k != 0) {
buf.Append("endbfrange\n");
}
size = Math.Min(100, metrics.Length - k);
buf.Append(size).Append(" beginbfrange\n");
}
--size;
int[] metric = (int[])metrics[k];
string fromTo = ToHex(metric[0]);
buf.Append(fromTo).Append(fromTo).Append(ToHex(metric[2])).Append('\n');
}
buf.Append(
"endbfrange\n" +
"endcmap\n" +
"CMapName currentdict /CMap defineresource pop\n" +
"end end\n");
string s = buf.ToString();
PdfStream stream = new PdfStream(PdfEncodings.ConvertToBytes(s, null));
stream.FlateCompress();
return stream;
}
/** Gets an hex string in the format "<HHHH>".
* @param n the number
* @return the hex string
*/
internal static string ToHex(int n) {
string s = System.Convert.ToString(n, 16);
return "<0000".Substring(0, 5 - s.Length) + s + ">";
}
/** Generates the CIDFontTyte2 dictionary.
* @param fontDescriptor the indirect reference to the font descriptor
* @param subsetPrefix the subset prefix
* @param metrics the horizontal width metrics
* @return a stream
*/
private PdfDictionary GetCIDFontType2(PdfIndirectReference fontDescriptor, string subsetPrefix, Object[] metrics) {
PdfDictionary dic = new PdfDictionary(PdfName.FONT);
// sivan; cff
if (cff) {
dic.Put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE0);
dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName+"-"+encoding));
}
else {
dic.Put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE2);
dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
}
dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor);
if (!cff)
dic.Put(PdfName.CIDTOGIDMAP,PdfName.IDENTITY);
PdfDictionary cdic = new PdfDictionary();
cdic.Put(PdfName.REGISTRY, new PdfString("Adobe"));
cdic.Put(PdfName.ORDERING, new PdfString("Identity"));
cdic.Put(PdfName.SUPPLEMENT, new PdfNumber(0));
dic.Put(PdfName.CIDSYSTEMINFO, cdic);
if (!vertical) {
dic.Put(PdfName.DW, new PdfNumber(1000));
StringBuilder buf = new StringBuilder("[");
int lastNumber = -10;
bool firstTime = true;
for (int k = 0; k < metrics.Length; ++k) {
int[] metric = (int[])metrics[k];
if (metric[1] == 1000)
continue;
int m = metric[0];
if (m == lastNumber + 1) {
buf.Append(' ').Append(metric[1]);
}
else {
if (!firstTime) {
buf.Append(']');
}
firstTime = false;
buf.Append(m).Append('[').Append(metric[1]);
}
lastNumber = m;
}
if (buf.Length > 1) {
buf.Append("]]");
dic.Put(PdfName.W, new PdfLiteral(buf.ToString()));
}
}
return dic;
}
/** Generates the font dictionary.
* @param descendant the descendant dictionary
* @param subsetPrefix the subset prefix
* @param toUnicode the ToUnicode stream
* @return the stream
*/
private PdfDictionary GetFontBaseType(PdfIndirectReference descendant, string subsetPrefix, PdfIndirectReference toUnicode) {
PdfDictionary dic = new PdfDictionary(PdfName.FONT);
dic.Put(PdfName.SUBTYPE, PdfName.TYPE0);
// The PDF Reference manual advises to add -encoding to CID font names
if (cff)
dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName+"-"+encoding));
else
dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
dic.Put(PdfName.ENCODING, new PdfName(encoding));
dic.Put(PdfName.DESCENDANTFONTS, new PdfArray(descendant));
if (toUnicode != null)
dic.Put(PdfName.TOUNICODE, toUnicode);
return dic;
}
/** The method used to sort the metrics array.
* @param o1 the first element
* @param o2 the second element
* @return the comparisation
*/
public int Compare(Object o1, Object o2) {
int m1 = ((int[])o1)[0];
int m2 = ((int[])o2)[0];
if (m1 < m2)
return -1;
if (m1 == m2)
return 0;
return 1;
}
/** Outputs to the writer the font dictionaries and streams.
* @param writer the writer for this document
* @param ref the font indirect reference
* @param parms several parameters that depend on the font type
* @throws IOException on error
* @throws DocumentException error in generating the object
*/
internal override void WriteFont(PdfWriter writer, PdfIndirectReference piref, Object[] parms) {
Hashtable longTag = (Hashtable)parms[0];
AddRangeUni(longTag, true, subset);
ArrayList tmp = new ArrayList();
|
[
" foreach (object o in longTag.Values) {"
] | 1,490
|
lcc
|
csharp
| null |
caded4c1338faaf5978525a343ec76e66b5546a6a35088a6
| 32
|
Your task is code completion.
using System;
using System.IO;
using System.Text;
using System.Collections;
/*
* $Id: TrueTypeFontUnicode.cs,v 1.7 2006/09/17 16:03:37 psoares33 Exp $
* $Name: $
*
* Copyright 2001, 2002 Paulo Soares
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
namespace iTextSharp.text.pdf {
/** Represents a True Type font with Unicode encoding. All the character
* in the font can be used directly by using the encoding Identity-H or
* Identity-V. This is the only way to represent some character sets such
* as Thai.
* @author Paulo Soares (psoares@consiste.pt)
*/
internal class TrueTypeFontUnicode : TrueTypeFont, IComparer {
/** <CODE>true</CODE> if the encoding is vertical.
*/
bool vertical = false;
/** Creates a new TrueType font addressed by Unicode characters. The font
* will always be embedded.
* @param ttFile the location of the font on file. The file must end in '.ttf'.
* The modifiers after the name are ignored.
* @param enc the encoding to be applied to this font
* @param emb true if the font is to be embedded in the PDF
* @param ttfAfm the font as a <CODE>byte</CODE> array
* @throws DocumentException the font is invalid
* @throws IOException the font file could not be read
*/
internal TrueTypeFontUnicode(string ttFile, string enc, bool emb, byte[] ttfAfm) {
string nameBase = GetBaseName(ttFile);
string ttcName = GetTTCName(nameBase);
if (nameBase.Length < ttFile.Length) {
style = ttFile.Substring(nameBase.Length);
}
encoding = enc;
embedded = emb;
fileName = ttcName;
ttcIndex = "";
if (ttcName.Length < nameBase.Length)
ttcIndex = nameBase.Substring(ttcName.Length + 1);
FontType = FONT_TYPE_TTUNI;
if ((fileName.ToLower().EndsWith(".ttf") || fileName.ToLower().EndsWith(".otf") || fileName.ToLower().EndsWith(".ttc")) && ((enc.Equals(IDENTITY_H) || enc.Equals(IDENTITY_V)) && emb)) {
Process(ttfAfm);
if (os_2.fsType == 2)
throw new DocumentException(fileName + style + " cannot be embedded due to licensing restrictions.");
// Sivan
if ((cmap31 == null && !fontSpecific) || (cmap10 == null && fontSpecific))
directTextToByte=true;
//throw new DocumentException(fileName + " " + style + " does not contain an usable cmap.");
if (fontSpecific) {
fontSpecific = false;
String tempEncoding = encoding;
encoding = "";
CreateEncoding();
encoding = tempEncoding;
fontSpecific = true;
}
}
else
throw new DocumentException(fileName + " " + style + " is not a TTF font file.");
vertical = enc.EndsWith("V");
}
/**
* Gets the width of a <CODE>string</CODE> in normalized 1000 units.
* @param text the <CODE>string</CODE> to get the witdth of
* @return the width in normalized 1000 units
*/
public override int GetWidth(string text) {
if (vertical)
return text.Length * 1000;
int total = 0;
if (fontSpecific) {
char[] cc = text.ToCharArray();
int len = cc.Length;
for (int k = 0; k < len; ++k) {
char c = cc[k];
if ((c & 0xff00) == 0 || (c & 0xff00) == 0xf000)
total += GetRawWidth(c & 0xff, null);
}
}
else {
int len = text.Length;
for (int k = 0; k < len; ++k)
total += GetRawWidth(text[k], encoding);
}
return total;
}
/** Creates a ToUnicode CMap to allow copy and paste from Acrobat.
* @param metrics metrics[0] contains the glyph index and metrics[2]
* contains the Unicode code
* @throws DocumentException on error
* @return the stream representing this CMap or <CODE>null</CODE>
*/
private PdfStream GetToUnicode(Object[] metrics) {
if (metrics.Length == 0)
return null;
StringBuilder buf = new StringBuilder(
"/CIDInit /ProcSet findresource begin\n" +
"12 dict begin\n" +
"begincmap\n" +
"/CIDSystemInfo\n" +
"<< /Registry (Adobe)\n" +
"/Ordering (UCS)\n" +
"/Supplement 0\n" +
">> def\n" +
"/CMapName /Adobe-Identity-UCS def\n" +
"/CMapType 2 def\n" +
"1 begincodespacerange\n" +
"<0000><FFFF>\n" +
"endcodespacerange\n");
int size = 0;
for (int k = 0; k < metrics.Length; ++k) {
if (size == 0) {
if (k != 0) {
buf.Append("endbfrange\n");
}
size = Math.Min(100, metrics.Length - k);
buf.Append(size).Append(" beginbfrange\n");
}
--size;
int[] metric = (int[])metrics[k];
string fromTo = ToHex(metric[0]);
buf.Append(fromTo).Append(fromTo).Append(ToHex(metric[2])).Append('\n');
}
buf.Append(
"endbfrange\n" +
"endcmap\n" +
"CMapName currentdict /CMap defineresource pop\n" +
"end end\n");
string s = buf.ToString();
PdfStream stream = new PdfStream(PdfEncodings.ConvertToBytes(s, null));
stream.FlateCompress();
return stream;
}
/** Gets an hex string in the format "<HHHH>".
* @param n the number
* @return the hex string
*/
internal static string ToHex(int n) {
string s = System.Convert.ToString(n, 16);
return "<0000".Substring(0, 5 - s.Length) + s + ">";
}
/** Generates the CIDFontTyte2 dictionary.
* @param fontDescriptor the indirect reference to the font descriptor
* @param subsetPrefix the subset prefix
* @param metrics the horizontal width metrics
* @return a stream
*/
private PdfDictionary GetCIDFontType2(PdfIndirectReference fontDescriptor, string subsetPrefix, Object[] metrics) {
PdfDictionary dic = new PdfDictionary(PdfName.FONT);
// sivan; cff
if (cff) {
dic.Put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE0);
dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName+"-"+encoding));
}
else {
dic.Put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE2);
dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
}
dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor);
if (!cff)
dic.Put(PdfName.CIDTOGIDMAP,PdfName.IDENTITY);
PdfDictionary cdic = new PdfDictionary();
cdic.Put(PdfName.REGISTRY, new PdfString("Adobe"));
cdic.Put(PdfName.ORDERING, new PdfString("Identity"));
cdic.Put(PdfName.SUPPLEMENT, new PdfNumber(0));
dic.Put(PdfName.CIDSYSTEMINFO, cdic);
if (!vertical) {
dic.Put(PdfName.DW, new PdfNumber(1000));
StringBuilder buf = new StringBuilder("[");
int lastNumber = -10;
bool firstTime = true;
for (int k = 0; k < metrics.Length; ++k) {
int[] metric = (int[])metrics[k];
if (metric[1] == 1000)
continue;
int m = metric[0];
if (m == lastNumber + 1) {
buf.Append(' ').Append(metric[1]);
}
else {
if (!firstTime) {
buf.Append(']');
}
firstTime = false;
buf.Append(m).Append('[').Append(metric[1]);
}
lastNumber = m;
}
if (buf.Length > 1) {
buf.Append("]]");
dic.Put(PdfName.W, new PdfLiteral(buf.ToString()));
}
}
return dic;
}
/** Generates the font dictionary.
* @param descendant the descendant dictionary
* @param subsetPrefix the subset prefix
* @param toUnicode the ToUnicode stream
* @return the stream
*/
private PdfDictionary GetFontBaseType(PdfIndirectReference descendant, string subsetPrefix, PdfIndirectReference toUnicode) {
PdfDictionary dic = new PdfDictionary(PdfName.FONT);
dic.Put(PdfName.SUBTYPE, PdfName.TYPE0);
// The PDF Reference manual advises to add -encoding to CID font names
if (cff)
dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName+"-"+encoding));
else
dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
dic.Put(PdfName.ENCODING, new PdfName(encoding));
dic.Put(PdfName.DESCENDANTFONTS, new PdfArray(descendant));
if (toUnicode != null)
dic.Put(PdfName.TOUNICODE, toUnicode);
return dic;
}
/** The method used to sort the metrics array.
* @param o1 the first element
* @param o2 the second element
* @return the comparisation
*/
public int Compare(Object o1, Object o2) {
int m1 = ((int[])o1)[0];
int m2 = ((int[])o2)[0];
if (m1 < m2)
return -1;
if (m1 == m2)
return 0;
return 1;
}
/** Outputs to the writer the font dictionaries and streams.
* @param writer the writer for this document
* @param ref the font indirect reference
* @param parms several parameters that depend on the font type
* @throws IOException on error
* @throws DocumentException error in generating the object
*/
internal override void WriteFont(PdfWriter writer, PdfIndirectReference piref, Object[] parms) {
Hashtable longTag = (Hashtable)parms[0];
AddRangeUni(longTag, true, subset);
ArrayList tmp = new ArrayList();
|
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]
internal override void WriteFont(PdfWriter writer, PdfIndirectReference piref, Object[] parms) {
Hashtable longTag = (Hashtable)parms[0];
AddRangeUni(longTag, true, subset);
ArrayList tmp = new ArrayList();
Relevant lines and variables:
- We are in the WriteFont() method, which is responsible for outputting font dictionaries and streams.
- The method takes three parameters: writer, piref, and parms.
- The parms array contains several parameters that depend on the font type.
- The longTag is a Hashtable that is obtained from the first element of the parms array.
- The subset is a variable that is used in the AddRangeUni() method.
Based on the context and the relevant lines and variables, the next line of code is likely to be related to processing the font metrics and generating the font dictionary. The WriteFont() method seems to be generating the font dictionaries and streams for the TrueType font.
Possible next line:
- The code will likely involve generating the font dictionary using the GetFontBaseType() method, which takes the descendant dictionary, subset prefix, and ToUnicode stream as parameters.
- The descendant dictionary is likely the piref (PdfIndirectReference) passed to the WriteFont() method.
- The subset prefix is likely the subset variable used in the AddRangeUni() method.
- The ToUnicode stream is likely the result of the GetToUnicode() method, which takes the font metrics as a parameter.
However, the exact next line of code depends on the specific implementation details and the requirements of the WriteFont() method.
|
|
Please complete the code given below.
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: CellChangeJobs.java
*
* Copyright (c) 2006 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user;
import com.sun.electric.database.IdMapper;
import com.sun.electric.database.ImmutableArcInst;
import com.sun.electric.database.geometry.EGraphics;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.GenMath;
import com.sun.electric.database.geometry.Orientation;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.id.CellId;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.text.Name;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Geometric;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.UserInterface;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.technologies.Artwork;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.user.ui.EditWindow;
import com.sun.electric.tool.user.ui.WindowContent;
import com.sun.electric.tool.user.ui.WindowFrame;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Class for Jobs that make changes to the cells.
*/
public class CellChangeJobs
{
// constructor, never used
private CellChangeJobs() {}
/****************************** DELETE A CELL ******************************/
/**
* Class to delete a cell in a new thread.
*/
public static class DeleteCell extends Job
{
Cell cell;
public DeleteCell(Cell cell)
{
super("Delete " + cell, User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
startJob();
}
public boolean doIt() throws JobException
{
// check cell usage once more
if (cell.isInUse("delete", false, true)) return false;
cell.kill();
return true;
}
}
/**
* This class implement the command to delete a list of cells.
*/
public static class DeleteManyCells extends Job
{
private List<Cell> cellsToDelete;
public DeleteManyCells(List<Cell> cellsToDelete)
{
super("Delete Multiple Cells", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cellsToDelete = cellsToDelete;
startJob();
}
public boolean doIt() throws JobException
{
// iteratively delete, allowing cells in use to be deferred
boolean didDelete = true;
while (didDelete)
{
didDelete = false;
for (int i=0; i<cellsToDelete.size(); i++)
{
Cell cell = cellsToDelete.get(i);
// if the cell is in use, defer
if (cell.isInUse(null, true, true)) continue;
// cell not in use: remove it from the list and delete it
cellsToDelete.remove(i);
i--;
System.out.println("Deleting " + cell);
cell.kill();
didDelete = true;
}
}
// warn about remaining cells that were in use
for(Cell cell : cellsToDelete)
cell.isInUse("delete", false, true);
return true;
}
public void terminateOK()
{
System.out.println("Deleted " + cellsToDelete.size() + " cells");
EditWindow.repaintAll();
}
}
/****************************** RENAME CELLS ******************************/
/**
* Class to rename a cell in a new thread.
*/
public static class RenameCell extends Job
{
private Cell cell;
private String newName;
private String newGroupCell;
private IdMapper idMapper;
public RenameCell(Cell cell, String newName, String newGroupCell)
{
super("Rename " + cell, User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.newName = newName;
this.newGroupCell = newGroupCell;
startJob();
}
public boolean doIt() throws JobException
{
idMapper = cell.rename(newName, newGroupCell);
fieldVariableChanged("idMapper");
return true;
}
public void terminateOK()
{
User.fixStaleCellReferences(idMapper);
}
}
/**
* Class to rename a cell in a new thread.
*/
public static class DeleteCellGroup extends Job
{
List<Cell> cells;
public DeleteCellGroup(Cell.CellGroup group)
{
super("Delete Cell Group", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
cells = new ArrayList<Cell>();
for(Iterator<Cell> it = group.getCells(); it.hasNext(); )
{
cells.add(it.next());
}
startJob();
}
public boolean doIt() throws JobException
{
for(Cell cell : cells)
{
// Doesn't check cells in the same group
// check cell usage once more
if (cell.isInUse("delete", false, false))
return false;
}
// Now real delete
for(Cell cell : cells)
{
cell.kill();
}
return true;
}
}
/**
* Class to rename a cell in a new thread.
*/
public static class RenameCellGroup extends Job
{
Cell cellInGroup;
String newName;
public RenameCellGroup(Cell cellInGroup, String newName)
{
super("Rename Cell Group", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cellInGroup = cellInGroup;
this.newName = newName;
startJob();
}
public boolean doIt() throws JobException
{
// see if all cells in the group have the same name
boolean allSameName = true;
String lastName = null;
for(Iterator<Cell> it = cellInGroup.getCellGroup().getCells(); it.hasNext(); )
{
String cellName = it.next().getName();
if (lastName != null && !lastName.equals(cellName))
{
allSameName = false;
break;
}
lastName = cellName;
}
List<Cell> cells = new ArrayList<Cell>();
for(Iterator<Cell> it = cellInGroup.getCellGroup().getCells(); it.hasNext(); )
cells.add(it.next());
String newGroupCell = null;
for(Cell cell : cells)
{
if (allSameName)
{
cell.rename(newName, newName);
} else
{
if (newGroupCell == null)
{
System.out.println("Renaming is not possible because cells in group don't have same root name.");
System.out.println("'" + newName + "' was added as prefix.");
newGroupCell = newName + cell.getName();
}
cell.rename(newName+cell.getName(), newGroupCell);
}
}
return true;
}
}
/****************************** SHOW CELLS GRAPHICALLY ******************************/
/**
* This class implement the command to make a graph of the cells.
*/
public static class GraphCells extends Job
{
private static final double TEXTHEIGHT = 2;
private Cell top;
private Cell graphCell;
private static class GraphNode
{
String name;
int depth;
int clock;
double x, y;
double yoff;
NodeInst pin;
NodeInst topPin;
NodeInst botPin;
GraphNode main;
}
public GraphCells(Cell top)
{
super("Graph Cells", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.top = top;
startJob();
}
public boolean doIt() throws JobException
{
// create the graph cell
graphCell = Cell.newInstance(Library.getCurrent(), "CellStructure");
fieldVariableChanged("graphCell");
if (graphCell == null) return false;
if (graphCell.getNumVersions() > 1)
System.out.println("Creating new version of cell: " + graphCell.getName()); else
System.out.println("Creating cell: " + graphCell.getName());
// create GraphNodes for every cell and initialize the depth to -1
Map<Cell,GraphNode> graphNodes = new HashMap<Cell,GraphNode>();
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
{
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); )
{
Cell cell = cIt.next();
GraphNode cgn = new GraphNode();
cgn.name = cell.describe(false);
cgn.depth = -1;
graphNodes.put(cell, cgn);
}
}
// find all top-level cells
int maxDepth = 0;
if (top != null)
{
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else
{
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); )
{
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0)
{
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
double xScale = 2.0 / 3.0;
double yScale = 20;
double yOffset = TEXTHEIGHT * 1.25;
double maxWidth = 0;
// now place all cells at their proper depth
boolean more = true;
while (more)
{
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
{
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); )
{
Cell cell = cIt.next();
|
[
"\t\t\t\t\t\tGraphNode cgn = graphNodes.get(cell);"
] | 1,113
|
lcc
|
java
| null |
341005dfebe6821d4201177ffce38b1e3048f5a0d9c30463
| 33
|
Your task is code completion.
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: CellChangeJobs.java
*
* Copyright (c) 2006 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user;
import com.sun.electric.database.IdMapper;
import com.sun.electric.database.ImmutableArcInst;
import com.sun.electric.database.geometry.EGraphics;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.GenMath;
import com.sun.electric.database.geometry.Orientation;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.id.CellId;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.text.Name;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Geometric;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.UserInterface;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.technologies.Artwork;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.user.ui.EditWindow;
import com.sun.electric.tool.user.ui.WindowContent;
import com.sun.electric.tool.user.ui.WindowFrame;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Class for Jobs that make changes to the cells.
*/
public class CellChangeJobs
{
// constructor, never used
private CellChangeJobs() {}
/****************************** DELETE A CELL ******************************/
/**
* Class to delete a cell in a new thread.
*/
public static class DeleteCell extends Job
{
Cell cell;
public DeleteCell(Cell cell)
{
super("Delete " + cell, User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
startJob();
}
public boolean doIt() throws JobException
{
// check cell usage once more
if (cell.isInUse("delete", false, true)) return false;
cell.kill();
return true;
}
}
/**
* This class implement the command to delete a list of cells.
*/
public static class DeleteManyCells extends Job
{
private List<Cell> cellsToDelete;
public DeleteManyCells(List<Cell> cellsToDelete)
{
super("Delete Multiple Cells", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cellsToDelete = cellsToDelete;
startJob();
}
public boolean doIt() throws JobException
{
// iteratively delete, allowing cells in use to be deferred
boolean didDelete = true;
while (didDelete)
{
didDelete = false;
for (int i=0; i<cellsToDelete.size(); i++)
{
Cell cell = cellsToDelete.get(i);
// if the cell is in use, defer
if (cell.isInUse(null, true, true)) continue;
// cell not in use: remove it from the list and delete it
cellsToDelete.remove(i);
i--;
System.out.println("Deleting " + cell);
cell.kill();
didDelete = true;
}
}
// warn about remaining cells that were in use
for(Cell cell : cellsToDelete)
cell.isInUse("delete", false, true);
return true;
}
public void terminateOK()
{
System.out.println("Deleted " + cellsToDelete.size() + " cells");
EditWindow.repaintAll();
}
}
/****************************** RENAME CELLS ******************************/
/**
* Class to rename a cell in a new thread.
*/
public static class RenameCell extends Job
{
private Cell cell;
private String newName;
private String newGroupCell;
private IdMapper idMapper;
public RenameCell(Cell cell, String newName, String newGroupCell)
{
super("Rename " + cell, User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.newName = newName;
this.newGroupCell = newGroupCell;
startJob();
}
public boolean doIt() throws JobException
{
idMapper = cell.rename(newName, newGroupCell);
fieldVariableChanged("idMapper");
return true;
}
public void terminateOK()
{
User.fixStaleCellReferences(idMapper);
}
}
/**
* Class to rename a cell in a new thread.
*/
public static class DeleteCellGroup extends Job
{
List<Cell> cells;
public DeleteCellGroup(Cell.CellGroup group)
{
super("Delete Cell Group", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
cells = new ArrayList<Cell>();
for(Iterator<Cell> it = group.getCells(); it.hasNext(); )
{
cells.add(it.next());
}
startJob();
}
public boolean doIt() throws JobException
{
for(Cell cell : cells)
{
// Doesn't check cells in the same group
// check cell usage once more
if (cell.isInUse("delete", false, false))
return false;
}
// Now real delete
for(Cell cell : cells)
{
cell.kill();
}
return true;
}
}
/**
* Class to rename a cell in a new thread.
*/
public static class RenameCellGroup extends Job
{
Cell cellInGroup;
String newName;
public RenameCellGroup(Cell cellInGroup, String newName)
{
super("Rename Cell Group", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cellInGroup = cellInGroup;
this.newName = newName;
startJob();
}
public boolean doIt() throws JobException
{
// see if all cells in the group have the same name
boolean allSameName = true;
String lastName = null;
for(Iterator<Cell> it = cellInGroup.getCellGroup().getCells(); it.hasNext(); )
{
String cellName = it.next().getName();
if (lastName != null && !lastName.equals(cellName))
{
allSameName = false;
break;
}
lastName = cellName;
}
List<Cell> cells = new ArrayList<Cell>();
for(Iterator<Cell> it = cellInGroup.getCellGroup().getCells(); it.hasNext(); )
cells.add(it.next());
String newGroupCell = null;
for(Cell cell : cells)
{
if (allSameName)
{
cell.rename(newName, newName);
} else
{
if (newGroupCell == null)
{
System.out.println("Renaming is not possible because cells in group don't have same root name.");
System.out.println("'" + newName + "' was added as prefix.");
newGroupCell = newName + cell.getName();
}
cell.rename(newName+cell.getName(), newGroupCell);
}
}
return true;
}
}
/****************************** SHOW CELLS GRAPHICALLY ******************************/
/**
* This class implement the command to make a graph of the cells.
*/
public static class GraphCells extends Job
{
private static final double TEXTHEIGHT = 2;
private Cell top;
private Cell graphCell;
private static class GraphNode
{
String name;
int depth;
int clock;
double x, y;
double yoff;
NodeInst pin;
NodeInst topPin;
NodeInst botPin;
GraphNode main;
}
public GraphCells(Cell top)
{
super("Graph Cells", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.top = top;
startJob();
}
public boolean doIt() throws JobException
{
// create the graph cell
graphCell = Cell.newInstance(Library.getCurrent(), "CellStructure");
fieldVariableChanged("graphCell");
if (graphCell == null) return false;
if (graphCell.getNumVersions() > 1)
System.out.println("Creating new version of cell: " + graphCell.getName()); else
System.out.println("Creating cell: " + graphCell.getName());
// create GraphNodes for every cell and initialize the depth to -1
Map<Cell,GraphNode> graphNodes = new HashMap<Cell,GraphNode>();
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
{
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); )
{
Cell cell = cIt.next();
GraphNode cgn = new GraphNode();
cgn.name = cell.describe(false);
cgn.depth = -1;
graphNodes.put(cell, cgn);
}
}
// find all top-level cells
int maxDepth = 0;
if (top != null)
{
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else
{
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); )
{
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0)
{
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
double xScale = 2.0 / 3.0;
double yScale = 20;
double yOffset = TEXTHEIGHT * 1.25;
double maxWidth = 0;
// now place all cells at their proper depth
boolean more = true;
while (more)
{
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); )
{
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); )
{
Cell cell = cIt.next();
|
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 the brevity]
public class CellChangeJobs {
// ...
public static class GraphCells extends Job {
// ...
public boolean doIt() throws JobException {
// ...
Map<Cell, GraphNode> graphNodes = new HashMap<Cell, GraphNode>();
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
GraphNode cgn = new GraphNode();
cgn.name = cell.describe(false);
cgn.depth = -1;
graphNodes.put(cell, cgn);
}
}
// ...
double xScale = 2.0 / 3.0;
double yScale = 20;
double yOffset = TEXTHEIGHT * 1.25;
double maxWidth = 0;
// now place all cells at their proper depth
boolean more = true;
while (more) {
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
// ...
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
// find all top-level cells
if (top != null) {
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else {
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0) {
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
// ...
}
// now place all cells at their proper depth
more = true;
while (more) {
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
// ...
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
// find all top-level cells
if (top != null) {
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else {
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0) {
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
// ...
}
// now place all cells at their proper depth
more = true;
while (more) {
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
// ...
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
// find all top-level cells
if (top != null) {
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else {
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0) {
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
// ...
}
// now place all cells at their proper depth
more = true;
while (more) {
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
// ...
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
// find all top-level cells
if (top != null) {
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else {
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0) {
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
// ...
}
// now place all cells at their proper depth
more = true;
while (more) {
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
// ...
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
// find all top-level cells
if (top != null) {
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else {
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0) {
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
// ...
}
// now place all cells at their proper depth
more = true;
while (more) {
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
// ...
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
// find all top-level cells
if (top != null) {
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else {
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0) {
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
// ...
}
// now place all cells at their proper depth
more = true;
while (more) {
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
// ...
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
// find all top-level cells
if (top != null) {
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else {
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0) {
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
// ...
}
// now place all cells at their proper depth
more = true;
while (more) {
more = false;
for(Iterator<Library> it = Library.getLibraries(); it.hasNext(); ) {
Library lib = it.next();
if (lib.isHidden()) continue;
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
// ...
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
// find all top-level cells
if (top != null) {
GraphNode cgn = graphNodes.get(top);
cgn.depth = 0;
} else {
for(Iterator<Cell> cIt = Library.getCurrent().getCells(); cIt.hasNext(); ) {
Cell cell = cIt.next();
if (cell.getNumUsagesIn() == 0) {
GraphNode cgn = graphNodes.get(cell);
cgn.depth = 0;
}
}
}
// ...
}
// now place all cells at their proper depth
more =
|
|
Please complete the code given below.
package org.thoughtcrime.securesms.components.emoji;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.util.SparseArray;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.BitmapDecodingException;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.FutureTaskListener;
import org.thoughtcrime.securesms.util.ListenableFutureTask;
import org.thoughtcrime.securesms.util.Util;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmojiProvider {
private static final String TAG = EmojiProvider.class.getSimpleName();
private static volatile EmojiProvider instance = null;
private static final Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
private final SparseArray<DrawInfo> offsets = new SparseArray<>();
@SuppressWarnings("MalformedRegex")
// 0x20a0-0x32ff 0x1f00-0x1fff 0xfe4e5-0xfe4ee
// |==== misc ====||======== emoticons ========||========= flags ==========|
private static final Pattern EMOJI_RANGE = Pattern.compile("[\\u20a0-\\u32ff\\ud83c\\udc00-\\ud83d\\udeff\\udbb9\\udce5-\\udbb9\\udcee]");
public static final int EMOJI_RAW_HEIGHT = 64;
public static final int EMOJI_RAW_WIDTH = 64;
public static final int EMOJI_VERT_PAD = 0;
public static final int EMOJI_PER_ROW = 32;
private final Context context;
private final float decodeScale;
private final float verticalPad;
public static EmojiProvider getInstance(Context context) {
if (instance == null) {
synchronized (EmojiProvider.class) {
if (instance == null) {
instance = new EmojiProvider(context);
}
}
}
return instance;
}
private EmojiProvider(Context context) {
this.context = context.getApplicationContext();
this.decodeScale = Math.min(1f, context.getResources().getDimension(R.dimen.emoji_drawer_size) / EMOJI_RAW_HEIGHT);
this.verticalPad = EMOJI_VERT_PAD * this.decodeScale;
for (EmojiPageModel page : EmojiPages.PAGES) {
if (page.hasSpriteMap()) {
final EmojiPageBitmap pageBitmap = new EmojiPageBitmap(page);
for (int i=0; i < page.getEmoji().length; i++) {
offsets.put(Character.codePointAt(page.getEmoji()[i], 0), new DrawInfo(pageBitmap, i));
}
}
}
}
public Spannable emojify(CharSequence text, TextView tv) {
Matcher matches = EMOJI_RANGE.matcher(text);
SpannableStringBuilder builder = new SpannableStringBuilder(text);
while (matches.find()) {
int codePoint = matches.group().codePointAt(0);
Drawable drawable = getEmojiDrawable(codePoint);
if (drawable != null) {
builder.setSpan(new EmojiSpan(drawable, tv), matches.start(), matches.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return builder;
}
public Drawable getEmojiDrawable(int emojiCode) {
return getEmojiDrawable(offsets.get(emojiCode));
}
private Drawable getEmojiDrawable(DrawInfo drawInfo) {
if (drawInfo == null) {
return null;
}
final EmojiDrawable drawable = new EmojiDrawable(drawInfo, decodeScale);
drawInfo.page.get().addListener(new FutureTaskListener<Bitmap>() {
@Override public void onSuccess(final Bitmap result) {
Util.runOnMain(new Runnable() {
@Override public void run() {
drawable.setBitmap(result);
}
});
}
@Override public void onFailure(Throwable error) {
Log.w(TAG, error);
}
});
return drawable;
}
public class EmojiDrawable extends Drawable {
private final DrawInfo info;
private Bitmap bmp;
private float intrinsicWidth;
private float intrinsicHeight;
@Override public int getIntrinsicWidth() {
return (int)intrinsicWidth;
}
@Override public int getIntrinsicHeight() {
return (int)intrinsicHeight;
}
public EmojiDrawable(DrawInfo info, float decodeScale) {
this.info = info;
this.intrinsicWidth = EMOJI_RAW_WIDTH * decodeScale;
this.intrinsicHeight = EMOJI_RAW_HEIGHT * decodeScale;
}
@Override
public void draw(Canvas canvas) {
if (bmp == null) {
return;
}
final int row = info.index / EMOJI_PER_ROW;
final int row_index = info.index % EMOJI_PER_ROW;
canvas.drawBitmap(bmp,
new Rect((int)(row_index * intrinsicWidth),
(int)(row * intrinsicHeight + row * verticalPad),
(int)((row_index + 1) * intrinsicWidth),
(int)((row + 1) * intrinsicHeight + row * verticalPad)),
getBounds(),
paint);
}
@TargetApi(VERSION_CODES.HONEYCOMB_MR1)
public void setBitmap(Bitmap bitmap) {
Util.assertMainThread();
if (VERSION.SDK_INT < VERSION_CODES.HONEYCOMB_MR1 || bmp == null || !bmp.sameAs(bitmap)) {
bmp = bitmap;
invalidateSelf();
}
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) { }
@Override
public void setColorFilter(ColorFilter cf) { }
}
class DrawInfo {
EmojiPageBitmap page;
int index;
public DrawInfo(final EmojiPageBitmap page, final int index) {
this.page = page;
this.index = index;
}
@Override
public String toString() {
return "DrawInfo{" +
"page=" + page +
", index=" + index +
'}';
}
}
private class EmojiPageBitmap {
private EmojiPageModel model;
private SoftReference<Bitmap> bitmapReference;
private ListenableFutureTask<Bitmap> task;
public EmojiPageBitmap(EmojiPageModel model) {
this.model = model;
}
private ListenableFutureTask<Bitmap> get() {
Util.assertMainThread();
if (bitmapReference != null && bitmapReference.get() != null) {
return new ListenableFutureTask<>(bitmapReference.get());
} else if (task != null) {
return task;
} else {
Callable<Bitmap> callable = new Callable<Bitmap>() {
@Override public Bitmap call() throws Exception {
try {
Log.w(TAG, "loading page " + model.getSprite());
return loadPage();
} catch (IOException ioe) {
Log.w(TAG, ioe);
}
return null;
}
};
|
[
" task = new ListenableFutureTask<>(callable);"
] | 629
|
lcc
|
java
| null |
32d36e0536e57f991a066ab60778b32884747e7689f3c816
| 34
|
Your task is code completion.
package org.thoughtcrime.securesms.components.emoji;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.util.SparseArray;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.BitmapDecodingException;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.FutureTaskListener;
import org.thoughtcrime.securesms.util.ListenableFutureTask;
import org.thoughtcrime.securesms.util.Util;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmojiProvider {
private static final String TAG = EmojiProvider.class.getSimpleName();
private static volatile EmojiProvider instance = null;
private static final Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
private final SparseArray<DrawInfo> offsets = new SparseArray<>();
@SuppressWarnings("MalformedRegex")
// 0x20a0-0x32ff 0x1f00-0x1fff 0xfe4e5-0xfe4ee
// |==== misc ====||======== emoticons ========||========= flags ==========|
private static final Pattern EMOJI_RANGE = Pattern.compile("[\\u20a0-\\u32ff\\ud83c\\udc00-\\ud83d\\udeff\\udbb9\\udce5-\\udbb9\\udcee]");
public static final int EMOJI_RAW_HEIGHT = 64;
public static final int EMOJI_RAW_WIDTH = 64;
public static final int EMOJI_VERT_PAD = 0;
public static final int EMOJI_PER_ROW = 32;
private final Context context;
private final float decodeScale;
private final float verticalPad;
public static EmojiProvider getInstance(Context context) {
if (instance == null) {
synchronized (EmojiProvider.class) {
if (instance == null) {
instance = new EmojiProvider(context);
}
}
}
return instance;
}
private EmojiProvider(Context context) {
this.context = context.getApplicationContext();
this.decodeScale = Math.min(1f, context.getResources().getDimension(R.dimen.emoji_drawer_size) / EMOJI_RAW_HEIGHT);
this.verticalPad = EMOJI_VERT_PAD * this.decodeScale;
for (EmojiPageModel page : EmojiPages.PAGES) {
if (page.hasSpriteMap()) {
final EmojiPageBitmap pageBitmap = new EmojiPageBitmap(page);
for (int i=0; i < page.getEmoji().length; i++) {
offsets.put(Character.codePointAt(page.getEmoji()[i], 0), new DrawInfo(pageBitmap, i));
}
}
}
}
public Spannable emojify(CharSequence text, TextView tv) {
Matcher matches = EMOJI_RANGE.matcher(text);
SpannableStringBuilder builder = new SpannableStringBuilder(text);
while (matches.find()) {
int codePoint = matches.group().codePointAt(0);
Drawable drawable = getEmojiDrawable(codePoint);
if (drawable != null) {
builder.setSpan(new EmojiSpan(drawable, tv), matches.start(), matches.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return builder;
}
public Drawable getEmojiDrawable(int emojiCode) {
return getEmojiDrawable(offsets.get(emojiCode));
}
private Drawable getEmojiDrawable(DrawInfo drawInfo) {
if (drawInfo == null) {
return null;
}
final EmojiDrawable drawable = new EmojiDrawable(drawInfo, decodeScale);
drawInfo.page.get().addListener(new FutureTaskListener<Bitmap>() {
@Override public void onSuccess(final Bitmap result) {
Util.runOnMain(new Runnable() {
@Override public void run() {
drawable.setBitmap(result);
}
});
}
@Override public void onFailure(Throwable error) {
Log.w(TAG, error);
}
});
return drawable;
}
public class EmojiDrawable extends Drawable {
private final DrawInfo info;
private Bitmap bmp;
private float intrinsicWidth;
private float intrinsicHeight;
@Override public int getIntrinsicWidth() {
return (int)intrinsicWidth;
}
@Override public int getIntrinsicHeight() {
return (int)intrinsicHeight;
}
public EmojiDrawable(DrawInfo info, float decodeScale) {
this.info = info;
this.intrinsicWidth = EMOJI_RAW_WIDTH * decodeScale;
this.intrinsicHeight = EMOJI_RAW_HEIGHT * decodeScale;
}
@Override
public void draw(Canvas canvas) {
if (bmp == null) {
return;
}
final int row = info.index / EMOJI_PER_ROW;
final int row_index = info.index % EMOJI_PER_ROW;
canvas.drawBitmap(bmp,
new Rect((int)(row_index * intrinsicWidth),
(int)(row * intrinsicHeight + row * verticalPad),
(int)((row_index + 1) * intrinsicWidth),
(int)((row + 1) * intrinsicHeight + row * verticalPad)),
getBounds(),
paint);
}
@TargetApi(VERSION_CODES.HONEYCOMB_MR1)
public void setBitmap(Bitmap bitmap) {
Util.assertMainThread();
if (VERSION.SDK_INT < VERSION_CODES.HONEYCOMB_MR1 || bmp == null || !bmp.sameAs(bitmap)) {
bmp = bitmap;
invalidateSelf();
}
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) { }
@Override
public void setColorFilter(ColorFilter cf) { }
}
class DrawInfo {
EmojiPageBitmap page;
int index;
public DrawInfo(final EmojiPageBitmap page, final int index) {
this.page = page;
this.index = index;
}
@Override
public String toString() {
return "DrawInfo{" +
"page=" + page +
", index=" + index +
'}';
}
}
private class EmojiPageBitmap {
private EmojiPageModel model;
private SoftReference<Bitmap> bitmapReference;
private ListenableFutureTask<Bitmap> task;
public EmojiPageBitmap(EmojiPageModel model) {
this.model = model;
}
private ListenableFutureTask<Bitmap> get() {
Util.assertMainThread();
if (bitmapReference != null && bitmapReference.get() != null) {
return new ListenableFutureTask<>(bitmapReference.get());
} else if (task != null) {
return task;
} else {
Callable<Bitmap> callable = new Callable<Bitmap>() {
@Override public Bitmap call() throws Exception {
try {
Log.w(TAG, "loading page " + model.getSprite());
return loadPage();
} catch (IOException ioe) {
Log.w(TAG, ioe);
}
return null;
}
};
|
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]
public class EmojiProvider {
// ...
private class EmojiPageBitmap {
// ...
private ListenableFutureTask<Bitmap> task;
public EmojiPageBitmap(EmojiPageModel model) {
this.model = model;
}
private ListenableFutureTask<Bitmap> get() {
Util.assertMainThread();
if (bitmapReference != null && bitmapReference.get() != null) {
return new ListenableFutureTask<>(bitmapReference.get());
} else if (task != null) {
return task;
} else {
Callable<Bitmap> callable = new Callable<Bitmap>() {
@Override public Bitmap call() throws Exception {
try {
Log.w(TAG, "loading page " + model.getSprite());
return loadPage();
} catch (IOException ioe) {
Log.w(TAG, ioe);
}
return null;
}
};
// ...
Cheatsheet (for next line):
- We are in the Callable<Bitmap> call() method, which should return a Bitmap object.
- The method loadPage() is called within this method, but its implementation is not shown.
- The method loadPage() is expected to return a Bitmap object.
- If an IOException occurs, the method returns null.
- The method is called within a try-catch block, which catches IOException.
- [Relevant lines: Callable<Bitmap> declaration, loadPage() call, return statement]
Next line will likely be: return loadPage();
|
|
Please complete the code given below.
/***************************************************************************
* Copyright 2006-2014 by Christian Ihle *
* contact@kouchat.net *
* *
* This file is part of KouChat. *
* *
* KouChat is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* KouChat is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with KouChat. *
* If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
package net.usikkert.kouchat.ui.swing;
import java.awt.AWTKeyStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import net.usikkert.kouchat.Constants;
import net.usikkert.kouchat.autocomplete.AutoCompleter;
import net.usikkert.kouchat.misc.CommandHistory;
import net.usikkert.kouchat.misc.ErrorHandler;
import net.usikkert.kouchat.settings.Settings;
import net.usikkert.kouchat.ui.ChatWindow;
import net.usikkert.kouchat.ui.swing.messages.SwingMessages;
import net.usikkert.kouchat.util.Validate;
/**
* This is the panel containing the main chat area, the input field,
* and the {@link SidePanel} on the right side.
* <br><br>
* The chat area has url recognition, and a right click menu. The input
* field has tab-completion, command history, and a right click menu.
*
* @author Christian Ihle
*/
public class MainPanel extends JPanel implements ActionListener, CaretListener, ChatWindow, KeyListener {
private static final Logger LOG = Logger.getLogger(MainPanel.class.getName());
private final JScrollPane chatSP;
private final JTextPane chatTP;
private final MutableAttributeSet chatAttr;
private final StyledDocument chatDoc;
private final JTextField msgTF;
private final CommandHistory cmdHistory;
private AutoCompleter autoCompleter;
private Mediator mediator;
/**
* Constructor. Creates the panel.
*
* @param sideP The panel on the right, containing the user list and the buttons.
* @param imageLoader The image loader.
* @param settings The settings to use.
* @param swingMessages The swing messages to use in copy/paste popups.
* @param errorHandler The error handler to use.
*/
public MainPanel(final SidePanel sideP, final ImageLoader imageLoader, final Settings settings,
final SwingMessages swingMessages, final ErrorHandler errorHandler) {
Validate.notNull(sideP, "Side panel can not be null");
Validate.notNull(imageLoader, "Image loader can not be null");
Validate.notNull(settings, "Settings can not be null");
Validate.notNull(swingMessages, "Swing messages can not be null");
Validate.notNull(errorHandler, "Error handler can not be null");
setLayout(new BorderLayout(2, 2));
chatTP = new JTextPane();
chatTP.setEditable(false);
chatTP.setBorder(BorderFactory.createEmptyBorder(4, 6, 4, 6));
chatTP.setEditorKit(new MiddleAlignedIconViewEditorKit());
chatTP.setBackground(UIManager.getColor("TextPane.background"));
chatSP = new JScrollPane(chatTP);
chatSP.setMinimumSize(new Dimension(290, 200));
chatAttr = new SimpleAttributeSet();
chatDoc = chatTP.getStyledDocument();
final URLMouseListener urlML = new URLMouseListener(chatTP, settings, errorHandler, swingMessages);
chatTP.addMouseListener(urlML);
chatTP.addMouseMotionListener(urlML);
final DocumentFilterList documentFilterList = new DocumentFilterList();
documentFilterList.addDocumentFilter(new URLDocumentFilter(false));
documentFilterList.addDocumentFilter(new SmileyDocumentFilter(false, imageLoader, settings));
final AbstractDocument doc = (AbstractDocument) chatDoc;
doc.setDocumentFilter(documentFilterList);
msgTF = new JTextField();
msgTF.addActionListener(this);
msgTF.addCaretListener(this);
msgTF.addKeyListener(this);
// Make sure tab generates key events
msgTF.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
new HashSet<AWTKeyStroke>());
final AbstractDocument msgDoc = (AbstractDocument) msgTF.getDocument();
msgDoc.setDocumentFilter(new SizeDocumentFilter(Constants.MESSAGE_MAX_BYTES));
add(chatSP, BorderLayout.CENTER);
add(sideP, BorderLayout.EAST);
add(msgTF, BorderLayout.SOUTH);
new CopyPastePopup(msgTF, swingMessages);
new CopyPopup(chatTP, swingMessages);
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
cmdHistory = new CommandHistory();
}
/**
* Sets the mediator to use in the listeners.
*
* @param mediator The mediator to use.
*/
public void setMediator(final Mediator mediator) {
this.mediator = mediator;
}
/**
* Sets the ready-to-use autocompleter for the input field.
*
* @param autoCompleter The autocompleter to use.
*/
public void setAutoCompleter(final AutoCompleter autoCompleter) {
this.autoCompleter = autoCompleter;
}
/**
* Adds the message to the chat area, in the chosen color.
*
* @param message The message to append.
* @param color The color to use for the message.
*/
@Override
public void appendToChat(final String message, final int color) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
StyleConstants.setForeground(chatAttr, new Color(color));
chatDoc.insertString(chatDoc.getLength(), message + "\n", chatAttr);
chatTP.setCaretPosition(chatDoc.getLength());
}
catch (final BadLocationException e) {
LOG.log(Level.SEVERE, e.toString(), e);
}
}
});
}
/**
* Gets the chat area.
*
* @return The chat area.
*/
public JTextPane getChatTP() {
return chatTP;
}
/**
* Gets the chat area's scrollpane.
*
* @return The chat area's scrollpane.
*/
public JScrollPane getChatSP() {
return chatSP;
}
/**
* Clears all the text from the chat area.
*/
public void clearChat() {
chatTP.setText("");
}
/**
* Gets the input field.
*
* @return The input field.
*/
public JTextField getMsgTF() {
return msgTF;
}
/**
* Updates the write status after the caret has moved.
*
* {@inheritDoc}
*/
@Override
public void caretUpdate(final CaretEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
mediator.updateWriting();
}
});
}
/**
* When enter is pressed in the input field, the text is added to the
* command history, and the mediator shows the text in the chat area.
*
* {@inheritDoc}
*/
@Override
public void actionPerformed(final ActionEvent e) {
// The input field
if (e.getSource() == msgTF) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
cmdHistory.add(msgTF.getText());
mediator.write();
}
});
}
}
/**
* When tab is pressed while in the input field, the word at the
* caret position will be autocompleted if any suggestions are found.
*
* {@inheritDoc}
*/
@Override
public void keyPressed(final KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Tab-completion
if (ke.getKeyCode() == KeyEvent.VK_TAB && ke.getModifiers() == 0) {
if (autoCompleter != null) {
final int caretPos = msgTF.getCaretPosition();
final String orgText = msgTF.getText();
final String newText = autoCompleter.completeWord(orgText, caretPos);
if (newText.length() > 0) {
msgTF.setText(newText);
msgTF.setCaretPosition(autoCompleter.getNewCaretPosition());
}
}
}
}
});
}
/**
* Not implemented.
*
* {@inheritDoc}
*/
@Override
public void keyTyped(final KeyEvent ke) {
}
/**
* After some text has been added to the command history, it can
* be accessed by browsing through the history with the up and down
* keys while focus is on the input field.
*
* {@inheritDoc}
*/
@Override
public void keyReleased(final KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Command history up
if (ke.getKeyCode() == KeyEvent.VK_UP) {
final String up = cmdHistory.goUp();
if (!msgTF.getText().equals(up)) {
msgTF.setText(up);
}
}
// Command history down
|
[
" else if (ke.getKeyCode() == KeyEvent.VK_DOWN) {"
] | 1,035
|
lcc
|
java
| null |
1f9066ab085c69885da88c003a539d651c2835d2ed83fd83
| 35
|
Your task is code completion.
/***************************************************************************
* Copyright 2006-2014 by Christian Ihle *
* contact@kouchat.net *
* *
* This file is part of KouChat. *
* *
* KouChat is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* KouChat is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with KouChat. *
* If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
package net.usikkert.kouchat.ui.swing;
import java.awt.AWTKeyStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import net.usikkert.kouchat.Constants;
import net.usikkert.kouchat.autocomplete.AutoCompleter;
import net.usikkert.kouchat.misc.CommandHistory;
import net.usikkert.kouchat.misc.ErrorHandler;
import net.usikkert.kouchat.settings.Settings;
import net.usikkert.kouchat.ui.ChatWindow;
import net.usikkert.kouchat.ui.swing.messages.SwingMessages;
import net.usikkert.kouchat.util.Validate;
/**
* This is the panel containing the main chat area, the input field,
* and the {@link SidePanel} on the right side.
* <br><br>
* The chat area has url recognition, and a right click menu. The input
* field has tab-completion, command history, and a right click menu.
*
* @author Christian Ihle
*/
public class MainPanel extends JPanel implements ActionListener, CaretListener, ChatWindow, KeyListener {
private static final Logger LOG = Logger.getLogger(MainPanel.class.getName());
private final JScrollPane chatSP;
private final JTextPane chatTP;
private final MutableAttributeSet chatAttr;
private final StyledDocument chatDoc;
private final JTextField msgTF;
private final CommandHistory cmdHistory;
private AutoCompleter autoCompleter;
private Mediator mediator;
/**
* Constructor. Creates the panel.
*
* @param sideP The panel on the right, containing the user list and the buttons.
* @param imageLoader The image loader.
* @param settings The settings to use.
* @param swingMessages The swing messages to use in copy/paste popups.
* @param errorHandler The error handler to use.
*/
public MainPanel(final SidePanel sideP, final ImageLoader imageLoader, final Settings settings,
final SwingMessages swingMessages, final ErrorHandler errorHandler) {
Validate.notNull(sideP, "Side panel can not be null");
Validate.notNull(imageLoader, "Image loader can not be null");
Validate.notNull(settings, "Settings can not be null");
Validate.notNull(swingMessages, "Swing messages can not be null");
Validate.notNull(errorHandler, "Error handler can not be null");
setLayout(new BorderLayout(2, 2));
chatTP = new JTextPane();
chatTP.setEditable(false);
chatTP.setBorder(BorderFactory.createEmptyBorder(4, 6, 4, 6));
chatTP.setEditorKit(new MiddleAlignedIconViewEditorKit());
chatTP.setBackground(UIManager.getColor("TextPane.background"));
chatSP = new JScrollPane(chatTP);
chatSP.setMinimumSize(new Dimension(290, 200));
chatAttr = new SimpleAttributeSet();
chatDoc = chatTP.getStyledDocument();
final URLMouseListener urlML = new URLMouseListener(chatTP, settings, errorHandler, swingMessages);
chatTP.addMouseListener(urlML);
chatTP.addMouseMotionListener(urlML);
final DocumentFilterList documentFilterList = new DocumentFilterList();
documentFilterList.addDocumentFilter(new URLDocumentFilter(false));
documentFilterList.addDocumentFilter(new SmileyDocumentFilter(false, imageLoader, settings));
final AbstractDocument doc = (AbstractDocument) chatDoc;
doc.setDocumentFilter(documentFilterList);
msgTF = new JTextField();
msgTF.addActionListener(this);
msgTF.addCaretListener(this);
msgTF.addKeyListener(this);
// Make sure tab generates key events
msgTF.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
new HashSet<AWTKeyStroke>());
final AbstractDocument msgDoc = (AbstractDocument) msgTF.getDocument();
msgDoc.setDocumentFilter(new SizeDocumentFilter(Constants.MESSAGE_MAX_BYTES));
add(chatSP, BorderLayout.CENTER);
add(sideP, BorderLayout.EAST);
add(msgTF, BorderLayout.SOUTH);
new CopyPastePopup(msgTF, swingMessages);
new CopyPopup(chatTP, swingMessages);
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
cmdHistory = new CommandHistory();
}
/**
* Sets the mediator to use in the listeners.
*
* @param mediator The mediator to use.
*/
public void setMediator(final Mediator mediator) {
this.mediator = mediator;
}
/**
* Sets the ready-to-use autocompleter for the input field.
*
* @param autoCompleter The autocompleter to use.
*/
public void setAutoCompleter(final AutoCompleter autoCompleter) {
this.autoCompleter = autoCompleter;
}
/**
* Adds the message to the chat area, in the chosen color.
*
* @param message The message to append.
* @param color The color to use for the message.
*/
@Override
public void appendToChat(final String message, final int color) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
StyleConstants.setForeground(chatAttr, new Color(color));
chatDoc.insertString(chatDoc.getLength(), message + "\n", chatAttr);
chatTP.setCaretPosition(chatDoc.getLength());
}
catch (final BadLocationException e) {
LOG.log(Level.SEVERE, e.toString(), e);
}
}
});
}
/**
* Gets the chat area.
*
* @return The chat area.
*/
public JTextPane getChatTP() {
return chatTP;
}
/**
* Gets the chat area's scrollpane.
*
* @return The chat area's scrollpane.
*/
public JScrollPane getChatSP() {
return chatSP;
}
/**
* Clears all the text from the chat area.
*/
public void clearChat() {
chatTP.setText("");
}
/**
* Gets the input field.
*
* @return The input field.
*/
public JTextField getMsgTF() {
return msgTF;
}
/**
* Updates the write status after the caret has moved.
*
* {@inheritDoc}
*/
@Override
public void caretUpdate(final CaretEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
mediator.updateWriting();
}
});
}
/**
* When enter is pressed in the input field, the text is added to the
* command history, and the mediator shows the text in the chat area.
*
* {@inheritDoc}
*/
@Override
public void actionPerformed(final ActionEvent e) {
// The input field
if (e.getSource() == msgTF) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
cmdHistory.add(msgTF.getText());
mediator.write();
}
});
}
}
/**
* When tab is pressed while in the input field, the word at the
* caret position will be autocompleted if any suggestions are found.
*
* {@inheritDoc}
*/
@Override
public void keyPressed(final KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Tab-completion
if (ke.getKeyCode() == KeyEvent.VK_TAB && ke.getModifiers() == 0) {
if (autoCompleter != null) {
final int caretPos = msgTF.getCaretPosition();
final String orgText = msgTF.getText();
final String newText = autoCompleter.completeWord(orgText, caretPos);
if (newText.length() > 0) {
msgTF.setText(newText);
msgTF.setCaretPosition(autoCompleter.getNewCaretPosition());
}
}
}
}
});
}
/**
* Not implemented.
*
* {@inheritDoc}
*/
@Override
public void keyTyped(final KeyEvent ke) {
}
/**
* After some text has been added to the command history, it can
* be accessed by browsing through the history with the up and down
* keys while focus is on the input field.
*
* {@inheritDoc}
*/
@Override
public void keyReleased(final KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Command history up
if (ke.getKeyCode() == KeyEvent.VK_UP) {
final String up = cmdHistory.goUp();
if (!msgTF.getText().equals(up)) {
msgTF.setText(up);
}
}
// Command history down
|
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 MainPanel extends JPanel implements ActionListener, CaretListener, ChatWindow, KeyListener {
// ... (many lines omitted for brevity)
@Override
public void keyReleased(final KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Command history up
if (ke.getKeyCode() == KeyEvent.VK_UP) {
final String up = cmdHistory.goUp();
if (!msgTF.getText().equals(up)) {
msgTF.setText(up);
}
}
// Command history down
if (ke.getKeyCode() == KeyEvent.VK_DOWN) {
final String down = cmdHistory.goDown();
if (!msgTF.getText().equals(down)) {
msgTF.setText(down);
}
}
}
});
}
// ... (many lines omitted for brevity)
Cheatsheet (for next line):
- We are in keyReleased(), which is handling the keyReleased event.
- The event is a KeyEvent with a keyCode of VK_DOWN.
- The task is to handle the command history down functionality.
- cmdHistory is an instance of CommandHistory.
- The method goDown() is likely to return the next command in the history.
- msgTF is the JTextField for the input field.
- The condition checks if the current text in the input field is not equal to the next command in the history.
- If not equal, the next command is set as the current text in the input field.
Next line will likely be:
if (ke.getKeyCode() == KeyEvent.VK_DOWN) {
final String down = cmdHistory.goDown();
if (!msgTF.getText().equals(down)) {
msgTF.setText(down);
}
}
|
|
Please complete the code given below.
# -*- coding: utf-8 -*-
# added new list_tbl definition
from functools import partial
import random
import itertools
from navmazing import NavigateToAttribute, NavigateToSibling
from widgetastic.widget import View
from widgetastic_manageiq import (
BootstrapSelect, Button, Table, Accordion, ManageIQTree, PaginationPane)
from cfme.common import Taggable, SummaryMixin
from cfme.containers.provider import ContainersProvider, Labelable,\
ContainerObjectAllBaseView, LoggingableView
from cfme.exceptions import NodeNotFound
from cfme.fixtures import pytest_selenium as sel
from cfme.web_ui import CheckboxTable, toolbar as tb, InfoBlock, match_location
from utils.appliance import Navigatable
from utils.appliance.implementations.ui import CFMENavigateStep, navigator, navigate_to
list_tbl = CheckboxTable(table_locator="//div[@id='list_grid']//table")
match_page = partial(match_location, controller='container_node', title='Nodes')
# TODO Replace with resource table widget
resource_locator = "//div[@id='records_div']/table//span[@title='{}']"
class NodeView(ContainerObjectAllBaseView, LoggingableView):
TITLE_TEXT = 'Nodes'
nodes = Table(locator="//div[@id='list_grid']//table")
@property
def table(self):
return self.nodes
@property
def in_cloud_instance(self):
return (
self.logged_in_as_current_user and
self.navigation.currently_selected == ['Compute', 'Containers', 'Container Nodes'] and
match_page() # No summary, just match controller and title
)
class NodeCollection(Navigatable):
"""Collection object for :py:class:`Node`."""
def instantiate(self, name, provider):
return Node(name=name, provider=provider, appliance=self.appliance)
def all(self):
# container_nodes table has ems_id, join with ext_mgmgt_systems on id for provider name
node_table = self.appliance.db.client['container_nodes']
ems_table = self.appliance.db.client['ext_management_systems']
node_query = self.appliance.db.client.session.query(node_table.name, ems_table.name)\
.join(ems_table, node_table.ems_id == ems_table.id)
nodes = []
for name, provider_name in node_query.all():
# Hopefully we can get by with just provider name?
nodes.append(Node(name=name,
provider=ContainersProvider(name=provider_name,
appliance=self.appliance),
collection=self))
return nodes
class NodeAllView(NodeView):
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='Nodes')
)
paginator = PaginationPane()
class Node(Taggable, Labelable, SummaryMixin, Navigatable):
PLURAL = 'Nodes'
def __init__(self, name, provider, collection=None, appliance=None):
self.name = name
self.provider = provider
if not collection:
collection = NodeCollection(appliance=appliance)
self.collection = collection
Navigatable.__init__(self, appliance=appliance)
def load_details(self, refresh=False):
navigate_to(self, 'Details')
if refresh:
tb.refresh()
def get_detail(self, *ident):
""" Gets details from the details infoblock
Args:
*ident: Table name and Key name, e.g. "Relationships", "Images"
Returns: A string representing the contents of the summary's value.
"""
self.load_details()
return InfoBlock.text(*ident)
@classmethod
def get_random_instances(cls, provider, count=1, appliance=None):
"""Generating random instances."""
node_list = provider.mgmt.list_node()
random.shuffle(node_list)
return [cls(obj.name, provider, appliance=appliance)
for obj in itertools.islice(node_list, count)]
# Still registering Node to keep on consistency on container objects navigations
@navigator.register(Node, 'All')
@navigator.register(NodeCollection, 'All')
class All(CFMENavigateStep):
VIEW = NodeAllView
prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn')
def step(self, *args, **kwargs):
self.prerequisite_view.navigation.select('Compute', 'Containers', 'Container Nodes')
def resetter(self):
# Reset view and selection
tb.select("List View")
class NodeDetailsView(NodeView):
download = Button(name='download_view')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='{} (Summary)'.format(self.context['object'].name))
)
@View.nested
class properties(Accordion): # noqa
tree = ManageIQTree()
@View.nested
class relationships(Accordion): # noqa
tree = ManageIQTree()
@navigator.register(Node, 'Details')
class Details(CFMENavigateStep):
VIEW = NodeDetailsView
prerequisite = NavigateToAttribute('collection', 'All')
def step(self, *args, **kwargs):
# Need to account for paged view
for _ in self.prerequisite_view.paginator.pages():
row = self.view.nodes.row(name=self.obj.name, provider=self.obj.provider.name)
if row:
row.click()
break
else:
raise NodeNotFound('Failed to navigate to node, could not find matching row')
class NodeEditTagsForm(NodeView):
tag_category = BootstrapSelect('tag_cat')
tag = BootstrapSelect('tag_add')
# TODO: table for added tags with removal support
# less than ideal button duplication between classes
save_button = Button('Save')
reset_button = Button('Reset')
cancel_button = Button('Cancel')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='Tag Assignment') and
sel.is_displayed(resource_locator.format(self.context['object'].name))
)
@navigator.register(Node, 'EditTags')
class EditTags(CFMENavigateStep):
VIEW = NodeEditTagsForm
prerequisite = NavigateToSibling('Details')
def step(self):
self.prerequisite_view.policy.item_select('Edit Tags')
class NodeManagePoliciesForm(NodeView):
policy_profiles = BootstrapSelect('protectbox')
# less than ideal button duplication between classes
save_button = Button('Save')
reset_button = Button('Reset')
cancel_button = Button('Cancel')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='Select Policy Profiles') and
sel.is_displayed(resource_locator.format(self.context['object'].name))
)
@navigator.register(Node, 'ManagePolicies')
class ManagePolicies(CFMENavigateStep):
VIEW = NodeManagePoliciesForm
|
[
" prerequisite = NavigateToSibling('Details')"
] | 534
|
lcc
|
python
| null |
88af654f6cc0799e1844ea6d4158729b1130dc62928ae169
| 36
|
Your task is code completion.
# -*- coding: utf-8 -*-
# added new list_tbl definition
from functools import partial
import random
import itertools
from navmazing import NavigateToAttribute, NavigateToSibling
from widgetastic.widget import View
from widgetastic_manageiq import (
BootstrapSelect, Button, Table, Accordion, ManageIQTree, PaginationPane)
from cfme.common import Taggable, SummaryMixin
from cfme.containers.provider import ContainersProvider, Labelable,\
ContainerObjectAllBaseView, LoggingableView
from cfme.exceptions import NodeNotFound
from cfme.fixtures import pytest_selenium as sel
from cfme.web_ui import CheckboxTable, toolbar as tb, InfoBlock, match_location
from utils.appliance import Navigatable
from utils.appliance.implementations.ui import CFMENavigateStep, navigator, navigate_to
list_tbl = CheckboxTable(table_locator="//div[@id='list_grid']//table")
match_page = partial(match_location, controller='container_node', title='Nodes')
# TODO Replace with resource table widget
resource_locator = "//div[@id='records_div']/table//span[@title='{}']"
class NodeView(ContainerObjectAllBaseView, LoggingableView):
TITLE_TEXT = 'Nodes'
nodes = Table(locator="//div[@id='list_grid']//table")
@property
def table(self):
return self.nodes
@property
def in_cloud_instance(self):
return (
self.logged_in_as_current_user and
self.navigation.currently_selected == ['Compute', 'Containers', 'Container Nodes'] and
match_page() # No summary, just match controller and title
)
class NodeCollection(Navigatable):
"""Collection object for :py:class:`Node`."""
def instantiate(self, name, provider):
return Node(name=name, provider=provider, appliance=self.appliance)
def all(self):
# container_nodes table has ems_id, join with ext_mgmgt_systems on id for provider name
node_table = self.appliance.db.client['container_nodes']
ems_table = self.appliance.db.client['ext_management_systems']
node_query = self.appliance.db.client.session.query(node_table.name, ems_table.name)\
.join(ems_table, node_table.ems_id == ems_table.id)
nodes = []
for name, provider_name in node_query.all():
# Hopefully we can get by with just provider name?
nodes.append(Node(name=name,
provider=ContainersProvider(name=provider_name,
appliance=self.appliance),
collection=self))
return nodes
class NodeAllView(NodeView):
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='Nodes')
)
paginator = PaginationPane()
class Node(Taggable, Labelable, SummaryMixin, Navigatable):
PLURAL = 'Nodes'
def __init__(self, name, provider, collection=None, appliance=None):
self.name = name
self.provider = provider
if not collection:
collection = NodeCollection(appliance=appliance)
self.collection = collection
Navigatable.__init__(self, appliance=appliance)
def load_details(self, refresh=False):
navigate_to(self, 'Details')
if refresh:
tb.refresh()
def get_detail(self, *ident):
""" Gets details from the details infoblock
Args:
*ident: Table name and Key name, e.g. "Relationships", "Images"
Returns: A string representing the contents of the summary's value.
"""
self.load_details()
return InfoBlock.text(*ident)
@classmethod
def get_random_instances(cls, provider, count=1, appliance=None):
"""Generating random instances."""
node_list = provider.mgmt.list_node()
random.shuffle(node_list)
return [cls(obj.name, provider, appliance=appliance)
for obj in itertools.islice(node_list, count)]
# Still registering Node to keep on consistency on container objects navigations
@navigator.register(Node, 'All')
@navigator.register(NodeCollection, 'All')
class All(CFMENavigateStep):
VIEW = NodeAllView
prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn')
def step(self, *args, **kwargs):
self.prerequisite_view.navigation.select('Compute', 'Containers', 'Container Nodes')
def resetter(self):
# Reset view and selection
tb.select("List View")
class NodeDetailsView(NodeView):
download = Button(name='download_view')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='{} (Summary)'.format(self.context['object'].name))
)
@View.nested
class properties(Accordion): # noqa
tree = ManageIQTree()
@View.nested
class relationships(Accordion): # noqa
tree = ManageIQTree()
@navigator.register(Node, 'Details')
class Details(CFMENavigateStep):
VIEW = NodeDetailsView
prerequisite = NavigateToAttribute('collection', 'All')
def step(self, *args, **kwargs):
# Need to account for paged view
for _ in self.prerequisite_view.paginator.pages():
row = self.view.nodes.row(name=self.obj.name, provider=self.obj.provider.name)
if row:
row.click()
break
else:
raise NodeNotFound('Failed to navigate to node, could not find matching row')
class NodeEditTagsForm(NodeView):
tag_category = BootstrapSelect('tag_cat')
tag = BootstrapSelect('tag_add')
# TODO: table for added tags with removal support
# less than ideal button duplication between classes
save_button = Button('Save')
reset_button = Button('Reset')
cancel_button = Button('Cancel')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='Tag Assignment') and
sel.is_displayed(resource_locator.format(self.context['object'].name))
)
@navigator.register(Node, 'EditTags')
class EditTags(CFMENavigateStep):
VIEW = NodeEditTagsForm
prerequisite = NavigateToSibling('Details')
def step(self):
self.prerequisite_view.policy.item_select('Edit Tags')
class NodeManagePoliciesForm(NodeView):
policy_profiles = BootstrapSelect('protectbox')
# less than ideal button duplication between classes
save_button = Button('Save')
reset_button = Button('Reset')
cancel_button = Button('Cancel')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='Select Policy Profiles') and
sel.is_displayed(resource_locator.format(self.context['object'].name))
)
@navigator.register(Node, 'ManagePolicies')
class ManagePolicies(CFMENavigateStep):
VIEW = NodeManagePoliciesForm
|
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]
class NodeDetailsView(NodeView):
download = Button(name='download_view')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='{} (Summary)'.format(self.context['object'].name))
)
@View.nested
class properties(Accordion): # noqa
tree = ManageIQTree()
@View.nested
class relationships(Accordion): # noqa
tree = ManageIQTree()
@navigator.register(Node, 'Details')
class Details(CFMENavigateStep):
VIEW = NodeDetailsView
prerequisite = NavigateToAttribute('collection', 'All')
def step(self, *args, **kwargs):
# Need to account for paged view
for _ in self.prerequisite_view.paginator.pages():
row = self.view.nodes.row(name=self.obj.name, provider=self.obj.provider.name)
if row:
row.click()
break
else:
raise NodeNotFound('Failed to navigate to node, could not find matching row')
class NodeEditTagsForm(NodeView):
tag_category = BootstrapSelect('tag_cat')
tag = BootstrapSelect('tag_add')
# TODO: table for added tags with removal support
# less than ideal button duplication between classes
save_button = Button('Save')
reset_button = Button('Reset')
cancel_button = Button('Cancel')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='Tag Assignment') and
sel.is_displayed(resource_locator.format(self.context['object'].name))
)
@navigator.register(Node, 'EditTags')
class EditTags(CFMENavigateStep):
VIEW = NodeEditTagsForm
prerequisite = NavigateToSibling('Details')
def step(self):
self.prerequisite_view.policy.item_select('Edit Tags')
class NodeManagePoliciesForm(NodeView):
policy_profiles = BootstrapSelect('protectbox')
# less than ideal button duplication between classes
save_button = Button('Save')
reset_button = Button('Reset')
cancel_button = Button('Cancel')
@property
def is_displayed(self):
return (
self.in_cloud_instance and
match_page(summary='Select Policy Profiles') and
sel.is_displayed(resource_locator.format(self.context['object'].name))
)
@navigator.register(Node, 'ManagePolicies')
class ManagePolicies(CFMENavigateStep):
VIEW = NodeManagePoliciesForm
Cheatsheet (for next line):
- We are in a class that inherits from NodeView.
- The class is named NodeDetailsView.
- The class has a nested class named properties.
- The nested class has a tree attribute.
- The tree attribute is an instance of ManageIQTree.
- [Relevant lines: class definition, nested class definition, attribute definition]
The next line of code is likely to be:
@View.nested
class [new_nested_class_name](Accordion): # noqa
tree = ManageIQTree()
|
|
Please complete the code given below.
package maejavawrapper;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import maejava.BoneVector;
import maejava.ColumnDefinitionVector;
import maejava.ETimeUnit;
import maejava.FlMovementController;
import maejava.FlSkeleton;
import maejava.GeneralPose;
import maejava.GeneralSkeleton;
import maejava.LabanSequence;
import maejava.LabanSequenceGenerator;
import maejava.LabanSequenceVector;
import maejava.StringVector;
public class WrappedMovementController extends FlMovementController {
List<IJRecognitionListener> recognitionListeners = new ArrayList<IJRecognitionListener>();
List<IJSequenceListener> sequenceListeners = new ArrayList<IJSequenceListener>();
List<IJPoseListener> poseListeners = new ArrayList<IJPoseListener>();
public WrappedMovementController(long pose_buffer_size, double framerate,
boolean debug) {
super(pose_buffer_size, framerate, debug);
}
public WrappedMovementController(long pose_buffer_size, double framerate) {
super(pose_buffer_size, framerate);
}
public WrappedMovementController(long pose_buffer_size) {
super(pose_buffer_size);
}
public WrappedMovementController() {
super();
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit,
double framerate, boolean debug) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure, beat_duration, time_unit, framerate, debug);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit,
double framerate) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure, beat_duration, time_unit, framerate);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure, beat_duration, time_unit);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure, long beat_duration) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure, beat_duration);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size) {
super(body_parts, column_definitions, pose_buffer_size);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions) {
super(body_parts, column_definitions);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit,
double framerate, boolean debug) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure, beat_duration, time_unit,
framerate, debug);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit,
double framerate) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure, beat_duration, time_unit,
framerate);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure, beat_duration, time_unit);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure, long beat_duration) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure, beat_duration);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator) {
super(body_parts, column_definitions, sequence_generator);
}
@Override
public void nextFrame(BigInteger timestamp, GeneralSkeleton skeleton) {
super.nextFrame(timestamp, skeleton);
notifySequenceListeners(timestamp, getCurrentSequence());
notifyRecognitionListeners(timestamp, getCurrentRecognition());
notifyPoseListeners(timestamp, getCurrentPose());
}
@Override
public void nextFrame(BigInteger timestamp, FlSkeleton skeleton) {
super.nextFrame(timestamp, skeleton);
notifySequenceListeners(timestamp, getCurrentSequence());
notifyRecognitionListeners(timestamp, getCurrentRecognition());
notifyPoseListeners(timestamp, getCurrentPose());
}
public void addListener(IJRecognitionListener listener) {
recognitionListeners.add(listener);
}
public boolean removeListener(IJRecognitionListener listener) {
return recognitionListeners.remove(listener);
}
public void addListener(IJSequenceListener listener) {
sequenceListeners.add(listener);
}
public boolean removeListener(IJSequenceListener listener) {
return sequenceListeners.remove(listener);
}
public void addListener(IJPoseListener listener) {
poseListeners.add(listener);
}
public boolean removeListener(IJPoseListener listener) {
return poseListeners.remove(listener);
}
public void notifySequenceListeners(BigInteger timestamp, LabanSequence sequence) {
for (IJSequenceListener listener : sequenceListeners) {
listener.onSequence(timestamp, sequence);
}
}
public void notifyRecognitionListeners(BigInteger timestamp,
LabanSequenceVector sequences) {
StringVector sequenceTitles = new StringVector();
for (int i = 0; i < sequences.size(); i++) {
sequenceTitles.add(sequences.get(i).getTitle());
}
|
[
"\t\tfor (IJRecognitionListener listener : recognitionListeners) {"
] | 482
|
lcc
|
java
| null |
08b681d309832c3aa506f61679aefcaed7ca5b6c115d2701
| 37
|
Your task is code completion.
package maejavawrapper;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import maejava.BoneVector;
import maejava.ColumnDefinitionVector;
import maejava.ETimeUnit;
import maejava.FlMovementController;
import maejava.FlSkeleton;
import maejava.GeneralPose;
import maejava.GeneralSkeleton;
import maejava.LabanSequence;
import maejava.LabanSequenceGenerator;
import maejava.LabanSequenceVector;
import maejava.StringVector;
public class WrappedMovementController extends FlMovementController {
List<IJRecognitionListener> recognitionListeners = new ArrayList<IJRecognitionListener>();
List<IJSequenceListener> sequenceListeners = new ArrayList<IJSequenceListener>();
List<IJPoseListener> poseListeners = new ArrayList<IJPoseListener>();
public WrappedMovementController(long pose_buffer_size, double framerate,
boolean debug) {
super(pose_buffer_size, framerate, debug);
}
public WrappedMovementController(long pose_buffer_size, double framerate) {
super(pose_buffer_size, framerate);
}
public WrappedMovementController(long pose_buffer_size) {
super(pose_buffer_size);
}
public WrappedMovementController() {
super();
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit,
double framerate, boolean debug) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure, beat_duration, time_unit, framerate, debug);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit,
double framerate) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure, beat_duration, time_unit, framerate);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure, beat_duration, time_unit);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure, long beat_duration) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure, beat_duration);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size,
long beats_per_measure) {
super(body_parts, column_definitions, pose_buffer_size,
beats_per_measure);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions, long pose_buffer_size) {
super(body_parts, column_definitions, pose_buffer_size);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions) {
super(body_parts, column_definitions);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit,
double framerate, boolean debug) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure, beat_duration, time_unit,
framerate, debug);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit,
double framerate) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure, beat_duration, time_unit,
framerate);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure, long beat_duration, ETimeUnit time_unit) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure, beat_duration, time_unit);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure, long beat_duration) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure, beat_duration);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size,
long beats_per_measure) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size, beats_per_measure);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator, long pose_buffer_size) {
super(body_parts, column_definitions, sequence_generator,
pose_buffer_size);
}
public WrappedMovementController(BoneVector body_parts,
ColumnDefinitionVector column_definitions,
LabanSequenceGenerator sequence_generator) {
super(body_parts, column_definitions, sequence_generator);
}
@Override
public void nextFrame(BigInteger timestamp, GeneralSkeleton skeleton) {
super.nextFrame(timestamp, skeleton);
notifySequenceListeners(timestamp, getCurrentSequence());
notifyRecognitionListeners(timestamp, getCurrentRecognition());
notifyPoseListeners(timestamp, getCurrentPose());
}
@Override
public void nextFrame(BigInteger timestamp, FlSkeleton skeleton) {
super.nextFrame(timestamp, skeleton);
notifySequenceListeners(timestamp, getCurrentSequence());
notifyRecognitionListeners(timestamp, getCurrentRecognition());
notifyPoseListeners(timestamp, getCurrentPose());
}
public void addListener(IJRecognitionListener listener) {
recognitionListeners.add(listener);
}
public boolean removeListener(IJRecognitionListener listener) {
return recognitionListeners.remove(listener);
}
public void addListener(IJSequenceListener listener) {
sequenceListeners.add(listener);
}
public boolean removeListener(IJSequenceListener listener) {
return sequenceListeners.remove(listener);
}
public void addListener(IJPoseListener listener) {
poseListeners.add(listener);
}
public boolean removeListener(IJPoseListener listener) {
return poseListeners.remove(listener);
}
public void notifySequenceListeners(BigInteger timestamp, LabanSequence sequence) {
for (IJSequenceListener listener : sequenceListeners) {
listener.onSequence(timestamp, sequence);
}
}
public void notifyRecognitionListeners(BigInteger timestamp,
LabanSequenceVector sequences) {
StringVector sequenceTitles = new StringVector();
for (int i = 0; i < sequences.size(); i++) {
sequenceTitles.add(sequences.get(i).getTitle());
}
|
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... ~20 constructors and methods omitted for brevity]
public void notifyPoseListeners(BigInteger timestamp, GeneralSkeleton skeleton) {
for (IJPoseListener listener : poseListeners) {
listener.onPose(timestamp, skeleton);
}
}
public void notifyPoseListeners(BigInteger timestamp, FlSkeleton skeleton) {
for (IJPoseListener listener : poseListeners) {
listener.onPose(timestamp, skeleton);
}
}
public void addListener(IJPoseListener listener) {
poseListeners.add(listener);
}
public boolean removeListener(IJPoseListener listener) {
return poseListeners.remove(listener);
}
Cheatsheet (for next line):
- We are in the implementation of notifyPoseListeners(BigInteger timestamp, FlSkeleton skeleton), which should notify all IJPoseListener instances in the poseListeners list.
- The method is similar to the other notifyPoseListeners method, which uses a for-each loop to iterate over the poseListeners list.
- The listener.onPose(timestamp, skeleton) method is called for each listener in the list.
- The method is likely intended to be similar to the other notifyPoseListeners method.
- [Relevant lines: for-each loop, listener.onPose(timestamp, skeleton)]
Next line will likely be: for (IJPoseListener listener : poseListeners) { listener.onPose(timestamp, skeleton); }
|
|
Please complete the code given below.
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using ClearCanvas.Common.Utilities;
[assembly: WebResource("ClearCanvas.ImageServer.Web.Common.WebControls.UI.ToolbarButton.js", "text/javascript")]
namespace ClearCanvas.ImageServer.Web.Common.WebControls.UI
{
public enum NoPermissionVisibility
{
Invisible,
Visible
}
[ToolboxData("<{0}:ToolbarButton runat=server></{0}:ToolbarButton>")]
[Themeable(true)]
public class ToolbarButton : ImageButton, IScriptControl
{
#region Private Members
private string _roleSeparator = ",";
private NoPermissionVisibility _noPermissionVisibilityMode;
#endregion
#region Public Properties
/// <summary>
/// Specifies the roles which users must have to access to this button.
/// </summary>
public string Roles
{
get
{
return ViewState["Roles"] as string;
}
set
{
ViewState["Roles"] = value;
}
}
/// <summary>
/// Specifies the visiblity of the button if the user doesn't have the roles specified in <see cref="Roles"/>
/// </summary>
public NoPermissionVisibility NoPermissionVisibilityMode
{
get { return _noPermissionVisibilityMode; }
set { _noPermissionVisibilityMode = value; }
}
/// <summary>
/// Sets or gets the url of the image to be used when the button is enabled.
/// </summary>
public string EnabledImageURL
{
get
{
String s = (String)ViewState["EnabledImageURL"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["EnabledImageURL"] = inspectURL(value);
}
}
/// <summary>
/// Sets or gets the url of the image to be used when the button enabled and user hovers the mouse over the button.
/// </summary>
public string HoverImageURL
{
get
{
String s = (String)ViewState["HoverImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["HoverImageURL"] = inspectURL(value);
}
}
/// <summary>
/// Sets or gets the url of the image to be used when the mouse button is clicked.
/// </summary>
public string ClickedImageURL
{
get
{
String s = (String)ViewState["ClickedImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["ClickedImageURL"] = inspectURL(value);
}
}
/// <summary>
/// Sets or gets the url of the image to be used when the button is disabled.
/// </summary>
public string DisabledImageURL
{
get
{
String s = (String)ViewState["DisabledImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["DisabledImageURL"] = inspectURL(value);
}
}
/// <summary>
/// Gets or sets the string that is used to seperate values in the <see cref="Roles"/> property.
/// </summary>
public string RoleSeparator
{
get { return _roleSeparator; }
set { _roleSeparator = value; }
}
#endregion Public Properties
#region Private Methods
private string inspectURL(string value)
{
if (!value.StartsWith("~/") && !value.StartsWith("/"))
value = value.Insert(0, "~/App_Themes/" + Page.Theme + "/");
return value;
}
#endregion Private Methods
public override void RenderControl(HtmlTextWriter writer)
{
if (Enabled)
ImageUrl = EnabledImageURL;
else
ImageUrl = DisabledImageURL;
base.RenderControl(writer);
}
#region IScriptControl Members
public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
ScriptControlDescriptor desc = new ScriptControlDescriptor("ClearCanvas.ImageServer.Web.Common.WebControls.UI.ToolbarButton", ClientID);
desc.AddProperty("EnabledImageUrl", Page.ResolveClientUrl(EnabledImageURL));
desc.AddProperty("DisabledImageUrl", Page.ResolveClientUrl(DisabledImageURL));
desc.AddProperty("HoverImageUrl", Page.ResolveClientUrl(HoverImageURL));
desc.AddProperty("ClickedImageUrl", Page.ResolveClientUrl(ClickedImageURL));
return new ScriptDescriptor[] { desc };
}
public IEnumerable<ScriptReference> GetScriptReferences()
{
ScriptReference reference = new ScriptReference();
reference.Path = Page.ClientScript.GetWebResourceUrl(typeof(ToolbarButton), "ClearCanvas.ImageServer.Web.Common.WebControls.UI.ToolbarButton.js");
return new ScriptReference[] { reference };
}
#endregion IScriptControl Members
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (!DesignMode)
{
ScriptManager sm = ScriptManager.GetCurrent(Page);
sm.RegisterScriptControl(this);
}
if (String.IsNullOrEmpty(Roles)==false)
{
string[] roles = Roles.Split(new String[]{ RoleSeparator}, StringSplitOptions.RemoveEmptyEntries);
bool allow = CollectionUtils.Contains(roles,
delegate(string role)
{
return Thread.CurrentPrincipal.IsInRole(role.Trim());
});
if (!allow)
{
Enabled = false;
Visible = NoPermissionVisibilityMode!=NoPermissionVisibility.Invisible;
}
}
}
protected override void Render(HtmlTextWriter writer)
{
if (!DesignMode)
{
|
[
" ScriptManager sm = ScriptManager.GetCurrent(Page);"
] | 655
|
lcc
|
csharp
| null |
1472d733364caca77c7f2605a8ceaee6c18fb02ebc460475
| 38
|
Your task is code completion.
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using ClearCanvas.Common.Utilities;
[assembly: WebResource("ClearCanvas.ImageServer.Web.Common.WebControls.UI.ToolbarButton.js", "text/javascript")]
namespace ClearCanvas.ImageServer.Web.Common.WebControls.UI
{
public enum NoPermissionVisibility
{
Invisible,
Visible
}
[ToolboxData("<{0}:ToolbarButton runat=server></{0}:ToolbarButton>")]
[Themeable(true)]
public class ToolbarButton : ImageButton, IScriptControl
{
#region Private Members
private string _roleSeparator = ",";
private NoPermissionVisibility _noPermissionVisibilityMode;
#endregion
#region Public Properties
/// <summary>
/// Specifies the roles which users must have to access to this button.
/// </summary>
public string Roles
{
get
{
return ViewState["Roles"] as string;
}
set
{
ViewState["Roles"] = value;
}
}
/// <summary>
/// Specifies the visiblity of the button if the user doesn't have the roles specified in <see cref="Roles"/>
/// </summary>
public NoPermissionVisibility NoPermissionVisibilityMode
{
get { return _noPermissionVisibilityMode; }
set { _noPermissionVisibilityMode = value; }
}
/// <summary>
/// Sets or gets the url of the image to be used when the button is enabled.
/// </summary>
public string EnabledImageURL
{
get
{
String s = (String)ViewState["EnabledImageURL"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["EnabledImageURL"] = inspectURL(value);
}
}
/// <summary>
/// Sets or gets the url of the image to be used when the button enabled and user hovers the mouse over the button.
/// </summary>
public string HoverImageURL
{
get
{
String s = (String)ViewState["HoverImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["HoverImageURL"] = inspectURL(value);
}
}
/// <summary>
/// Sets or gets the url of the image to be used when the mouse button is clicked.
/// </summary>
public string ClickedImageURL
{
get
{
String s = (String)ViewState["ClickedImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["ClickedImageURL"] = inspectURL(value);
}
}
/// <summary>
/// Sets or gets the url of the image to be used when the button is disabled.
/// </summary>
public string DisabledImageURL
{
get
{
String s = (String)ViewState["DisabledImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["DisabledImageURL"] = inspectURL(value);
}
}
/// <summary>
/// Gets or sets the string that is used to seperate values in the <see cref="Roles"/> property.
/// </summary>
public string RoleSeparator
{
get { return _roleSeparator; }
set { _roleSeparator = value; }
}
#endregion Public Properties
#region Private Methods
private string inspectURL(string value)
{
if (!value.StartsWith("~/") && !value.StartsWith("/"))
value = value.Insert(0, "~/App_Themes/" + Page.Theme + "/");
return value;
}
#endregion Private Methods
public override void RenderControl(HtmlTextWriter writer)
{
if (Enabled)
ImageUrl = EnabledImageURL;
else
ImageUrl = DisabledImageURL;
base.RenderControl(writer);
}
#region IScriptControl Members
public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
ScriptControlDescriptor desc = new ScriptControlDescriptor("ClearCanvas.ImageServer.Web.Common.WebControls.UI.ToolbarButton", ClientID);
desc.AddProperty("EnabledImageUrl", Page.ResolveClientUrl(EnabledImageURL));
desc.AddProperty("DisabledImageUrl", Page.ResolveClientUrl(DisabledImageURL));
desc.AddProperty("HoverImageUrl", Page.ResolveClientUrl(HoverImageURL));
desc.AddProperty("ClickedImageUrl", Page.ResolveClientUrl(ClickedImageURL));
return new ScriptDescriptor[] { desc };
}
public IEnumerable<ScriptReference> GetScriptReferences()
{
ScriptReference reference = new ScriptReference();
reference.Path = Page.ClientScript.GetWebResourceUrl(typeof(ToolbarButton), "ClearCanvas.ImageServer.Web.Common.WebControls.UI.ToolbarButton.js");
return new ScriptReference[] { reference };
}
#endregion IScriptControl Members
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (!DesignMode)
{
ScriptManager sm = ScriptManager.GetCurrent(Page);
sm.RegisterScriptControl(this);
}
if (String.IsNullOrEmpty(Roles)==false)
{
string[] roles = Roles.Split(new String[]{ RoleSeparator}, StringSplitOptions.RemoveEmptyEntries);
bool allow = CollectionUtils.Contains(roles,
delegate(string role)
{
return Thread.CurrentPrincipal.IsInRole(role.Trim());
});
if (!allow)
{
Enabled = false;
Visible = NoPermissionVisibilityMode!=NoPermissionVisibility.Invisible;
}
}
}
protected override void Render(HtmlTextWriter writer)
{
if (!DesignMode)
{
|
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 Code Completion Task:
**Context:**
[Previous code... ~10,000 lines omitted for brevity]
public class ToolbarButton : ImageButton, IScriptControl
{
#region Public Properties
public string Roles
{
get
{
return ViewState["Roles"] as string;
}
set
{
ViewState["Roles"] = value;
}
}
public NoPermissionVisibility NoPermissionVisibilityMode
{
get { return _noPermissionVisibilityMode; }
set { _noPermissionVisibilityMode = value; }
}
public string EnabledImageURL
{
get
{
String s = (String)ViewState["EnabledImageURL"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["EnabledImageURL"] = inspectURL(value);
}
}
public string HoverImageURL
{
get
{
String s = (String)ViewState["HoverImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["HoverImageURL"] = inspectURL(value);
}
}
public string ClickedImageURL
{
get
{
String s = (String)ViewState["ClickedImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["ClickedImageURL"] = inspectURL(value);
}
}
public string DisabledImageURL
{
get
{
String s = (String)ViewState["DisabledImageURL"];
return (s ?? String.Empty);
}
set
{
ViewState["DisabledImageURL"] = inspectURL(value);
}
}
public string RoleSeparator
{
get { return _roleSeparator; }
set { _roleSeparator = value; }
}
#endregion Public Properties
#region IScriptControl Members
public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
ScriptControlDescriptor desc = new ScriptControlDescriptor("ClearCanvas.ImageServer.Web.Common.WebControls.UI.ToolbarButton", ClientID);
desc.AddProperty("EnabledImageUrl", Page.ResolveClientUrl(EnabledImageURL));
desc.AddProperty("DisabledImageUrl", Page.ResolveClientUrl(DisabledImageURL));
desc.AddProperty("HoverImageUrl", Page.ResolveClientUrl(HoverImageURL));
desc.AddProperty("ClickedImageUrl", Page.ResolveClientUrl(ClickedImageURL));
return new ScriptDescriptor[] { desc };
}
public IEnumerable<ScriptReference> GetScriptReferences()
{
ScriptReference reference = new ScriptReference();
reference.Path = Page.ClientScript.GetWebResourceUrl(typeof(ToolbarButton), "ClearCanvas.ImageServer.Web.Common.WebControls.UI.ToolbarButton.js");
return new ScriptReference[] { reference };
}
#endregion IScriptControl Members
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (!DesignMode)
{
ScriptManager sm = ScriptManager.GetCurrent(Page);
sm.RegisterScriptControl(this);
}
if (String.IsNullOrEmpty(Roles)==false)
{
string[] roles = Roles.Split(new String[]{ RoleSeparator}, StringSplitOptions.RemoveEmptyEntries);
bool allow = CollectionUtils.Contains(roles,
delegate(string role)
{
return Thread.CurrentPrincipal.IsInRole(role.Trim());
});
if (!allow)
{
Enabled = false;
Visible = NoPermissionVisibilityMode!=NoPermissionVisibility.Invisible;
}
}
}
protected override void Render(HtmlTextWriter writer)
{
if (!DesignMode)
{
// [Code to be completed]
}
}
}
**Cheat Sheet:**
- We are in the Render method, which is responsible for rendering the control.
- The control is a ToolbarButton, which is a custom ImageButton.
- The Render method is overridden to customize the rendering behavior.
- The method takes an HtmlTextWriter writer as a parameter.
- The method is called when the control is rendered to the client.
- The control's Enabled and Visible properties are set based on the user's roles in the OnPreRender method.
**Relevant lines:**
- The Render method header
- The Enabled and Visible properties
- The OnPreRender method
**Next line will likely be:**
```csharp
writer.WriteLine("<img src=\"" + ImageUrl + "\" alt=\"" + AlternateText + "\" />");
```
This line writes the HTML image tag to the writer, using the ImageUrl property to determine the source of the image. The AlternateText property is also used to set the alt attribute of the image tag.
|
|
Please complete the code given below.
package com.github.lazylazuli.traps.common.tile;
import com.github.lazylazuli.traps.common.block.BlockSpikeTrap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentDurability;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.init.Enchantments;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.DamageSource;
import net.minecraft.util.ITickable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.Random;
import static com.github.lazylazuli.lib.common.block.BlockDyed.COLOR;
import static com.github.lazylazuli.traps.common.TrapObjects.SMOOTH_GRANITE_SLAB;
public class TileSpikeTrap extends TileEntity implements ITickable
{
private NonNullList<ItemStack> inventory = NonNullList.withSize(1, ItemStack.EMPTY);
private int sharpness;
private int fire;
private int blast;
private int smite;
private int bane;
private int damageCooldown;
private int damage;
public int getBlastResistance()
{
return blast;
}
@Override
public void update()
{
if (damageCooldown > 0)
{
damageCooldown--;
}
}
public void initializeStack(ItemStack stack)
{
inventory.set(0, stack.copy());
inventory.get(0)
.setCount(1);
NBTTagCompound compound = stack.getTagCompound();
if (compound == null)
{
return;
}
if (compound.hasKey("ToolDamage"))
{
damage = stack.getTagCompound()
.getInteger("ToolDamage");
}
NBTTagList list = stack.getEnchantmentTagList();
if (list == null)
{
return;
}
for (int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound ench = (NBTTagCompound) list.get(i);
int id = ench.getShort("id");
int lvl = ench.getShort("lvl");
if (Enchantment.REGISTRY.getIDForObject(Enchantments.SHARPNESS) == id)
{
sharpness = lvl;
} else if (Enchantment.REGISTRY.getIDForObject(Enchantments.FIRE_ASPECT) == id)
{
fire = lvl;
} else if (Enchantment.REGISTRY.getIDForObject(Enchantments.BLAST_PROTECTION) == id)
{
blast = lvl;
} else if (Enchantment.REGISTRY.getIDForObject(Enchantments.BANE_OF_ARTHROPODS) == id)
{
bane = lvl;
} else if (Enchantment.REGISTRY.getIDForObject(Enchantments.SMITE) == id)
{
smite = lvl;
}
}
}
public ItemStack getItemDropped()
{
ItemStack stack = inventory.get(0)
.copy();
if (damage > 0)
{
NBTTagCompound compound = stack.getTagCompound();
if (compound == null)
{
compound = new NBTTagCompound();
stack.setTagCompound(compound);
}
compound.setInteger("ToolDamage", damage);
}
return stack;
}
private Item.ToolMaterial getToolMaterial()
{
return ((BlockSpikeTrap) getBlockType()).getToolMaterial();
}
private float getDamageMultiplier(Entity entityIn)
{
float dmg = getToolMaterial().getDamageVsEntity() + 1;
dmg += sharpness;
if (entityIn instanceof EntityMob)
{
switch (((EntityMob) entityIn).getCreatureAttribute())
{
case UNDEAD:
dmg += smite;
break;
case ARTHROPOD:
dmg += bane;
break;
}
}
return dmg;
}
public void onFallenUpon(Entity entityIn, float fallDistance)
{
float dmg = getDamageMultiplier(entityIn) + 1;
float fall = Math.max(4, fallDistance);
entityIn.fall(fall, dmg);
damageBlock((int) fall);
}
public void onEntityWalk(Entity entityIn)
{
if (!entityIn.isSneaking())
{
entityIn.attackEntityFrom(DamageSource.CACTUS, getDamageMultiplier(entityIn));
if (!world.isRaining())
{
entityIn.setFire(((int) getToolMaterial().getDamageVsEntity() + 1) * fire);
}
damageBlock(1);
}
}
private void damageBlock(int dmg)
{
if (damageCooldown > 0)
{
return;
}
boolean isBroken = attemptDamageItem(dmg, world.rand);
damageCooldown = 8;
markDirty();
if (isBroken)
{
EnumDyeColor color = EnumDyeColor.byMetadata(getBlockMetadata());
world.setBlockState(pos, SMOOTH_GRANITE_SLAB.getDefaultState()
.withProperty(COLOR, color));
}
}
private boolean attemptDamageItem(int amount, Random rand)
{
ItemStack stack = inventory.get(0);
int i = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack);
int j = 0;
for (int k = 0; i > 0 && k < amount; ++k)
{
if (EnchantmentDurability.negateDamage(stack, i, rand))
{
++j;
}
}
amount -= j;
if (amount <= 0)
{
return false;
}
damage += amount;
return damage > getToolMaterial().getMaxUses();
}
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate)
{
return !oldState.getBlock()
.isAssociatedBlock(newSate.getBlock());
}
// NBT
@Override
public void readFromNBT(NBTTagCompound compound)
{
super.readFromNBT(compound);
ItemStackHelper.loadAllItems(compound, inventory);
initializeStack(inventory.get(0));
|
[
"\t\tdamageCooldown = compound.getInteger(\"DamageCooldown\");"
] | 475
|
lcc
|
java
| null |
2abe780e4777e159876fcba6fb9c21888d8a0782e7499c3e
| 39
|
Your task is code completion.
package com.github.lazylazuli.traps.common.tile;
import com.github.lazylazuli.traps.common.block.BlockSpikeTrap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentDurability;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.init.Enchantments;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.DamageSource;
import net.minecraft.util.ITickable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.Random;
import static com.github.lazylazuli.lib.common.block.BlockDyed.COLOR;
import static com.github.lazylazuli.traps.common.TrapObjects.SMOOTH_GRANITE_SLAB;
public class TileSpikeTrap extends TileEntity implements ITickable
{
private NonNullList<ItemStack> inventory = NonNullList.withSize(1, ItemStack.EMPTY);
private int sharpness;
private int fire;
private int blast;
private int smite;
private int bane;
private int damageCooldown;
private int damage;
public int getBlastResistance()
{
return blast;
}
@Override
public void update()
{
if (damageCooldown > 0)
{
damageCooldown--;
}
}
public void initializeStack(ItemStack stack)
{
inventory.set(0, stack.copy());
inventory.get(0)
.setCount(1);
NBTTagCompound compound = stack.getTagCompound();
if (compound == null)
{
return;
}
if (compound.hasKey("ToolDamage"))
{
damage = stack.getTagCompound()
.getInteger("ToolDamage");
}
NBTTagList list = stack.getEnchantmentTagList();
if (list == null)
{
return;
}
for (int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound ench = (NBTTagCompound) list.get(i);
int id = ench.getShort("id");
int lvl = ench.getShort("lvl");
if (Enchantment.REGISTRY.getIDForObject(Enchantments.SHARPNESS) == id)
{
sharpness = lvl;
} else if (Enchantment.REGISTRY.getIDForObject(Enchantments.FIRE_ASPECT) == id)
{
fire = lvl;
} else if (Enchantment.REGISTRY.getIDForObject(Enchantments.BLAST_PROTECTION) == id)
{
blast = lvl;
} else if (Enchantment.REGISTRY.getIDForObject(Enchantments.BANE_OF_ARTHROPODS) == id)
{
bane = lvl;
} else if (Enchantment.REGISTRY.getIDForObject(Enchantments.SMITE) == id)
{
smite = lvl;
}
}
}
public ItemStack getItemDropped()
{
ItemStack stack = inventory.get(0)
.copy();
if (damage > 0)
{
NBTTagCompound compound = stack.getTagCompound();
if (compound == null)
{
compound = new NBTTagCompound();
stack.setTagCompound(compound);
}
compound.setInteger("ToolDamage", damage);
}
return stack;
}
private Item.ToolMaterial getToolMaterial()
{
return ((BlockSpikeTrap) getBlockType()).getToolMaterial();
}
private float getDamageMultiplier(Entity entityIn)
{
float dmg = getToolMaterial().getDamageVsEntity() + 1;
dmg += sharpness;
if (entityIn instanceof EntityMob)
{
switch (((EntityMob) entityIn).getCreatureAttribute())
{
case UNDEAD:
dmg += smite;
break;
case ARTHROPOD:
dmg += bane;
break;
}
}
return dmg;
}
public void onFallenUpon(Entity entityIn, float fallDistance)
{
float dmg = getDamageMultiplier(entityIn) + 1;
float fall = Math.max(4, fallDistance);
entityIn.fall(fall, dmg);
damageBlock((int) fall);
}
public void onEntityWalk(Entity entityIn)
{
if (!entityIn.isSneaking())
{
entityIn.attackEntityFrom(DamageSource.CACTUS, getDamageMultiplier(entityIn));
if (!world.isRaining())
{
entityIn.setFire(((int) getToolMaterial().getDamageVsEntity() + 1) * fire);
}
damageBlock(1);
}
}
private void damageBlock(int dmg)
{
if (damageCooldown > 0)
{
return;
}
boolean isBroken = attemptDamageItem(dmg, world.rand);
damageCooldown = 8;
markDirty();
if (isBroken)
{
EnumDyeColor color = EnumDyeColor.byMetadata(getBlockMetadata());
world.setBlockState(pos, SMOOTH_GRANITE_SLAB.getDefaultState()
.withProperty(COLOR, color));
}
}
private boolean attemptDamageItem(int amount, Random rand)
{
ItemStack stack = inventory.get(0);
int i = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack);
int j = 0;
for (int k = 0; i > 0 && k < amount; ++k)
{
if (EnchantmentDurability.negateDamage(stack, i, rand))
{
++j;
}
}
amount -= j;
if (amount <= 0)
{
return false;
}
damage += amount;
return damage > getToolMaterial().getMaxUses();
}
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate)
{
return !oldState.getBlock()
.isAssociatedBlock(newSate.getBlock());
}
// NBT
@Override
public void readFromNBT(NBTTagCompound compound)
{
super.readFromNBT(compound);
ItemStackHelper.loadAllItems(compound, inventory);
initializeStack(inventory.get(0));
|
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:
**TileSpikeTrap Class**
- The class extends `TileEntity` and implements `ITickable`.
- It has several fields: `inventory`, `sharpness`, `fire`, `blast`, `bane`, `damageCooldown`, and `damage`.
- The `update()` method is used to decrement `damageCooldown`.
- The `initializeStack()` method is used to initialize the `inventory` and extract enchantments from the given `ItemStack`.
- The `getItemDropped()` method returns a copy of the `inventory` item with the `ToolDamage` NBT tag set if `damage > 0`.
- The `getToolMaterial()` method returns the `Item.ToolMaterial` of the block type.
- The `getDamageMultiplier()` method calculates the damage multiplier based on the tool material, sharpness, and enchantments.
- The `onFallenUpon()` and `onEntityWalk()` methods deal damage to entities and damage the block.
- The `damageBlock()` method attempts to damage the item and updates the block state if it breaks.
- The `attemptDamageItem()` method attempts to damage the item based on the enchantments and the amount of damage.
**Relevant lines and variables:**
- `inventory`: a list of item stacks
- `damage`: the total damage taken by the item
- `damageCooldown`: a cooldown for damaging the block
- `getToolMaterial()`: returns the tool material of the block type
- `getDamageMultiplier()`: calculates the damage multiplier based on the tool material, sharpness, and enchantments
- `onFallenUpon()` and `onEntityWalk()`: deal damage to entities and damage the block
- `damageBlock()`: attempts to damage the item and updates the block state if it breaks
**Context for the code completion task:**
The code completion task is likely related to the `onEntityWalk()` method, which deals damage to entities and sets them on fire if the world is not raining. The task might involve completing the method to handle the case where the entity is a player.
**Possible code completion tasks:**
1. Complete the `onEntityWalk()` method to handle the case where the entity is a player.
2. Implement a method to handle the case where the entity is a player in the `onEntityWalk()` method.
3. Add a check to prevent the entity from being set on fire if it is a player.
Please let me know which task you would like me to solve.
|
|
Please complete the code given below.
/**
* Copyright (C) 2002-2015 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
import static net.sf.freecol.common.util.CollectionUtils.*;
/**
* The effect of a natural disaster or other event. How the
* probability of the effect is interpreted depends on the number of
* effects value of the disaster or event. If the number of effects is
* ALL, the probability is ignored. If it is ONE, then the probability
* may be an arbitrary integer, and is used only for comparison with
* other effects. If the number of effects is SEVERAL, however, the
* probability must be a percentage.
*
* @see Disaster
*/
public class Effect extends FreeColGameObjectType {
public static final String DAMAGED_UNIT
= "model.disaster.effect.damagedUnit";
public static final String LOSS_OF_UNIT
= "model.disaster.effect.lossOfUnit";
public static final String LOSS_OF_MONEY
= "model.disaster.effect.lossOfMoney";
public static final String LOSS_OF_GOODS
= "model.disaster.effect.lossOfGoods";
public static final String LOSS_OF_TILE_PRODUCTION
= "model.disaster.effect.lossOfTileProduction";
public static final String LOSS_OF_BUILDING
= "model.disaster.effect.lossOfBuilding";
public static final String LOSS_OF_BUILDING_PRODUCTION
= "model.disaster.effect.lossOfBuildingProduction";
/** The probability of this effect. */
private int probability;
/** Scopes that might limit this Effect to certain types of objects. */
private List<Scope> scopes = null;
/**
* Deliberately empty constructor.
*/
protected Effect() {}
/**
* Creates a new <code>Effect</code> instance.
*
* @param xr The <code>FreeColXMLReader</code> to read from.
* @param specification The <code>Specification</code> to refer to.
* @exception XMLStreamException if an error occurs
*/
public Effect(FreeColXMLReader xr, Specification specification) throws XMLStreamException {
setSpecification(specification);
readFromXML(xr);
}
/**
* Create a new effect from an existing one.
*
* @param template The <code>Effect</code> to copy from.
*/
public Effect(Effect template) {
setId(template.getId());
setSpecification(template.getSpecification());
this.probability = template.probability;
this.scopes = template.scopes;
addFeatures(template);
}
/**
* Get the probability of this effect.
*
* @return The probability.
*/
public final int getProbability() {
return probability;
}
/**
* Get the scopes applicable to this effect.
*
* @return A list of <code>Scope</code>s.
*/
public final List<Scope> getScopes() {
return (scopes == null) ? Collections.<Scope>emptyList()
: scopes;
}
/**
* Add a scope.
*
* @param scope The <code>Scope</code> to add.
*/
private void addScope(Scope scope) {
if (scopes == null) scopes = new ArrayList<>();
scopes.add(scope);
}
/**
* Does at least one of this effect's scopes apply to an object.
*
* @param objectType The <code>FreeColGameObjectType</code> to check.
* @return True if this effect applies.
*/
public boolean appliesTo(final FreeColGameObjectType objectType) {
return (scopes == null || scopes.isEmpty()) ? true
: any(scopes, s -> s.appliesTo(objectType));
}
// Serialization
private static final String PROBABILITY_TAG = "probability";
/**
* {@inheritDoc}
*/
@Override
protected void writeAttributes(FreeColXMLWriter xw) throws XMLStreamException {
super.writeAttributes(xw);
xw.writeAttribute(PROBABILITY_TAG, probability);
}
/**
* {@inheritDoc}
*/
@Override
protected void writeChildren(FreeColXMLWriter xw) throws XMLStreamException {
super.writeChildren(xw);
for (Scope scope : getScopes()) scope.toXML(xw);
}
/**
* {@inheritDoc}
*/
@Override
protected void readAttributes(FreeColXMLReader xr) throws XMLStreamException {
super.readAttributes(xr);
probability = xr.getAttribute(PROBABILITY_TAG, 0);
}
/**
* {@inheritDoc}
*/
@Override
protected void readChildren(FreeColXMLReader xr) throws XMLStreamException {
// Clear containers.
if (xr.shouldClearContainers()) {
scopes = null;
}
super.readChildren(xr);
}
/**
* {@inheritDoc}
*/
@Override
protected void readChild(FreeColXMLReader xr) throws XMLStreamException {
final String tag = xr.getLocalName();
if (Scope.getXMLElementTagName().equals(tag)) {
addScope(new Scope(xr));
} else {
super.readChild(xr);
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
|
[
" StringBuilder sb = new StringBuilder(32);"
] | 661
|
lcc
|
java
| null |
214bccc94127564a29c72827ff53ccb4c3bd880918d517fa
| 40
|
Your task is code completion.
/**
* Copyright (C) 2002-2015 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
import static net.sf.freecol.common.util.CollectionUtils.*;
/**
* The effect of a natural disaster or other event. How the
* probability of the effect is interpreted depends on the number of
* effects value of the disaster or event. If the number of effects is
* ALL, the probability is ignored. If it is ONE, then the probability
* may be an arbitrary integer, and is used only for comparison with
* other effects. If the number of effects is SEVERAL, however, the
* probability must be a percentage.
*
* @see Disaster
*/
public class Effect extends FreeColGameObjectType {
public static final String DAMAGED_UNIT
= "model.disaster.effect.damagedUnit";
public static final String LOSS_OF_UNIT
= "model.disaster.effect.lossOfUnit";
public static final String LOSS_OF_MONEY
= "model.disaster.effect.lossOfMoney";
public static final String LOSS_OF_GOODS
= "model.disaster.effect.lossOfGoods";
public static final String LOSS_OF_TILE_PRODUCTION
= "model.disaster.effect.lossOfTileProduction";
public static final String LOSS_OF_BUILDING
= "model.disaster.effect.lossOfBuilding";
public static final String LOSS_OF_BUILDING_PRODUCTION
= "model.disaster.effect.lossOfBuildingProduction";
/** The probability of this effect. */
private int probability;
/** Scopes that might limit this Effect to certain types of objects. */
private List<Scope> scopes = null;
/**
* Deliberately empty constructor.
*/
protected Effect() {}
/**
* Creates a new <code>Effect</code> instance.
*
* @param xr The <code>FreeColXMLReader</code> to read from.
* @param specification The <code>Specification</code> to refer to.
* @exception XMLStreamException if an error occurs
*/
public Effect(FreeColXMLReader xr, Specification specification) throws XMLStreamException {
setSpecification(specification);
readFromXML(xr);
}
/**
* Create a new effect from an existing one.
*
* @param template The <code>Effect</code> to copy from.
*/
public Effect(Effect template) {
setId(template.getId());
setSpecification(template.getSpecification());
this.probability = template.probability;
this.scopes = template.scopes;
addFeatures(template);
}
/**
* Get the probability of this effect.
*
* @return The probability.
*/
public final int getProbability() {
return probability;
}
/**
* Get the scopes applicable to this effect.
*
* @return A list of <code>Scope</code>s.
*/
public final List<Scope> getScopes() {
return (scopes == null) ? Collections.<Scope>emptyList()
: scopes;
}
/**
* Add a scope.
*
* @param scope The <code>Scope</code> to add.
*/
private void addScope(Scope scope) {
if (scopes == null) scopes = new ArrayList<>();
scopes.add(scope);
}
/**
* Does at least one of this effect's scopes apply to an object.
*
* @param objectType The <code>FreeColGameObjectType</code> to check.
* @return True if this effect applies.
*/
public boolean appliesTo(final FreeColGameObjectType objectType) {
return (scopes == null || scopes.isEmpty()) ? true
: any(scopes, s -> s.appliesTo(objectType));
}
// Serialization
private static final String PROBABILITY_TAG = "probability";
/**
* {@inheritDoc}
*/
@Override
protected void writeAttributes(FreeColXMLWriter xw) throws XMLStreamException {
super.writeAttributes(xw);
xw.writeAttribute(PROBABILITY_TAG, probability);
}
/**
* {@inheritDoc}
*/
@Override
protected void writeChildren(FreeColXMLWriter xw) throws XMLStreamException {
super.writeChildren(xw);
for (Scope scope : getScopes()) scope.toXML(xw);
}
/**
* {@inheritDoc}
*/
@Override
protected void readAttributes(FreeColXMLReader xr) throws XMLStreamException {
super.readAttributes(xr);
probability = xr.getAttribute(PROBABILITY_TAG, 0);
}
/**
* {@inheritDoc}
*/
@Override
protected void readChildren(FreeColXMLReader xr) throws XMLStreamException {
// Clear containers.
if (xr.shouldClearContainers()) {
scopes = null;
}
super.readChildren(xr);
}
/**
* {@inheritDoc}
*/
@Override
protected void readChild(FreeColXMLReader xr) throws XMLStreamException {
final String tag = xr.getLocalName();
if (Scope.getXMLElementTagName().equals(tag)) {
addScope(new Scope(xr));
} else {
super.readChild(xr);
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
|
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]
public class Effect extends FreeColGameObjectType {
// ... (many lines omitted for brevity)
/**
* Get the probability of this effect.
*
* @return The probability.
*/
public final int getProbability() {
return probability;
}
/**
* Get the scopes applicable to this effect.
*
* @return A list of <code>Scope</code>s.
*/
public final List<Scope> getScopes() {
return (scopes == null) ? Collections.<Scope>emptyList()
: scopes;
}
/**
* Add a scope.
*
* @param scope The <code>Scope</code> to add.
*/
private void addScope(Scope scope) {
if (scopes == null) scopes = new ArrayList<>();
scopes.add(scope);
}
/**
* Does at least one of this effect's scopes apply to an object.
*
* @param objectType The <code>FreeColGameObjectType</code> to check.
* @return True if this effect applies.
*/
public boolean appliesTo(final FreeColGameObjectType objectType) {
return (scopes == null || scopes.isEmpty()) ? true
: any(scopes, s -> s.appliesTo(objectType));
}
// Serialization
// ... (many lines omitted for brevity)
Cheatsheet (for next line):
- We are in a method that is likely related to serialization or deserialization.
- The method is writeAttributes(FreeColXMLWriter xw) and it is overriding a method from the superclass.
- The method is writing attributes of the current object to an XML writer.
- The method has already called super.writeAttributes(xw); to write the attributes of the superclass.
- The current object has a field named probability that needs to be written to the XML writer.
- The method is using a constant named PROBABILITY_TAG to identify the attribute in the XML.
Next line will likely be: xw.writeAttribute(PROBABILITY_TAG, probability);
|
|
Please complete the code given below.
import pytest
from csirtg_indicator import Indicator
from cif.store import Store
from cif.auth import Auth
from elasticsearch_dsl.connections import connections
import os
import arrow
from cifsdk.exceptions import AuthError
from pprint import pprint
import json
DISABLE_TESTS = True
if os.environ.get('CIF_ELASTICSEARCH_TEST'):
if os.environ['CIF_ELASTICSEARCH_TEST'] == '1':
DISABLE_TESTS = False
@pytest.fixture
def store():
try:
connections.get_connection().indices.delete(index='indicators-*')
connections.get_connection().indices.delete(index='tokens')
except Exception as e:
pass
with Store(store_type='elasticsearch', nodes='127.0.0.1:9200', hunter_token='abc123') as s:
s._load_plugin(nodes='127.0.0.1:9200')
yield s
try:
assert connections.get_connection().indices.delete(index='indicators-*')
assert connections.get_connection().indices.delete(index='tokens')
except Exception:
pass
@pytest.fixture
def auth():
with Auth(store_type='elasticsearch', nodes='127.0.0.1:9200') as a:
a._load_plugin(nodes='127.0.0.1:9200')
yield a
@pytest.fixture
def token(store):
t = store.store.tokens.create({
'username': u'test_admin',
'groups': [u'everyone'],
'read': u'1',
'write': u'1',
'admin': u'1'
})
assert t
yield t
@pytest.fixture
def indicator():
return Indicator(
indicator='example.com',
tags='botnet',
provider='csirtg.io',
group='everyone',
lasttime=arrow.utcnow().datetime,
reporttime=arrow.utcnow().datetime
)
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups1(store, auth, token, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff', 'everyone'],
'read': True,
'write': True
})
assert t
assert t['groups'] == ['staff', 'everyone']
assert t['write']
assert t['read']
assert not t.get('admin')
i = None
_t = auth.auth.handle_token_search(t['token'])
mtype = 'indicators_create'
data = json.dumps({
'indicator': 'example.com',
'group': 'staff2',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'reporttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
})
with pytest.raises(AuthError):
auth.check_token_perms(mtype, _t, data)
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(t, {'itype': 'fqdn'})
i = json.loads(i)
i = [i['_source'] for i in i['hits']['hits']]
assert len(list(i)) > 0
pprint(i)
i = store.handle_indicators_search(t, {'indicator': 'example.com'})
assert len(list(i)) > 0
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups2(store, auth, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff'],
'read': True,
'write': True
})
_t = auth.auth.handle_token_search(t['token'])
mtype = 'indicators_create'
data = json.dumps({
'indicator': 'example.com',
'group': 'staff2',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'reporttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
})
with pytest.raises(AuthError):
auth.check_token_perms(mtype, _t, data)
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups3(store, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff'],
'write': True
})
t2 = store.store.tokens.create({
'username': 'test',
'groups': ['staff2'],
'read': True,
})
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(t2, {'itype': 'fqdn'})
i = json.loads(i)
assert len(i) == 0
i = store.handle_indicators_search(t2, {'indicator': 'example.com'})
i = json.loads(i)
assert len(i) == 0
i = store.handle_indicators_search(t2, {'indicator': 'example.com', 'groups': 'staff'})
i = json.loads(i)
assert len(i) == 0
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups4(store, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff', 'staff2'],
'write': True,
'read': True
})
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff2',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(t, {'itype': 'fqdn', 'groups': 'staff'})
i = json.loads(i)
i = [i['_source'] for i in i['hits']['hits']]
assert len(i) == 1
# test hunter submit to any group
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups5(store, token, indicator):
t = store.store.tokens.create({
'username': 'hunter',
'groups': ['hunter_test'],
'token': 'abc123',
'write': True,
'read': False
})
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'everyone',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(token, {'itype': 'fqdn', 'groups': 'everyone'})
i = json.loads(i)
i = [i['_source'] for i in i['hits']['hits']]
assert len(i) == 1
# allow admin to access any group
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups6(store, token, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['private'],
'write': True,
'read': False
})
|
[
" i = store.handle_indicators_create(t, {"
] | 577
|
lcc
|
python
| null |
492de4fd744409d77007630f3cf7e7c49b13037cb2b2a8c6
| 41
|
Your task is code completion.
import pytest
from csirtg_indicator import Indicator
from cif.store import Store
from cif.auth import Auth
from elasticsearch_dsl.connections import connections
import os
import arrow
from cifsdk.exceptions import AuthError
from pprint import pprint
import json
DISABLE_TESTS = True
if os.environ.get('CIF_ELASTICSEARCH_TEST'):
if os.environ['CIF_ELASTICSEARCH_TEST'] == '1':
DISABLE_TESTS = False
@pytest.fixture
def store():
try:
connections.get_connection().indices.delete(index='indicators-*')
connections.get_connection().indices.delete(index='tokens')
except Exception as e:
pass
with Store(store_type='elasticsearch', nodes='127.0.0.1:9200', hunter_token='abc123') as s:
s._load_plugin(nodes='127.0.0.1:9200')
yield s
try:
assert connections.get_connection().indices.delete(index='indicators-*')
assert connections.get_connection().indices.delete(index='tokens')
except Exception:
pass
@pytest.fixture
def auth():
with Auth(store_type='elasticsearch', nodes='127.0.0.1:9200') as a:
a._load_plugin(nodes='127.0.0.1:9200')
yield a
@pytest.fixture
def token(store):
t = store.store.tokens.create({
'username': u'test_admin',
'groups': [u'everyone'],
'read': u'1',
'write': u'1',
'admin': u'1'
})
assert t
yield t
@pytest.fixture
def indicator():
return Indicator(
indicator='example.com',
tags='botnet',
provider='csirtg.io',
group='everyone',
lasttime=arrow.utcnow().datetime,
reporttime=arrow.utcnow().datetime
)
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups1(store, auth, token, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff', 'everyone'],
'read': True,
'write': True
})
assert t
assert t['groups'] == ['staff', 'everyone']
assert t['write']
assert t['read']
assert not t.get('admin')
i = None
_t = auth.auth.handle_token_search(t['token'])
mtype = 'indicators_create'
data = json.dumps({
'indicator': 'example.com',
'group': 'staff2',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'reporttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
})
with pytest.raises(AuthError):
auth.check_token_perms(mtype, _t, data)
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(t, {'itype': 'fqdn'})
i = json.loads(i)
i = [i['_source'] for i in i['hits']['hits']]
assert len(list(i)) > 0
pprint(i)
i = store.handle_indicators_search(t, {'indicator': 'example.com'})
assert len(list(i)) > 0
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups2(store, auth, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff'],
'read': True,
'write': True
})
_t = auth.auth.handle_token_search(t['token'])
mtype = 'indicators_create'
data = json.dumps({
'indicator': 'example.com',
'group': 'staff2',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'reporttime': arrow.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
})
with pytest.raises(AuthError):
auth.check_token_perms(mtype, _t, data)
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups3(store, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff'],
'write': True
})
t2 = store.store.tokens.create({
'username': 'test',
'groups': ['staff2'],
'read': True,
})
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(t2, {'itype': 'fqdn'})
i = json.loads(i)
assert len(i) == 0
i = store.handle_indicators_search(t2, {'indicator': 'example.com'})
i = json.loads(i)
assert len(i) == 0
i = store.handle_indicators_search(t2, {'indicator': 'example.com', 'groups': 'staff'})
i = json.loads(i)
assert len(i) == 0
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups4(store, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff', 'staff2'],
'write': True,
'read': True
})
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff2',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(t, {'itype': 'fqdn', 'groups': 'staff'})
i = json.loads(i)
i = [i['_source'] for i in i['hits']['hits']]
assert len(i) == 1
# test hunter submit to any group
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups5(store, token, indicator):
t = store.store.tokens.create({
'username': 'hunter',
'groups': ['hunter_test'],
'token': 'abc123',
'write': True,
'read': False
})
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'everyone',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(token, {'itype': 'fqdn', 'groups': 'everyone'})
i = json.loads(i)
i = [i['_source'] for i in i['hits']['hits']]
assert len(i) == 1
# allow admin to access any group
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups6(store, token, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['private'],
'write': True,
'read': False
})
|
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]
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups4(store, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff', 'staff2'],
'write': True,
'read': True
})
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff2',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(t, {'itype': 'fqdn', 'groups': 'staff'})
i = json.loads(i)
i = [i['_source'] for i in i['hits']['hits']]
assert len(i) == 1
Cheatsheet (for next line):
- We are in a test function, specifically test_store_elasticsearch_tokens_groups4.
- The test function is testing the functionality of the store's handle_indicators_search method.
- The method is called with a token t, which has groups ['staff', 'staff2].
- The search query is {'itype': 'fqdn', 'groups': 'staff'}.
- The expected result is that the search should return 1 indicator.
- The current result is stored in the variable i, which is a list of indicators.
- The length of the list i is compared to 1 using the assert statement.
Next line will likely be:
assert len(i) == 1 (already present in the code)
However, the task is to write a new test case for the same function. The new test case should test the scenario where the token has groups ['staff', 'staff2] and the search query is {'itype': 'fqdn', 'groups': 'staff2'}.
New test case:
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CIF_ELASTICSEARCH_TEST=1 to run')
def test_store_elasticsearch_tokens_groups7(store, indicator):
t = store.store.tokens.create({
'username': 'test',
'groups': ['staff', 'staff2'],
'write': True,
'read': True
})
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_create(t, {
'indicator': 'example.com',
'group': 'staff2',
'provider': 'example.com',
'tags': ['test'],
'itype': 'fqdn',
'lasttime': arrow.utcnow().datetime,
'reporttime': arrow.utcnow().datetime
}, flush=True)
assert i
i = store.handle_indicators_search(t, {'itype': 'fqdn', 'groups': 'staff2'})
i = json.loads(i)
i = [i['_source'] for i in i['hits']['hits']]
assert len(i) == 1
|
|
Please complete the code given below.
# -*- coding: utf-8 -*-
import sys
sys.path[0:0] = [""]
import unittest
from bson import SON
from mongoengine import *
from mongoengine.connection import get_db
__all__ = ("DeltaTest",)
class DeltaTest(unittest.TestCase):
def setUp(self):
connect(db='mongoenginetest')
self.db = get_db()
class Person(Document):
name = StringField()
age = IntField()
non_field = True
meta = {"allow_inheritance": True}
self.Person = Person
def tearDown(self):
for collection in self.db.collection_names():
if 'system.' in collection:
continue
self.db.drop_collection(collection)
def test_delta(self):
self.delta(Document)
self.delta(DynamicDocument)
def delta(self, DocClass):
class Doc(DocClass):
string_field = StringField()
int_field = IntField()
dict_field = DictField()
list_field = ListField()
Doc.drop_collection()
doc = Doc()
doc.save()
doc = Doc.objects.first()
self.assertEqual(doc._get_changed_fields(), [])
self.assertEqual(doc._delta(), ({}, {}))
doc.string_field = 'hello'
self.assertEqual(doc._get_changed_fields(), ['string_field'])
self.assertEqual(doc._delta(), ({'string_field': 'hello'}, {}))
doc._changed_fields = []
doc.int_field = 1
self.assertEqual(doc._get_changed_fields(), ['int_field'])
self.assertEqual(doc._delta(), ({'int_field': 1}, {}))
doc._changed_fields = []
dict_value = {'hello': 'world', 'ping': 'pong'}
doc.dict_field = dict_value
self.assertEqual(doc._get_changed_fields(), ['dict_field'])
self.assertEqual(doc._delta(), ({'dict_field': dict_value}, {}))
doc._changed_fields = []
list_value = ['1', 2, {'hello': 'world'}]
doc.list_field = list_value
self.assertEqual(doc._get_changed_fields(), ['list_field'])
self.assertEqual(doc._delta(), ({'list_field': list_value}, {}))
# Test unsetting
doc._changed_fields = []
doc.dict_field = {}
self.assertEqual(doc._get_changed_fields(), ['dict_field'])
self.assertEqual(doc._delta(), ({}, {'dict_field': 1}))
doc._changed_fields = []
doc.list_field = []
self.assertEqual(doc._get_changed_fields(), ['list_field'])
self.assertEqual(doc._delta(), ({}, {'list_field': 1}))
def test_delta_recursive(self):
self.delta_recursive(Document, EmbeddedDocument)
self.delta_recursive(DynamicDocument, EmbeddedDocument)
self.delta_recursive(Document, DynamicEmbeddedDocument)
self.delta_recursive(DynamicDocument, DynamicEmbeddedDocument)
def delta_recursive(self, DocClass, EmbeddedClass):
class Embedded(EmbeddedClass):
string_field = StringField()
int_field = IntField()
dict_field = DictField()
list_field = ListField()
class Doc(DocClass):
string_field = StringField()
int_field = IntField()
dict_field = DictField()
list_field = ListField()
embedded_field = EmbeddedDocumentField(Embedded)
Doc.drop_collection()
doc = Doc()
doc.save()
doc = Doc.objects.first()
self.assertEqual(doc._get_changed_fields(), [])
self.assertEqual(doc._delta(), ({}, {}))
embedded_1 = Embedded()
embedded_1.string_field = 'hello'
embedded_1.int_field = 1
embedded_1.dict_field = {'hello': 'world'}
embedded_1.list_field = ['1', 2, {'hello': 'world'}]
doc.embedded_field = embedded_1
self.assertEqual(doc._get_changed_fields(), ['embedded_field'])
embedded_delta = {
'string_field': 'hello',
'int_field': 1,
'dict_field': {'hello': 'world'},
'list_field': ['1', 2, {'hello': 'world'}]
}
self.assertEqual(doc.embedded_field._delta(), (embedded_delta, {}))
self.assertEqual(doc._delta(),
({'embedded_field': embedded_delta}, {}))
doc.save()
doc = doc.reload(10)
doc.embedded_field.dict_field = {}
self.assertEqual(doc._get_changed_fields(),
['embedded_field.dict_field'])
self.assertEqual(doc.embedded_field._delta(), ({}, {'dict_field': 1}))
self.assertEqual(doc._delta(), ({}, {'embedded_field.dict_field': 1}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.dict_field, {})
doc.embedded_field.list_field = []
self.assertEqual(doc._get_changed_fields(),
['embedded_field.list_field'])
self.assertEqual(doc.embedded_field._delta(), ({}, {'list_field': 1}))
self.assertEqual(doc._delta(), ({}, {'embedded_field.list_field': 1}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field, [])
embedded_2 = Embedded()
embedded_2.string_field = 'hello'
embedded_2.int_field = 1
embedded_2.dict_field = {'hello': 'world'}
embedded_2.list_field = ['1', 2, {'hello': 'world'}]
doc.embedded_field.list_field = ['1', 2, embedded_2]
self.assertEqual(doc._get_changed_fields(),
['embedded_field.list_field'])
self.assertEqual(doc.embedded_field._delta(), ({
'list_field': ['1', 2, {
'_cls': 'Embedded',
'string_field': 'hello',
'dict_field': {'hello': 'world'},
'int_field': 1,
'list_field': ['1', 2, {'hello': 'world'}],
}]
}, {}))
self.assertEqual(doc._delta(), ({
'embedded_field.list_field': ['1', 2, {
'_cls': 'Embedded',
'string_field': 'hello',
'dict_field': {'hello': 'world'},
'int_field': 1,
'list_field': ['1', 2, {'hello': 'world'}],
}]
}, {}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[0], '1')
self.assertEqual(doc.embedded_field.list_field[1], 2)
for k in doc.embedded_field.list_field[2]._fields:
self.assertEqual(doc.embedded_field.list_field[2][k],
embedded_2[k])
doc.embedded_field.list_field[2].string_field = 'world'
self.assertEqual(doc._get_changed_fields(),
['embedded_field.list_field.2.string_field'])
self.assertEqual(doc.embedded_field._delta(),
({'list_field.2.string_field': 'world'}, {}))
self.assertEqual(doc._delta(),
({'embedded_field.list_field.2.string_field': 'world'}, {}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[2].string_field,
'world')
# Test multiple assignments
doc.embedded_field.list_field[2].string_field = 'hello world'
doc.embedded_field.list_field[2] = doc.embedded_field.list_field[2]
self.assertEqual(doc._get_changed_fields(),
['embedded_field.list_field'])
self.assertEqual(doc.embedded_field._delta(), ({
'list_field': ['1', 2, {
'_cls': 'Embedded',
'string_field': 'hello world',
'int_field': 1,
'list_field': ['1', 2, {'hello': 'world'}],
'dict_field': {'hello': 'world'}}]}, {}))
self.assertEqual(doc._delta(), ({
'embedded_field.list_field': ['1', 2, {
'_cls': 'Embedded',
'string_field': 'hello world',
'int_field': 1,
'list_field': ['1', 2, {'hello': 'world'}],
'dict_field': {'hello': 'world'}}
]}, {}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[2].string_field,
'hello world')
# Test list native methods
doc.embedded_field.list_field[2].list_field.pop(0)
self.assertEqual(doc._delta(),
({'embedded_field.list_field.2.list_field':
[2, {'hello': 'world'}]}, {}))
doc.save()
doc = doc.reload(10)
doc.embedded_field.list_field[2].list_field.append(1)
self.assertEqual(doc._delta(),
({'embedded_field.list_field.2.list_field':
[2, {'hello': 'world'}, 1]}, {}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[2].list_field,
[2, {'hello': 'world'}, 1])
doc.embedded_field.list_field[2].list_field.sort(key=str)
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[2].list_field,
[1, 2, {'hello': 'world'}])
del(doc.embedded_field.list_field[2].list_field[2]['hello'])
self.assertEqual(doc._delta(),
({'embedded_field.list_field.2.list_field': [1, 2, {}]}, {}))
doc.save()
doc = doc.reload(10)
del(doc.embedded_field.list_field[2].list_field)
self.assertEqual(doc._delta(),
({}, {'embedded_field.list_field.2.list_field': 1}))
doc.save()
doc = doc.reload(10)
doc.dict_field['Embedded'] = embedded_1
doc.save()
doc = doc.reload(10)
doc.dict_field['Embedded'].string_field = 'Hello World'
self.assertEqual(doc._get_changed_fields(),
['dict_field.Embedded.string_field'])
self.assertEqual(doc._delta(),
({'dict_field.Embedded.string_field': 'Hello World'}, {}))
def test_circular_reference_deltas(self):
self.circular_reference_deltas(Document, Document)
self.circular_reference_deltas(Document, DynamicDocument)
self.circular_reference_deltas(DynamicDocument, Document)
self.circular_reference_deltas(DynamicDocument, DynamicDocument)
def circular_reference_deltas(self, DocClass1, DocClass2):
class Person(DocClass1):
name = StringField()
owns = ListField(ReferenceField('Organization'))
class Organization(DocClass2):
name = StringField()
owner = ReferenceField('Person')
Person.drop_collection()
Organization.drop_collection()
person = Person(name="owner").save()
organization = Organization(name="company").save()
person.owns.append(organization)
organization.owner = person
person.save()
organization.save()
p = Person.objects[0].select_related()
o = Organization.objects.first()
self.assertEqual(p.owns[0], o)
self.assertEqual(o.owner, p)
def test_circular_reference_deltas_2(self):
self.circular_reference_deltas_2(Document, Document)
self.circular_reference_deltas_2(Document, DynamicDocument)
self.circular_reference_deltas_2(DynamicDocument, Document)
self.circular_reference_deltas_2(DynamicDocument, DynamicDocument)
def circular_reference_deltas_2(self, DocClass1, DocClass2, dbref=True):
class Person(DocClass1):
name = StringField()
owns = ListField(ReferenceField('Organization', dbref=dbref))
employer = ReferenceField('Organization', dbref=dbref)
class Organization(DocClass2):
name = StringField()
owner = ReferenceField('Person', dbref=dbref)
employees = ListField(ReferenceField('Person', dbref=dbref))
Person.drop_collection()
Organization.drop_collection()
person = Person(name="owner").save()
employee = Person(name="employee").save()
organization = Organization(name="company").save()
person.owns.append(organization)
organization.owner = person
organization.employees.append(employee)
employee.employer = organization
person.save()
organization.save()
employee.save()
|
[
" p = Person.objects.get(name=\"owner\")"
] | 701
|
lcc
|
python
| null |
a507514e59d02bec9d48f262b48dffcb180b6665ae945f96
| 42
|
Your task is code completion.
# -*- coding: utf-8 -*-
import sys
sys.path[0:0] = [""]
import unittest
from bson import SON
from mongoengine import *
from mongoengine.connection import get_db
__all__ = ("DeltaTest",)
class DeltaTest(unittest.TestCase):
def setUp(self):
connect(db='mongoenginetest')
self.db = get_db()
class Person(Document):
name = StringField()
age = IntField()
non_field = True
meta = {"allow_inheritance": True}
self.Person = Person
def tearDown(self):
for collection in self.db.collection_names():
if 'system.' in collection:
continue
self.db.drop_collection(collection)
def test_delta(self):
self.delta(Document)
self.delta(DynamicDocument)
def delta(self, DocClass):
class Doc(DocClass):
string_field = StringField()
int_field = IntField()
dict_field = DictField()
list_field = ListField()
Doc.drop_collection()
doc = Doc()
doc.save()
doc = Doc.objects.first()
self.assertEqual(doc._get_changed_fields(), [])
self.assertEqual(doc._delta(), ({}, {}))
doc.string_field = 'hello'
self.assertEqual(doc._get_changed_fields(), ['string_field'])
self.assertEqual(doc._delta(), ({'string_field': 'hello'}, {}))
doc._changed_fields = []
doc.int_field = 1
self.assertEqual(doc._get_changed_fields(), ['int_field'])
self.assertEqual(doc._delta(), ({'int_field': 1}, {}))
doc._changed_fields = []
dict_value = {'hello': 'world', 'ping': 'pong'}
doc.dict_field = dict_value
self.assertEqual(doc._get_changed_fields(), ['dict_field'])
self.assertEqual(doc._delta(), ({'dict_field': dict_value}, {}))
doc._changed_fields = []
list_value = ['1', 2, {'hello': 'world'}]
doc.list_field = list_value
self.assertEqual(doc._get_changed_fields(), ['list_field'])
self.assertEqual(doc._delta(), ({'list_field': list_value}, {}))
# Test unsetting
doc._changed_fields = []
doc.dict_field = {}
self.assertEqual(doc._get_changed_fields(), ['dict_field'])
self.assertEqual(doc._delta(), ({}, {'dict_field': 1}))
doc._changed_fields = []
doc.list_field = []
self.assertEqual(doc._get_changed_fields(), ['list_field'])
self.assertEqual(doc._delta(), ({}, {'list_field': 1}))
def test_delta_recursive(self):
self.delta_recursive(Document, EmbeddedDocument)
self.delta_recursive(DynamicDocument, EmbeddedDocument)
self.delta_recursive(Document, DynamicEmbeddedDocument)
self.delta_recursive(DynamicDocument, DynamicEmbeddedDocument)
def delta_recursive(self, DocClass, EmbeddedClass):
class Embedded(EmbeddedClass):
string_field = StringField()
int_field = IntField()
dict_field = DictField()
list_field = ListField()
class Doc(DocClass):
string_field = StringField()
int_field = IntField()
dict_field = DictField()
list_field = ListField()
embedded_field = EmbeddedDocumentField(Embedded)
Doc.drop_collection()
doc = Doc()
doc.save()
doc = Doc.objects.first()
self.assertEqual(doc._get_changed_fields(), [])
self.assertEqual(doc._delta(), ({}, {}))
embedded_1 = Embedded()
embedded_1.string_field = 'hello'
embedded_1.int_field = 1
embedded_1.dict_field = {'hello': 'world'}
embedded_1.list_field = ['1', 2, {'hello': 'world'}]
doc.embedded_field = embedded_1
self.assertEqual(doc._get_changed_fields(), ['embedded_field'])
embedded_delta = {
'string_field': 'hello',
'int_field': 1,
'dict_field': {'hello': 'world'},
'list_field': ['1', 2, {'hello': 'world'}]
}
self.assertEqual(doc.embedded_field._delta(), (embedded_delta, {}))
self.assertEqual(doc._delta(),
({'embedded_field': embedded_delta}, {}))
doc.save()
doc = doc.reload(10)
doc.embedded_field.dict_field = {}
self.assertEqual(doc._get_changed_fields(),
['embedded_field.dict_field'])
self.assertEqual(doc.embedded_field._delta(), ({}, {'dict_field': 1}))
self.assertEqual(doc._delta(), ({}, {'embedded_field.dict_field': 1}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.dict_field, {})
doc.embedded_field.list_field = []
self.assertEqual(doc._get_changed_fields(),
['embedded_field.list_field'])
self.assertEqual(doc.embedded_field._delta(), ({}, {'list_field': 1}))
self.assertEqual(doc._delta(), ({}, {'embedded_field.list_field': 1}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field, [])
embedded_2 = Embedded()
embedded_2.string_field = 'hello'
embedded_2.int_field = 1
embedded_2.dict_field = {'hello': 'world'}
embedded_2.list_field = ['1', 2, {'hello': 'world'}]
doc.embedded_field.list_field = ['1', 2, embedded_2]
self.assertEqual(doc._get_changed_fields(),
['embedded_field.list_field'])
self.assertEqual(doc.embedded_field._delta(), ({
'list_field': ['1', 2, {
'_cls': 'Embedded',
'string_field': 'hello',
'dict_field': {'hello': 'world'},
'int_field': 1,
'list_field': ['1', 2, {'hello': 'world'}],
}]
}, {}))
self.assertEqual(doc._delta(), ({
'embedded_field.list_field': ['1', 2, {
'_cls': 'Embedded',
'string_field': 'hello',
'dict_field': {'hello': 'world'},
'int_field': 1,
'list_field': ['1', 2, {'hello': 'world'}],
}]
}, {}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[0], '1')
self.assertEqual(doc.embedded_field.list_field[1], 2)
for k in doc.embedded_field.list_field[2]._fields:
self.assertEqual(doc.embedded_field.list_field[2][k],
embedded_2[k])
doc.embedded_field.list_field[2].string_field = 'world'
self.assertEqual(doc._get_changed_fields(),
['embedded_field.list_field.2.string_field'])
self.assertEqual(doc.embedded_field._delta(),
({'list_field.2.string_field': 'world'}, {}))
self.assertEqual(doc._delta(),
({'embedded_field.list_field.2.string_field': 'world'}, {}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[2].string_field,
'world')
# Test multiple assignments
doc.embedded_field.list_field[2].string_field = 'hello world'
doc.embedded_field.list_field[2] = doc.embedded_field.list_field[2]
self.assertEqual(doc._get_changed_fields(),
['embedded_field.list_field'])
self.assertEqual(doc.embedded_field._delta(), ({
'list_field': ['1', 2, {
'_cls': 'Embedded',
'string_field': 'hello world',
'int_field': 1,
'list_field': ['1', 2, {'hello': 'world'}],
'dict_field': {'hello': 'world'}}]}, {}))
self.assertEqual(doc._delta(), ({
'embedded_field.list_field': ['1', 2, {
'_cls': 'Embedded',
'string_field': 'hello world',
'int_field': 1,
'list_field': ['1', 2, {'hello': 'world'}],
'dict_field': {'hello': 'world'}}
]}, {}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[2].string_field,
'hello world')
# Test list native methods
doc.embedded_field.list_field[2].list_field.pop(0)
self.assertEqual(doc._delta(),
({'embedded_field.list_field.2.list_field':
[2, {'hello': 'world'}]}, {}))
doc.save()
doc = doc.reload(10)
doc.embedded_field.list_field[2].list_field.append(1)
self.assertEqual(doc._delta(),
({'embedded_field.list_field.2.list_field':
[2, {'hello': 'world'}, 1]}, {}))
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[2].list_field,
[2, {'hello': 'world'}, 1])
doc.embedded_field.list_field[2].list_field.sort(key=str)
doc.save()
doc = doc.reload(10)
self.assertEqual(doc.embedded_field.list_field[2].list_field,
[1, 2, {'hello': 'world'}])
del(doc.embedded_field.list_field[2].list_field[2]['hello'])
self.assertEqual(doc._delta(),
({'embedded_field.list_field.2.list_field': [1, 2, {}]}, {}))
doc.save()
doc = doc.reload(10)
del(doc.embedded_field.list_field[2].list_field)
self.assertEqual(doc._delta(),
({}, {'embedded_field.list_field.2.list_field': 1}))
doc.save()
doc = doc.reload(10)
doc.dict_field['Embedded'] = embedded_1
doc.save()
doc = doc.reload(10)
doc.dict_field['Embedded'].string_field = 'Hello World'
self.assertEqual(doc._get_changed_fields(),
['dict_field.Embedded.string_field'])
self.assertEqual(doc._delta(),
({'dict_field.Embedded.string_field': 'Hello World'}, {}))
def test_circular_reference_deltas(self):
self.circular_reference_deltas(Document, Document)
self.circular_reference_deltas(Document, DynamicDocument)
self.circular_reference_deltas(DynamicDocument, Document)
self.circular_reference_deltas(DynamicDocument, DynamicDocument)
def circular_reference_deltas(self, DocClass1, DocClass2):
class Person(DocClass1):
name = StringField()
owns = ListField(ReferenceField('Organization'))
class Organization(DocClass2):
name = StringField()
owner = ReferenceField('Person')
Person.drop_collection()
Organization.drop_collection()
person = Person(name="owner").save()
organization = Organization(name="company").save()
person.owns.append(organization)
organization.owner = person
person.save()
organization.save()
p = Person.objects[0].select_related()
o = Organization.objects.first()
self.assertEqual(p.owns[0], o)
self.assertEqual(o.owner, p)
def test_circular_reference_deltas_2(self):
self.circular_reference_deltas_2(Document, Document)
self.circular_reference_deltas_2(Document, DynamicDocument)
self.circular_reference_deltas_2(DynamicDocument, Document)
self.circular_reference_deltas_2(DynamicDocument, DynamicDocument)
def circular_reference_deltas_2(self, DocClass1, DocClass2, dbref=True):
class Person(DocClass1):
name = StringField()
owns = ListField(ReferenceField('Organization', dbref=dbref))
employer = ReferenceField('Organization', dbref=dbref)
class Organization(DocClass2):
name = StringField()
owner = ReferenceField('Person', dbref=dbref)
employees = ListField(ReferenceField('Person', dbref=dbref))
Person.drop_collection()
Organization.drop_collection()
person = Person(name="owner").save()
employee = Person(name="employee").save()
organization = Organization(name="company").save()
person.owns.append(organization)
organization.owner = person
organization.employees.append(employee)
employee.employer = organization
person.save()
organization.save()
employee.save()
|
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_circular_reference_deltas_2(self):
self.circular_reference_deltas_2(Document, Document)
self.circular_reference_deltas_2(Document, DynamicDocument)
self.circular_reference_deltas_2(DynamicDocument, Document)
self.circular_reference_deltas_2(DynamicDocument, DynamicDocument)
def circular_reference_deltas_2(self, DocClass1, DocClass2, dbref=True):
class Person(DocClass1):
name = StringField()
owns = ListField(ReferenceField('Organization', dbref=dbref))
employer = ReferenceField('Organization', dbref=dbref)
class Organization(DocClass2):
name = StringField()
owner = ReferenceField('Person', dbref=dbref)
employees = ListField(ReferenceField('Person', dbref=dbref))
Person.drop_collection()
Organization.drop_collection()
person = Person(name="owner").save()
employee = Person(name="employee").save()
organization = Organization(name="company").save()
person.owns.append(organization)
organization.owner = person
organization.employees.append(employee)
employee.employer = organization
person.save()
organization.save()
employee.save()
Relevant lines and variables:
- We are in the method `circular_reference_deltas_2`.
- The method has three parameters: `DocClass1`, `DocClass2`, and `dbref`.
- The method is testing circular references between `Person` and `Organization` documents.
- The `dbref` parameter is a boolean flag that determines whether to use database references.
- The `Person` and `Organization` classes are defined within the method.
- The `Person` class has fields `owns`, `employer`, and `name`.
- The `Organization` class has fields `owner`, `employees`, and `name`.
Based on this context, the next line of code is likely to be a test case for the circular reference deltas. The test case should cover the scenario where the `dbref` parameter is set to `False`.
Next line of code:
```python
self.circular_reference_deltas_2(DynamicDocument, DynamicDocument, dbref=False)
```
|
|
Please complete the code given below.
import os.path
import bokeh
import bokeh.io
import bokeh.model
import bokeh.plotting
import bokeh.util.platform
import ipywidgets as widgets
import matplotlib.pyplot as plt
import numpy as np
import pyproj
from IPython.display import display
from bokeh.models import ColumnDataSource, Circle
from bokeh.tile_providers import STAMEN_TERRAIN
from ipywidgets import interact, fixed
from matplotlib.collections import LineCollection, PolyCollection
# noinspection PyUnresolvedReferences
from mpl_toolkits.mplot3d import Axes3D
from netCDF4 import Dataset, num2date
from numpy import ndarray
from .figurewriter import FigureWriter
# (Plotting) Resources:
# * http://matplotlib.org/api/pyplot_api.html
# * http://matplotlib.org/users/image_tutorial.html
# * http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#d-plots-in-3d
# * http://ipywidgets.readthedocs.io/en/latest/
# * http://bokeh.pydata.org/en/0.11.1/docs/user_guide/geo.html
# * http://bokeh.pydata.org/en/0.11.1/docs/user_guide/notebook.html
def inspect_l1b_product(product_file_path, output_path=None, output_format=None) -> 'L1bProductInspector':
"""
Open a L1B product for inspection.
If *output_format* is "dir" then a new directory given by *output_path*
will be created. Each plot figure will will be saved in a new file.
If *output_format* is "pdf" then a new multi-page PDF document given by *output_path*
will be created or overwritten if it exists. Each plot figure will will be saved in a new PDF page.
Format "pdf" does not support all plot types.
If *output_format* is not given it defaults it is derived from *output_path*.
Note that both *output_path* and *output_format* arguments are ignored if the inspection is run in an
Jupyter (IPython) Notebook.
:param product_file_path: The file path of the LB product.
:param output_path: The output path where plot figures are written to.
:param output_format: The output format. Supported formats are "pdf" and "dir".
"""
if output_path:
figure_writer = FigureWriter(output_path, output_format)
else:
bokeh.io.output_notebook(hide_banner=True)
figure_writer = None
return L1bProductInspector(product_file_path, figure_writer)
class L1bProductInspector:
"""
The `L1bInspector` class provides access to L1B contents and provides a number of analysis functions.
"""
def __init__(self, product_file_path, figure_writer: FigureWriter):
if not product_file_path:
raise ValueError('product_file_path must be given')
self._plot = L1bProductInspectorPlots(self, figure_writer)
self._file_path = product_file_path
dataset = Dataset(product_file_path)
self._dataset = dataset
self.dim_names = sorted(list(dataset.dimensions.keys()))
self.var_names = sorted(list(dataset.variables))
if 'time_l1bs_echo_sar_ku' in self.var_names:
product_type = 'l1bs'
print('WARNING: L1BS product inspection not yet fully supported.')
elif 'time_l1b_echo_sar_ku' in self.var_names:
product_type = 'l1b'
else:
raise ValueError('"%s" is neither a supported L1B nor L1BS product' % product_file_path)
self.dim_name_to_size = {}
for name, dim in dataset.dimensions.items():
self.dim_name_to_size[name] = dim.size
self.dim_names_to_var_names = {}
for v in dataset.variables:
dims = tuple(dataset[v].dimensions)
if dims in self.dim_names_to_var_names:
self.dim_names_to_var_names[dims].add(v)
else:
self.dim_names_to_var_names[dims] = {v}
self.attributes = {name: dataset.getncattr(name) for name in dataset.ncattrs()}
self.lat = dataset['lat_%s_echo_sar_ku' % product_type][:]
self.lon = dataset['lon_%s_echo_sar_ku' % product_type][:]
self.lat_0 = self.lat.mean()
self.lon_0 = self.lon.mean()
self.lat_range = self.lat.min(), self.lat.max()
self.lon_range = self.lon.min(), self.lon.max()
time_var = dataset['time_%s_echo_sar_ku' % product_type]
time = time_var[:]
self.time = num2date(time, time_var.units, calendar=time_var.calendar)
self.time_0 = num2date(time.mean(), time_var.units, calendar=time_var.calendar)
self.time_range = self.time.min(), self.time.max()
waveform_counts = dataset['i2q2_meas_ku_%s_echo_sar_ku' % product_type][:]
waveform_scaling = dataset['scale_factor_ku_%s_echo_sar_ku' % product_type][:]
waveform_scaling = waveform_scaling.reshape(waveform_scaling.shape + (1,))
self._waveform = waveform_scaling * waveform_counts
self.waveform_range = self.waveform.min(), self.waveform.max()
self.num_times = waveform_counts.shape[0]
self.num_samples = waveform_counts.shape[1]
self.echo_sample_ind = np.arange(0, self.num_samples)
@property
def file_path(self) -> str:
"""
Get the L1b file path.
"""
return self._file_path
@property
def plot(self) -> 'L1bProductInspectorPlots':
"""
Get the plotting context.
"""
return self._plot
@property
def dataset(self) -> Dataset:
"""
Get the underlying netCDF dataset object.
"""
return self._dataset
@property
def waveform(self) -> ndarray:
"""
Get the pre-scaled waveform array.
"""
return self._waveform
def close(self):
"""Close the underlying dataset's file access."""
self._dataset.close()
self._plot.close()
class L1bProductInspectorPlots:
def __init__(self, inspector: 'L1bProductInspector', figure_writer: FigureWriter):
self._inspector = inspector
self._interactive = figure_writer is None
self._figure_writer = figure_writer
def locations(self, color='blue'):
"""
Plot product locations as circles onto a world map.
"""
# Spherical Mercator
mercator = pyproj.Proj(init='epsg:3857')
# Equirectangular lat/lon on WGS84
equirectangular = pyproj.Proj(init='epsg:4326')
lon = self._inspector.lon
lat = self._inspector.lat
x, y = pyproj.transform(equirectangular, mercator, lon, lat)
# print(list(zip(lon, lat)))
# print(list(zip(x, y)))
source = ColumnDataSource(data=dict(x=x, y=y))
circle = Circle(x='x', y='y', size=6, fill_color=color, fill_alpha=0.5, line_color=None)
# map_options = GMapOptions(lat=30.29, lng=-97.73, map_type="roadmap", zoom=11)
# plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options)
# plot.title.text = 'L1B Footprint'
# plot.add_glyph(source, circle)
# plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
fig = bokeh.plotting.figure(x_range=(x.min(), x.max()), y_range=(y.min(), y.max()), toolbar_location='above')
fig.axis.visible = False
# fig.add_tile(STAMEN_TONER)
fig.add_tile(STAMEN_TERRAIN)
fig.title.text = 'L1B Locations'
# fig.title = 'L1B Footprint'
fig.add_glyph(source, circle)
if self._interactive:
bokeh.io.show(fig)
elif self._figure_writer.output_format == "dir":
os.makedirs(self._figure_writer.output_path, exist_ok=True)
bokeh.io.save(fig, os.path.join(self._figure_writer.output_path, 'fig-locations.html'),
title='L1B Locations')
else:
print('warning: cannot save locations figure with output format "%s"' % self._figure_writer.output_format)
def waveform_im(self, vmin=None, vmax=None, cmap='jet'):
vmin = vmin if vmin else self._inspector.waveform_range[0]
vmax = vmax if vmax else self._inspector.waveform_range[1]
plt.figure(figsize=(10, 10))
plt.imshow(self._inspector.waveform, interpolation='nearest', aspect='auto', vmin=vmin, vmax=vmax, cmap=cmap)
plt.xlabel('Echo Sample Index')
plt.ylabel('Time Index')
plt.title('Waveform')
plt.colorbar(orientation='vertical')
if self._interactive:
plt.show()
else:
self.savefig("fig-waveform-im.png")
def waveform_3d_surf(self, zmin=0, zmax=None, cmap='jet'):
self._waveform_3d(fig_type='surf', zmin=zmin, zmax=zmax, alpha=1, cmap=cmap)
def waveform_3d_poly(self, zmin=0, zmax=None, alpha=0.5, cmap='jet'):
self._waveform_3d(fig_type='poly', zmin=zmin, zmax=zmax, alpha=alpha, cmap=cmap)
def waveform_3d_line(self, zmin=0, zmax=None, alpha=0.5, cmap='jet'):
self._waveform_3d(fig_type='line', zmin=zmin, zmax=zmax, alpha=alpha, cmap=cmap)
def _waveform_3d(self, fig_type, zmin, zmax, alpha, cmap):
fig = plt.figure(figsize=(10, 10))
ax = fig.gca(projection='3d')
num_times = self._inspector.num_times
num_samples = self._inspector.num_samples
if fig_type == 'surf':
x = np.arange(0, num_samples)
y = np.arange(0, num_times)
x, y = np.meshgrid(x, y)
z = self._inspector.waveform
surf = ax.plot_surface(x, y, z, rstride=3, cstride=3, cmap=cmap, shade=True,
linewidth=0, antialiased=False)
# ax.zaxis.set_major_locator(LinearLocator(10))
# ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
else:
waveforms = []
for y_index in range(num_times):
waveform = np.ndarray(shape=(num_samples, 2), dtype=np.float64)
waveform[:, 0] = np.arange(0, num_samples)
waveform[:, 1] = self._inspector.waveform[y_index]
waveforms.append(waveform)
line_widths = [0.5] * num_times
# TODO (forman, 20160725): check why cmap is not recognized
if fig_type == 'poly':
edge_colors = ((0.2, 0.2, 1., 0.7),) * num_times
face_colors = ((1., 1., 1., 0.5),) * num_times
collection = PolyCollection(waveforms, cmap=cmap,
linewidths=line_widths,
edgecolors=edge_colors,
facecolors=face_colors)
else:
colors = ((0.2, 0.2, 1., 0.7),) * num_times
collection = LineCollection(waveforms, cmap=cmap,
linewidths=line_widths, colors=colors)
collection.set_alpha(alpha)
ax.add_collection3d(collection, zs=np.arange(0, num_times), zdir='y')
wf_min, wf_max = self._inspector.waveform_range
ax.set_xlabel('Echo Sample Index')
ax.set_xlim3d(0, num_samples - 1)
ax.set_ylabel('Time Index')
ax.set_ylim3d(0, num_times - 1)
ax.set_zlabel('Waveform')
ax.set_zlim3d(zmin if zmin is not None else wf_min, zmax if zmax is not None else wf_max)
if self._interactive:
plt.show()
else:
self.savefig("fig-waveform-3d-%s.png" % fig_type)
def waveform_hist(self, vmin=None, vmax=None, bins=128, log=False, color='green'):
"""
Draw waveform histogram.
:param vmin: Minimum display value
:param vmax: Maximum display value
:param bins: Number of bins
:param log: Show logarithms of bin counts
:param color: Color of the histogram bars, e.g. 'green'
"""
vmin = vmin if vmin else self._inspector.waveform_range[0]
vmax = vmax if vmax else self._inspector.waveform_range[1]
vmax = vmin + 1 if vmin == vmax else vmax
plt.figure(figsize=(12, 6))
plt.hist(self._inspector.waveform.flatten(),
range=(vmin, vmax),
bins=bins,
log=log,
facecolor=color,
alpha=1,
normed=True)
plt.xlabel('Waveform')
plt.ylabel('Counts')
plt.title('Waveform Histogram')
plt.grid(True)
if self._interactive:
plt.show()
else:
self.savefig("fig-waveform-hist.png")
def waveform_line(self, ind=None, ref_ind=None):
"""
Draw waveform 2D line plot.
:param ind: Time index
:param ref_ind: Reference time index
"""
if ind is None and self._interactive:
interact(self._plot_waveform_line, ind=(0, self._inspector.num_times - 1), ref_ind=fixed(ref_ind))
else:
self._plot_waveform_line(ind=ind if ind else 0, ref_ind=ref_ind)
def _plot_waveform_line(self, ind: int, ref_ind=None):
plt.figure(figsize=(12, 6))
plt.plot(self._inspector.echo_sample_ind, self._inspector.waveform[ind], 'b-')
plt.xlabel('Echo Sample Index')
plt.ylabel('Waveform')
plt.title('Waveform at #%s' % ind)
plt.grid(True)
if ref_ind is not None:
plt.plot(self._inspector.echo_sample_ind, self._inspector.waveform[ref_ind], 'r-', label='ref')
plt.legend(['#%s' % ind, '#%s' % ref_ind])
if self._interactive:
plt.show()
else:
self.savefig("fig-waveform-x-%d.png" % ind)
def im(self, z=None, zmin=None, zmax=None, cmap='jet'):
if z is None:
if self._interactive:
name_options = list()
for dim_names, var_names in self._inspector.dim_names_to_var_names.items():
no_zero_dim = all([self._inspector.dim_name_to_size[dim] > 0 for dim in dim_names])
if no_zero_dim and len(dim_names) == 2:
name_options.extend(var_names)
name_options = sorted(name_options)
# TODO (forman, 20160709): add sliders for zmin, zmax
interact(self._plot_im, z_name=name_options, zmin=fixed(zmax), zmax=fixed(zmax), cmap=fixed(cmap))
else:
raise ValueError('name must be given')
else:
self._plot_im(z_name=z, zmin=zmin, zmax=zmax, cmap=cmap)
def _plot_im(self, z_name, zmin=None, zmax=None, cmap='jet'):
if z_name not in self._inspector.dataset.variables:
print('Error: "%s" is not a variable' % z_name)
return
var = self._inspector.dataset[z_name]
if len(var.shape) != 2:
print('Error: "%s" is not 2-dimensional' % z_name)
return
var_data = var[:]
zmin = zmin if zmin else var_data.min()
zmax = zmax if zmax else var_data.max()
plt.figure(figsize=(10, 10))
plt.imshow(self._inspector.waveform, interpolation='nearest', aspect='auto', vmin=zmin, vmax=zmax, cmap=cmap)
# TODO (forman, 20160709): show labels in units of dimension variables
plt.xlabel('%s (index)' % var.dimensions[1])
plt.ylabel('%s (index)' % var.dimensions[0])
plt.title('%s (%s)' % (z_name, var.units if hasattr(var, 'units') else '?'))
plt.colorbar(orientation='vertical')
if self._interactive:
plt.show()
else:
self.savefig('fig-%s.png' % z_name)
def line(self, x=None, y=None, sel_dim=False):
"""
Plot two 1D-variables against each other.
:param x: Name of a 1D-variable
:param y: Name of another 1D-variable, must have the same dimension as *x*.
:param sel_dim: Whether to display a dimension selector.
"""
if not x or not y:
if self._interactive:
valid_dim_names = set()
valid_var_names = []
for dim_names, var_names in self._inspector.dim_names_to_var_names.items():
if len(dim_names) == 1 and len(var_names) > 1:
dim_name = dim_names[0]
if self._inspector.dim_name_to_size[dim_name] > 0:
valid_dim_names.add(dim_name)
valid_var_names.extend(var_names)
valid_dim_names = sorted(valid_dim_names)
valid_var_names = sorted(valid_var_names)
if sel_dim:
widget_dim_options = valid_dim_names
widget_dim_value = widget_dim_options[0]
widget_y_options = sorted(list(self._inspector.dim_names_to_var_names[(widget_dim_value,)]))
widget_y_value = y if y and y in widget_y_options else widget_y_options[0]
widget_x_options = ['index'] + widget_y_options
widget_x_value = x if x and x in widget_x_options else widget_x_options[0]
widget_dim = widgets.Dropdown(options=widget_dim_options, value=widget_dim_value,
description='Dim:')
widget_x = widgets.Dropdown(options=widget_x_options, value=widget_x_value, description='X:')
widget_y = widgets.Dropdown(options=widget_y_options, value=widget_y_value, description='Y:')
display(widget_dim)
# noinspection PyUnusedLocal
def on_widget_dim_change(change):
nonlocal widget_x, widget_y
widget_y.options = sorted(list(self._inspector.dim_names_to_var_names[(widget_dim.value,)]))
widget_x.options = ['index'] + widget_y.options
widget_y.value = widget_y.options[0]
widget_x.value = widget_x.options[0]
# noinspection PyUnusedLocal
def on_widget_x_change(change):
display()
# noinspection PyUnusedLocal
def on_widget_y_change(change):
display()
widget_dim.observe(on_widget_dim_change, names='value')
widget_x.observe(on_widget_x_change, names='value')
widget_y.observe(on_widget_y_change, names='value')
|
[
" interact(self._plot_line, x_name=widget_x, y_name=widget_y)"
] | 1,433
|
lcc
|
python
| null |
821b5076e7642f35d6db6b0af29ca2ff7694928b53b0dace
| 43
|
Your task is code completion.
import os.path
import bokeh
import bokeh.io
import bokeh.model
import bokeh.plotting
import bokeh.util.platform
import ipywidgets as widgets
import matplotlib.pyplot as plt
import numpy as np
import pyproj
from IPython.display import display
from bokeh.models import ColumnDataSource, Circle
from bokeh.tile_providers import STAMEN_TERRAIN
from ipywidgets import interact, fixed
from matplotlib.collections import LineCollection, PolyCollection
# noinspection PyUnresolvedReferences
from mpl_toolkits.mplot3d import Axes3D
from netCDF4 import Dataset, num2date
from numpy import ndarray
from .figurewriter import FigureWriter
# (Plotting) Resources:
# * http://matplotlib.org/api/pyplot_api.html
# * http://matplotlib.org/users/image_tutorial.html
# * http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#d-plots-in-3d
# * http://ipywidgets.readthedocs.io/en/latest/
# * http://bokeh.pydata.org/en/0.11.1/docs/user_guide/geo.html
# * http://bokeh.pydata.org/en/0.11.1/docs/user_guide/notebook.html
def inspect_l1b_product(product_file_path, output_path=None, output_format=None) -> 'L1bProductInspector':
"""
Open a L1B product for inspection.
If *output_format* is "dir" then a new directory given by *output_path*
will be created. Each plot figure will will be saved in a new file.
If *output_format* is "pdf" then a new multi-page PDF document given by *output_path*
will be created or overwritten if it exists. Each plot figure will will be saved in a new PDF page.
Format "pdf" does not support all plot types.
If *output_format* is not given it defaults it is derived from *output_path*.
Note that both *output_path* and *output_format* arguments are ignored if the inspection is run in an
Jupyter (IPython) Notebook.
:param product_file_path: The file path of the LB product.
:param output_path: The output path where plot figures are written to.
:param output_format: The output format. Supported formats are "pdf" and "dir".
"""
if output_path:
figure_writer = FigureWriter(output_path, output_format)
else:
bokeh.io.output_notebook(hide_banner=True)
figure_writer = None
return L1bProductInspector(product_file_path, figure_writer)
class L1bProductInspector:
"""
The `L1bInspector` class provides access to L1B contents and provides a number of analysis functions.
"""
def __init__(self, product_file_path, figure_writer: FigureWriter):
if not product_file_path:
raise ValueError('product_file_path must be given')
self._plot = L1bProductInspectorPlots(self, figure_writer)
self._file_path = product_file_path
dataset = Dataset(product_file_path)
self._dataset = dataset
self.dim_names = sorted(list(dataset.dimensions.keys()))
self.var_names = sorted(list(dataset.variables))
if 'time_l1bs_echo_sar_ku' in self.var_names:
product_type = 'l1bs'
print('WARNING: L1BS product inspection not yet fully supported.')
elif 'time_l1b_echo_sar_ku' in self.var_names:
product_type = 'l1b'
else:
raise ValueError('"%s" is neither a supported L1B nor L1BS product' % product_file_path)
self.dim_name_to_size = {}
for name, dim in dataset.dimensions.items():
self.dim_name_to_size[name] = dim.size
self.dim_names_to_var_names = {}
for v in dataset.variables:
dims = tuple(dataset[v].dimensions)
if dims in self.dim_names_to_var_names:
self.dim_names_to_var_names[dims].add(v)
else:
self.dim_names_to_var_names[dims] = {v}
self.attributes = {name: dataset.getncattr(name) for name in dataset.ncattrs()}
self.lat = dataset['lat_%s_echo_sar_ku' % product_type][:]
self.lon = dataset['lon_%s_echo_sar_ku' % product_type][:]
self.lat_0 = self.lat.mean()
self.lon_0 = self.lon.mean()
self.lat_range = self.lat.min(), self.lat.max()
self.lon_range = self.lon.min(), self.lon.max()
time_var = dataset['time_%s_echo_sar_ku' % product_type]
time = time_var[:]
self.time = num2date(time, time_var.units, calendar=time_var.calendar)
self.time_0 = num2date(time.mean(), time_var.units, calendar=time_var.calendar)
self.time_range = self.time.min(), self.time.max()
waveform_counts = dataset['i2q2_meas_ku_%s_echo_sar_ku' % product_type][:]
waveform_scaling = dataset['scale_factor_ku_%s_echo_sar_ku' % product_type][:]
waveform_scaling = waveform_scaling.reshape(waveform_scaling.shape + (1,))
self._waveform = waveform_scaling * waveform_counts
self.waveform_range = self.waveform.min(), self.waveform.max()
self.num_times = waveform_counts.shape[0]
self.num_samples = waveform_counts.shape[1]
self.echo_sample_ind = np.arange(0, self.num_samples)
@property
def file_path(self) -> str:
"""
Get the L1b file path.
"""
return self._file_path
@property
def plot(self) -> 'L1bProductInspectorPlots':
"""
Get the plotting context.
"""
return self._plot
@property
def dataset(self) -> Dataset:
"""
Get the underlying netCDF dataset object.
"""
return self._dataset
@property
def waveform(self) -> ndarray:
"""
Get the pre-scaled waveform array.
"""
return self._waveform
def close(self):
"""Close the underlying dataset's file access."""
self._dataset.close()
self._plot.close()
class L1bProductInspectorPlots:
def __init__(self, inspector: 'L1bProductInspector', figure_writer: FigureWriter):
self._inspector = inspector
self._interactive = figure_writer is None
self._figure_writer = figure_writer
def locations(self, color='blue'):
"""
Plot product locations as circles onto a world map.
"""
# Spherical Mercator
mercator = pyproj.Proj(init='epsg:3857')
# Equirectangular lat/lon on WGS84
equirectangular = pyproj.Proj(init='epsg:4326')
lon = self._inspector.lon
lat = self._inspector.lat
x, y = pyproj.transform(equirectangular, mercator, lon, lat)
# print(list(zip(lon, lat)))
# print(list(zip(x, y)))
source = ColumnDataSource(data=dict(x=x, y=y))
circle = Circle(x='x', y='y', size=6, fill_color=color, fill_alpha=0.5, line_color=None)
# map_options = GMapOptions(lat=30.29, lng=-97.73, map_type="roadmap", zoom=11)
# plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options)
# plot.title.text = 'L1B Footprint'
# plot.add_glyph(source, circle)
# plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
fig = bokeh.plotting.figure(x_range=(x.min(), x.max()), y_range=(y.min(), y.max()), toolbar_location='above')
fig.axis.visible = False
# fig.add_tile(STAMEN_TONER)
fig.add_tile(STAMEN_TERRAIN)
fig.title.text = 'L1B Locations'
# fig.title = 'L1B Footprint'
fig.add_glyph(source, circle)
if self._interactive:
bokeh.io.show(fig)
elif self._figure_writer.output_format == "dir":
os.makedirs(self._figure_writer.output_path, exist_ok=True)
bokeh.io.save(fig, os.path.join(self._figure_writer.output_path, 'fig-locations.html'),
title='L1B Locations')
else:
print('warning: cannot save locations figure with output format "%s"' % self._figure_writer.output_format)
def waveform_im(self, vmin=None, vmax=None, cmap='jet'):
vmin = vmin if vmin else self._inspector.waveform_range[0]
vmax = vmax if vmax else self._inspector.waveform_range[1]
plt.figure(figsize=(10, 10))
plt.imshow(self._inspector.waveform, interpolation='nearest', aspect='auto', vmin=vmin, vmax=vmax, cmap=cmap)
plt.xlabel('Echo Sample Index')
plt.ylabel('Time Index')
plt.title('Waveform')
plt.colorbar(orientation='vertical')
if self._interactive:
plt.show()
else:
self.savefig("fig-waveform-im.png")
def waveform_3d_surf(self, zmin=0, zmax=None, cmap='jet'):
self._waveform_3d(fig_type='surf', zmin=zmin, zmax=zmax, alpha=1, cmap=cmap)
def waveform_3d_poly(self, zmin=0, zmax=None, alpha=0.5, cmap='jet'):
self._waveform_3d(fig_type='poly', zmin=zmin, zmax=zmax, alpha=alpha, cmap=cmap)
def waveform_3d_line(self, zmin=0, zmax=None, alpha=0.5, cmap='jet'):
self._waveform_3d(fig_type='line', zmin=zmin, zmax=zmax, alpha=alpha, cmap=cmap)
def _waveform_3d(self, fig_type, zmin, zmax, alpha, cmap):
fig = plt.figure(figsize=(10, 10))
ax = fig.gca(projection='3d')
num_times = self._inspector.num_times
num_samples = self._inspector.num_samples
if fig_type == 'surf':
x = np.arange(0, num_samples)
y = np.arange(0, num_times)
x, y = np.meshgrid(x, y)
z = self._inspector.waveform
surf = ax.plot_surface(x, y, z, rstride=3, cstride=3, cmap=cmap, shade=True,
linewidth=0, antialiased=False)
# ax.zaxis.set_major_locator(LinearLocator(10))
# ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
else:
waveforms = []
for y_index in range(num_times):
waveform = np.ndarray(shape=(num_samples, 2), dtype=np.float64)
waveform[:, 0] = np.arange(0, num_samples)
waveform[:, 1] = self._inspector.waveform[y_index]
waveforms.append(waveform)
line_widths = [0.5] * num_times
# TODO (forman, 20160725): check why cmap is not recognized
if fig_type == 'poly':
edge_colors = ((0.2, 0.2, 1., 0.7),) * num_times
face_colors = ((1., 1., 1., 0.5),) * num_times
collection = PolyCollection(waveforms, cmap=cmap,
linewidths=line_widths,
edgecolors=edge_colors,
facecolors=face_colors)
else:
colors = ((0.2, 0.2, 1., 0.7),) * num_times
collection = LineCollection(waveforms, cmap=cmap,
linewidths=line_widths, colors=colors)
collection.set_alpha(alpha)
ax.add_collection3d(collection, zs=np.arange(0, num_times), zdir='y')
wf_min, wf_max = self._inspector.waveform_range
ax.set_xlabel('Echo Sample Index')
ax.set_xlim3d(0, num_samples - 1)
ax.set_ylabel('Time Index')
ax.set_ylim3d(0, num_times - 1)
ax.set_zlabel('Waveform')
ax.set_zlim3d(zmin if zmin is not None else wf_min, zmax if zmax is not None else wf_max)
if self._interactive:
plt.show()
else:
self.savefig("fig-waveform-3d-%s.png" % fig_type)
def waveform_hist(self, vmin=None, vmax=None, bins=128, log=False, color='green'):
"""
Draw waveform histogram.
:param vmin: Minimum display value
:param vmax: Maximum display value
:param bins: Number of bins
:param log: Show logarithms of bin counts
:param color: Color of the histogram bars, e.g. 'green'
"""
vmin = vmin if vmin else self._inspector.waveform_range[0]
vmax = vmax if vmax else self._inspector.waveform_range[1]
vmax = vmin + 1 if vmin == vmax else vmax
plt.figure(figsize=(12, 6))
plt.hist(self._inspector.waveform.flatten(),
range=(vmin, vmax),
bins=bins,
log=log,
facecolor=color,
alpha=1,
normed=True)
plt.xlabel('Waveform')
plt.ylabel('Counts')
plt.title('Waveform Histogram')
plt.grid(True)
if self._interactive:
plt.show()
else:
self.savefig("fig-waveform-hist.png")
def waveform_line(self, ind=None, ref_ind=None):
"""
Draw waveform 2D line plot.
:param ind: Time index
:param ref_ind: Reference time index
"""
if ind is None and self._interactive:
interact(self._plot_waveform_line, ind=(0, self._inspector.num_times - 1), ref_ind=fixed(ref_ind))
else:
self._plot_waveform_line(ind=ind if ind else 0, ref_ind=ref_ind)
def _plot_waveform_line(self, ind: int, ref_ind=None):
plt.figure(figsize=(12, 6))
plt.plot(self._inspector.echo_sample_ind, self._inspector.waveform[ind], 'b-')
plt.xlabel('Echo Sample Index')
plt.ylabel('Waveform')
plt.title('Waveform at #%s' % ind)
plt.grid(True)
if ref_ind is not None:
plt.plot(self._inspector.echo_sample_ind, self._inspector.waveform[ref_ind], 'r-', label='ref')
plt.legend(['#%s' % ind, '#%s' % ref_ind])
if self._interactive:
plt.show()
else:
self.savefig("fig-waveform-x-%d.png" % ind)
def im(self, z=None, zmin=None, zmax=None, cmap='jet'):
if z is None:
if self._interactive:
name_options = list()
for dim_names, var_names in self._inspector.dim_names_to_var_names.items():
no_zero_dim = all([self._inspector.dim_name_to_size[dim] > 0 for dim in dim_names])
if no_zero_dim and len(dim_names) == 2:
name_options.extend(var_names)
name_options = sorted(name_options)
# TODO (forman, 20160709): add sliders for zmin, zmax
interact(self._plot_im, z_name=name_options, zmin=fixed(zmax), zmax=fixed(zmax), cmap=fixed(cmap))
else:
raise ValueError('name must be given')
else:
self._plot_im(z_name=z, zmin=zmin, zmax=zmax, cmap=cmap)
def _plot_im(self, z_name, zmin=None, zmax=None, cmap='jet'):
if z_name not in self._inspector.dataset.variables:
print('Error: "%s" is not a variable' % z_name)
return
var = self._inspector.dataset[z_name]
if len(var.shape) != 2:
print('Error: "%s" is not 2-dimensional' % z_name)
return
var_data = var[:]
zmin = zmin if zmin else var_data.min()
zmax = zmax if zmax else var_data.max()
plt.figure(figsize=(10, 10))
plt.imshow(self._inspector.waveform, interpolation='nearest', aspect='auto', vmin=zmin, vmax=zmax, cmap=cmap)
# TODO (forman, 20160709): show labels in units of dimension variables
plt.xlabel('%s (index)' % var.dimensions[1])
plt.ylabel('%s (index)' % var.dimensions[0])
plt.title('%s (%s)' % (z_name, var.units if hasattr(var, 'units') else '?'))
plt.colorbar(orientation='vertical')
if self._interactive:
plt.show()
else:
self.savefig('fig-%s.png' % z_name)
def line(self, x=None, y=None, sel_dim=False):
"""
Plot two 1D-variables against each other.
:param x: Name of a 1D-variable
:param y: Name of another 1D-variable, must have the same dimension as *x*.
:param sel_dim: Whether to display a dimension selector.
"""
if not x or not y:
if self._interactive:
valid_dim_names = set()
valid_var_names = []
for dim_names, var_names in self._inspector.dim_names_to_var_names.items():
if len(dim_names) == 1 and len(var_names) > 1:
dim_name = dim_names[0]
if self._inspector.dim_name_to_size[dim_name] > 0:
valid_dim_names.add(dim_name)
valid_var_names.extend(var_names)
valid_dim_names = sorted(valid_dim_names)
valid_var_names = sorted(valid_var_names)
if sel_dim:
widget_dim_options = valid_dim_names
widget_dim_value = widget_dim_options[0]
widget_y_options = sorted(list(self._inspector.dim_names_to_var_names[(widget_dim_value,)]))
widget_y_value = y if y and y in widget_y_options else widget_y_options[0]
widget_x_options = ['index'] + widget_y_options
widget_x_value = x if x and x in widget_x_options else widget_x_options[0]
widget_dim = widgets.Dropdown(options=widget_dim_options, value=widget_dim_value,
description='Dim:')
widget_x = widgets.Dropdown(options=widget_x_options, value=widget_x_value, description='X:')
widget_y = widgets.Dropdown(options=widget_y_options, value=widget_y_value, description='Y:')
display(widget_dim)
# noinspection PyUnusedLocal
def on_widget_dim_change(change):
nonlocal widget_x, widget_y
widget_y.options = sorted(list(self._inspector.dim_names_to_var_names[(widget_dim.value,)]))
widget_x.options = ['index'] + widget_y.options
widget_y.value = widget_y.options[0]
widget_x.value = widget_x.options[0]
# noinspection PyUnusedLocal
def on_widget_x_change(change):
display()
# noinspection PyUnusedLocal
def on_widget_y_change(change):
display()
widget_dim.observe(on_widget_dim_change, names='value')
widget_x.observe(on_widget_x_change, names='value')
widget_y.observe(on_widget_y_change, names='value')
|
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]
def line(self, x=None, y=None, sel_dim=False):
"""
Plot two 1D-variables against each other.
:param x: Name of a 1D-variable
:param y: Name of another 1D-variable, must have the same dimension as *x*.
:param sel_dim: Whether to display a dimension selector.
"""
if not x or not y:
if self._interactive:
valid_dim_names = set()
valid_var_names = []
for dim_names, var_names in self._inspector.dim_names_to_var_names.items():
if len(dim_names) == 1 and len(var_names) > 1:
dim_name = dim_names[0]
if self._inspector.dim_name_to_size[dim_name] > 0:
valid_dim_names.add(dim_name)
valid_var_names.extend(var_names)
valid_dim_names = sorted(valid_dim_names)
valid_var_names = sorted(valid_var_names)
if sel_dim:
widget_dim_options = valid_dim_names
widget_dim_value = widget_dim_options[0]
widget_y_options = sorted(list(self._inspector.dim_names_to_var_names[(widget_dim_value,)]))
widget_y_value = y if y and y in widget_y_options else widget_y_options[0]
widget_x_options = ['index'] + widget_y_options
widget_x_value = x if x and x in widget_x_options else widget_x_options[0]
widget_dim = widgets.Dropdown(options=widget_dim_options, value=widget_dim_value,
description='Dim:')
widget_x = widgets.Dropdown(options=widget_x_options, value=widget_x_value, description='X:')
widget_y = widgets.Dropdown(options=widget_y_options, value=widget_y_value, description='Y:')
display(widget_dim)
# noinspection PyUnusedLocal
def on_widget_dim_change(change):
nonlocal widget_x, widget_y
widget_y.options = sorted(list(self._inspector.dim_names_to_var_names[(widget_dim.value,)]))
widget_x.options = ['index'] + widget_y.options
widget_y.value = widget_y.options[0]
widget_x.value = widget_x.options[0]
# noinspection PyUnusedLocal
def on_widget_x_change(change):
display()
# noinspection PyUnusedLocal
def on_widget_y_change(change):
display()
widget_dim.observe(on_widget_dim_change, names='value')
widget_x.observe(on_widget_x_change, names='value')
widget_y.observe(on_widget_y_change, names='value')
Cheatsheet (for next line):
- We are in the if self._interactive block, which is a conditional statement.
- The code is creating interactive widgets for dimension and variable selection.
- The goal is to display the widgets.
- [Relevant lines: if self._interactive, widget creation, display() function]
Next line will likely be: display(widget_x); display(widget_y);
|
|
Please complete the code given below.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NLog;
using NzbDrone.Common.Disk;
using NzbDrone.Common.Extensions;
using NzbDrone.Common.TPL;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Configuration.Events;
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.Lifecycle;
using NzbDrone.Core.MediaFiles.Commands;
using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.RootFolders;
namespace NzbDrone.Core.MediaFiles
{
public interface IRootFolderWatchingService
{
void ReportFileSystemChangeBeginning(params string[] paths);
}
public sealed class RootFolderWatchingService : IRootFolderWatchingService,
IDisposable,
IHandle<ModelEvent<RootFolder>>,
IHandle<ApplicationStartedEvent>,
IHandle<ConfigSavedEvent>
{
private const int DEBOUNCE_TIMEOUT_SECONDS = 30;
private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string, FileSystemWatcher>();
private readonly ConcurrentDictionary<string, int> _tempIgnoredPaths = new ConcurrentDictionary<string, int>();
private readonly ConcurrentDictionary<string, string> _changedPaths = new ConcurrentDictionary<string, string>();
private readonly IRootFolderService _rootFolderService;
private readonly IManageCommandQueue _commandQueueManager;
private readonly IConfigService _configService;
private readonly Logger _logger;
private readonly Debouncer _scanDebouncer;
private bool _watchForChanges;
public RootFolderWatchingService(IRootFolderService rootFolderService,
IManageCommandQueue commandQueueManager,
IConfigService configService,
Logger logger)
{
_rootFolderService = rootFolderService;
_commandQueueManager = commandQueueManager;
_configService = configService;
_logger = logger;
_scanDebouncer = new Debouncer(ScanPending, TimeSpan.FromSeconds(DEBOUNCE_TIMEOUT_SECONDS), true);
}
public void Dispose()
{
foreach (var watcher in _fileSystemWatchers.Values)
{
DisposeWatcher(watcher, false);
}
}
public void ReportFileSystemChangeBeginning(params string[] paths)
{
foreach (var path in paths.Where(x => x.IsNotNullOrWhiteSpace()))
{
_logger.Trace($"reporting start of change to {path}");
_tempIgnoredPaths.AddOrUpdate(path.CleanFilePathBasic(), 1, (key, value) => value + 1);
}
}
public void Handle(ApplicationStartedEvent message)
{
_watchForChanges = _configService.WatchLibraryForChanges;
if (_watchForChanges)
{
_rootFolderService.All().ForEach(x => StartWatchingPath(x.Path));
}
}
public void Handle(ConfigSavedEvent message)
{
var oldWatch = _watchForChanges;
_watchForChanges = _configService.WatchLibraryForChanges;
if (_watchForChanges != oldWatch)
{
if (_watchForChanges)
{
_rootFolderService.All().ForEach(x => StartWatchingPath(x.Path));
}
else
{
_rootFolderService.All().ForEach(x => StopWatchingPath(x.Path));
}
}
}
public void Handle(ModelEvent<RootFolder> message)
{
if (message.Action == ModelAction.Created && _watchForChanges)
{
StartWatchingPath(message.Model.Path);
}
else if (message.Action == ModelAction.Deleted)
{
StopWatchingPath(message.Model.Path);
}
}
private void StartWatchingPath(string path)
{
// Already being watched
if (_fileSystemWatchers.ContainsKey(path))
{
return;
}
// Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
Task.Run(() =>
{
try
{
var newWatcher = new FileSystemWatcher(path, "*")
{
IncludeSubdirectories = true,
InternalBufferSize = 65536,
NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite
};
newWatcher.Created += Watcher_Changed;
newWatcher.Deleted += Watcher_Changed;
newWatcher.Renamed += Watcher_Changed;
newWatcher.Changed += Watcher_Changed;
newWatcher.Error += Watcher_Error;
if (_fileSystemWatchers.TryAdd(path, newWatcher))
{
newWatcher.EnableRaisingEvents = true;
_logger.Info("Watching directory {0}", path);
}
else
{
DisposeWatcher(newWatcher, false);
}
}
catch (Exception ex)
{
_logger.Error(ex, "Error watching path: {0}", path);
}
});
}
private void StopWatchingPath(string path)
{
if (_fileSystemWatchers.TryGetValue(path, out var watcher))
{
DisposeWatcher(watcher, true);
}
}
private void Watcher_Error(object sender, ErrorEventArgs e)
{
var ex = e.GetException();
var dw = (FileSystemWatcher)sender;
if (ex.GetType() == typeof(InternalBufferOverflowException))
{
_logger.Warn(ex, "The file system watcher experienced an internal buffer overflow for: {0}", dw.Path);
_changedPaths.TryAdd(dw.Path, dw.Path);
_scanDebouncer.Execute();
}
else
{
_logger.Error(ex, "Error in Directory watcher for: {0}" + dw.Path);
DisposeWatcher(dw, true);
}
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
try
{
var rootFolder = ((FileSystemWatcher)sender).Path;
var path = e.FullPath;
if (path.IsNullOrWhiteSpace())
{
throw new ArgumentNullException("path");
}
_changedPaths.TryAdd(path, rootFolder);
_scanDebouncer.Execute();
}
catch (Exception ex)
{
_logger.Error(ex, "Exception in ReportFileSystemChanged. Path: {0}", e.FullPath);
}
}
private void ScanPending()
{
var pairs = _changedPaths.ToArray();
_changedPaths.Clear();
var ignored = _tempIgnoredPaths.Keys.ToArray();
_tempIgnoredPaths.Clear();
var toScan = new HashSet<string>();
foreach (var item in pairs)
{
var path = item.Key.CleanFilePathBasic();
var rootFolder = item.Value;
|
[
" if (!ShouldIgnoreChange(path, ignored))"
] | 513
|
lcc
|
csharp
| null |
33a191efb28d5b529c26b622495441d20e705cfb2dc5be9f
| 44
|
Your task is code completion.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NLog;
using NzbDrone.Common.Disk;
using NzbDrone.Common.Extensions;
using NzbDrone.Common.TPL;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Configuration.Events;
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.Lifecycle;
using NzbDrone.Core.MediaFiles.Commands;
using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.RootFolders;
namespace NzbDrone.Core.MediaFiles
{
public interface IRootFolderWatchingService
{
void ReportFileSystemChangeBeginning(params string[] paths);
}
public sealed class RootFolderWatchingService : IRootFolderWatchingService,
IDisposable,
IHandle<ModelEvent<RootFolder>>,
IHandle<ApplicationStartedEvent>,
IHandle<ConfigSavedEvent>
{
private const int DEBOUNCE_TIMEOUT_SECONDS = 30;
private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string, FileSystemWatcher>();
private readonly ConcurrentDictionary<string, int> _tempIgnoredPaths = new ConcurrentDictionary<string, int>();
private readonly ConcurrentDictionary<string, string> _changedPaths = new ConcurrentDictionary<string, string>();
private readonly IRootFolderService _rootFolderService;
private readonly IManageCommandQueue _commandQueueManager;
private readonly IConfigService _configService;
private readonly Logger _logger;
private readonly Debouncer _scanDebouncer;
private bool _watchForChanges;
public RootFolderWatchingService(IRootFolderService rootFolderService,
IManageCommandQueue commandQueueManager,
IConfigService configService,
Logger logger)
{
_rootFolderService = rootFolderService;
_commandQueueManager = commandQueueManager;
_configService = configService;
_logger = logger;
_scanDebouncer = new Debouncer(ScanPending, TimeSpan.FromSeconds(DEBOUNCE_TIMEOUT_SECONDS), true);
}
public void Dispose()
{
foreach (var watcher in _fileSystemWatchers.Values)
{
DisposeWatcher(watcher, false);
}
}
public void ReportFileSystemChangeBeginning(params string[] paths)
{
foreach (var path in paths.Where(x => x.IsNotNullOrWhiteSpace()))
{
_logger.Trace($"reporting start of change to {path}");
_tempIgnoredPaths.AddOrUpdate(path.CleanFilePathBasic(), 1, (key, value) => value + 1);
}
}
public void Handle(ApplicationStartedEvent message)
{
_watchForChanges = _configService.WatchLibraryForChanges;
if (_watchForChanges)
{
_rootFolderService.All().ForEach(x => StartWatchingPath(x.Path));
}
}
public void Handle(ConfigSavedEvent message)
{
var oldWatch = _watchForChanges;
_watchForChanges = _configService.WatchLibraryForChanges;
if (_watchForChanges != oldWatch)
{
if (_watchForChanges)
{
_rootFolderService.All().ForEach(x => StartWatchingPath(x.Path));
}
else
{
_rootFolderService.All().ForEach(x => StopWatchingPath(x.Path));
}
}
}
public void Handle(ModelEvent<RootFolder> message)
{
if (message.Action == ModelAction.Created && _watchForChanges)
{
StartWatchingPath(message.Model.Path);
}
else if (message.Action == ModelAction.Deleted)
{
StopWatchingPath(message.Model.Path);
}
}
private void StartWatchingPath(string path)
{
// Already being watched
if (_fileSystemWatchers.ContainsKey(path))
{
return;
}
// Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
Task.Run(() =>
{
try
{
var newWatcher = new FileSystemWatcher(path, "*")
{
IncludeSubdirectories = true,
InternalBufferSize = 65536,
NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite
};
newWatcher.Created += Watcher_Changed;
newWatcher.Deleted += Watcher_Changed;
newWatcher.Renamed += Watcher_Changed;
newWatcher.Changed += Watcher_Changed;
newWatcher.Error += Watcher_Error;
if (_fileSystemWatchers.TryAdd(path, newWatcher))
{
newWatcher.EnableRaisingEvents = true;
_logger.Info("Watching directory {0}", path);
}
else
{
DisposeWatcher(newWatcher, false);
}
}
catch (Exception ex)
{
_logger.Error(ex, "Error watching path: {0}", path);
}
});
}
private void StopWatchingPath(string path)
{
if (_fileSystemWatchers.TryGetValue(path, out var watcher))
{
DisposeWatcher(watcher, true);
}
}
private void Watcher_Error(object sender, ErrorEventArgs e)
{
var ex = e.GetException();
var dw = (FileSystemWatcher)sender;
if (ex.GetType() == typeof(InternalBufferOverflowException))
{
_logger.Warn(ex, "The file system watcher experienced an internal buffer overflow for: {0}", dw.Path);
_changedPaths.TryAdd(dw.Path, dw.Path);
_scanDebouncer.Execute();
}
else
{
_logger.Error(ex, "Error in Directory watcher for: {0}" + dw.Path);
DisposeWatcher(dw, true);
}
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
try
{
var rootFolder = ((FileSystemWatcher)sender).Path;
var path = e.FullPath;
if (path.IsNullOrWhiteSpace())
{
throw new ArgumentNullException("path");
}
_changedPaths.TryAdd(path, rootFolder);
_scanDebouncer.Execute();
}
catch (Exception ex)
{
_logger.Error(ex, "Exception in ReportFileSystemChanged. Path: {0}", e.FullPath);
}
}
private void ScanPending()
{
var pairs = _changedPaths.ToArray();
_changedPaths.Clear();
var ignored = _tempIgnoredPaths.Keys.ToArray();
_tempIgnoredPaths.Clear();
var toScan = new HashSet<string>();
foreach (var item in pairs)
{
var path = item.Key.CleanFilePathBasic();
var rootFolder = item.Value;
|
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]
public class RootFolderWatchingService : IRootFolderWatchingService,
IDisposable,
IHandle<ModelEvent<RootFolder>>,
IHandle<ApplicationStartedEvent>,
IHandle<ConfigSavedEvent>
{
// ...
private void ScanPending()
{
var pairs = _changedPaths.ToArray();
_changedPaths.Clear();
var ignored = _tempIgnoredPaths.Keys.ToArray();
_tempIgnoredPaths.Clear();
var toScan = new HashSet<string>();
foreach (var item in pairs)
{
var path = item.Key.CleanFilePathBasic();
var rootFolder = item.Value;
**Relevant lines and variables:**
* We are in the `ScanPending()` method, which is called when a file system change is detected.
* `_changedPaths` is a dictionary that stores the paths that have changed.
* `_tempIgnoredPaths` is a dictionary that stores paths that are temporarily ignored.
* `toScan` is a set of paths that need to be scanned.
* `path` is the current path being processed.
* `rootFolder` is the root folder of the current path.
**Task:** The code is iterating over the changed paths and needs to add them to the `toScan` set. However, it should ignore paths that are temporarily ignored.
**Cheat sheet:**
* We need to add the `path` to the `toScan` set.
* We should check if the `path` is not in the `_tempIgnoredPaths` dictionary before adding it to `toScan`.
* The `CleanFilePathBasic()` method is used to clean the path.
**Next line(s) of code:**
```csharp
if (!_tempIgnoredPaths.ContainsKey(path)) {
toScan.Add(path);
}
```
However, considering the context, it seems like the intention is to ignore paths that are temporarily ignored, so the correct code should be:
```csharp
if (_tempIgnoredPaths.ContainsKey(path)) {
toScan.Add(path);
}
```
This will add the path to the `toScan` set if it is temporarily ignored.
|
|
Please complete the code given below.
package com.electronwill.nightconfig.core.utils;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
*
* A TransformingMap contains an internal {@code Map<K, InternalV>} values, and exposes the
* features of a {@code Map<K, ExternalV>} applying transformations to the values.
* <p>
* The transformations are applied "just in time", that is, the values are converted only when
* they are used, not during the construction of the TransformingMap.
* <p>
* For instance, if you have a {@code Map<String, String>} and you want to convert its values
* "just in time" to integers, you use a {@code TransformingMap<String, String, Integer>}.
* To get one, you create these three functions:
* <ul>
* <li>one that converts a String to an Integer: that's the parse transformation. It converts an
* Integer read from the internal map to a String.
* <li>one that converts an Integer to a String: that's the write transformation. It converts a
* String given to the TransformingMap to an Integer.
* <li>one that converts an Object to another Object: that's the search transformation. It is used
* (mainly) by the {@link #containsKey(Object)} method of the TransformingMap. If its argument is
* an Integer then it should convert it to an String in the same way as the write transformation.
* Otherwise, it is free to try to convert it to a String if possible, or not to.
* </ul>
*
* @author TheElectronWill
*/
@SuppressWarnings("unchecked")
public final class TransformingMap<K, I, E> extends AbstractMap<K, E> {
private final BiFunction<K, ? super I, ? extends E> readTransform;
private final BiFunction<K, ? super E, ? extends I> writeTransform;
private final Function<Object, ? extends I> searchTransform;
private final Map<K, I> internalMap;
/**
* Create a new TransformingMap.
*
* @param map the internal map to use
* @param readTransform the parse transformation (see javadoc of the class)
* @param writeTransform the write transformation (see javadoc of the class)
* @param searchTransform the search transformation (see javadoc of the class)
*/
public TransformingMap(Map<K, I> map,
Function<? super I, ? extends E> readTransform,
Function<? super E, ? extends I> writeTransform,
Function<Object, ? extends I> searchTransform) {
this.internalMap = map;
this.readTransform = (k, v) -> readTransform.apply(v);
this.writeTransform = (k, v) -> writeTransform.apply(v);
this.searchTransform = searchTransform;
}
/**
* Create a new TransformingMap.
*
* @param map the internal map to use
* @param readTransform the parse transformation (see javadoc of the class)
* @param writeTransform the write transformation (see javadoc of the class)
* @param searchTransform the search transformation (see javadoc of the class)
*/
public TransformingMap(Map<K, I> map,
BiFunction<K, ? super I, ? extends E> readTransform,
BiFunction<K, ? super E, ? extends I> writeTransform,
Function<Object, ? extends I> searchTransform) {
this.internalMap = map;
this.readTransform = readTransform;
this.writeTransform = writeTransform;
this.searchTransform = searchTransform;
}
private E read(Object key, I value) {
return readTransform.apply((K)key, value);
}
private I write(Object key, E value) {
return writeTransform.apply((K)key, value);
}
private I search(Object arg) {
return searchTransform.apply(arg);
}
@Override
public int size() {
return internalMap.size();
}
@Override
public boolean isEmpty() {
return internalMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return internalMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return internalMap.containsValue(searchTransform.apply(value));
}
@Override
public E get(Object key) {
return read(key, internalMap.get(key));
}
@Override
public E put(K key, E value) {
return read(key, internalMap.put(key, write(key, value)));
}
@Override
public E remove(Object key) {
return read(key, internalMap.remove(key));
}
@Override
public void putAll(Map<? extends K, ? extends E> m) {
internalMap.putAll(new TransformingMap(m, writeTransform, (k, o) -> o, o -> o));
}
@Override
public void clear() {
internalMap.clear();
}
@Override
public Set<K> keySet() {
return internalMap.keySet();
}
@Override
public Collection<E> values() {
return new TransformingCollection<>(internalMap.values(), o->read(null,o),
o->write(null,o), searchTransform);
}
@Override
public Set<Map.Entry<K, E>> entrySet() {
Function<Entry<K, I>, Entry<K, E>> read =
i -> TransformingMapEntry.from(i, readTransform, writeTransform);
Function<Entry<K, E>, Entry<K, I>> write =
e -> TransformingMapEntry.from(e, writeTransform, readTransform);
Function<Object, Map.Entry<K, I>> search = o -> {
if (o instanceof Map.Entry) {
Map.Entry<K, E> entry = (Map.Entry)o;
return TransformingMapEntry.from(entry, writeTransform, readTransform);
}
return null;
};
return new TransformingSet<>(internalMap.entrySet(), read, write, search);
}
@Override
public E getOrDefault(Object key, E defaultValue) {
I result = internalMap.get(key);
return (result == null || result == defaultValue) ? defaultValue : read(key, result);
}
@Override
public void forEach(BiConsumer<? super K, ? super E> action) {
internalMap.forEach((k, o) -> action.accept(k, read(k, o)));
}
@Override
public void replaceAll(BiFunction<? super K, ? super E, ? extends E> function) {
internalMap.replaceAll(transform(function));
}
@Override
public E putIfAbsent(K key, E value) {
return read(key, internalMap.putIfAbsent(key, write(key, value)));
}
@Override
public boolean remove(Object key, Object value) {
return internalMap.remove(key, search(value));
}
@Override
public boolean replace(K key, E oldValue, E newValue) {
return internalMap.replace(key, search(oldValue), write(key, newValue));
}
@Override
public E replace(K key, E value) {
return read(key, internalMap.replace(key, write(key, value)));
}
@Override
public E computeIfAbsent(K key, Function<? super K, ? extends E> mappingFunction) {
Function<K, I> function = k -> write(k, mappingFunction.apply(k));
return read(key, internalMap.computeIfAbsent(key, function));
}
@Override
public E computeIfPresent(K key,
BiFunction<? super K, ? super E, ? extends E> remappingFunction) {
I computed = internalMap.computeIfPresent(key, transform(remappingFunction));
|
[
"\t\treturn read(key, computed);"
] | 837
|
lcc
|
java
| null |
6fac8d0b410c99d32f6421d53dcbd4534f8f4a65b4dcede9
| 45
|
Your task is code completion.
package com.electronwill.nightconfig.core.utils;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
*
* A TransformingMap contains an internal {@code Map<K, InternalV>} values, and exposes the
* features of a {@code Map<K, ExternalV>} applying transformations to the values.
* <p>
* The transformations are applied "just in time", that is, the values are converted only when
* they are used, not during the construction of the TransformingMap.
* <p>
* For instance, if you have a {@code Map<String, String>} and you want to convert its values
* "just in time" to integers, you use a {@code TransformingMap<String, String, Integer>}.
* To get one, you create these three functions:
* <ul>
* <li>one that converts a String to an Integer: that's the parse transformation. It converts an
* Integer read from the internal map to a String.
* <li>one that converts an Integer to a String: that's the write transformation. It converts a
* String given to the TransformingMap to an Integer.
* <li>one that converts an Object to another Object: that's the search transformation. It is used
* (mainly) by the {@link #containsKey(Object)} method of the TransformingMap. If its argument is
* an Integer then it should convert it to an String in the same way as the write transformation.
* Otherwise, it is free to try to convert it to a String if possible, or not to.
* </ul>
*
* @author TheElectronWill
*/
@SuppressWarnings("unchecked")
public final class TransformingMap<K, I, E> extends AbstractMap<K, E> {
private final BiFunction<K, ? super I, ? extends E> readTransform;
private final BiFunction<K, ? super E, ? extends I> writeTransform;
private final Function<Object, ? extends I> searchTransform;
private final Map<K, I> internalMap;
/**
* Create a new TransformingMap.
*
* @param map the internal map to use
* @param readTransform the parse transformation (see javadoc of the class)
* @param writeTransform the write transformation (see javadoc of the class)
* @param searchTransform the search transformation (see javadoc of the class)
*/
public TransformingMap(Map<K, I> map,
Function<? super I, ? extends E> readTransform,
Function<? super E, ? extends I> writeTransform,
Function<Object, ? extends I> searchTransform) {
this.internalMap = map;
this.readTransform = (k, v) -> readTransform.apply(v);
this.writeTransform = (k, v) -> writeTransform.apply(v);
this.searchTransform = searchTransform;
}
/**
* Create a new TransformingMap.
*
* @param map the internal map to use
* @param readTransform the parse transformation (see javadoc of the class)
* @param writeTransform the write transformation (see javadoc of the class)
* @param searchTransform the search transformation (see javadoc of the class)
*/
public TransformingMap(Map<K, I> map,
BiFunction<K, ? super I, ? extends E> readTransform,
BiFunction<K, ? super E, ? extends I> writeTransform,
Function<Object, ? extends I> searchTransform) {
this.internalMap = map;
this.readTransform = readTransform;
this.writeTransform = writeTransform;
this.searchTransform = searchTransform;
}
private E read(Object key, I value) {
return readTransform.apply((K)key, value);
}
private I write(Object key, E value) {
return writeTransform.apply((K)key, value);
}
private I search(Object arg) {
return searchTransform.apply(arg);
}
@Override
public int size() {
return internalMap.size();
}
@Override
public boolean isEmpty() {
return internalMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return internalMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return internalMap.containsValue(searchTransform.apply(value));
}
@Override
public E get(Object key) {
return read(key, internalMap.get(key));
}
@Override
public E put(K key, E value) {
return read(key, internalMap.put(key, write(key, value)));
}
@Override
public E remove(Object key) {
return read(key, internalMap.remove(key));
}
@Override
public void putAll(Map<? extends K, ? extends E> m) {
internalMap.putAll(new TransformingMap(m, writeTransform, (k, o) -> o, o -> o));
}
@Override
public void clear() {
internalMap.clear();
}
@Override
public Set<K> keySet() {
return internalMap.keySet();
}
@Override
public Collection<E> values() {
return new TransformingCollection<>(internalMap.values(), o->read(null,o),
o->write(null,o), searchTransform);
}
@Override
public Set<Map.Entry<K, E>> entrySet() {
Function<Entry<K, I>, Entry<K, E>> read =
i -> TransformingMapEntry.from(i, readTransform, writeTransform);
Function<Entry<K, E>, Entry<K, I>> write =
e -> TransformingMapEntry.from(e, writeTransform, readTransform);
Function<Object, Map.Entry<K, I>> search = o -> {
if (o instanceof Map.Entry) {
Map.Entry<K, E> entry = (Map.Entry)o;
return TransformingMapEntry.from(entry, writeTransform, readTransform);
}
return null;
};
return new TransformingSet<>(internalMap.entrySet(), read, write, search);
}
@Override
public E getOrDefault(Object key, E defaultValue) {
I result = internalMap.get(key);
return (result == null || result == defaultValue) ? defaultValue : read(key, result);
}
@Override
public void forEach(BiConsumer<? super K, ? super E> action) {
internalMap.forEach((k, o) -> action.accept(k, read(k, o)));
}
@Override
public void replaceAll(BiFunction<? super K, ? super E, ? extends E> function) {
internalMap.replaceAll(transform(function));
}
@Override
public E putIfAbsent(K key, E value) {
return read(key, internalMap.putIfAbsent(key, write(key, value)));
}
@Override
public boolean remove(Object key, Object value) {
return internalMap.remove(key, search(value));
}
@Override
public boolean replace(K key, E oldValue, E newValue) {
return internalMap.replace(key, search(oldValue), write(key, newValue));
}
@Override
public E replace(K key, E value) {
return read(key, internalMap.replace(key, write(key, value)));
}
@Override
public E computeIfAbsent(K key, Function<? super K, ? extends E> mappingFunction) {
Function<K, I> function = k -> write(k, mappingFunction.apply(k));
return read(key, internalMap.computeIfAbsent(key, function));
}
@Override
public E computeIfPresent(K key,
BiFunction<? super K, ? super E, ? extends E> remappingFunction) {
I computed = internalMap.computeIfPresent(key, transform(remappingFunction));
|
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:**
The code is for a `TransformingMap` class, which extends `AbstractMap`. It applies transformations to the values of the internal map.
**Relevant lines and variables:**
* `readTransform`: a `BiFunction` that converts an internal value to an external value
* `writeTransform`: a `BiFunction` that converts an external value to an internal value
* `searchTransform`: a `Function` that converts an object to an internal value
* `internalMap`: the internal map that stores the actual values
* `key` and `value` are objects used in the `get`, `put`, `remove`, etc. methods
**Task-specific information:**
* The task is to complete the implementation of the `computeIfPresent` method, which is similar to the `computeIfAbsent` method.
* The `computeIfPresent` method takes a `key` and a `remappingFunction` as arguments, and returns the result of applying the `remappingFunction` to the existing value associated with the `key` if it exists.
**Cheat sheet:**
* We are in the `computeIfPresent` method, which should apply the `remappingFunction` to the existing value associated with the `key` if it exists.
* The `remappingFunction` is a `BiFunction` that takes the `key` and the existing value as arguments and returns the new value.
* The existing value is stored in the `internalMap` under the `key`.
* We need to use the `transform` method to apply the `remappingFunction` to the existing value.
**Next line(s) of code:**
Based on the cheat sheet, the next line of code should apply the `remappingFunction` to the existing value associated with the `key` in the `internalMap`. The `transform` method is used to apply the `remappingFunction` to the existing value.
```java
I computed = internalMap.computeIfPresent(key, transform(remappingFunction));
```
However, this line is already given in the prompt. The next line should be the one that applies the `readTransform` to the `computed` value to get the external value.
```java
return read(key, computed);
```
|
|
Please complete the code given below.
###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distributed under the GPL v3 license
#along with commercial support options.
#
#cyn.in is a Cynapse Invention.
#
#Copyright (C) 2008 Cynapse India Pvt. Ltd.
#
#This program is free software: you can redistribute it and/or modify it under
#the terms of the GNU General Public License as published by the Free Software
#Foundation, either version 3 of the License, or any later version and observe
#the Additional Terms applicable to this program and must display appropriate
#legal notices. In accordance with Section 7(b) of the GNU General Public
#License version 3, these Appropriate Legal Notices must retain the display of
#the "Powered by cyn.in" AND "A Cynapse Invention" logos. You should have
#received a copy of the detailed Additional Terms License with this program.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
#Public License for more details.
#
#You should have received a copy of the GNU General Public License along with
#this program. If not, see <http://www.gnu.org/licenses/>.
#
#You can contact Cynapse at support@cynapse.com with any problems with cyn.in.
#For any queries regarding the licensing, please send your mails to
# legal@cynapse.com
#
#You can also contact Cynapse at:
#802, Building No. 1,
#Dheeraj Sagar, Malad(W)
#Mumbai-400064, India
###############################################################################
import jsonlib
from Products.CMFCore.utils import getToolByName
from zope.component import getMultiAdapter
from ubify.cyninv2theme import setCurrentStatusMessageForUser
from ubify.cyninv2theme import getLocationListForAddContent
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from ubify.policy import CyninMessageFactory as _
from AccessControl import getSecurityManager
from Acquisition import aq_inner, aq_parent
from DateTime import DateTime
from plone.intelligenttext.transforms import convertWebIntelligentPlainTextToHtml
from ubify.policy import CyninMessageFactory as _
from kss.core import force_unicode
EmptymessageError = 'Empty message'
EmptydiscussionError = 'Empty Discussion'
RatingError = 'Rating Error'
EmptycommentError = 'Empty comment text'
def get_displaycountforlist():
return 5
def canreply(obj):
return getSecurityManager().checkPermission('Reply to item', aq_inner(obj)) > 0
def getjsondata(context,reply_dict,portal_url,item_url,extra_data={}):
site_encoding = context.plone_utils.getSiteEncoding()
mi = getToolByName(context, 'portal_membership')
util = getToolByName(context,'translation_service')
output = {}
items = []
for eachobj in reply_dict:
temp = {}
temp['depth'] = 0
if eachobj.has_key('prev_id'):
temp['prev_id'] = eachobj['prev_id']
else:
temp['prev_id'] = ''
reply = eachobj['object']
if reply <> None:
temp['id'] = reply.id
temp['replyurl'] = reply.absolute_url()
temp['replytoid'] = '-1'
if reply.inReplyTo() and reply.inReplyTo().portal_type == 'Discussion Item':
temp['replytoid'] = reply.inReplyTo().getId()
temp['depth'] = eachobj['depth']
temp['mdate'] = util.ulocalized_time(reply.ModificationDate(), 1, context, domain='plonelocales')
creator = reply.Creator()
temp['userid'] = creator
temp['userinfourl'] = portal_url + '/userinfo?userid=' + creator
temp['useravatarurl'] = mi.getPersonalPortrait(creator).absolute_url()
temp['replycooked'] = reply.cooked_text.decode(site_encoding)
temp['permalink'] = item_url + '#' + reply.id
items.append(temp)
output['items'] = items
for key,val in extra_data.items():
output[key] = val
return jsonlib.write(output)
class CustomMethods(object):
def findpreviouscommentid(self,allreplies,current_reply):
prev_id = ''
indexlist = [j for j in [allreplies.index(k) for k in allreplies if k['id'] == current_reply.id]]
if len(indexlist) > 0:
idx_reply = indexlist[0]
prev_idx = idx_reply - 1
#find id of an object with previndex
prev_list = [k['id'] for k in allreplies if allreplies.index(k) == prev_idx]
if len(prev_list) > 0:
prev_id = prev_list[0]
return prev_id
def get_replies(self,pd,object):
replies = []
def getRs(obj, replies, counter):
rs = pd.getDiscussionFor(obj).getReplies()
if len(rs) > 0:
rs.sort(lambda x, y: cmp(x.modified(), y.modified()))
for r in rs:
replies.append({'depth':counter,'id':r.id, 'object':r})
getRs(r, replies, counter=counter + 1)
try:
getRs(object, replies, 0)
except DiscussionNotAllowed:
# We tried to get discussions for an object that has not only
# discussions turned off but also no discussion container.
return []
return replies
def setstatusmessage(self):
portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
if portal_state.anonymous():
return
user_token = portal_state.member().getId()
if user_token is None:
return
message = ''
if self.request.form.has_key('com.cynapse.cynin.statusmessageinput'):
message = self.request.form['com.cynapse.cynin.statusmessageinput']
htmltitle = ''
if self.request.form.has_key('comcynapsesmessagetitle'):
htmltitle = self.request.form['comcynapsesmessagetitle']
message = message.strip(' ')
if message == '' or message.lower() == htmltitle.lower():
raise EmptymessageError, 'Unable to set message.'
obj = setCurrentStatusMessageForUser(portal_state.portal(),user_token,message,self.context)
return message
def creatediscussion(self):
strDiscussion = ''
strTags = ''
discussiontitle = ''
tagstitle = ''
obj = None
location = self.context
is_discussiontitle_reqd = False
strDiscussionTitle = ''
portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
cat = getToolByName(self.context, 'uid_catalog')
portal = portal_state.portal()
if self.request.has_key('com.cynapse.cynin.discussionmessageinput'):
strDiscussion = self.request['com.cynapse.cynin.discussionmessageinput']
if self.request.has_key('comcynapsediscussiontag'):
strTags = self.request['comcynapsediscussiontag']
if self.request.has_key('comcynapsediscussiontitle'):
discussiontitle = self.request['comcynapsediscussiontitle']
if self.request.has_key('comcynapsetagstitle'):
tagstitle = self.request['comcynapsetagstitle']
if self.request.has_key('comcynapseadddiscussioncontextuid'):
locationuid = self.request['comcynapseadddiscussioncontextuid']
else:
locationuid = ''
if self.request.has_key('com.cynapse.cynin.discussiontitle'):
is_discussiontitle_reqd = True
strDiscussionTitle = self.request['com.cynapse.cynin.discussiontitle']
query = {'UID':locationuid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
location = resbrains[0].getObject()
if strDiscussion == '' or strDiscussion.lower() == discussiontitle.lower():
raise EmptydiscussionError, 'Unable to add discussion with blank text.'
elif is_discussiontitle_reqd and (strDiscussionTitle == ''):
raise EmptydiscussionError, 'Unable to add discussion with blank title.'
else:
from ubify.cyninv2theme import addDiscussion
strActualTags = ''
if strTags.lower() != tagstitle.lower():
strActualTags = strTags
obj = addDiscussion(portal,strDiscussion,strActualTags,location,strDiscussionTitle)
if obj <> None:
here_text = _(u'lbl_here',u'here')
strlink = "<a href='%s'>%s</a>" % (obj.absolute_url(),self.context.translate(here_text),)
return strlink
def fetchlocationstoaddcontent(self):
portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
portal = portal_state.portal()
results = getLocationListForAddContent(portal)
output = {}
items = []
for eachobj in results:
temp = {}
temp['title'] = force_unicode(eachobj['object'].Title,'utf8')
temp['UID'] = eachobj['object'].UID
temp['occ'] = ''
if eachobj['canAdd'] == False or 'Discussion' in eachobj['disallowedtypes']:
temp['occ'] = 'disabledspaceselection'
temp['depth'] = eachobj['depth']
items.append(temp)
output['items'] = items
output = jsonlib.write(output)
return output
def ratecontent(self):
ratevalue = None
uid = None
if self.request.form.has_key('ratevalue'):
ratevalue = self.request.form['ratevalue']
if self.request.form.has_key('itemUID'):
uid = self.request.form['itemUID']
if ratevalue is None:
raise RatingError,'No rating value.'
elif uid is None:
raise RatingError,'No rating item.'
else:
pr = getToolByName(self.context, 'portal_ratings', None)
cat = getToolByName(self.context, 'uid_catalog')
pr.addRating(int(ratevalue), uid)
query = {'UID':uid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
obj = resbrains[0].getObject()
obj.reindexObject()
myval = int(pr.getUserRating(uid))
newval = int(pr.getRatingMean(uid))
ratecount = pr.getRatingCount(uid)
value_totalscore = pr.getCyninRating(uid)
value_scorecountlist = pr.getCyninRatingCount(uid)
value_pscore = value_scorecountlist['positivescore']
value_pcount = value_scorecountlist['positive']
value_nscore = value_scorecountlist['negativescore']
value_ncount = value_scorecountlist['negative']
if myval == 1:
newtitle=_(u'hated_it',u"Hate it (-2)")
elif myval == 2:
newtitle=_(u'didnt_like_it',u"Dislike it (-1)")
elif myval == 3:
newtitle=''
elif myval == 4:
newtitle=_(u'liked_it',u"Like it (+1)")
elif myval == 5:
newtitle=_(u'loved_it',u"Love it (+2)")
trans_title = self.context.translate(newtitle)
if value_totalscore > 0:
plus_sign = "+"
else:
plus_sign = ""
totalscore = plus_sign + str(value_totalscore)
output = trans_title + ',' + totalscore + ',' + str(value_pcount) + ',' + str(value_ncount)
return output
def fetchcomments(self,uid,itemindex,lasttimestamp,commentcount,lastcommentid,viewtype):
query = {'UID':uid}
pdt = getToolByName(self.context, 'portal_discussion', None)
cat = getToolByName(self.context, 'uid_catalog')
resbrains = cat.searchResults(query)
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
isDiscussable = contobj.isDiscussable()
canReply = canreply(contobj)
if isDiscussable and canReply:
passedcommentcount = 0
passedcommentcount = int(commentcount)
flasttimestamp = float(lasttimestamp)
datefromlasttimestamp = DateTime(flasttimestamp)
newlastdate = datefromlasttimestamp.timeTime()
marker_delete_objectid = ''
removeallcomments = False
disc_container = pdt.getDiscussionFor(contobj)
newreplycount = disc_container.replyCount(contobj)
allreplies = self.get_replies(pdt,contobj)
if passedcommentcount <> newreplycount:
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),contobj.absolute_url())
alldiscussions = disc_container.objectValues()
newlastcommentid = lastcommentid
newlyaddedcomments = [k for k in alldiscussions if k.modified().greaterThan(datefromlasttimestamp) and k.id not in (lastcommentid)]
newlyaddedcomments.sort(lambda x,y:cmp(x.modified(),y.modified()))
lenofnewcomments = len(newlyaddedcomments)
display_count = get_displaycountforlist()
lastxdiscussions = []
if lenofnewcomments >= display_count:
newlyaddedcomments.sort(lambda x,y:cmp(x.modified(),y.modified()),reverse=True)
lastxdiscussions = newlyaddedcomments[:display_count]
lastxdiscussions.sort(lambda x,y:cmp(x.modified(),y.modified()))
if viewtype.lower() == 'listview':
removeallcomments = True
else:
lastxdiscussions = newlyaddedcomments
if lenofnewcomments > 0 and len(alldiscussions) > display_count and viewtype.lower() == 'listview':
alldiscussions.sort(lambda x,y:cmp(x.modified(),y.modified()),reverse=True)
marker_discussion = alldiscussions[display_count-1: display_count]
if len(marker_discussion) > 0:
#delete nodes before this item
marker_delete_objectid = 'commenttable' + marker_discussion[0].id
complete_output = ''
list_reply_ids = []
for eachcomment in lastxdiscussions:
reply = disc_container.getReply(eachcomment.id)
if reply <> None:
parentsInThread = reply.parentsInThread()
depthvalue = 0
if viewtype.lower() == 'threadedview':
lenofparents = len(parentsInThread)
depthvalue = lenofparents - 1
prev_reply_id = self.findpreviouscommentid(allreplies,reply)
newlastdate = reply.modified().timeTime()
newlastcommentid = reply.id
replydict.append({'depth': depthvalue, 'object': reply,'prev_id':prev_reply_id,'view_type':viewtype})
list_reply_ids.append(reply.id)
other_data = {}
other_data['timeoutuid'] = uid
other_data['timeoutindex'] = itemindex
other_data['timeouttimestamp'] = str(newlastdate)
other_data['timeoutlastcommentid'] = newlastcommentid
other_data['timeoutcommentcount'] = str(newreplycount)
other_data['marker_delete'] = marker_delete_objectid
other_data['removeallcomments'] = str(removeallcomments)
other_data['shownocomments'] = str(False)
other_data['showmorecomments'] = str(False)
other_data['view_type'] = viewtype
other_data['canreply'] = str(canReply)
if newreplycount > display_count:
xmorecomments = newreplycount - display_count
other_data['xmorecomments'] = str(xmorecomments)
other_data['showmorecomments'] = str(True)
elif newreplycount > 0 and newreplycount <= display_count:
other_data['xmorecomments'] = ''
else:
other_data['shownocomments'] = str(True)
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),contobj.absolute_url(),other_data)
return jsondata
def fetchcommentsforlist(self):
uid = self.request['comcynapsecyninfetchUID']
itemindex = self.request['comcynapsecyninfetchindex']
lasttimestamp = self.request['comcynapselasttimestamp']
lastcommentid = self.request['comcynapselastcommentid']
lastcommentcount = self.request['comcynapsecommentcount']
viewtype = self.request['comcynapseviewtype']
return self.fetchcomments(uid,itemindex,lasttimestamp,lastcommentcount,lastcommentid,viewtype)
def fetchnewcomments(self):
uid = self.request['comcynapsecynincontextUID']
itemindex = ''
if self.request.has_key('comcynapsecyninfetchindex'):
itemindex = self.request['comcynapsecyninfetchindex']
lasttimestamp = self.request['comcynapselasttimestamp']
lastcommentid = self.request['comcynapselastcommentid']
lastcommentcount = self.request['comcynapsecommentcount']
viewtype = self.request['comcynapseviewtype']
return self.fetchcomments(uid,itemindex,lasttimestamp,lastcommentcount,lastcommentid,viewtype)
def addnewcomment(self):
uid = ''
itemindex = ''
viewtype = ''
lasttimestamp = ''
lastcommentid = ''
commentscount = ''
inreplyto = ''
if self.request.has_key('comcynapsecynincontextUID'):
uid = self.request['comcynapsecynincontextUID']
if self.request.has_key('comcynapsecyninitemindex'):
itemindex = self.request['comcynapsecyninitemindex']
if self.request.has_key('comcynapseviewtype'):
viewtype = self.request['comcynapseviewtype']
if self.request.has_key('comcynapselasttimestamp'):
lasttimestamp = self.request['comcynapselasttimestamp']
if self.request.has_key('comcynapselastcommentid'):
lastcommentid = self.request['comcynapselastcommentid']
if self.request.has_key('comcynapsecommentcount'):
commentscount = self.request['comcynapsecommentcount']
if self.request.has_key('inreplyto'):
inreplyto = self.request['inreplyto']
query = {'UID':uid}
pdt = getToolByName(self.context, 'portal_discussion', None)
cat = getToolByName(self.context, 'uid_catalog')
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
if contobj.isDiscussable() and canreply(contobj):
mtool = getToolByName(self.context, 'portal_membership')
username = mtool.getAuthenticatedMember().getId()
dobj = pdt.getDiscussionFor(contobj)
if len(self.request['comcynapsecyninNewCommentBody'].strip(' ')) == 0 or self.request['comcynapsecyninNewCommentBody'].lower() == self.request['comcynapsenewcommenttitle'].lower():
raise EmptycommentError, 'No comment text provided.'
else:
id = dobj.createReply(title="",text=self.request['comcynapsecyninNewCommentBody'], Creator=username)
reply = dobj.getReply(id)
reply.cooked_text = convertWebIntelligentPlainTextToHtml(reply.text)
if inreplyto != '':
replyto = dobj.getReply(inreplyto)
reply.setReplyTo(replyto)
if reply <> None:
from ubify.cyninv2theme import triggerAddOnDiscussionItem
triggerAddOnDiscussionItem(reply)
return self.fetchcomments(uid,itemindex,lasttimestamp,commentscount,lastcommentid,viewtype)
def togglecommentsview(self):
uid = ''
itemindex = ''
viewtype = ''
if self.request.has_key('uid'):
uid = self.request['uid']
if self.request.has_key('viewtype'):
viewtype = self.request['viewtype']
objcommentslist = []
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
pdt = getToolByName(self.context, 'portal_discussion', None)
query = {'UID':uid}
|
[
" cat = getToolByName(self.context, 'uid_catalog')"
] | 1,519
|
lcc
|
python
| null |
b581893ac400757aaad32eed292afd06559e04175e8d6fdf
| 46
|
Your task is code completion.
###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distributed under the GPL v3 license
#along with commercial support options.
#
#cyn.in is a Cynapse Invention.
#
#Copyright (C) 2008 Cynapse India Pvt. Ltd.
#
#This program is free software: you can redistribute it and/or modify it under
#the terms of the GNU General Public License as published by the Free Software
#Foundation, either version 3 of the License, or any later version and observe
#the Additional Terms applicable to this program and must display appropriate
#legal notices. In accordance with Section 7(b) of the GNU General Public
#License version 3, these Appropriate Legal Notices must retain the display of
#the "Powered by cyn.in" AND "A Cynapse Invention" logos. You should have
#received a copy of the detailed Additional Terms License with this program.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
#Public License for more details.
#
#You should have received a copy of the GNU General Public License along with
#this program. If not, see <http://www.gnu.org/licenses/>.
#
#You can contact Cynapse at support@cynapse.com with any problems with cyn.in.
#For any queries regarding the licensing, please send your mails to
# legal@cynapse.com
#
#You can also contact Cynapse at:
#802, Building No. 1,
#Dheeraj Sagar, Malad(W)
#Mumbai-400064, India
###############################################################################
import jsonlib
from Products.CMFCore.utils import getToolByName
from zope.component import getMultiAdapter
from ubify.cyninv2theme import setCurrentStatusMessageForUser
from ubify.cyninv2theme import getLocationListForAddContent
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from ubify.policy import CyninMessageFactory as _
from AccessControl import getSecurityManager
from Acquisition import aq_inner, aq_parent
from DateTime import DateTime
from plone.intelligenttext.transforms import convertWebIntelligentPlainTextToHtml
from ubify.policy import CyninMessageFactory as _
from kss.core import force_unicode
EmptymessageError = 'Empty message'
EmptydiscussionError = 'Empty Discussion'
RatingError = 'Rating Error'
EmptycommentError = 'Empty comment text'
def get_displaycountforlist():
return 5
def canreply(obj):
return getSecurityManager().checkPermission('Reply to item', aq_inner(obj)) > 0
def getjsondata(context,reply_dict,portal_url,item_url,extra_data={}):
site_encoding = context.plone_utils.getSiteEncoding()
mi = getToolByName(context, 'portal_membership')
util = getToolByName(context,'translation_service')
output = {}
items = []
for eachobj in reply_dict:
temp = {}
temp['depth'] = 0
if eachobj.has_key('prev_id'):
temp['prev_id'] = eachobj['prev_id']
else:
temp['prev_id'] = ''
reply = eachobj['object']
if reply <> None:
temp['id'] = reply.id
temp['replyurl'] = reply.absolute_url()
temp['replytoid'] = '-1'
if reply.inReplyTo() and reply.inReplyTo().portal_type == 'Discussion Item':
temp['replytoid'] = reply.inReplyTo().getId()
temp['depth'] = eachobj['depth']
temp['mdate'] = util.ulocalized_time(reply.ModificationDate(), 1, context, domain='plonelocales')
creator = reply.Creator()
temp['userid'] = creator
temp['userinfourl'] = portal_url + '/userinfo?userid=' + creator
temp['useravatarurl'] = mi.getPersonalPortrait(creator).absolute_url()
temp['replycooked'] = reply.cooked_text.decode(site_encoding)
temp['permalink'] = item_url + '#' + reply.id
items.append(temp)
output['items'] = items
for key,val in extra_data.items():
output[key] = val
return jsonlib.write(output)
class CustomMethods(object):
def findpreviouscommentid(self,allreplies,current_reply):
prev_id = ''
indexlist = [j for j in [allreplies.index(k) for k in allreplies if k['id'] == current_reply.id]]
if len(indexlist) > 0:
idx_reply = indexlist[0]
prev_idx = idx_reply - 1
#find id of an object with previndex
prev_list = [k['id'] for k in allreplies if allreplies.index(k) == prev_idx]
if len(prev_list) > 0:
prev_id = prev_list[0]
return prev_id
def get_replies(self,pd,object):
replies = []
def getRs(obj, replies, counter):
rs = pd.getDiscussionFor(obj).getReplies()
if len(rs) > 0:
rs.sort(lambda x, y: cmp(x.modified(), y.modified()))
for r in rs:
replies.append({'depth':counter,'id':r.id, 'object':r})
getRs(r, replies, counter=counter + 1)
try:
getRs(object, replies, 0)
except DiscussionNotAllowed:
# We tried to get discussions for an object that has not only
# discussions turned off but also no discussion container.
return []
return replies
def setstatusmessage(self):
portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
if portal_state.anonymous():
return
user_token = portal_state.member().getId()
if user_token is None:
return
message = ''
if self.request.form.has_key('com.cynapse.cynin.statusmessageinput'):
message = self.request.form['com.cynapse.cynin.statusmessageinput']
htmltitle = ''
if self.request.form.has_key('comcynapsesmessagetitle'):
htmltitle = self.request.form['comcynapsesmessagetitle']
message = message.strip(' ')
if message == '' or message.lower() == htmltitle.lower():
raise EmptymessageError, 'Unable to set message.'
obj = setCurrentStatusMessageForUser(portal_state.portal(),user_token,message,self.context)
return message
def creatediscussion(self):
strDiscussion = ''
strTags = ''
discussiontitle = ''
tagstitle = ''
obj = None
location = self.context
is_discussiontitle_reqd = False
strDiscussionTitle = ''
portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
cat = getToolByName(self.context, 'uid_catalog')
portal = portal_state.portal()
if self.request.has_key('com.cynapse.cynin.discussionmessageinput'):
strDiscussion = self.request['com.cynapse.cynin.discussionmessageinput']
if self.request.has_key('comcynapsediscussiontag'):
strTags = self.request['comcynapsediscussiontag']
if self.request.has_key('comcynapsediscussiontitle'):
discussiontitle = self.request['comcynapsediscussiontitle']
if self.request.has_key('comcynapsetagstitle'):
tagstitle = self.request['comcynapsetagstitle']
if self.request.has_key('comcynapseadddiscussioncontextuid'):
locationuid = self.request['comcynapseadddiscussioncontextuid']
else:
locationuid = ''
if self.request.has_key('com.cynapse.cynin.discussiontitle'):
is_discussiontitle_reqd = True
strDiscussionTitle = self.request['com.cynapse.cynin.discussiontitle']
query = {'UID':locationuid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
location = resbrains[0].getObject()
if strDiscussion == '' or strDiscussion.lower() == discussiontitle.lower():
raise EmptydiscussionError, 'Unable to add discussion with blank text.'
elif is_discussiontitle_reqd and (strDiscussionTitle == ''):
raise EmptydiscussionError, 'Unable to add discussion with blank title.'
else:
from ubify.cyninv2theme import addDiscussion
strActualTags = ''
if strTags.lower() != tagstitle.lower():
strActualTags = strTags
obj = addDiscussion(portal,strDiscussion,strActualTags,location,strDiscussionTitle)
if obj <> None:
here_text = _(u'lbl_here',u'here')
strlink = "<a href='%s'>%s</a>" % (obj.absolute_url(),self.context.translate(here_text),)
return strlink
def fetchlocationstoaddcontent(self):
portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
portal = portal_state.portal()
results = getLocationListForAddContent(portal)
output = {}
items = []
for eachobj in results:
temp = {}
temp['title'] = force_unicode(eachobj['object'].Title,'utf8')
temp['UID'] = eachobj['object'].UID
temp['occ'] = ''
if eachobj['canAdd'] == False or 'Discussion' in eachobj['disallowedtypes']:
temp['occ'] = 'disabledspaceselection'
temp['depth'] = eachobj['depth']
items.append(temp)
output['items'] = items
output = jsonlib.write(output)
return output
def ratecontent(self):
ratevalue = None
uid = None
if self.request.form.has_key('ratevalue'):
ratevalue = self.request.form['ratevalue']
if self.request.form.has_key('itemUID'):
uid = self.request.form['itemUID']
if ratevalue is None:
raise RatingError,'No rating value.'
elif uid is None:
raise RatingError,'No rating item.'
else:
pr = getToolByName(self.context, 'portal_ratings', None)
cat = getToolByName(self.context, 'uid_catalog')
pr.addRating(int(ratevalue), uid)
query = {'UID':uid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
obj = resbrains[0].getObject()
obj.reindexObject()
myval = int(pr.getUserRating(uid))
newval = int(pr.getRatingMean(uid))
ratecount = pr.getRatingCount(uid)
value_totalscore = pr.getCyninRating(uid)
value_scorecountlist = pr.getCyninRatingCount(uid)
value_pscore = value_scorecountlist['positivescore']
value_pcount = value_scorecountlist['positive']
value_nscore = value_scorecountlist['negativescore']
value_ncount = value_scorecountlist['negative']
if myval == 1:
newtitle=_(u'hated_it',u"Hate it (-2)")
elif myval == 2:
newtitle=_(u'didnt_like_it',u"Dislike it (-1)")
elif myval == 3:
newtitle=''
elif myval == 4:
newtitle=_(u'liked_it',u"Like it (+1)")
elif myval == 5:
newtitle=_(u'loved_it',u"Love it (+2)")
trans_title = self.context.translate(newtitle)
if value_totalscore > 0:
plus_sign = "+"
else:
plus_sign = ""
totalscore = plus_sign + str(value_totalscore)
output = trans_title + ',' + totalscore + ',' + str(value_pcount) + ',' + str(value_ncount)
return output
def fetchcomments(self,uid,itemindex,lasttimestamp,commentcount,lastcommentid,viewtype):
query = {'UID':uid}
pdt = getToolByName(self.context, 'portal_discussion', None)
cat = getToolByName(self.context, 'uid_catalog')
resbrains = cat.searchResults(query)
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
isDiscussable = contobj.isDiscussable()
canReply = canreply(contobj)
if isDiscussable and canReply:
passedcommentcount = 0
passedcommentcount = int(commentcount)
flasttimestamp = float(lasttimestamp)
datefromlasttimestamp = DateTime(flasttimestamp)
newlastdate = datefromlasttimestamp.timeTime()
marker_delete_objectid = ''
removeallcomments = False
disc_container = pdt.getDiscussionFor(contobj)
newreplycount = disc_container.replyCount(contobj)
allreplies = self.get_replies(pdt,contobj)
if passedcommentcount <> newreplycount:
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),contobj.absolute_url())
alldiscussions = disc_container.objectValues()
newlastcommentid = lastcommentid
newlyaddedcomments = [k for k in alldiscussions if k.modified().greaterThan(datefromlasttimestamp) and k.id not in (lastcommentid)]
newlyaddedcomments.sort(lambda x,y:cmp(x.modified(),y.modified()))
lenofnewcomments = len(newlyaddedcomments)
display_count = get_displaycountforlist()
lastxdiscussions = []
if lenofnewcomments >= display_count:
newlyaddedcomments.sort(lambda x,y:cmp(x.modified(),y.modified()),reverse=True)
lastxdiscussions = newlyaddedcomments[:display_count]
lastxdiscussions.sort(lambda x,y:cmp(x.modified(),y.modified()))
if viewtype.lower() == 'listview':
removeallcomments = True
else:
lastxdiscussions = newlyaddedcomments
if lenofnewcomments > 0 and len(alldiscussions) > display_count and viewtype.lower() == 'listview':
alldiscussions.sort(lambda x,y:cmp(x.modified(),y.modified()),reverse=True)
marker_discussion = alldiscussions[display_count-1: display_count]
if len(marker_discussion) > 0:
#delete nodes before this item
marker_delete_objectid = 'commenttable' + marker_discussion[0].id
complete_output = ''
list_reply_ids = []
for eachcomment in lastxdiscussions:
reply = disc_container.getReply(eachcomment.id)
if reply <> None:
parentsInThread = reply.parentsInThread()
depthvalue = 0
if viewtype.lower() == 'threadedview':
lenofparents = len(parentsInThread)
depthvalue = lenofparents - 1
prev_reply_id = self.findpreviouscommentid(allreplies,reply)
newlastdate = reply.modified().timeTime()
newlastcommentid = reply.id
replydict.append({'depth': depthvalue, 'object': reply,'prev_id':prev_reply_id,'view_type':viewtype})
list_reply_ids.append(reply.id)
other_data = {}
other_data['timeoutuid'] = uid
other_data['timeoutindex'] = itemindex
other_data['timeouttimestamp'] = str(newlastdate)
other_data['timeoutlastcommentid'] = newlastcommentid
other_data['timeoutcommentcount'] = str(newreplycount)
other_data['marker_delete'] = marker_delete_objectid
other_data['removeallcomments'] = str(removeallcomments)
other_data['shownocomments'] = str(False)
other_data['showmorecomments'] = str(False)
other_data['view_type'] = viewtype
other_data['canreply'] = str(canReply)
if newreplycount > display_count:
xmorecomments = newreplycount - display_count
other_data['xmorecomments'] = str(xmorecomments)
other_data['showmorecomments'] = str(True)
elif newreplycount > 0 and newreplycount <= display_count:
other_data['xmorecomments'] = ''
else:
other_data['shownocomments'] = str(True)
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),contobj.absolute_url(),other_data)
return jsondata
def fetchcommentsforlist(self):
uid = self.request['comcynapsecyninfetchUID']
itemindex = self.request['comcynapsecyninfetchindex']
lasttimestamp = self.request['comcynapselasttimestamp']
lastcommentid = self.request['comcynapselastcommentid']
lastcommentcount = self.request['comcynapsecommentcount']
viewtype = self.request['comcynapseviewtype']
return self.fetchcomments(uid,itemindex,lasttimestamp,lastcommentcount,lastcommentid,viewtype)
def fetchnewcomments(self):
uid = self.request['comcynapsecynincontextUID']
itemindex = ''
if self.request.has_key('comcynapsecyninfetchindex'):
itemindex = self.request['comcynapsecyninfetchindex']
lasttimestamp = self.request['comcynapselasttimestamp']
lastcommentid = self.request['comcynapselastcommentid']
lastcommentcount = self.request['comcynapsecommentcount']
viewtype = self.request['comcynapseviewtype']
return self.fetchcomments(uid,itemindex,lasttimestamp,lastcommentcount,lastcommentid,viewtype)
def addnewcomment(self):
uid = ''
itemindex = ''
viewtype = ''
lasttimestamp = ''
lastcommentid = ''
commentscount = ''
inreplyto = ''
if self.request.has_key('comcynapsecynincontextUID'):
uid = self.request['comcynapsecynincontextUID']
if self.request.has_key('comcynapsecyninitemindex'):
itemindex = self.request['comcynapsecyninitemindex']
if self.request.has_key('comcynapseviewtype'):
viewtype = self.request['comcynapseviewtype']
if self.request.has_key('comcynapselasttimestamp'):
lasttimestamp = self.request['comcynapselasttimestamp']
if self.request.has_key('comcynapselastcommentid'):
lastcommentid = self.request['comcynapselastcommentid']
if self.request.has_key('comcynapsecommentcount'):
commentscount = self.request['comcynapsecommentcount']
if self.request.has_key('inreplyto'):
inreplyto = self.request['inreplyto']
query = {'UID':uid}
pdt = getToolByName(self.context, 'portal_discussion', None)
cat = getToolByName(self.context, 'uid_catalog')
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
if contobj.isDiscussable() and canreply(contobj):
mtool = getToolByName(self.context, 'portal_membership')
username = mtool.getAuthenticatedMember().getId()
dobj = pdt.getDiscussionFor(contobj)
if len(self.request['comcynapsecyninNewCommentBody'].strip(' ')) == 0 or self.request['comcynapsecyninNewCommentBody'].lower() == self.request['comcynapsenewcommenttitle'].lower():
raise EmptycommentError, 'No comment text provided.'
else:
id = dobj.createReply(title="",text=self.request['comcynapsecyninNewCommentBody'], Creator=username)
reply = dobj.getReply(id)
reply.cooked_text = convertWebIntelligentPlainTextToHtml(reply.text)
if inreplyto != '':
replyto = dobj.getReply(inreplyto)
reply.setReplyTo(replyto)
if reply <> None:
from ubify.cyninv2theme import triggerAddOnDiscussionItem
triggerAddOnDiscussionItem(reply)
return self.fetchcomments(uid,itemindex,lasttimestamp,commentscount,lastcommentid,viewtype)
def togglecommentsview(self):
uid = ''
itemindex = ''
viewtype = ''
if self.request.has_key('uid'):
uid = self.request['uid']
if self.request.has_key('viewtype'):
viewtype = self.request['viewtype']
objcommentslist = []
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
pdt = getToolByName(self.context, 'portal_discussion', None)
query = {'UID':uid}
|
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 togglecommentsview(self):
uid = ''
itemindex = ''
viewtype = ''
if self.request.has_key('uid'):
uid = self.request['uid']
if self.request.has_key('viewtype'):
viewtype = self.request['viewtype']
objcommentslist = []
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
pdt = getToolByName(self.context, 'portal_discussion', None)
query = {'UID':uid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
if contobj.isDiscussable() and canreply(contobj):
mtool = getToolByName(self.context, 'portal_membership')
username = mtool.getAuthenticatedMember().getId()
dobj = pdt.getDiscussionFor(contobj)
if len(self.request['comcynapsecyninNewCommentBody'].strip(' ')) == 0 or self.request['comcynapsecyninNewCommentBody'].lower() == self.request['comcynapsenewcommenttitle'].lower():
raise EmptycommentError, 'No comment text provided.'
else:
id = dobj.createReply(title="",text=self.request['comcynapsecyninNewCommentBody'], Creator=username)
reply = dobj.getReply(id)
reply.cooked_text = convertWebIntelligentPlainTextToHtml(reply.text)
if inreplyto != '':
replyto = dobj.getReply(inreplyto)
reply.setReplyTo(replyto)
if reply <> None:
from ubify.cyninv2theme import triggerAddOnDiscussionItem
triggerAddOnDiscussionItem(reply)
return self.fetchcomments(uid,itemindex,lasttimestamp,commentscount,lastcommentid,viewtype)
def togglecommentsview(self):
uid = ''
itemindex = ''
viewtype = ''
if self.request.has_key('uid'):
uid = self.request['uid']
if self.request.has_key('viewtype'):
viewtype = self.request['viewtype']
objcommentslist = []
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
pdt = getToolByName(self.context, 'portal_discussion', None)
query = {'UID':uid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
if contobj.isDiscussable() and canreply(contobj):
mtool = getToolByName(self.context, 'portal_membership')
username = mtool.getAuthenticatedMember().getId()
dobj = pdt.getDiscussionFor(contobj)
if len(self.request['comcynapsecyninNewCommentBody'].strip(' ')) == 0 or self.request['comcynapsecyninNewCommentBody'].lower() == self.request['comcynapsenewcommenttitle'].lower():
raise EmptycommentError, 'No comment text provided.'
else:
id = dobj.createReply(title="",text=self.request['comcynapsecyninNewCommentBody'], Creator=username)
reply = dobj.getReply(id)
reply.cooked_text = convertWebIntelligentPlainTextToHtml(reply.text)
if inreplyto != '':
replyto = dobj.getReply(inreplyto)
reply.setReplyTo(replyto)
if reply <> None:
from ubify.cyninv2theme import triggerAddOnDiscussionItem
triggerAddOnDiscussionItem(reply)
return self.fetchcomments(uid,itemindex,lasttimestamp,commentscount,lastcommentid,viewtype)
def togglecommentsview(self):
uid = ''
itemindex = ''
viewtype = ''
if self.request.has_key('uid'):
uid = self.request['uid']
if self.request.has_key('viewtype'):
viewtype = self.request['viewtype']
objcommentslist = []
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
pdt = getToolByName(self.context, 'portal_discussion', None)
query = {'UID':uid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
if contobj.isDiscussable() and canreply(contobj):
mtool = getToolByName(self.context, 'portal_membership')
username = mtool.getAuthenticatedMember().getId()
dobj = pdt.getDiscussionFor(contobj)
if len(self.request['comcynapsecyninNewCommentBody'].strip(' ')) == 0 or self.request['comcynapsecyninNewCommentBody'].lower() == self.request['comcynapsenewcommenttitle'].lower():
raise EmptycommentError, 'No comment text provided.'
else:
id = dobj.createReply(title="",text=self.request['comcynapsecyninNewCommentBody'], Creator=username)
reply = dobj.getReply(id)
reply.cooked_text = convertWebIntelligentPlainTextToHtml(reply.text)
if inreplyto != '':
replyto = dobj.getReply(inreplyto)
reply.setReplyTo(replyto)
if reply <> None:
from ubify.cyninv2theme import triggerAddOnDiscussionItem
triggerAddOnDiscussionItem(reply)
return self.fetchcomments(uid,itemindex,lasttimestamp,commentscount,lastcommentid,viewtype)
def togglecommentsview(self):
uid = ''
itemindex = ''
viewtype = ''
if self.request.has_key('uid'):
uid = self.request['uid']
if self.request.has_key('viewtype'):
viewtype = self.request['viewtype']
objcommentslist = []
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
pdt = getToolByName(self.context, 'portal_discussion', None)
query = {'UID':uid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
if contobj.isDiscussable() and canreply(contobj):
mtool = getToolByName(self.context, 'portal_membership')
username = mtool.getAuthenticatedMember().getId()
dobj = pdt.getDiscussionFor(contobj)
if len(self.request['comcynapsecyninNewCommentBody'].strip(' ')) == 0 or self.request['comcynapsecyninNewCommentBody'].lower() == self.request['comcynapsenewcommenttitle'].lower():
raise EmptycommentError, 'No comment text provided.'
else:
id = dobj.createReply(title="",text=self.request['comcynapsecyninNewCommentBody'], Creator=username)
reply = dobj.getReply(id)
reply.cooked_text = convertWebIntelligentPlainTextToHtml(reply.text)
if inreplyto != '':
replyto = dobj.getReply(inreplyto)
reply.setReplyTo(replyto)
if reply <> None:
from ubify.cyninv2theme import triggerAddOnDiscussionItem
triggerAddOnDiscussionItem(reply)
return self.fetchcomments(uid,itemindex,lasttimestamp,commentscount,lastcommentid,viewtype)
def togglecommentsview(self):
uid = ''
itemindex = ''
viewtype = ''
if self.request.has_key('uid'):
uid = self.request['uid']
if self.request.has_key('viewtype'):
viewtype = self.request['viewtype']
objcommentslist = []
replydict = []
jsondata = getjsondata(self.context,replydict,self.context.portal_url(),'')
pdt = getToolByName(self.context, 'portal_discussion', None)
query = {'UID':uid}
resbrains = cat.searchResults(query)
if len(resbrains) == 1:
contobj = resbrains[0].getObject()
if contobj.isDiscussable() and canreply(contobj):
mtool = getToolByName(self.context, 'portal_membership')
username = mtool.getAuthenticatedMember().getId()
dobj = pdt.getDiscussionFor(contobj)
if len(self.request['comcynapsecyninNewCommentBody'].strip(' ')) == 0 or self.request['comcynapsecyninNewCommentBody'].lower() == self.request['comcynapsenewcommenttitle'].lower():
raise EmptycommentError, 'No comment text provided.'
else:
id = dobj.createReply(title="",text=self.request['comcynapsecyninNewCommentBody'], Creator=username)
reply = dobj.getReply(id)
reply.cooked_text = convertWebIntelligentPlainTextToHtml(reply.text)
if inreplyto != '':
replyto = dobj.getReply(inreplyto)
reply.setReplyTo(replyto)
if reply <> None:
from ubify.cyninv2theme import triggerAddOnDiscussionItem
triggerAddOnDiscussionItem(reply)
return self.fetchcomments(uid,itemindex,lasttimestamp,commentscount,lastcommentid,viewtype)
def togglecommentsview(self):
uid =
|
|
Please complete the code given below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.InteropServices;
namespace Server
{
public class TileMatrix
{
private static readonly ILog log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType );
private readonly Tile[][][][][] m_StaticTiles;
private readonly Tile[][][] m_LandTiles;
private readonly Tile[] m_InvalidLandBlock;
private readonly UopIndex m_MapIndex;
private readonly int m_FileIndex;
private readonly int[][] m_StaticPatches;
private readonly int[][] m_LandPatches;
public Map Owner { get; }
public int BlockWidth { get; }
public int BlockHeight { get; }
public int Width { get; }
public int Height { get; }
public FileStream MapStream { get; set; }
public bool MapUOPPacked => ( m_MapIndex != null );
public FileStream IndexStream { get; set; }
public FileStream DataStream { get; set; }
public BinaryReader IndexReader { get; set; }
public bool Exists => ( MapStream != null && IndexStream != null && DataStream != null );
private static readonly List<TileMatrix> m_Instances = new List<TileMatrix>();
private readonly List<TileMatrix> m_FileShare;
public TileMatrix( Map owner, int fileIndex, int mapID, int width, int height )
{
m_FileShare = new List<TileMatrix>();
for ( int i = 0; i < m_Instances.Count; ++i )
{
TileMatrix tm = m_Instances[i];
if ( tm.m_FileIndex == fileIndex )
{
tm.m_FileShare.Add( this );
m_FileShare.Add( tm );
}
}
m_Instances.Add( this );
m_FileIndex = fileIndex;
Width = width;
Height = height;
BlockWidth = width >> 3;
BlockHeight = height >> 3;
Owner = owner;
if ( fileIndex != 0x7F )
{
string mapPath = Core.FindDataFile( "map{0}.mul", fileIndex );
if ( File.Exists( mapPath ) )
{
MapStream = new FileStream( mapPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
}
else
{
mapPath = Core.FindDataFile( "map{0}LegacyMUL.uop", fileIndex );
if ( File.Exists( mapPath ) )
{
MapStream = new FileStream( mapPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
m_MapIndex = new UopIndex( MapStream );
}
}
string indexPath = Core.FindDataFile( "staidx{0}.mul", fileIndex );
if ( File.Exists( indexPath ) )
{
IndexStream = new FileStream( indexPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
IndexReader = new BinaryReader( IndexStream );
}
string staticsPath = Core.FindDataFile( "statics{0}.mul", fileIndex );
if ( File.Exists( staticsPath ) )
DataStream = new FileStream( staticsPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
}
EmptyStaticBlock = new Tile[8][][];
for ( int i = 0; i < 8; ++i )
{
EmptyStaticBlock[i] = new Tile[8][];
for ( int j = 0; j < 8; ++j )
EmptyStaticBlock[i][j] = new Tile[0];
}
m_InvalidLandBlock = new Tile[196];
m_LandTiles = new Tile[BlockWidth][][];
m_StaticTiles = new Tile[BlockWidth][][][][];
m_StaticPatches = new int[BlockWidth][];
m_LandPatches = new int[BlockWidth][];
}
public Tile[][][] EmptyStaticBlock { get; }
public void SetStaticBlock( int x, int y, Tile[][][] value )
{
if ( x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight )
return;
if ( m_StaticTiles[x] == null )
m_StaticTiles[x] = new Tile[BlockHeight][][][];
m_StaticTiles[x][y] = value;
if ( m_StaticPatches[x] == null )
m_StaticPatches[x] = new int[( BlockHeight + 31 ) >> 5];
m_StaticPatches[x][y >> 5] |= 1 << ( y & 0x1F );
}
public Tile[][][] GetStaticBlock( int x, int y )
{
if ( x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight || DataStream == null || IndexStream == null )
return EmptyStaticBlock;
if ( m_StaticTiles[x] == null )
m_StaticTiles[x] = new Tile[BlockHeight][][][];
Tile[][][] tiles = m_StaticTiles[x][y];
if ( tiles == null )
{
for ( int i = 0; tiles == null && i < m_FileShare.Count; ++i )
{
TileMatrix shared = m_FileShare[i];
if ( x >= 0 && x < shared.BlockWidth && y >= 0 && y < shared.BlockHeight )
{
Tile[][][][] theirTiles = shared.m_StaticTiles[x];
if ( theirTiles != null )
tiles = theirTiles[y];
if ( tiles != null )
{
int[] theirBits = shared.m_StaticPatches[x];
if ( theirBits != null && ( theirBits[y >> 5] & ( 1 << ( y & 0x1F ) ) ) != 0 )
tiles = null;
}
}
}
if ( tiles == null )
tiles = ReadStaticBlock( x, y );
m_StaticTiles[x][y] = tiles;
}
return tiles;
}
public Tile[] GetStaticTiles( int x, int y )
{
Tile[][][] tiles = GetStaticBlock( x >> 3, y >> 3 );
return Season.PatchTiles( tiles[x & 0x7][y & 0x7], Owner.Season );
}
private static readonly TileList m_TilesList = new TileList();
public Tile[] GetStaticTiles( int x, int y, bool multis )
{
if ( !multis )
return GetStaticTiles( x, y );
Tile[][][] tiles = GetStaticBlock( x >> 3, y >> 3 );
var eable = Owner.GetMultiTilesAt( x, y );
if ( !eable.Any() )
return Season.PatchTiles( tiles[x & 0x7][y & 0x7], Owner.Season );
foreach ( Tile[] multiTiles in eable )
{
m_TilesList.AddRange( multiTiles );
}
m_TilesList.AddRange( Season.PatchTiles( tiles[x & 0x7][y & 0x7], Owner.Season ) );
return m_TilesList.ToArray();
}
public void SetLandBlock( int x, int y, Tile[] value )
{
if ( x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight )
return;
if ( m_LandTiles[x] == null )
m_LandTiles[x] = new Tile[BlockHeight][];
m_LandTiles[x][y] = value;
if ( m_LandPatches[x] == null )
m_LandPatches[x] = new int[( BlockHeight + 31 ) >> 5];
m_LandPatches[x][y >> 5] |= 1 << ( y & 0x1F );
}
public Tile[] GetLandBlock( int x, int y )
{
if ( x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight || MapStream == null )
return m_InvalidLandBlock;
if ( m_LandTiles[x] == null )
m_LandTiles[x] = new Tile[BlockHeight][];
Tile[] tiles = m_LandTiles[x][y];
if ( tiles == null )
{
for ( int i = 0; tiles == null && i < m_FileShare.Count; ++i )
{
TileMatrix shared = m_FileShare[i];
if ( x >= 0 && x < shared.BlockWidth && y >= 0 && y < shared.BlockHeight )
{
Tile[][] theirTiles = shared.m_LandTiles[x];
if ( theirTiles != null )
tiles = theirTiles[y];
if ( tiles != null )
{
int[] theirBits = shared.m_LandPatches[x];
if ( theirBits != null && ( theirBits[y >> 5] & ( 1 << ( y & 0x1F ) ) ) != 0 )
tiles = null;
}
}
}
if ( tiles == null )
tiles = ReadLandBlock( x, y );
m_LandTiles[x][y] = tiles;
}
return tiles;
}
public Tile GetLandTile( int x, int y )
{
Tile[] tiles = GetLandBlock( x >> 3, y >> 3 );
return tiles[( ( y & 0x7 ) << 3 ) + ( x & 0x7 )];
}
private static TileList[][] m_Lists;
private static byte[] m_Buffer;
private static StaticTile[] m_TileBuffer = new StaticTile[128];
private unsafe Tile[][][] ReadStaticBlock( int x, int y )
{
try
{
IndexReader.BaseStream.Seek( ( ( x * BlockHeight ) + y ) * 12, SeekOrigin.Begin );
int lookup = IndexReader.ReadInt32();
int length = IndexReader.ReadInt32();
if ( lookup < 0 || length <= 0 )
{
return EmptyStaticBlock;
}
else
{
int count = length / 7;
DataStream.Seek( lookup, SeekOrigin.Begin );
if ( m_TileBuffer.Length < count )
m_TileBuffer = new StaticTile[count];
StaticTile[] staTiles = m_TileBuffer; // new StaticTile[tileCount];
fixed ( StaticTile* pTiles = staTiles )
{
if ( m_Buffer == null || length > m_Buffer.Length )
m_Buffer = new byte[length];
DataStream.Read( m_Buffer, 0, length );
Marshal.Copy( m_Buffer, 0, new IntPtr( pTiles ), length );
if ( m_Lists == null )
{
m_Lists = new TileList[8][];
for ( int i = 0; i < 8; ++i )
{
m_Lists[i] = new TileList[8];
for ( int j = 0; j < 8; ++j )
m_Lists[i][j] = new TileList();
}
}
TileList[][] lists = m_Lists;
for ( int i = 0; i < count; i++ )
{
StaticTile* pCur = pTiles + i;
lists[pCur->m_X & 0x7][pCur->m_Y & 0x7].Add( pCur->m_ID, pCur->m_Z );
}
Tile[][][] tiles = new Tile[8][][];
for ( int i = 0; i < 8; ++i )
{
tiles[i] = new Tile[8][];
for ( int j = 0; j < 8; ++j )
tiles[i][j] = lists[i][j].ToArray();
}
return tiles;
}
}
}
catch ( EndOfStreamException )
{
if ( DateTime.UtcNow >= m_NextStaticWarning )
{
log.Warning( "Static EOS for {0} ({1}, {2})", Owner, x, y );
m_NextStaticWarning = DateTime.UtcNow + TimeSpan.FromMinutes( 1.0 );
}
return EmptyStaticBlock;
}
}
private DateTime m_NextStaticWarning;
private DateTime m_NextLandWarning;
private unsafe Tile[] ReadLandBlock( int x, int y )
{
try
{
int offset = ( ( x * BlockHeight ) + y ) * 196 + 4;
if ( m_MapIndex != null )
offset = m_MapIndex.Lookup( offset );
MapStream.Seek( offset, SeekOrigin.Begin );
Tile[] tiles = new Tile[64];
fixed ( Tile* pTiles = tiles )
{
if ( m_Buffer == null || 192 > m_Buffer.Length )
m_Buffer = new byte[192];
MapStream.Read( m_Buffer, 0, 192 );
Marshal.Copy( m_Buffer, 0, new IntPtr( pTiles ), 192 );
}
return tiles;
}
catch
{
if ( DateTime.UtcNow >= m_NextLandWarning )
{
log.Warning( "Land EOS for {0} ({1}, {2})", Owner, x, y );
m_NextLandWarning = DateTime.UtcNow + TimeSpan.FromMinutes( 1.0 );
}
return m_InvalidLandBlock;
}
}
public void Dispose()
{
if ( MapStream != null )
MapStream.Close();
if ( m_MapIndex != null )
m_MapIndex.Close();
if ( DataStream != null )
DataStream.Close();
if ( IndexReader != null )
IndexReader.Close();
}
}
[System.Runtime.InteropServices.StructLayout( System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1 )]
public struct StaticTile
{
public ushort m_ID;
public byte m_X;
public byte m_Y;
public sbyte m_Z;
public short m_Hue;
}
[System.Runtime.InteropServices.StructLayout( System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1 )]
public struct Tile
{
internal ushort m_ID;
internal sbyte m_Z;
public int ID
{
get { return m_ID; }
|
[
"\t\t\tset { m_ID = (ushort)value; }"
] | 1,528
|
lcc
|
csharp
| null |
b5474d9a2623627f5e344cff1193ab0629353b34b75b1c81
| 47
|
Your task is code completion.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.InteropServices;
namespace Server
{
public class TileMatrix
{
private static readonly ILog log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType );
private readonly Tile[][][][][] m_StaticTiles;
private readonly Tile[][][] m_LandTiles;
private readonly Tile[] m_InvalidLandBlock;
private readonly UopIndex m_MapIndex;
private readonly int m_FileIndex;
private readonly int[][] m_StaticPatches;
private readonly int[][] m_LandPatches;
public Map Owner { get; }
public int BlockWidth { get; }
public int BlockHeight { get; }
public int Width { get; }
public int Height { get; }
public FileStream MapStream { get; set; }
public bool MapUOPPacked => ( m_MapIndex != null );
public FileStream IndexStream { get; set; }
public FileStream DataStream { get; set; }
public BinaryReader IndexReader { get; set; }
public bool Exists => ( MapStream != null && IndexStream != null && DataStream != null );
private static readonly List<TileMatrix> m_Instances = new List<TileMatrix>();
private readonly List<TileMatrix> m_FileShare;
public TileMatrix( Map owner, int fileIndex, int mapID, int width, int height )
{
m_FileShare = new List<TileMatrix>();
for ( int i = 0; i < m_Instances.Count; ++i )
{
TileMatrix tm = m_Instances[i];
if ( tm.m_FileIndex == fileIndex )
{
tm.m_FileShare.Add( this );
m_FileShare.Add( tm );
}
}
m_Instances.Add( this );
m_FileIndex = fileIndex;
Width = width;
Height = height;
BlockWidth = width >> 3;
BlockHeight = height >> 3;
Owner = owner;
if ( fileIndex != 0x7F )
{
string mapPath = Core.FindDataFile( "map{0}.mul", fileIndex );
if ( File.Exists( mapPath ) )
{
MapStream = new FileStream( mapPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
}
else
{
mapPath = Core.FindDataFile( "map{0}LegacyMUL.uop", fileIndex );
if ( File.Exists( mapPath ) )
{
MapStream = new FileStream( mapPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
m_MapIndex = new UopIndex( MapStream );
}
}
string indexPath = Core.FindDataFile( "staidx{0}.mul", fileIndex );
if ( File.Exists( indexPath ) )
{
IndexStream = new FileStream( indexPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
IndexReader = new BinaryReader( IndexStream );
}
string staticsPath = Core.FindDataFile( "statics{0}.mul", fileIndex );
if ( File.Exists( staticsPath ) )
DataStream = new FileStream( staticsPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
}
EmptyStaticBlock = new Tile[8][][];
for ( int i = 0; i < 8; ++i )
{
EmptyStaticBlock[i] = new Tile[8][];
for ( int j = 0; j < 8; ++j )
EmptyStaticBlock[i][j] = new Tile[0];
}
m_InvalidLandBlock = new Tile[196];
m_LandTiles = new Tile[BlockWidth][][];
m_StaticTiles = new Tile[BlockWidth][][][][];
m_StaticPatches = new int[BlockWidth][];
m_LandPatches = new int[BlockWidth][];
}
public Tile[][][] EmptyStaticBlock { get; }
public void SetStaticBlock( int x, int y, Tile[][][] value )
{
if ( x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight )
return;
if ( m_StaticTiles[x] == null )
m_StaticTiles[x] = new Tile[BlockHeight][][][];
m_StaticTiles[x][y] = value;
if ( m_StaticPatches[x] == null )
m_StaticPatches[x] = new int[( BlockHeight + 31 ) >> 5];
m_StaticPatches[x][y >> 5] |= 1 << ( y & 0x1F );
}
public Tile[][][] GetStaticBlock( int x, int y )
{
if ( x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight || DataStream == null || IndexStream == null )
return EmptyStaticBlock;
if ( m_StaticTiles[x] == null )
m_StaticTiles[x] = new Tile[BlockHeight][][][];
Tile[][][] tiles = m_StaticTiles[x][y];
if ( tiles == null )
{
for ( int i = 0; tiles == null && i < m_FileShare.Count; ++i )
{
TileMatrix shared = m_FileShare[i];
if ( x >= 0 && x < shared.BlockWidth && y >= 0 && y < shared.BlockHeight )
{
Tile[][][][] theirTiles = shared.m_StaticTiles[x];
if ( theirTiles != null )
tiles = theirTiles[y];
if ( tiles != null )
{
int[] theirBits = shared.m_StaticPatches[x];
if ( theirBits != null && ( theirBits[y >> 5] & ( 1 << ( y & 0x1F ) ) ) != 0 )
tiles = null;
}
}
}
if ( tiles == null )
tiles = ReadStaticBlock( x, y );
m_StaticTiles[x][y] = tiles;
}
return tiles;
}
public Tile[] GetStaticTiles( int x, int y )
{
Tile[][][] tiles = GetStaticBlock( x >> 3, y >> 3 );
return Season.PatchTiles( tiles[x & 0x7][y & 0x7], Owner.Season );
}
private static readonly TileList m_TilesList = new TileList();
public Tile[] GetStaticTiles( int x, int y, bool multis )
{
if ( !multis )
return GetStaticTiles( x, y );
Tile[][][] tiles = GetStaticBlock( x >> 3, y >> 3 );
var eable = Owner.GetMultiTilesAt( x, y );
if ( !eable.Any() )
return Season.PatchTiles( tiles[x & 0x7][y & 0x7], Owner.Season );
foreach ( Tile[] multiTiles in eable )
{
m_TilesList.AddRange( multiTiles );
}
m_TilesList.AddRange( Season.PatchTiles( tiles[x & 0x7][y & 0x7], Owner.Season ) );
return m_TilesList.ToArray();
}
public void SetLandBlock( int x, int y, Tile[] value )
{
if ( x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight )
return;
if ( m_LandTiles[x] == null )
m_LandTiles[x] = new Tile[BlockHeight][];
m_LandTiles[x][y] = value;
if ( m_LandPatches[x] == null )
m_LandPatches[x] = new int[( BlockHeight + 31 ) >> 5];
m_LandPatches[x][y >> 5] |= 1 << ( y & 0x1F );
}
public Tile[] GetLandBlock( int x, int y )
{
if ( x < 0 || y < 0 || x >= BlockWidth || y >= BlockHeight || MapStream == null )
return m_InvalidLandBlock;
if ( m_LandTiles[x] == null )
m_LandTiles[x] = new Tile[BlockHeight][];
Tile[] tiles = m_LandTiles[x][y];
if ( tiles == null )
{
for ( int i = 0; tiles == null && i < m_FileShare.Count; ++i )
{
TileMatrix shared = m_FileShare[i];
if ( x >= 0 && x < shared.BlockWidth && y >= 0 && y < shared.BlockHeight )
{
Tile[][] theirTiles = shared.m_LandTiles[x];
if ( theirTiles != null )
tiles = theirTiles[y];
if ( tiles != null )
{
int[] theirBits = shared.m_LandPatches[x];
if ( theirBits != null && ( theirBits[y >> 5] & ( 1 << ( y & 0x1F ) ) ) != 0 )
tiles = null;
}
}
}
if ( tiles == null )
tiles = ReadLandBlock( x, y );
m_LandTiles[x][y] = tiles;
}
return tiles;
}
public Tile GetLandTile( int x, int y )
{
Tile[] tiles = GetLandBlock( x >> 3, y >> 3 );
return tiles[( ( y & 0x7 ) << 3 ) + ( x & 0x7 )];
}
private static TileList[][] m_Lists;
private static byte[] m_Buffer;
private static StaticTile[] m_TileBuffer = new StaticTile[128];
private unsafe Tile[][][] ReadStaticBlock( int x, int y )
{
try
{
IndexReader.BaseStream.Seek( ( ( x * BlockHeight ) + y ) * 12, SeekOrigin.Begin );
int lookup = IndexReader.ReadInt32();
int length = IndexReader.ReadInt32();
if ( lookup < 0 || length <= 0 )
{
return EmptyStaticBlock;
}
else
{
int count = length / 7;
DataStream.Seek( lookup, SeekOrigin.Begin );
if ( m_TileBuffer.Length < count )
m_TileBuffer = new StaticTile[count];
StaticTile[] staTiles = m_TileBuffer; // new StaticTile[tileCount];
fixed ( StaticTile* pTiles = staTiles )
{
if ( m_Buffer == null || length > m_Buffer.Length )
m_Buffer = new byte[length];
DataStream.Read( m_Buffer, 0, length );
Marshal.Copy( m_Buffer, 0, new IntPtr( pTiles ), length );
if ( m_Lists == null )
{
m_Lists = new TileList[8][];
for ( int i = 0; i < 8; ++i )
{
m_Lists[i] = new TileList[8];
for ( int j = 0; j < 8; ++j )
m_Lists[i][j] = new TileList();
}
}
TileList[][] lists = m_Lists;
for ( int i = 0; i < count; i++ )
{
StaticTile* pCur = pTiles + i;
lists[pCur->m_X & 0x7][pCur->m_Y & 0x7].Add( pCur->m_ID, pCur->m_Z );
}
Tile[][][] tiles = new Tile[8][][];
for ( int i = 0; i < 8; ++i )
{
tiles[i] = new Tile[8][];
for ( int j = 0; j < 8; ++j )
tiles[i][j] = lists[i][j].ToArray();
}
return tiles;
}
}
}
catch ( EndOfStreamException )
{
if ( DateTime.UtcNow >= m_NextStaticWarning )
{
log.Warning( "Static EOS for {0} ({1}, {2})", Owner, x, y );
m_NextStaticWarning = DateTime.UtcNow + TimeSpan.FromMinutes( 1.0 );
}
return EmptyStaticBlock;
}
}
private DateTime m_NextStaticWarning;
private DateTime m_NextLandWarning;
private unsafe Tile[] ReadLandBlock( int x, int y )
{
try
{
int offset = ( ( x * BlockHeight ) + y ) * 196 + 4;
if ( m_MapIndex != null )
offset = m_MapIndex.Lookup( offset );
MapStream.Seek( offset, SeekOrigin.Begin );
Tile[] tiles = new Tile[64];
fixed ( Tile* pTiles = tiles )
{
if ( m_Buffer == null || 192 > m_Buffer.Length )
m_Buffer = new byte[192];
MapStream.Read( m_Buffer, 0, 192 );
Marshal.Copy( m_Buffer, 0, new IntPtr( pTiles ), 192 );
}
return tiles;
}
catch
{
if ( DateTime.UtcNow >= m_NextLandWarning )
{
log.Warning( "Land EOS for {0} ({1}, {2})", Owner, x, y );
m_NextLandWarning = DateTime.UtcNow + TimeSpan.FromMinutes( 1.0 );
}
return m_InvalidLandBlock;
}
}
public void Dispose()
{
if ( MapStream != null )
MapStream.Close();
if ( m_MapIndex != null )
m_MapIndex.Close();
if ( DataStream != null )
DataStream.Close();
if ( IndexReader != null )
IndexReader.Close();
}
}
[System.Runtime.InteropServices.StructLayout( System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1 )]
public struct StaticTile
{
public ushort m_ID;
public byte m_X;
public byte m_Y;
public sbyte m_Z;
public short m_Hue;
}
[System.Runtime.InteropServices.StructLayout( System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1 )]
public struct Tile
{
internal ushort m_ID;
internal sbyte m_Z;
public int ID
{
get { return m_ID; }
|
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]
public class TileMatrix {
// ...
public Tile GetLandTile( int x, int y )
{
Tile[] tiles = GetLandBlock( x >> 3, y >> 3 );
return tiles[( ( y & 0x7 ) << 3 ) + ( x & 0x7 )];
}
// ...
**Cheat sheet (for next line):**
- We are in GetLandTile(), which should return a single Tile object from the land block.
- tiles is an array of Tile objects.
- The method is trying to access a specific tile at position (x, y) within the land block.
- The land block is divided into 8x8 tiles, with each tile having an index of (y & 0x7) << 3 + (x & 0x7).
- [Relevant lines: GetLandBlock() method call, tile indexing]
**Next line will likely be:**
return tiles[( ( y & 0x7 ) << 3 ) + ( x & 0x7 )]; (already present in the code)
However, considering the context, the next line might be a more specific implementation of the GetLandTile() method, such as:
- Returning a specific tile from the land block based on the given coordinates.
- Using a more efficient indexing method.
- Handling edge cases where the coordinates are out of bounds.
To provide a more accurate answer, I would need more information about the expected behavior of the GetLandTile() method.
|
|
Please complete the code given below.
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using Mono.Addins;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps = OpenSim.Framework.Capabilities.Caps;
using System.Text.RegularExpressions;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FreeSwitchVoiceModule")]
public class FreeSwitchVoiceModule : ISharedRegionModule, IVoiceModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Capability string prefixes
private static readonly string m_parcelVoiceInfoRequestPath = "0207/";
private static readonly string m_provisionVoiceAccountRequestPath = "0208/";
private static readonly string m_chatSessionRequestPath = "0209/";
// Control info
private static bool m_Enabled = false;
// FreeSwitch server is going to contact us and ask us all
// sorts of things.
// SLVoice client will do a GET on this prefix
private static string m_freeSwitchAPIPrefix;
// We need to return some information to SLVoice
// figured those out via curl
// http://vd1.vivox.com/api2/viv_get_prelogin.php
//
// need to figure out whether we do need to return ALL of
// these...
private static string m_freeSwitchRealm;
private static string m_freeSwitchSIPProxy;
private static bool m_freeSwitchAttemptUseSTUN;
private static string m_freeSwitchEchoServer;
private static int m_freeSwitchEchoPort;
private static string m_freeSwitchDefaultWellKnownIP;
private static int m_freeSwitchDefaultTimeout;
private static string m_freeSwitchUrlResetPassword;
private uint m_freeSwitchServicePort;
private string m_openSimWellKnownHTTPAddress;
// private string m_freeSwitchContext;
private readonly Dictionary<string, string> m_UUIDName = new Dictionary<string, string>();
private Dictionary<string, string> m_ParcelAddress = new Dictionary<string, string>();
private IConfig m_Config;
private IFreeswitchService m_FreeswitchService;
public void Initialise(IConfigSource config)
{
m_Config = config.Configs["FreeSwitchVoice"];
if (m_Config == null)
return;
if (!m_Config.GetBoolean("Enabled", false))
return;
try
{
string serviceDll = m_Config.GetString("LocalServiceModule",
String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[FreeSwitchVoice]: No LocalServiceModule named in section FreeSwitchVoice. Not starting.");
return;
}
Object[] args = new Object[] { config };
m_FreeswitchService = ServerUtils.LoadPlugin<IFreeswitchService>(serviceDll, args);
string jsonConfig = m_FreeswitchService.GetJsonConfig();
//m_log.Debug("[FreeSwitchVoice]: Configuration string: " + jsonConfig);
OSDMap map = (OSDMap)OSDParser.DeserializeJson(jsonConfig);
m_freeSwitchAPIPrefix = map["APIPrefix"].AsString();
m_freeSwitchRealm = map["Realm"].AsString();
m_freeSwitchSIPProxy = map["SIPProxy"].AsString();
m_freeSwitchAttemptUseSTUN = map["AttemptUseSTUN"].AsBoolean();
m_freeSwitchEchoServer = map["EchoServer"].AsString();
m_freeSwitchEchoPort = map["EchoPort"].AsInteger();
m_freeSwitchDefaultWellKnownIP = map["DefaultWellKnownIP"].AsString();
m_freeSwitchDefaultTimeout = map["DefaultTimeout"].AsInteger();
m_freeSwitchUrlResetPassword = String.Empty;
// m_freeSwitchContext = map["Context"].AsString();
if (String.IsNullOrEmpty(m_freeSwitchRealm) ||
String.IsNullOrEmpty(m_freeSwitchAPIPrefix))
{
m_log.Error("[FreeSwitchVoice]: Freeswitch service mis-configured. Not starting.");
return;
}
// set up http request handlers for
// - prelogin: viv_get_prelogin.php
// - signin: viv_signin.php
// - buddies: viv_buddy.php
// - ???: viv_watcher.php
// - signout: viv_signout.php
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceGetPreloginHTTPHandler);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/freeswitch-config", m_freeSwitchAPIPrefix), FreeSwitchConfigHTTPHandler);
// RestStreamHandler h = new
// RestStreamHandler("GET",
// String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceGetPreloginHTTPHandler);
// MainServer.Instance.AddStreamHandler(h);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_signin.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceSigninHTTPHandler);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_buddy.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceBuddyHTTPHandler);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_watcher.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceWatcherHTTPHandler);
m_log.InfoFormat("[FreeSwitchVoice]: using FreeSwitch server {0}", m_freeSwitchRealm);
m_Enabled = true;
m_log.Info("[FreeSwitchVoice]: plugin enabled");
}
catch (Exception e)
{
m_log.ErrorFormat("[FreeSwitchVoice]: plugin initialization failed: {0} {1}", e.Message, e.StackTrace);
return;
}
// This here is a region module trying to make a global setting.
// Not really a good idea but it's Windows only, so I can't test.
try
{
ServicePointManager.ServerCertificateValidationCallback += CustomCertificateValidation;
}
catch (NotImplementedException)
{
try
{
#pragma warning disable 0612, 0618
// Mono does not implement the ServicePointManager.ServerCertificateValidationCallback yet! Don't remove this!
ServicePointManager.CertificatePolicy = new MonoCert();
#pragma warning restore 0612, 0618
}
catch (Exception)
{
// COmmented multiline spam log message
//m_log.Error("[FreeSwitchVoice]: Certificate validation handler change not supported. You may get ssl certificate validation errors teleporting from your region to some SSL regions.");
}
}
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
// We generate these like this: The region's external host name
// as defined in Regions.ini is a good address to use. It's a
// dotted quad (or should be!) and it can reach this host from
// a client. The port is grabbed from the region's HTTP server.
m_openSimWellKnownHTTPAddress = scene.RegionInfo.ExternalHostName;
m_freeSwitchServicePort = MainServer.Instance.Port;
if (m_Enabled)
{
// we need to capture scene in an anonymous method
// here as we need it later in the callbacks
scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
{
OnRegisterCaps(scene, agentID, caps);
};
}
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (m_Enabled)
{
m_log.Info("[FreeSwitchVoice]: registering IVoiceModule with the scene");
// register the voice interface for this module, so the script engine can call us
scene.RegisterModuleInterface<IVoiceModule>(this);
}
}
public void Close()
{
}
public string Name
{
get { return "FreeSwitchVoiceModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
// <summary>
// implementation of IVoiceModule, called by osSetParcelSIPAddress script function
// </summary>
public void setLandSIPAddress(string SIPAddress,UUID GlobalID)
{
m_log.DebugFormat("[FreeSwitchVoice]: setLandSIPAddress parcel id {0}: setting sip address {1}",
GlobalID, SIPAddress);
lock (m_ParcelAddress)
{
if (m_ParcelAddress.ContainsKey(GlobalID.ToString()))
{
m_ParcelAddress[GlobalID.ToString()] = SIPAddress;
}
else
{
m_ParcelAddress.Add(GlobalID.ToString(), SIPAddress);
}
}
}
// <summary>
// OnRegisterCaps is invoked via the scene.EventManager
// everytime OpenSim hands out capabilities to a client
// (login, region crossing). We contribute two capabilities to
// the set of capabilities handed back to the client:
// ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
//
// ProvisionVoiceAccountRequest allows the client to obtain
// the voice account credentials for the avatar it is
// controlling (e.g., user name, password, etc).
//
// ParcelVoiceInfoRequest is invoked whenever the client
// changes from one region or parcel to another.
//
// Note that OnRegisterCaps is called here via a closure
// delegate containing the scene of the respective region (see
// Initialise()).
// </summary>
public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
{
m_log.DebugFormat(
"[FreeSwitchVoice]: OnRegisterCaps() called with agentID {0} caps {1} in scene {2}",
agentID, caps, scene.RegionInfo.RegionName);
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler(
"ProvisionVoiceAccountRequest",
new RestStreamHandler(
"POST",
capsBase + m_provisionVoiceAccountRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ProvisionVoiceAccountRequest(scene, request, path, param, agentID, caps),
"ProvisionVoiceAccountRequest",
agentID.ToString()));
caps.RegisterHandler(
"ParcelVoiceInfoRequest",
new RestStreamHandler(
"POST",
capsBase + m_parcelVoiceInfoRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ParcelVoiceInfoRequest(scene, request, path, param, agentID, caps),
"ParcelVoiceInfoRequest",
agentID.ToString()));
caps.RegisterHandler(
"ChatSessionRequest",
new RestStreamHandler(
"POST",
capsBase + m_chatSessionRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ChatSessionRequest(scene, request, path, param, agentID, caps),
"ChatSessionRequest",
agentID.ToString()));
}
/// <summary>
/// Callback for a client request for Voice Account Details
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
m_log.DebugFormat(
"[FreeSwitchVoice][PROVISIONVOICE]: ProvisionVoiceAccountRequest() request: {0}, path: {1}, param: {2}", request, path, param);
ScenePresence avatar = scene.GetScenePresence(agentID);
if (avatar == null)
{
System.Threading.Thread.Sleep(2000);
avatar = scene.GetScenePresence(agentID);
if (avatar == null)
return "<llsd>undef</llsd>";
}
string avatarName = avatar.Name;
try
{
//XmlElement resp;
string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
string password = "1234";//temp hack//new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
// XXX: we need to cache the voice credentials, as
// FreeSwitch is later going to come and ask us for
// those
agentname = agentname.Replace('+', '-').Replace('/', '_');
lock (m_UUIDName)
{
if (m_UUIDName.ContainsKey(agentname))
{
m_UUIDName[agentname] = avatarName;
}
else
{
m_UUIDName.Add(agentname, avatarName);
}
}
// LLSDVoiceAccountResponse voiceAccountResponse =
// new LLSDVoiceAccountResponse(agentname, password, m_freeSwitchRealm, "http://etsvc02.hursley.ibm.com/api");
LLSDVoiceAccountResponse voiceAccountResponse =
new LLSDVoiceAccountResponse(agentname, password, m_freeSwitchRealm,
String.Format("http://{0}:{1}{2}/", m_openSimWellKnownHTTPAddress,
m_freeSwitchServicePort, m_freeSwitchAPIPrefix));
string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
// m_log.DebugFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r);
return r;
}
catch (Exception e)
{
m_log.ErrorFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1}, retry later", avatarName, e.Message);
m_log.DebugFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1} failed", avatarName, e.ToString());
return "<llsd>undef</llsd>";
}
}
/// <summary>
/// Callback for a client request for ParcelVoiceInfo
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
m_log.DebugFormat(
"[FreeSwitchVoice][PARCELVOICE]: ParcelVoiceInfoRequest() on {0} for {1}",
scene.RegionInfo.RegionName, agentID);
ScenePresence avatar = scene.GetScenePresence(agentID);
string avatarName = avatar.Name;
// - check whether we have a region channel in our cache
// - if not:
// create it and cache it
// - send it to the client
// - send channel_uri: as "sip:regionID@m_sipDomain"
try
{
LLSDParcelVoiceInfoResponse parcelVoiceInfo;
string channelUri;
if (null == scene.LandChannel)
throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available",
scene.RegionInfo.RegionName, avatarName));
// get channel_uri: check first whether estate
// settings allow voice, then whether parcel allows
// voice, if all do retrieve or obtain the parcel
// voice channel
LandData land = scene.GetLandData(avatar.AbsolutePosition);
//m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
// TODO: EstateSettings don't seem to get propagated...
// if (!scene.RegionInfo.EstateSettings.AllowVoice)
// {
// m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
// scene.RegionInfo.RegionName);
// channel_uri = String.Empty;
// }
// else
if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
{
// m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
channelUri = String.Empty;
}
else
{
|
[
" channelUri = ChannelUri(scene, land);"
] | 1,661
|
lcc
|
csharp
| null |
c357dc85d4b8de20bfeb7e4f0a5fb6c3f1e2ad3fba2c7691
| 48
|
Your task is code completion.
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using Mono.Addins;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps = OpenSim.Framework.Capabilities.Caps;
using System.Text.RegularExpressions;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FreeSwitchVoiceModule")]
public class FreeSwitchVoiceModule : ISharedRegionModule, IVoiceModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Capability string prefixes
private static readonly string m_parcelVoiceInfoRequestPath = "0207/";
private static readonly string m_provisionVoiceAccountRequestPath = "0208/";
private static readonly string m_chatSessionRequestPath = "0209/";
// Control info
private static bool m_Enabled = false;
// FreeSwitch server is going to contact us and ask us all
// sorts of things.
// SLVoice client will do a GET on this prefix
private static string m_freeSwitchAPIPrefix;
// We need to return some information to SLVoice
// figured those out via curl
// http://vd1.vivox.com/api2/viv_get_prelogin.php
//
// need to figure out whether we do need to return ALL of
// these...
private static string m_freeSwitchRealm;
private static string m_freeSwitchSIPProxy;
private static bool m_freeSwitchAttemptUseSTUN;
private static string m_freeSwitchEchoServer;
private static int m_freeSwitchEchoPort;
private static string m_freeSwitchDefaultWellKnownIP;
private static int m_freeSwitchDefaultTimeout;
private static string m_freeSwitchUrlResetPassword;
private uint m_freeSwitchServicePort;
private string m_openSimWellKnownHTTPAddress;
// private string m_freeSwitchContext;
private readonly Dictionary<string, string> m_UUIDName = new Dictionary<string, string>();
private Dictionary<string, string> m_ParcelAddress = new Dictionary<string, string>();
private IConfig m_Config;
private IFreeswitchService m_FreeswitchService;
public void Initialise(IConfigSource config)
{
m_Config = config.Configs["FreeSwitchVoice"];
if (m_Config == null)
return;
if (!m_Config.GetBoolean("Enabled", false))
return;
try
{
string serviceDll = m_Config.GetString("LocalServiceModule",
String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[FreeSwitchVoice]: No LocalServiceModule named in section FreeSwitchVoice. Not starting.");
return;
}
Object[] args = new Object[] { config };
m_FreeswitchService = ServerUtils.LoadPlugin<IFreeswitchService>(serviceDll, args);
string jsonConfig = m_FreeswitchService.GetJsonConfig();
//m_log.Debug("[FreeSwitchVoice]: Configuration string: " + jsonConfig);
OSDMap map = (OSDMap)OSDParser.DeserializeJson(jsonConfig);
m_freeSwitchAPIPrefix = map["APIPrefix"].AsString();
m_freeSwitchRealm = map["Realm"].AsString();
m_freeSwitchSIPProxy = map["SIPProxy"].AsString();
m_freeSwitchAttemptUseSTUN = map["AttemptUseSTUN"].AsBoolean();
m_freeSwitchEchoServer = map["EchoServer"].AsString();
m_freeSwitchEchoPort = map["EchoPort"].AsInteger();
m_freeSwitchDefaultWellKnownIP = map["DefaultWellKnownIP"].AsString();
m_freeSwitchDefaultTimeout = map["DefaultTimeout"].AsInteger();
m_freeSwitchUrlResetPassword = String.Empty;
// m_freeSwitchContext = map["Context"].AsString();
if (String.IsNullOrEmpty(m_freeSwitchRealm) ||
String.IsNullOrEmpty(m_freeSwitchAPIPrefix))
{
m_log.Error("[FreeSwitchVoice]: Freeswitch service mis-configured. Not starting.");
return;
}
// set up http request handlers for
// - prelogin: viv_get_prelogin.php
// - signin: viv_signin.php
// - buddies: viv_buddy.php
// - ???: viv_watcher.php
// - signout: viv_signout.php
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceGetPreloginHTTPHandler);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/freeswitch-config", m_freeSwitchAPIPrefix), FreeSwitchConfigHTTPHandler);
// RestStreamHandler h = new
// RestStreamHandler("GET",
// String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceGetPreloginHTTPHandler);
// MainServer.Instance.AddStreamHandler(h);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_signin.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceSigninHTTPHandler);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_buddy.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceBuddyHTTPHandler);
MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_watcher.php", m_freeSwitchAPIPrefix),
FreeSwitchSLVoiceWatcherHTTPHandler);
m_log.InfoFormat("[FreeSwitchVoice]: using FreeSwitch server {0}", m_freeSwitchRealm);
m_Enabled = true;
m_log.Info("[FreeSwitchVoice]: plugin enabled");
}
catch (Exception e)
{
m_log.ErrorFormat("[FreeSwitchVoice]: plugin initialization failed: {0} {1}", e.Message, e.StackTrace);
return;
}
// This here is a region module trying to make a global setting.
// Not really a good idea but it's Windows only, so I can't test.
try
{
ServicePointManager.ServerCertificateValidationCallback += CustomCertificateValidation;
}
catch (NotImplementedException)
{
try
{
#pragma warning disable 0612, 0618
// Mono does not implement the ServicePointManager.ServerCertificateValidationCallback yet! Don't remove this!
ServicePointManager.CertificatePolicy = new MonoCert();
#pragma warning restore 0612, 0618
}
catch (Exception)
{
// COmmented multiline spam log message
//m_log.Error("[FreeSwitchVoice]: Certificate validation handler change not supported. You may get ssl certificate validation errors teleporting from your region to some SSL regions.");
}
}
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
// We generate these like this: The region's external host name
// as defined in Regions.ini is a good address to use. It's a
// dotted quad (or should be!) and it can reach this host from
// a client. The port is grabbed from the region's HTTP server.
m_openSimWellKnownHTTPAddress = scene.RegionInfo.ExternalHostName;
m_freeSwitchServicePort = MainServer.Instance.Port;
if (m_Enabled)
{
// we need to capture scene in an anonymous method
// here as we need it later in the callbacks
scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
{
OnRegisterCaps(scene, agentID, caps);
};
}
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (m_Enabled)
{
m_log.Info("[FreeSwitchVoice]: registering IVoiceModule with the scene");
// register the voice interface for this module, so the script engine can call us
scene.RegisterModuleInterface<IVoiceModule>(this);
}
}
public void Close()
{
}
public string Name
{
get { return "FreeSwitchVoiceModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
// <summary>
// implementation of IVoiceModule, called by osSetParcelSIPAddress script function
// </summary>
public void setLandSIPAddress(string SIPAddress,UUID GlobalID)
{
m_log.DebugFormat("[FreeSwitchVoice]: setLandSIPAddress parcel id {0}: setting sip address {1}",
GlobalID, SIPAddress);
lock (m_ParcelAddress)
{
if (m_ParcelAddress.ContainsKey(GlobalID.ToString()))
{
m_ParcelAddress[GlobalID.ToString()] = SIPAddress;
}
else
{
m_ParcelAddress.Add(GlobalID.ToString(), SIPAddress);
}
}
}
// <summary>
// OnRegisterCaps is invoked via the scene.EventManager
// everytime OpenSim hands out capabilities to a client
// (login, region crossing). We contribute two capabilities to
// the set of capabilities handed back to the client:
// ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
//
// ProvisionVoiceAccountRequest allows the client to obtain
// the voice account credentials for the avatar it is
// controlling (e.g., user name, password, etc).
//
// ParcelVoiceInfoRequest is invoked whenever the client
// changes from one region or parcel to another.
//
// Note that OnRegisterCaps is called here via a closure
// delegate containing the scene of the respective region (see
// Initialise()).
// </summary>
public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
{
m_log.DebugFormat(
"[FreeSwitchVoice]: OnRegisterCaps() called with agentID {0} caps {1} in scene {2}",
agentID, caps, scene.RegionInfo.RegionName);
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler(
"ProvisionVoiceAccountRequest",
new RestStreamHandler(
"POST",
capsBase + m_provisionVoiceAccountRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ProvisionVoiceAccountRequest(scene, request, path, param, agentID, caps),
"ProvisionVoiceAccountRequest",
agentID.ToString()));
caps.RegisterHandler(
"ParcelVoiceInfoRequest",
new RestStreamHandler(
"POST",
capsBase + m_parcelVoiceInfoRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ParcelVoiceInfoRequest(scene, request, path, param, agentID, caps),
"ParcelVoiceInfoRequest",
agentID.ToString()));
caps.RegisterHandler(
"ChatSessionRequest",
new RestStreamHandler(
"POST",
capsBase + m_chatSessionRequestPath,
(request, path, param, httpRequest, httpResponse)
=> ChatSessionRequest(scene, request, path, param, agentID, caps),
"ChatSessionRequest",
agentID.ToString()));
}
/// <summary>
/// Callback for a client request for Voice Account Details
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
m_log.DebugFormat(
"[FreeSwitchVoice][PROVISIONVOICE]: ProvisionVoiceAccountRequest() request: {0}, path: {1}, param: {2}", request, path, param);
ScenePresence avatar = scene.GetScenePresence(agentID);
if (avatar == null)
{
System.Threading.Thread.Sleep(2000);
avatar = scene.GetScenePresence(agentID);
if (avatar == null)
return "<llsd>undef</llsd>";
}
string avatarName = avatar.Name;
try
{
//XmlElement resp;
string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
string password = "1234";//temp hack//new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
// XXX: we need to cache the voice credentials, as
// FreeSwitch is later going to come and ask us for
// those
agentname = agentname.Replace('+', '-').Replace('/', '_');
lock (m_UUIDName)
{
if (m_UUIDName.ContainsKey(agentname))
{
m_UUIDName[agentname] = avatarName;
}
else
{
m_UUIDName.Add(agentname, avatarName);
}
}
// LLSDVoiceAccountResponse voiceAccountResponse =
// new LLSDVoiceAccountResponse(agentname, password, m_freeSwitchRealm, "http://etsvc02.hursley.ibm.com/api");
LLSDVoiceAccountResponse voiceAccountResponse =
new LLSDVoiceAccountResponse(agentname, password, m_freeSwitchRealm,
String.Format("http://{0}:{1}{2}/", m_openSimWellKnownHTTPAddress,
m_freeSwitchServicePort, m_freeSwitchAPIPrefix));
string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse);
// m_log.DebugFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r);
return r;
}
catch (Exception e)
{
m_log.ErrorFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1}, retry later", avatarName, e.Message);
m_log.DebugFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1} failed", avatarName, e.ToString());
return "<llsd>undef</llsd>";
}
}
/// <summary>
/// Callback for a client request for ParcelVoiceInfo
/// </summary>
/// <param name="scene">current scene object of the client</param>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
m_log.DebugFormat(
"[FreeSwitchVoice][PARCELVOICE]: ParcelVoiceInfoRequest() on {0} for {1}",
scene.RegionInfo.RegionName, agentID);
ScenePresence avatar = scene.GetScenePresence(agentID);
string avatarName = avatar.Name;
// - check whether we have a region channel in our cache
// - if not:
// create it and cache it
// - send it to the client
// - send channel_uri: as "sip:regionID@m_sipDomain"
try
{
LLSDParcelVoiceInfoResponse parcelVoiceInfo;
string channelUri;
if (null == scene.LandChannel)
throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available",
scene.RegionInfo.RegionName, avatarName));
// get channel_uri: check first whether estate
// settings allow voice, then whether parcel allows
// voice, if all do retrieve or obtain the parcel
// voice channel
LandData land = scene.GetLandData(avatar.AbsolutePosition);
//m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
// TODO: EstateSettings don't seem to get propagated...
// if (!scene.RegionInfo.EstateSettings.AllowVoice)
// {
// m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
// scene.RegionInfo.RegionName);
// channel_uri = String.Empty;
// }
// else
if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
{
// m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
channelUri = String.Empty;
}
else
{
|
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 string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param,
UUID agentID, Caps caps)
{
...
try
{
LLSDParcelVoiceInfoResponse parcelVoiceInfo;
string channelUri;
if (null == scene.LandChannel)
throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available",
scene.RegionInfo.RegionName, avatarName));
// get channel_uri: check first whether estate
// settings allow voice, then whether parcel allows
// voice, if all do retrieve or obtain the parcel
// voice channel
LandData land = scene.GetLandData(avatar.AbsolutePosition);
//m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
// TODO: EstateSettings don't seem to get propagated...
// if (!scene.RegionInfo.EstateSettings.AllowVoice)
// {
// m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
// scene.RegionInfo.RegionName);
// channel_uri = String.Empty;
// }
// else
if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
{
// m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
channelUri = String.Empty;
}
else
{
Cheatsheet (for next line):
- We are in the ParcelVoiceInfoRequest method, which is supposed to return a string.
- The method is currently inside a try block, and we are checking if the land data is available.
- If the land data is available, we are checking if the parcel allows voice chat.
- If the parcel allows voice chat, we need to create an LLSDParcelVoiceInfoResponse object and set its properties.
- The method is supposed to return a string, which is likely the serialized LLSDParcelVoiceInfoResponse object.
- The LLSDParcelVoiceInfoResponse object is not initialized yet.
- The channelUri variable is not used in the method, but it might be used to set a property of the LLSDParcelVoiceInfoResponse object.
Relevant lines:
- Method header
- Try block
- LLSDParcelVoiceInfoResponse declaration
- ParcelFlags enum
Next line will likely be:
parcelVoiceInfo = new LLSDParcelVoiceInfoResponse();
|
|
Please complete the code given below.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using OpenDentBusiness;
namespace OpenDental{
/// <summary>
/// Summary description for FormBasicTemplate.
/// </summary>
public class FormPayPeriodEdit : System.Windows.Forms.Form{
private OpenDental.UI.Button butCancel;
private OpenDental.UI.Button butOK;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
///<summary></summary>
public bool IsNew;
private ValidDate textDateStart;
private Label label1;
private ValidDate textDateStop;
private Label label2;
private ValidDate textDatePaycheck;
private Label label3;
private PayPeriod PayPeriodCur;
///<summary></summary>
public FormPayPeriodEdit(PayPeriod payPeriodCur)
{
//
// Required for Windows Form Designer support
//
PayPeriodCur=payPeriodCur;
InitializeComponent();
Lan.F(this);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
OpenDental.UI.Button butDelete;
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormPayPeriodEdit));
this.butCancel = new OpenDental.UI.Button();
this.butOK = new OpenDental.UI.Button();
this.textDateStart = new OpenDental.ValidDate();
this.label1 = new System.Windows.Forms.Label();
this.textDateStop = new OpenDental.ValidDate();
this.label2 = new System.Windows.Forms.Label();
this.textDatePaycheck = new OpenDental.ValidDate();
this.label3 = new System.Windows.Forms.Label();
butDelete = new OpenDental.UI.Button();
this.SuspendLayout();
//
// butDelete
//
butDelete.AdjustImageLocation = new System.Drawing.Point(0,0);
butDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
butDelete.Autosize = true;
butDelete.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle;
butDelete.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver;
butDelete.CornerRadius = 4F;
butDelete.Image = global::OpenDental.Properties.Resources.deleteX;
butDelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
butDelete.Location = new System.Drawing.Point(15,137);
butDelete.Name = "butDelete";
butDelete.Size = new System.Drawing.Size(75,26);
butDelete.TabIndex = 16;
butDelete.Text = "&Delete";
butDelete.Click += new System.EventHandler(this.butDelete_Click);
//
// butCancel
//
this.butCancel.AdjustImageLocation = new System.Drawing.Point(0,0);
this.butCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.butCancel.Autosize = true;
this.butCancel.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle;
this.butCancel.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver;
this.butCancel.CornerRadius = 4F;
this.butCancel.Location = new System.Drawing.Point(314,137);
this.butCancel.Name = "butCancel";
this.butCancel.Size = new System.Drawing.Size(75,26);
this.butCancel.TabIndex = 9;
this.butCancel.Text = "&Cancel";
this.butCancel.Click += new System.EventHandler(this.butCancel_Click);
//
// butOK
//
this.butOK.AdjustImageLocation = new System.Drawing.Point(0,0);
this.butOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.butOK.Autosize = true;
this.butOK.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle;
this.butOK.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver;
this.butOK.CornerRadius = 4F;
this.butOK.Location = new System.Drawing.Point(314,105);
this.butOK.Name = "butOK";
this.butOK.Size = new System.Drawing.Size(75,26);
this.butOK.TabIndex = 8;
this.butOK.Text = "&OK";
this.butOK.Click += new System.EventHandler(this.butOK_Click);
//
// textDateStart
//
this.textDateStart.Location = new System.Drawing.Point(111,24);
this.textDateStart.Name = "textDateStart";
this.textDateStart.Size = new System.Drawing.Size(100,20);
this.textDateStart.TabIndex = 10;
//
// label1
//
this.label1.Location = new System.Drawing.Point(12,24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100,20);
this.label1.TabIndex = 11;
this.label1.Text = "Start Date";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textDateStop
//
this.textDateStop.Location = new System.Drawing.Point(111,50);
this.textDateStop.Name = "textDateStop";
this.textDateStop.Size = new System.Drawing.Size(100,20);
this.textDateStop.TabIndex = 12;
//
// label2
//
this.label2.Location = new System.Drawing.Point(12,50);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(100,20);
this.label2.TabIndex = 13;
this.label2.Text = "End Date";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textDatePaycheck
//
this.textDatePaycheck.Location = new System.Drawing.Point(111,76);
this.textDatePaycheck.Name = "textDatePaycheck";
this.textDatePaycheck.Size = new System.Drawing.Size(100,20);
this.textDatePaycheck.TabIndex = 14;
//
// label3
//
this.label3.Location = new System.Drawing.Point(12,76);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(100,20);
this.label3.TabIndex = 15;
this.label3.Text = "Paycheck Date";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// FormPayPeriodEdit
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,13);
this.ClientSize = new System.Drawing.Size(415,181);
this.Controls.Add(butDelete);
this.Controls.Add(this.textDatePaycheck);
this.Controls.Add(this.label3);
this.Controls.Add(this.textDateStop);
this.Controls.Add(this.label2);
this.Controls.Add(this.textDateStart);
this.Controls.Add(this.label1);
this.Controls.Add(this.butOK);
this.Controls.Add(this.butCancel);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FormPayPeriodEdit";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Edit Pay Period";
this.Load += new System.EventHandler(this.FormPayPeriodEdit_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void FormPayPeriodEdit_Load(object sender, System.EventArgs e) {
if(PayPeriodCur.DateStart.Year>1880){
textDateStart.Text=PayPeriodCur.DateStart.ToShortDateString();
}
if(PayPeriodCur.DateStop.Year>1880){
textDateStop.Text=PayPeriodCur.DateStop.ToShortDateString();
}
if(PayPeriodCur.DatePaycheck.Year>1880){
textDatePaycheck.Text=PayPeriodCur.DatePaycheck.ToShortDateString();
}
}
private void butDelete_Click(object sender,EventArgs e) {
if(IsNew){
DialogResult=DialogResult.Cancel;
return;
}
PayPeriods.Delete(PayPeriodCur);
DialogResult=DialogResult.OK;
}
private void butOK_Click(object sender, System.EventArgs e) {
if(textDateStart.errorProvider1.GetError(textDateStart)!=""
|| textDateStop.errorProvider1.GetError(textDateStop)!=""
|| textDatePaycheck.errorProvider1.GetError(textDatePaycheck)!="")
{
|
[
"\t\t\t\tMsgBox.Show(this,\"Please fix data entry errors first.\");"
] | 576
|
lcc
|
csharp
| null |
7c3bba0835a61180b3615e5a45405828fb9f896470cd8acb
| 49
|
Your task is code completion.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using OpenDentBusiness;
namespace OpenDental{
/// <summary>
/// Summary description for FormBasicTemplate.
/// </summary>
public class FormPayPeriodEdit : System.Windows.Forms.Form{
private OpenDental.UI.Button butCancel;
private OpenDental.UI.Button butOK;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
///<summary></summary>
public bool IsNew;
private ValidDate textDateStart;
private Label label1;
private ValidDate textDateStop;
private Label label2;
private ValidDate textDatePaycheck;
private Label label3;
private PayPeriod PayPeriodCur;
///<summary></summary>
public FormPayPeriodEdit(PayPeriod payPeriodCur)
{
//
// Required for Windows Form Designer support
//
PayPeriodCur=payPeriodCur;
InitializeComponent();
Lan.F(this);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
OpenDental.UI.Button butDelete;
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormPayPeriodEdit));
this.butCancel = new OpenDental.UI.Button();
this.butOK = new OpenDental.UI.Button();
this.textDateStart = new OpenDental.ValidDate();
this.label1 = new System.Windows.Forms.Label();
this.textDateStop = new OpenDental.ValidDate();
this.label2 = new System.Windows.Forms.Label();
this.textDatePaycheck = new OpenDental.ValidDate();
this.label3 = new System.Windows.Forms.Label();
butDelete = new OpenDental.UI.Button();
this.SuspendLayout();
//
// butDelete
//
butDelete.AdjustImageLocation = new System.Drawing.Point(0,0);
butDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
butDelete.Autosize = true;
butDelete.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle;
butDelete.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver;
butDelete.CornerRadius = 4F;
butDelete.Image = global::OpenDental.Properties.Resources.deleteX;
butDelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
butDelete.Location = new System.Drawing.Point(15,137);
butDelete.Name = "butDelete";
butDelete.Size = new System.Drawing.Size(75,26);
butDelete.TabIndex = 16;
butDelete.Text = "&Delete";
butDelete.Click += new System.EventHandler(this.butDelete_Click);
//
// butCancel
//
this.butCancel.AdjustImageLocation = new System.Drawing.Point(0,0);
this.butCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.butCancel.Autosize = true;
this.butCancel.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle;
this.butCancel.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver;
this.butCancel.CornerRadius = 4F;
this.butCancel.Location = new System.Drawing.Point(314,137);
this.butCancel.Name = "butCancel";
this.butCancel.Size = new System.Drawing.Size(75,26);
this.butCancel.TabIndex = 9;
this.butCancel.Text = "&Cancel";
this.butCancel.Click += new System.EventHandler(this.butCancel_Click);
//
// butOK
//
this.butOK.AdjustImageLocation = new System.Drawing.Point(0,0);
this.butOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.butOK.Autosize = true;
this.butOK.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle;
this.butOK.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver;
this.butOK.CornerRadius = 4F;
this.butOK.Location = new System.Drawing.Point(314,105);
this.butOK.Name = "butOK";
this.butOK.Size = new System.Drawing.Size(75,26);
this.butOK.TabIndex = 8;
this.butOK.Text = "&OK";
this.butOK.Click += new System.EventHandler(this.butOK_Click);
//
// textDateStart
//
this.textDateStart.Location = new System.Drawing.Point(111,24);
this.textDateStart.Name = "textDateStart";
this.textDateStart.Size = new System.Drawing.Size(100,20);
this.textDateStart.TabIndex = 10;
//
// label1
//
this.label1.Location = new System.Drawing.Point(12,24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100,20);
this.label1.TabIndex = 11;
this.label1.Text = "Start Date";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textDateStop
//
this.textDateStop.Location = new System.Drawing.Point(111,50);
this.textDateStop.Name = "textDateStop";
this.textDateStop.Size = new System.Drawing.Size(100,20);
this.textDateStop.TabIndex = 12;
//
// label2
//
this.label2.Location = new System.Drawing.Point(12,50);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(100,20);
this.label2.TabIndex = 13;
this.label2.Text = "End Date";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// textDatePaycheck
//
this.textDatePaycheck.Location = new System.Drawing.Point(111,76);
this.textDatePaycheck.Name = "textDatePaycheck";
this.textDatePaycheck.Size = new System.Drawing.Size(100,20);
this.textDatePaycheck.TabIndex = 14;
//
// label3
//
this.label3.Location = new System.Drawing.Point(12,76);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(100,20);
this.label3.TabIndex = 15;
this.label3.Text = "Paycheck Date";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// FormPayPeriodEdit
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,13);
this.ClientSize = new System.Drawing.Size(415,181);
this.Controls.Add(butDelete);
this.Controls.Add(this.textDatePaycheck);
this.Controls.Add(this.label3);
this.Controls.Add(this.textDateStop);
this.Controls.Add(this.label2);
this.Controls.Add(this.textDateStart);
this.Controls.Add(this.label1);
this.Controls.Add(this.butOK);
this.Controls.Add(this.butCancel);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FormPayPeriodEdit";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Edit Pay Period";
this.Load += new System.EventHandler(this.FormPayPeriodEdit_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void FormPayPeriodEdit_Load(object sender, System.EventArgs e) {
if(PayPeriodCur.DateStart.Year>1880){
textDateStart.Text=PayPeriodCur.DateStart.ToShortDateString();
}
if(PayPeriodCur.DateStop.Year>1880){
textDateStop.Text=PayPeriodCur.DateStop.ToShortDateString();
}
if(PayPeriodCur.DatePaycheck.Year>1880){
textDatePaycheck.Text=PayPeriodCur.DatePaycheck.ToShortDateString();
}
}
private void butDelete_Click(object sender,EventArgs e) {
if(IsNew){
DialogResult=DialogResult.Cancel;
return;
}
PayPeriods.Delete(PayPeriodCur);
DialogResult=DialogResult.OK;
}
private void butOK_Click(object sender, System.EventArgs e) {
if(textDateStart.errorProvider1.GetError(textDateStart)!=""
|| textDateStop.errorProvider1.GetError(textDateStop)!=""
|| textDatePaycheck.errorProvider1.GetError(textDatePaycheck)!="")
{
|
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]
private void butOK_Click(object sender, System.EventArgs e) {
if(textDateStart.errorProvider1.GetError(textDateStart)!=""
|| textDateStop.errorProvider1.GetError(textDateStop)!=""
|| textDatePaycheck.errorProvider1.GetError(textDatePaycheck)!="")
{
// [Code to be completed]
}
Cheatsheet (for next line):
- We are in the if condition, which checks for errors in the date fields.
- The condition is checking for non-empty error messages in errorProvider1 for textDateStart, textDateStop, and textDatePaycheck.
- If the condition is true, we need to display an error message or prevent the form from closing.
- The form has a Cancel button, but it's not clear if it's the default button for the form.
- The form has a OK button, which is likely the default button for the form.
- The DialogResult property of the form is used to determine the result of the form's ShowDialog method.
- The DialogResult property can be set to Cancel, OK, or other values to indicate the result of the form's operation.
Possible next lines:
- Display an error message to the user, e.g., using MessageBox.Show.
- Prevent the form from closing by setting DialogResult to Cancel.
- Validate the date fields and set their error messages accordingly.
- Set the DialogResult property to Cancel to indicate that the form's operation was cancelled.
- Call a method to handle the error or invalid input.
Please let me know which one you would like me to complete.
|
|
Please complete the code given below.
# (C) British Crown Copyright 2013 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""NAME file format loading functions."""
from __future__ import (absolute_import, division, print_function)
from six.moves import range, zip
import collections
import datetime
import re
import warnings
import numpy as np
from iris.coords import AuxCoord, DimCoord, CellMethod
import iris.coord_systems
import iris.cube
from iris.exceptions import TranslationError
import iris.util
import iris.unit
EARTH_RADIUS = 6371229.0
NAMEIII_DATETIME_FORMAT = '%d/%m/%Y %H:%M %Z'
NAMEII_FIELD_DATETIME_FORMAT = '%H%M%Z %d/%m/%Y'
NAMEII_TIMESERIES_DATETIME_FORMAT = '%d/%m/%Y %H:%M:%S'
NAMECoord = collections.namedtuple('NAMECoord', ['name',
'dimension',
'values'])
def _split_name_and_units(name):
units = None
if "(" in name and ")" in name:
split = name.rsplit("(", 1)
try_units = split[1].replace(")", "").strip()
try:
try_units = iris.unit.Unit(try_units)
except ValueError:
pass
else:
name = split[0].strip()
units = try_units
return name, units
def read_header(file_handle):
"""
Return a dictionary containing the header information extracted
from the the provided NAME file object.
Args:
* file_handle (file-like object):
A file-like object from which to read the header information.
Returns:
A dictionary containing the extracted header information.
"""
header = {}
header['NAME Version'] = file_handle.next().strip()
for line in file_handle:
words = line.split(':', 1)
if len(words) != 2:
break
key, value = [word.strip() for word in words]
header[key] = value
# Cast some values into floats or integers if they match a
# given name. Set any empty string values to None.
for key, value in header.items():
if value:
if key in ['X grid origin', 'Y grid origin',
'X grid resolution', 'Y grid resolution']:
header[key] = float(value)
elif key in ['X grid size', 'Y grid size',
'Number of preliminary cols',
'Number of field cols',
'Number of fields',
'Number of series']:
header[key] = int(value)
else:
header[key] = None
return header
def _read_data_arrays(file_handle, n_arrays, shape):
"""
Return a list of NumPy arrays containing the data extracted from
the provided file object. The number and shape of the arrays
must be specified.
"""
data_arrays = [np.zeros(shape, dtype=np.float32) for
i in range(n_arrays)]
# Iterate over the remaining lines which represent the data in
# a column form.
for line in file_handle:
# Split the line by comma, removing the last empty column
# caused by the trailing comma
vals = line.split(',')[:-1]
# Cast the x and y grid positions to integers and convert
# them to zero based indices
x = int(float(vals[0])) - 1
y = int(float(vals[1])) - 1
# Populate the data arrays (i.e. all columns but the leading 4).
for i, data_array in enumerate(data_arrays):
data_array[y, x] = float(vals[i + 4])
return data_arrays
def _build_lat_lon_for_NAME_field(header):
"""
Return regular latitude and longitude coordinates extracted from
the provided header dictionary.
"""
start = header['X grid origin']
step = header['X grid resolution']
count = header['X grid size']
pts = start + np.arange(count, dtype=np.float64) * step
lon = NAMECoord(name='longitude', dimension=1, values=pts)
start = header['Y grid origin']
step = header['Y grid resolution']
count = header['Y grid size']
pts = start + np.arange(count, dtype=np.float64) * step
lat = NAMECoord(name='latitude', dimension=0, values=pts)
return lat, lon
def _build_lat_lon_for_NAME_timeseries(column_headings):
"""
Return regular latitude and longitude coordinates extracted from
the provided column_headings dictionary.
"""
pattern = re.compile(r'\-?[0-9]*\.[0-9]*')
new_Xlocation_column_header = []
for t in column_headings['X']:
if 'Lat-Long' in t:
matches = pattern.search(t)
new_Xlocation_column_header.append(float(matches.group(0)))
else:
new_Xlocation_column_header.append(t)
column_headings['X'] = new_Xlocation_column_header
lon = NAMECoord(name='longitude', dimension=None,
values=column_headings['X'])
new_Ylocation_column_header = []
for t in column_headings['Y']:
if 'Lat-Long' in t:
matches = pattern.search(t)
new_Ylocation_column_header.append(float(matches.group(0)))
else:
new_Ylocation_column_header.append(t)
column_headings['Y'] = new_Ylocation_column_header
lat = NAMECoord(name='latitude', dimension=None,
values=column_headings['Y'])
return lat, lon
def _calc_integration_period(time_avgs):
"""
Return a list of datetime.timedelta objects determined from the provided
list of averaging/integration period column headings.
"""
integration_periods = []
pattern = re.compile(
r'(\d{0,2})(day)?\s*(\d{1,2})(hr)?\s*(\d{1,2})(min)?\s*(\w*)')
for time_str in time_avgs:
days = 0
hours = 0
minutes = 0
matches = pattern.search(time_str)
if matches:
if len(matches.group(1)) > 0:
days = float(matches.group(1))
if len(matches.group(3)) > 0:
hours = float(matches.group(3))
if len(matches.group(1)) > 0:
minutes = float(matches.group(5))
total_hours = days * 24.0 + hours + minutes / 60.0
integration_periods.append(datetime.timedelta(hours=total_hours))
return integration_periods
def _parse_units(units):
"""
Return a known :class:`iris.unit.Unit` given a NAME unit
.. note::
* Some NAME units are not currently handled.
* Units which are in the wrong case (case is ignored in NAME)
* Units where the space between SI units is missing
* Units where the characters used are non-standard (i.e. 'mc' for
micro instead of 'u')
Args:
* units (string):
NAME units.
Returns:
An instance of :class:`iris.unit.Unit`.
"""
unit_mapper = {'Risks/m3': '1', # Used for Bluetongue
'TCID50s/m3': '1', # Used for Foot and Mouth
'TCID50/m3': '1', # Used for Foot and Mouth
'N/A': '1', # Used for CHEMET area at risk
'lb': 'pounds', # pounds
'oz': '1', # ounces
'deg': 'degree', # angular degree
'oktas': '1', # oktas
'deg C': 'deg_C', # degrees Celsius
'FL': 'unknown' # flight level
}
units = unit_mapper.get(units, units)
units = units.replace('Kg', 'kg')
units = units.replace('gs', 'g s')
units = units.replace('Bqs', 'Bq s')
units = units.replace('mcBq', 'uBq')
units = units.replace('mcg', 'ug')
try:
units = iris.unit.Unit(units)
except ValueError:
warnings.warn('Unknown units: {!r}'.format(units))
units = iris.unit.Unit(None)
return units
def _cf_height_from_name(z_coord):
"""
Parser for the z component of field headings.
This parse is specifically for handling the z component of NAME field
headings, which include height above ground level, height above sea level
and flight level etc. This function returns an iris coordinate
representing this field heading.
Args:
* z_coord (list):
A field heading, specifically the z component.
Returns:
An instance of :class:`iris.coords.AuxCoord` representing the
interpretation of the supplied field heading.
"""
# NAMEII - integer/float support.
# Match against height agl, asl and Pa.
pattern = re.compile(r'^From\s*'
'(?P<lower_bound>[0-9]+(\.[0-9]+)?)'
'\s*-\s*'
'(?P<upper_bound>[0-9]+(\.[0-9]+)?)'
'\s*(?P<type>m\s*asl|m\s*agl|Pa)'
'(?P<extra>.*)')
# Match against flight level.
pattern_fl = re.compile(r'^From\s*'
'(?P<type>FL)'
'(?P<lower_bound>[0-9]+(\.[0-9]+)?)'
'\s*-\s*FL'
'(?P<upper_bound>[0-9]+(\.[0-9]+)?)'
'(?P<extra>.*)')
# NAMEIII - integer/float support.
# Match scalar against height agl, asl, Pa, FL
pattern_scalar = re.compile(r'Z\s*=\s*'
'(?P<point>[0-9]+(\.[0-9]+)?)'
'\s*(?P<type>m\s*agl|m\s*asl|FL|Pa)'
'(?P<extra>.*)')
type_name = {'magl': 'height', 'masl': 'altitude', 'FL': 'flight_level',
'Pa': 'air_pressure'}
patterns = [pattern, pattern_fl, pattern_scalar]
units = 'no-unit'
points = z_coord
bounds = None
standard_name = None
long_name = 'z'
for pattern in patterns:
match = pattern.match(z_coord)
if match:
match = match.groupdict()
# Do not interpret if there is additional information to the match
if match['extra']:
break
units = match['type'].replace(' ', '')
name = type_name[units]
# Interpret points if present.
if 'point' in match:
points = float(match['point'])
# Interpret points from bounds.
else:
bounds = np.array([float(match['lower_bound']),
float(match['upper_bound'])])
points = bounds.sum() / 2.
long_name = None
if name == 'altitude':
units = units[0]
standard_name = name
long_name = 'altitude above sea level'
elif name == 'height':
units = units[0]
standard_name = name
long_name = 'height above ground level'
elif name == 'air_pressure':
standard_name = name
elif name == 'flight_level':
long_name = name
units = _parse_units(units)
break
coord = AuxCoord(points, units=units, standard_name=standard_name,
long_name=long_name, bounds=bounds)
return coord
def _generate_cubes(header, column_headings, coords, data_arrays,
cell_methods=None):
"""
Yield :class:`iris.cube.Cube` instances given
the headers, column headings, coords and data_arrays extracted
from a NAME file.
"""
for i, data_array in enumerate(data_arrays):
# Turn the dictionary of column headings with a list of header
# information for each field into a dictionary of headings for
# just this field.
field_headings = {k: v[i] for k, v in
column_headings.iteritems()}
# Make a cube.
cube = iris.cube.Cube(data_array)
# Determine the name and units.
name = '{} {}'.format(field_headings['Species'],
field_headings['Quantity'])
name = name.upper().replace(' ', '_')
cube.rename(name)
# Some units are not in SI units, are missing spaces or typed
# in the wrong case. _parse_units returns units that are
# recognised by Iris.
cube.units = _parse_units(field_headings['Unit'])
# Define and add the singular coordinates of the field (flight
# level, time etc.)
z_coord = _cf_height_from_name(field_headings['Z'])
cube.add_aux_coord(z_coord)
# Define the time unit and use it to serialise the datetime for
# the time coordinate.
time_unit = iris.unit.Unit(
'hours since epoch', calendar=iris.unit.CALENDAR_GREGORIAN)
# Build time, latitude and longitude coordinates.
for coord in coords:
pts = coord.values
coord_sys = None
if coord.name == 'latitude' or coord.name == 'longitude':
coord_units = 'degrees'
coord_sys = iris.coord_systems.GeogCS(EARTH_RADIUS)
if coord.name == 'time':
coord_units = time_unit
pts = time_unit.date2num(coord.values)
if coord.dimension is not None:
if coord.name == 'longitude':
circular = iris.util._is_circular(pts, 360.0)
else:
circular = False
icoord = DimCoord(points=pts,
standard_name=coord.name,
units=coord_units,
coord_system=coord_sys,
circular=circular)
if coord.name == 'time' and 'Av or Int period' in \
field_headings:
dt = coord.values - \
field_headings['Av or Int period']
bnds = time_unit.date2num(
np.vstack((dt, coord.values)).T)
icoord.bounds = bnds
else:
icoord.guess_bounds()
cube.add_dim_coord(icoord, coord.dimension)
else:
icoord = AuxCoord(points=pts[i],
standard_name=coord.name,
coord_system=coord_sys,
units=coord_units)
if coord.name == 'time' and 'Av or Int period' in \
field_headings:
dt = coord.values - \
field_headings['Av or Int period']
bnds = time_unit.date2num(
np.vstack((dt, coord.values)).T)
icoord.bounds = bnds[i, :]
cube.add_aux_coord(icoord)
# Headings/column headings which are encoded elsewhere.
headings = ['X', 'Y', 'Z', 'Time', 'Unit', 'Av or Int period',
'X grid origin', 'Y grid origin',
'X grid size', 'Y grid size',
'X grid resolution', 'Y grid resolution', ]
# Add the Main Headings as attributes.
for key, value in header.iteritems():
if value is not None and value != '' and \
key not in headings:
cube.attributes[key] = value
# Add the Column Headings as attributes
for key, value in field_headings.iteritems():
if value is not None and value != '' and \
key not in headings:
cube.attributes[key] = value
if cell_methods is not None:
cube.add_cell_method(cell_methods[i])
yield cube
def _build_cell_methods(av_or_ints, coord):
"""
Return a list of :class:`iris.coords.CellMethod` instances
based on the provided list of column heading entries and the
associated coordinate. If a given entry does not correspond to a cell
method (e.g. "No time averaging"), a value of None is inserted.
Args:
* av_or_ints (iterable of strings):
An iterable of strings containing the colummn heading entries
to be parsed.
* coord (string or :class:`iris.coords.Coord`):
The coordinate name (or :class:`iris.coords.Coord` instance)
to which the column heading entries refer.
Returns:
A list that is the same length as `av_or_ints` containing
:class:`iris.coords.CellMethod` instances or values of None.
"""
cell_methods = []
no_avg_pattern = re.compile(r'^(no( (.* )?averaging)?)?$', re.IGNORECASE)
for av_or_int in av_or_ints:
if no_avg_pattern.search(av_or_int) is not None:
cell_method = None
elif 'average' in av_or_int or 'averaged' in av_or_int:
cell_method = CellMethod('mean', coord)
elif 'integral' in av_or_int or 'integrated' in av_or_int:
cell_method = CellMethod('sum', coord)
else:
cell_method = None
msg = 'Unknown {} statistic: {!r}. Unable to create cell method.'
warnings.warn(msg.format(coord, av_or_int))
cell_methods.append(cell_method)
return cell_methods
def load_NAMEIII_field(filename):
"""
Load a NAME III grid output file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
# Loading a file gives a generator of lines which can be progressed using
# the next() method. This will come in handy as we wish to progress
# through the file line by line.
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# Skip the next line (contains the word Fields:) in the file.
next(file_handle)
# Read the lines of column definitions.
# In this version a fixed order of column headings is assumed (and
# first 4 columns are ignored).
column_headings = {}
for column_header_name in ['Species Category', 'Name', 'Quantity',
'Species', 'Unit', 'Sources', 'Ensemble Av',
'Time Av or Int', 'Horizontal Av or Int',
'Vertical Av or Int', 'Prob Perc',
'Prob Perc Ens', 'Prob Perc Time',
'Time', 'Z', 'D']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[4:-1]
# Convert the time to python datetimes.
new_time_column_header = []
for i, t in enumerate(column_headings['Time']):
dt = datetime.datetime.strptime(t, NAMEIII_DATETIME_FORMAT)
new_time_column_header.append(dt)
column_headings['Time'] = new_time_column_header
# Convert averaging/integrating period to timedeltas.
column_headings['Av or Int period'] = _calc_integration_period(
column_headings['Time Av or Int'])
# Build a time coordinate.
tdim = NAMECoord(name='time', dimension=None,
values=np.array(column_headings['Time']))
cell_methods = _build_cell_methods(column_headings['Time Av or Int'],
tdim.name)
# Build regular latitude and longitude coordinates.
lat, lon = _build_lat_lon_for_NAME_field(header)
coords = [lon, lat, tdim]
# Skip the line after the column headings.
next(file_handle)
# Create data arrays to hold the data for each column.
n_arrays = header['Number of field cols']
shape = (header['Y grid size'], header['X grid size'])
data_arrays = _read_data_arrays(file_handle, n_arrays, shape)
return _generate_cubes(header, column_headings, coords, data_arrays,
cell_methods)
def load_NAMEII_field(filename):
"""
Load a NAME II grid output file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# Origin in namever=2 format is bottom-left hand corner so alter this
# to centre of a grid box
header['X grid origin'] = header['X grid origin'] + \
header['X grid resolution'] / 2
header['Y grid origin'] = header['Y grid origin'] + \
header['Y grid resolution'] / 2
# Read the lines of column definitions.
# In this version a fixed order of column headings is assumed (and
# first 4 columns are ignored).
column_headings = {}
for column_header_name in ['Species Category', 'Species',
'Time Av or Int', 'Quantity',
'Unit', 'Z', 'Time']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[4:-1]
# Convert the time to python datetimes
new_time_column_header = []
for i, t in enumerate(column_headings['Time']):
dt = datetime.datetime.strptime(t, NAMEII_FIELD_DATETIME_FORMAT)
new_time_column_header.append(dt)
column_headings['Time'] = new_time_column_header
# Convert averaging/integrating period to timedeltas.
pattern = re.compile(r'\s*(\d{3})\s*(hr)?\s*(time)\s*(\w*)')
column_headings['Av or Int period'] = []
for i, t in enumerate(column_headings['Time Av or Int']):
matches = pattern.search(t)
hours = 0
if matches:
if len(matches.group(1)) > 0:
hours = float(matches.group(1))
column_headings['Av or Int period'].append(
datetime.timedelta(hours=hours))
# Build a time coordinate.
tdim = NAMECoord(name='time', dimension=None,
values=np.array(column_headings['Time']))
cell_methods = _build_cell_methods(column_headings['Time Av or Int'],
tdim.name)
# Build regular latitude and longitude coordinates.
lat, lon = _build_lat_lon_for_NAME_field(header)
coords = [lon, lat, tdim]
# Skip the blank line after the column headings.
next(file_handle)
# Create data arrays to hold the data for each column.
n_arrays = header['Number of fields']
shape = (header['Y grid size'], header['X grid size'])
data_arrays = _read_data_arrays(file_handle, n_arrays, shape)
return _generate_cubes(header, column_headings, coords, data_arrays,
cell_methods)
def load_NAMEIII_timeseries(filename):
"""
Load a NAME III time series file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# skip the next line (contains the word Fields:) in the file.
next(file_handle)
# Read the lines of column definitions - currently hardwired
column_headings = {}
for column_header_name in ['Species Category', 'Name', 'Quantity',
'Species', 'Unit', 'Sources', 'Ens Av',
'Time Av or Int', 'Horizontal Av or Int',
'Vertical Av or Int', 'Prob Perc',
'Prob Perc Ens', 'Prob Perc Time',
'Location', 'X', 'Y', 'Z', 'D']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[1:-1]
# Determine the coordinates of the data and store in namedtuples.
# Extract latitude and longitude information from X, Y location
# headings.
lat, lon = _build_lat_lon_for_NAME_timeseries(column_headings)
# Convert averaging/integrating period to timedeltas.
column_headings['Av or Int period'] = _calc_integration_period(
column_headings['Time Av or Int'])
# Skip the line after the column headings.
next(file_handle)
# Make a list of data lists to hold the data for each column.
data_lists = [[] for i in range(header['Number of field cols'])]
time_list = []
# Iterate over the remaining lines which represent the data in a
# column form.
for line in file_handle:
# Split the line by comma, removing the last empty column caused
# by the trailing comma.
vals = line.split(',')[:-1]
# Time is stored in the first column.
t = vals[0].strip()
dt = datetime.datetime.strptime(t, NAMEIII_DATETIME_FORMAT)
time_list.append(dt)
# Populate the data arrays.
for i, data_list in enumerate(data_lists):
data_list.append(float(vals[i + 1]))
data_arrays = [np.array(l) for l in data_lists]
time_array = np.array(time_list)
tdim = NAMECoord(name='time', dimension=0, values=time_array)
coords = [lon, lat, tdim]
return _generate_cubes(header, column_headings, coords, data_arrays)
def load_NAMEII_timeseries(filename):
"""
Load a NAME II Time Series file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# Read the lines of column definitions.
column_headings = {}
for column_header_name in ['Y', 'X', 'Location',
'Species Category', 'Species',
'Quantity', 'Z', 'Unit']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[1:-1]
# Determine the coordinates of the data and store in namedtuples.
# Extract latitude and longitude information from X, Y location
# headings.
|
[
" lat, lon = _build_lat_lon_for_NAME_timeseries(column_headings)"
] | 2,765
|
lcc
|
python
| null |
d6baed6ebf26ec130b53d88863008a04aa5759c9dbf5f916
| 50
|
Your task is code completion.
# (C) British Crown Copyright 2013 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""NAME file format loading functions."""
from __future__ import (absolute_import, division, print_function)
from six.moves import range, zip
import collections
import datetime
import re
import warnings
import numpy as np
from iris.coords import AuxCoord, DimCoord, CellMethod
import iris.coord_systems
import iris.cube
from iris.exceptions import TranslationError
import iris.util
import iris.unit
EARTH_RADIUS = 6371229.0
NAMEIII_DATETIME_FORMAT = '%d/%m/%Y %H:%M %Z'
NAMEII_FIELD_DATETIME_FORMAT = '%H%M%Z %d/%m/%Y'
NAMEII_TIMESERIES_DATETIME_FORMAT = '%d/%m/%Y %H:%M:%S'
NAMECoord = collections.namedtuple('NAMECoord', ['name',
'dimension',
'values'])
def _split_name_and_units(name):
units = None
if "(" in name and ")" in name:
split = name.rsplit("(", 1)
try_units = split[1].replace(")", "").strip()
try:
try_units = iris.unit.Unit(try_units)
except ValueError:
pass
else:
name = split[0].strip()
units = try_units
return name, units
def read_header(file_handle):
"""
Return a dictionary containing the header information extracted
from the the provided NAME file object.
Args:
* file_handle (file-like object):
A file-like object from which to read the header information.
Returns:
A dictionary containing the extracted header information.
"""
header = {}
header['NAME Version'] = file_handle.next().strip()
for line in file_handle:
words = line.split(':', 1)
if len(words) != 2:
break
key, value = [word.strip() for word in words]
header[key] = value
# Cast some values into floats or integers if they match a
# given name. Set any empty string values to None.
for key, value in header.items():
if value:
if key in ['X grid origin', 'Y grid origin',
'X grid resolution', 'Y grid resolution']:
header[key] = float(value)
elif key in ['X grid size', 'Y grid size',
'Number of preliminary cols',
'Number of field cols',
'Number of fields',
'Number of series']:
header[key] = int(value)
else:
header[key] = None
return header
def _read_data_arrays(file_handle, n_arrays, shape):
"""
Return a list of NumPy arrays containing the data extracted from
the provided file object. The number and shape of the arrays
must be specified.
"""
data_arrays = [np.zeros(shape, dtype=np.float32) for
i in range(n_arrays)]
# Iterate over the remaining lines which represent the data in
# a column form.
for line in file_handle:
# Split the line by comma, removing the last empty column
# caused by the trailing comma
vals = line.split(',')[:-1]
# Cast the x and y grid positions to integers and convert
# them to zero based indices
x = int(float(vals[0])) - 1
y = int(float(vals[1])) - 1
# Populate the data arrays (i.e. all columns but the leading 4).
for i, data_array in enumerate(data_arrays):
data_array[y, x] = float(vals[i + 4])
return data_arrays
def _build_lat_lon_for_NAME_field(header):
"""
Return regular latitude and longitude coordinates extracted from
the provided header dictionary.
"""
start = header['X grid origin']
step = header['X grid resolution']
count = header['X grid size']
pts = start + np.arange(count, dtype=np.float64) * step
lon = NAMECoord(name='longitude', dimension=1, values=pts)
start = header['Y grid origin']
step = header['Y grid resolution']
count = header['Y grid size']
pts = start + np.arange(count, dtype=np.float64) * step
lat = NAMECoord(name='latitude', dimension=0, values=pts)
return lat, lon
def _build_lat_lon_for_NAME_timeseries(column_headings):
"""
Return regular latitude and longitude coordinates extracted from
the provided column_headings dictionary.
"""
pattern = re.compile(r'\-?[0-9]*\.[0-9]*')
new_Xlocation_column_header = []
for t in column_headings['X']:
if 'Lat-Long' in t:
matches = pattern.search(t)
new_Xlocation_column_header.append(float(matches.group(0)))
else:
new_Xlocation_column_header.append(t)
column_headings['X'] = new_Xlocation_column_header
lon = NAMECoord(name='longitude', dimension=None,
values=column_headings['X'])
new_Ylocation_column_header = []
for t in column_headings['Y']:
if 'Lat-Long' in t:
matches = pattern.search(t)
new_Ylocation_column_header.append(float(matches.group(0)))
else:
new_Ylocation_column_header.append(t)
column_headings['Y'] = new_Ylocation_column_header
lat = NAMECoord(name='latitude', dimension=None,
values=column_headings['Y'])
return lat, lon
def _calc_integration_period(time_avgs):
"""
Return a list of datetime.timedelta objects determined from the provided
list of averaging/integration period column headings.
"""
integration_periods = []
pattern = re.compile(
r'(\d{0,2})(day)?\s*(\d{1,2})(hr)?\s*(\d{1,2})(min)?\s*(\w*)')
for time_str in time_avgs:
days = 0
hours = 0
minutes = 0
matches = pattern.search(time_str)
if matches:
if len(matches.group(1)) > 0:
days = float(matches.group(1))
if len(matches.group(3)) > 0:
hours = float(matches.group(3))
if len(matches.group(1)) > 0:
minutes = float(matches.group(5))
total_hours = days * 24.0 + hours + minutes / 60.0
integration_periods.append(datetime.timedelta(hours=total_hours))
return integration_periods
def _parse_units(units):
"""
Return a known :class:`iris.unit.Unit` given a NAME unit
.. note::
* Some NAME units are not currently handled.
* Units which are in the wrong case (case is ignored in NAME)
* Units where the space between SI units is missing
* Units where the characters used are non-standard (i.e. 'mc' for
micro instead of 'u')
Args:
* units (string):
NAME units.
Returns:
An instance of :class:`iris.unit.Unit`.
"""
unit_mapper = {'Risks/m3': '1', # Used for Bluetongue
'TCID50s/m3': '1', # Used for Foot and Mouth
'TCID50/m3': '1', # Used for Foot and Mouth
'N/A': '1', # Used for CHEMET area at risk
'lb': 'pounds', # pounds
'oz': '1', # ounces
'deg': 'degree', # angular degree
'oktas': '1', # oktas
'deg C': 'deg_C', # degrees Celsius
'FL': 'unknown' # flight level
}
units = unit_mapper.get(units, units)
units = units.replace('Kg', 'kg')
units = units.replace('gs', 'g s')
units = units.replace('Bqs', 'Bq s')
units = units.replace('mcBq', 'uBq')
units = units.replace('mcg', 'ug')
try:
units = iris.unit.Unit(units)
except ValueError:
warnings.warn('Unknown units: {!r}'.format(units))
units = iris.unit.Unit(None)
return units
def _cf_height_from_name(z_coord):
"""
Parser for the z component of field headings.
This parse is specifically for handling the z component of NAME field
headings, which include height above ground level, height above sea level
and flight level etc. This function returns an iris coordinate
representing this field heading.
Args:
* z_coord (list):
A field heading, specifically the z component.
Returns:
An instance of :class:`iris.coords.AuxCoord` representing the
interpretation of the supplied field heading.
"""
# NAMEII - integer/float support.
# Match against height agl, asl and Pa.
pattern = re.compile(r'^From\s*'
'(?P<lower_bound>[0-9]+(\.[0-9]+)?)'
'\s*-\s*'
'(?P<upper_bound>[0-9]+(\.[0-9]+)?)'
'\s*(?P<type>m\s*asl|m\s*agl|Pa)'
'(?P<extra>.*)')
# Match against flight level.
pattern_fl = re.compile(r'^From\s*'
'(?P<type>FL)'
'(?P<lower_bound>[0-9]+(\.[0-9]+)?)'
'\s*-\s*FL'
'(?P<upper_bound>[0-9]+(\.[0-9]+)?)'
'(?P<extra>.*)')
# NAMEIII - integer/float support.
# Match scalar against height agl, asl, Pa, FL
pattern_scalar = re.compile(r'Z\s*=\s*'
'(?P<point>[0-9]+(\.[0-9]+)?)'
'\s*(?P<type>m\s*agl|m\s*asl|FL|Pa)'
'(?P<extra>.*)')
type_name = {'magl': 'height', 'masl': 'altitude', 'FL': 'flight_level',
'Pa': 'air_pressure'}
patterns = [pattern, pattern_fl, pattern_scalar]
units = 'no-unit'
points = z_coord
bounds = None
standard_name = None
long_name = 'z'
for pattern in patterns:
match = pattern.match(z_coord)
if match:
match = match.groupdict()
# Do not interpret if there is additional information to the match
if match['extra']:
break
units = match['type'].replace(' ', '')
name = type_name[units]
# Interpret points if present.
if 'point' in match:
points = float(match['point'])
# Interpret points from bounds.
else:
bounds = np.array([float(match['lower_bound']),
float(match['upper_bound'])])
points = bounds.sum() / 2.
long_name = None
if name == 'altitude':
units = units[0]
standard_name = name
long_name = 'altitude above sea level'
elif name == 'height':
units = units[0]
standard_name = name
long_name = 'height above ground level'
elif name == 'air_pressure':
standard_name = name
elif name == 'flight_level':
long_name = name
units = _parse_units(units)
break
coord = AuxCoord(points, units=units, standard_name=standard_name,
long_name=long_name, bounds=bounds)
return coord
def _generate_cubes(header, column_headings, coords, data_arrays,
cell_methods=None):
"""
Yield :class:`iris.cube.Cube` instances given
the headers, column headings, coords and data_arrays extracted
from a NAME file.
"""
for i, data_array in enumerate(data_arrays):
# Turn the dictionary of column headings with a list of header
# information for each field into a dictionary of headings for
# just this field.
field_headings = {k: v[i] for k, v in
column_headings.iteritems()}
# Make a cube.
cube = iris.cube.Cube(data_array)
# Determine the name and units.
name = '{} {}'.format(field_headings['Species'],
field_headings['Quantity'])
name = name.upper().replace(' ', '_')
cube.rename(name)
# Some units are not in SI units, are missing spaces or typed
# in the wrong case. _parse_units returns units that are
# recognised by Iris.
cube.units = _parse_units(field_headings['Unit'])
# Define and add the singular coordinates of the field (flight
# level, time etc.)
z_coord = _cf_height_from_name(field_headings['Z'])
cube.add_aux_coord(z_coord)
# Define the time unit and use it to serialise the datetime for
# the time coordinate.
time_unit = iris.unit.Unit(
'hours since epoch', calendar=iris.unit.CALENDAR_GREGORIAN)
# Build time, latitude and longitude coordinates.
for coord in coords:
pts = coord.values
coord_sys = None
if coord.name == 'latitude' or coord.name == 'longitude':
coord_units = 'degrees'
coord_sys = iris.coord_systems.GeogCS(EARTH_RADIUS)
if coord.name == 'time':
coord_units = time_unit
pts = time_unit.date2num(coord.values)
if coord.dimension is not None:
if coord.name == 'longitude':
circular = iris.util._is_circular(pts, 360.0)
else:
circular = False
icoord = DimCoord(points=pts,
standard_name=coord.name,
units=coord_units,
coord_system=coord_sys,
circular=circular)
if coord.name == 'time' and 'Av or Int period' in \
field_headings:
dt = coord.values - \
field_headings['Av or Int period']
bnds = time_unit.date2num(
np.vstack((dt, coord.values)).T)
icoord.bounds = bnds
else:
icoord.guess_bounds()
cube.add_dim_coord(icoord, coord.dimension)
else:
icoord = AuxCoord(points=pts[i],
standard_name=coord.name,
coord_system=coord_sys,
units=coord_units)
if coord.name == 'time' and 'Av or Int period' in \
field_headings:
dt = coord.values - \
field_headings['Av or Int period']
bnds = time_unit.date2num(
np.vstack((dt, coord.values)).T)
icoord.bounds = bnds[i, :]
cube.add_aux_coord(icoord)
# Headings/column headings which are encoded elsewhere.
headings = ['X', 'Y', 'Z', 'Time', 'Unit', 'Av or Int period',
'X grid origin', 'Y grid origin',
'X grid size', 'Y grid size',
'X grid resolution', 'Y grid resolution', ]
# Add the Main Headings as attributes.
for key, value in header.iteritems():
if value is not None and value != '' and \
key not in headings:
cube.attributes[key] = value
# Add the Column Headings as attributes
for key, value in field_headings.iteritems():
if value is not None and value != '' and \
key not in headings:
cube.attributes[key] = value
if cell_methods is not None:
cube.add_cell_method(cell_methods[i])
yield cube
def _build_cell_methods(av_or_ints, coord):
"""
Return a list of :class:`iris.coords.CellMethod` instances
based on the provided list of column heading entries and the
associated coordinate. If a given entry does not correspond to a cell
method (e.g. "No time averaging"), a value of None is inserted.
Args:
* av_or_ints (iterable of strings):
An iterable of strings containing the colummn heading entries
to be parsed.
* coord (string or :class:`iris.coords.Coord`):
The coordinate name (or :class:`iris.coords.Coord` instance)
to which the column heading entries refer.
Returns:
A list that is the same length as `av_or_ints` containing
:class:`iris.coords.CellMethod` instances or values of None.
"""
cell_methods = []
no_avg_pattern = re.compile(r'^(no( (.* )?averaging)?)?$', re.IGNORECASE)
for av_or_int in av_or_ints:
if no_avg_pattern.search(av_or_int) is not None:
cell_method = None
elif 'average' in av_or_int or 'averaged' in av_or_int:
cell_method = CellMethod('mean', coord)
elif 'integral' in av_or_int or 'integrated' in av_or_int:
cell_method = CellMethod('sum', coord)
else:
cell_method = None
msg = 'Unknown {} statistic: {!r}. Unable to create cell method.'
warnings.warn(msg.format(coord, av_or_int))
cell_methods.append(cell_method)
return cell_methods
def load_NAMEIII_field(filename):
"""
Load a NAME III grid output file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
# Loading a file gives a generator of lines which can be progressed using
# the next() method. This will come in handy as we wish to progress
# through the file line by line.
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# Skip the next line (contains the word Fields:) in the file.
next(file_handle)
# Read the lines of column definitions.
# In this version a fixed order of column headings is assumed (and
# first 4 columns are ignored).
column_headings = {}
for column_header_name in ['Species Category', 'Name', 'Quantity',
'Species', 'Unit', 'Sources', 'Ensemble Av',
'Time Av or Int', 'Horizontal Av or Int',
'Vertical Av or Int', 'Prob Perc',
'Prob Perc Ens', 'Prob Perc Time',
'Time', 'Z', 'D']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[4:-1]
# Convert the time to python datetimes.
new_time_column_header = []
for i, t in enumerate(column_headings['Time']):
dt = datetime.datetime.strptime(t, NAMEIII_DATETIME_FORMAT)
new_time_column_header.append(dt)
column_headings['Time'] = new_time_column_header
# Convert averaging/integrating period to timedeltas.
column_headings['Av or Int period'] = _calc_integration_period(
column_headings['Time Av or Int'])
# Build a time coordinate.
tdim = NAMECoord(name='time', dimension=None,
values=np.array(column_headings['Time']))
cell_methods = _build_cell_methods(column_headings['Time Av or Int'],
tdim.name)
# Build regular latitude and longitude coordinates.
lat, lon = _build_lat_lon_for_NAME_field(header)
coords = [lon, lat, tdim]
# Skip the line after the column headings.
next(file_handle)
# Create data arrays to hold the data for each column.
n_arrays = header['Number of field cols']
shape = (header['Y grid size'], header['X grid size'])
data_arrays = _read_data_arrays(file_handle, n_arrays, shape)
return _generate_cubes(header, column_headings, coords, data_arrays,
cell_methods)
def load_NAMEII_field(filename):
"""
Load a NAME II grid output file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# Origin in namever=2 format is bottom-left hand corner so alter this
# to centre of a grid box
header['X grid origin'] = header['X grid origin'] + \
header['X grid resolution'] / 2
header['Y grid origin'] = header['Y grid origin'] + \
header['Y grid resolution'] / 2
# Read the lines of column definitions.
# In this version a fixed order of column headings is assumed (and
# first 4 columns are ignored).
column_headings = {}
for column_header_name in ['Species Category', 'Species',
'Time Av or Int', 'Quantity',
'Unit', 'Z', 'Time']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[4:-1]
# Convert the time to python datetimes
new_time_column_header = []
for i, t in enumerate(column_headings['Time']):
dt = datetime.datetime.strptime(t, NAMEII_FIELD_DATETIME_FORMAT)
new_time_column_header.append(dt)
column_headings['Time'] = new_time_column_header
# Convert averaging/integrating period to timedeltas.
pattern = re.compile(r'\s*(\d{3})\s*(hr)?\s*(time)\s*(\w*)')
column_headings['Av or Int period'] = []
for i, t in enumerate(column_headings['Time Av or Int']):
matches = pattern.search(t)
hours = 0
if matches:
if len(matches.group(1)) > 0:
hours = float(matches.group(1))
column_headings['Av or Int period'].append(
datetime.timedelta(hours=hours))
# Build a time coordinate.
tdim = NAMECoord(name='time', dimension=None,
values=np.array(column_headings['Time']))
cell_methods = _build_cell_methods(column_headings['Time Av or Int'],
tdim.name)
# Build regular latitude and longitude coordinates.
lat, lon = _build_lat_lon_for_NAME_field(header)
coords = [lon, lat, tdim]
# Skip the blank line after the column headings.
next(file_handle)
# Create data arrays to hold the data for each column.
n_arrays = header['Number of fields']
shape = (header['Y grid size'], header['X grid size'])
data_arrays = _read_data_arrays(file_handle, n_arrays, shape)
return _generate_cubes(header, column_headings, coords, data_arrays,
cell_methods)
def load_NAMEIII_timeseries(filename):
"""
Load a NAME III time series file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# skip the next line (contains the word Fields:) in the file.
next(file_handle)
# Read the lines of column definitions - currently hardwired
column_headings = {}
for column_header_name in ['Species Category', 'Name', 'Quantity',
'Species', 'Unit', 'Sources', 'Ens Av',
'Time Av or Int', 'Horizontal Av or Int',
'Vertical Av or Int', 'Prob Perc',
'Prob Perc Ens', 'Prob Perc Time',
'Location', 'X', 'Y', 'Z', 'D']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[1:-1]
# Determine the coordinates of the data and store in namedtuples.
# Extract latitude and longitude information from X, Y location
# headings.
lat, lon = _build_lat_lon_for_NAME_timeseries(column_headings)
# Convert averaging/integrating period to timedeltas.
column_headings['Av or Int period'] = _calc_integration_period(
column_headings['Time Av or Int'])
# Skip the line after the column headings.
next(file_handle)
# Make a list of data lists to hold the data for each column.
data_lists = [[] for i in range(header['Number of field cols'])]
time_list = []
# Iterate over the remaining lines which represent the data in a
# column form.
for line in file_handle:
# Split the line by comma, removing the last empty column caused
# by the trailing comma.
vals = line.split(',')[:-1]
# Time is stored in the first column.
t = vals[0].strip()
dt = datetime.datetime.strptime(t, NAMEIII_DATETIME_FORMAT)
time_list.append(dt)
# Populate the data arrays.
for i, data_list in enumerate(data_lists):
data_list.append(float(vals[i + 1]))
data_arrays = [np.array(l) for l in data_lists]
time_array = np.array(time_list)
tdim = NAMECoord(name='time', dimension=0, values=time_array)
coords = [lon, lat, tdim]
return _generate_cubes(header, column_headings, coords, data_arrays)
def load_NAMEII_timeseries(filename):
"""
Load a NAME II Time Series file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# Read the lines of column definitions.
column_headings = {}
for column_header_name in ['Y', 'X', 'Location',
'Species Category', 'Species',
'Quantity', 'Z', 'Unit']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[1:-1]
# Determine the coordinates of the data and store in namedtuples.
# Extract latitude and longitude information from X, Y location
# headings.
|
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]
def load_NAMEII_timeseries(filename):
"""
Load a NAME II Time Series file returning a
generator of :class:`iris.cube.Cube` instances.
Args:
* filename (string):
Name of file to load.
Returns:
A generator :class:`iris.cube.Cube` instances.
"""
with open(filename, 'r') as file_handle:
# Create a dictionary which can hold the header metadata about this
# file.
header = read_header(file_handle)
# Read the lines of column definitions.
column_headings = {}
for column_header_name in ['Y', 'X', 'Location',
'Species Category', 'Species',
'Quantity', 'Z', 'Unit']:
cols = [col.strip() for col in file_handle.next().split(',')]
column_headings[column_header_name] = cols[1:-1]
# Determine the coordinates of the data and store in namedtuples.
# Extract latitude and longitude information from X, Y location
# headings.
lat, lon = _build_lat_lon_for_NAME_timeseries(column_headings)
# Convert averaging/integrating period to timedeltas.
column_headings['Av or Int period'] = _calc_integration_period(
column_headings['Time Av or Int'])
# Skip the line after the column headings.
next(file_handle)
# Make a list of data lists to hold the data for each column.
data_lists = [[] for i in range(header['Number of fields'])]
time_list = []
# Iterate over the remaining lines which represent the data in a
# column form.
for line in file_handle:
# Split the line by comma, removing the last empty column caused
# by the trailing comma.
vals = line.split(',')[:-1]
# Time is stored in the first column.
t = vals[0].strip()
dt = datetime.datetime.strptime(t, NAMEII_TIMESERIES_DATETIME_FORMAT)
time_list.append(dt)
# Populate the data arrays.
for i, data_list in enumerate(data_lists):
data_list.append(float(vals[i + 1]))
data_arrays = [np.array(l) for l in data_lists]
time_array = np.array(time_list)
tdim = NAMECoord(name='time', dimension=0, values=time_array)
coords = [lon, lat, tdim]
return _generate_cubes(header, column_headings, coords, data_arrays)
Cheatsheet (for next line):
- We are in load_NAMEII_timeseries() function.
- The function is supposed to return a generator of iris.cube.Cube instances.
- The function has already created a dictionary of column_headings.
- The function has already created a list of data_arrays.
- The function has already created a time_array and a tdim (time coordinate).
- The function has already created a list of coordinates (coords).
- The function is supposed to call _generate_cubes() function to create iris.cube.Cube instances.
- The _generate_cubes() function requires the following parameters: header, column_headings, coords, data_arrays, cell_methods.
- The cell_methods parameter is missing in the current function.
Next line will likely be: cell_methods = _build_cell_methods(column_headings['Time Av or Int'], tdim.name); return _generate_cubes(header, column_headings, coords, data_arrays, cell_methods);
|
|
Please complete the code given below.
# encoding: utf-8
import ckan.logic as logic
import ckan.authz as authz
import ckan.logic.auth as logic_auth
from ckan.common import _
@logic.auth_allow_anonymous_access
def package_create(context, data_dict=None):
user = context['user']
if authz.auth_is_anon_user(context):
check1 = all(authz.check_config_permission(p) for p in (
'anon_create_dataset',
'create_dataset_if_not_in_organization',
'create_unowned_dataset',
))
else:
check1 = all(authz.check_config_permission(p) for p in (
'create_dataset_if_not_in_organization',
'create_unowned_dataset',
)) or authz.has_user_permission_for_some_org(
user, 'create_dataset')
if not check1:
return {'success': False, 'msg': _('User %s not authorized to create packages') % user}
check2 = _check_group_auth(context,data_dict)
if not check2:
return {'success': False, 'msg': _('User %s not authorized to edit these groups') % user}
# If an organization is given are we able to add a dataset to it?
data_dict = data_dict or {}
org_id = data_dict.get('owner_org')
if org_id and not authz.has_user_permission_for_group_or_org(
org_id, user, 'create_dataset'):
return {'success': False, 'msg': _('User %s not authorized to add dataset to this organization') % user}
return {'success': True}
def file_upload(context, data_dict=None):
user = context['user']
if authz.auth_is_anon_user(context):
return {'success': False, 'msg': _('User %s not authorized to create packages') % user}
return {'success': True}
def resource_create(context, data_dict):
model = context['model']
user = context.get('user')
package_id = data_dict.get('package_id')
if not package_id and data_dict.get('id'):
# This can happen when auth is deferred, eg from `resource_view_create`
resource = logic_auth.get_resource_object(context, data_dict)
package_id = resource.package_id
if not package_id:
raise logic.NotFound(
_('No dataset id provided, cannot check auth.')
)
# check authentication against package
pkg = model.Package.get(package_id)
if not pkg:
raise logic.NotFound(
_('No package found for this resource, cannot check auth.')
)
pkg_dict = {'id': pkg.id}
authorized = authz.is_authorized('package_update', context, pkg_dict).get('success')
if not authorized:
return {'success': False,
'msg': _('User %s not authorized to create resources on dataset %s') %
(str(user), package_id)}
else:
return {'success': True}
def resource_view_create(context, data_dict):
return authz.is_authorized('resource_create', context, {'id': data_dict['resource_id']})
def resource_create_default_resource_views(context, data_dict):
return authz.is_authorized('resource_create', context, {'id': data_dict['resource']['id']})
def package_create_default_resource_views(context, data_dict):
return authz.is_authorized('package_update', context,
data_dict['package'])
def package_relationship_create(context, data_dict):
user = context['user']
id = data_dict['subject']
id2 = data_dict['object']
# If we can update each package we can see the relationships
authorized1 = authz.is_authorized_boolean(
'package_update', context, {'id': id})
authorized2 = authz.is_authorized_boolean(
'package_update', context, {'id': id2})
if not authorized1 and authorized2:
return {'success': False, 'msg': _('User %s not authorized to edit these packages') % user}
else:
return {'success': True}
def group_create(context, data_dict=None):
user = context['user']
user = authz.get_user_id_for_username(user, allow_none=True)
if user and authz.check_config_permission('user_create_groups'):
return {'success': True}
return {'success': False,
'msg': _('User %s not authorized to create groups') % user}
def organization_create(context, data_dict=None):
user = context['user']
user = authz.get_user_id_for_username(user, allow_none=True)
if user and authz.check_config_permission('user_create_organizations'):
return {'success': True}
return {'success': False,
'msg': _('User %s not authorized to create organizations') % user}
def rating_create(context, data_dict):
# No authz check in the logic function
return {'success': True}
@logic.auth_allow_anonymous_access
def user_create(context, data_dict=None):
using_api = 'api_version' in context
create_user_via_api = authz.check_config_permission(
'create_user_via_api')
create_user_via_web = authz.check_config_permission(
'create_user_via_web')
if using_api and not create_user_via_api:
return {'success': False, 'msg': _('User {user} not authorized to '
'create users via the API').format(user=context.get('user'))}
if not using_api and not create_user_via_web:
return {'success': False, 'msg': _('Not authorized to '
'create users')}
return {'success': True}
def user_invite(context, data_dict):
data_dict['id'] = data_dict['group_id']
return group_member_create(context, data_dict)
def _check_group_auth(context, data_dict):
'''Has this user got update permission for all of the given groups?
If there is a package in the context then ignore that package's groups.
(owner_org is checked elsewhere.)
:returns: False if not allowed to update one (or more) of the given groups.
True otherwise. i.e. True is the default. A blank data_dict
mentions no groups, so it returns True.
'''
# FIXME This code is shared amoung other logic.auth files and should be
# somewhere better
if not data_dict:
return True
model = context['model']
user = context['user']
pkg = context.get("package")
api_version = context.get('api_version') or '1'
group_blobs = data_dict.get('groups', [])
groups = set()
for group_blob in group_blobs:
# group_blob might be a dict or a group_ref
if isinstance(group_blob, dict):
# use group id by default, but we can accept name as well
id = group_blob.get('id') or group_blob.get('name')
if not id:
continue
else:
id = group_blob
grp = model.Group.get(id)
if grp is None:
raise logic.NotFound(_('Group was not found.'))
groups.add(grp)
if pkg:
pkg_groups = pkg.get_groups()
groups = groups - set(pkg_groups)
for group in groups:
if not authz.has_user_permission_for_group_or_org(group.id, user, 'update'):
return False
return True
## Modifications for rest api
def package_create_rest(context, data_dict):
model = context['model']
user = context['user']
if not user:
return {'success': False, 'msg': _('Valid API key needed to create a package')}
return authz.is_authorized('package_create', context, data_dict)
def group_create_rest(context, data_dict):
model = context['model']
user = context['user']
if not user:
return {'success': False, 'msg': _('Valid API key needed to create a group')}
return authz.is_authorized('group_create', context, data_dict)
def vocabulary_create(context, data_dict):
# sysadmins only
return {'success': False}
def activity_create(context, data_dict):
# sysadmins only
return {'success': False}
def tag_create(context, data_dict):
# sysadmins only
return {'success': False}
def _group_or_org_member_create(context, data_dict):
user = context['user']
|
[
" group_id = data_dict['id']"
] | 772
|
lcc
|
python
| null |
37c8cc83faf991e5dab1a2d463f96ea1e173fbf645387307
| 51
|
Your task is code completion.
# encoding: utf-8
import ckan.logic as logic
import ckan.authz as authz
import ckan.logic.auth as logic_auth
from ckan.common import _
@logic.auth_allow_anonymous_access
def package_create(context, data_dict=None):
user = context['user']
if authz.auth_is_anon_user(context):
check1 = all(authz.check_config_permission(p) for p in (
'anon_create_dataset',
'create_dataset_if_not_in_organization',
'create_unowned_dataset',
))
else:
check1 = all(authz.check_config_permission(p) for p in (
'create_dataset_if_not_in_organization',
'create_unowned_dataset',
)) or authz.has_user_permission_for_some_org(
user, 'create_dataset')
if not check1:
return {'success': False, 'msg': _('User %s not authorized to create packages') % user}
check2 = _check_group_auth(context,data_dict)
if not check2:
return {'success': False, 'msg': _('User %s not authorized to edit these groups') % user}
# If an organization is given are we able to add a dataset to it?
data_dict = data_dict or {}
org_id = data_dict.get('owner_org')
if org_id and not authz.has_user_permission_for_group_or_org(
org_id, user, 'create_dataset'):
return {'success': False, 'msg': _('User %s not authorized to add dataset to this organization') % user}
return {'success': True}
def file_upload(context, data_dict=None):
user = context['user']
if authz.auth_is_anon_user(context):
return {'success': False, 'msg': _('User %s not authorized to create packages') % user}
return {'success': True}
def resource_create(context, data_dict):
model = context['model']
user = context.get('user')
package_id = data_dict.get('package_id')
if not package_id and data_dict.get('id'):
# This can happen when auth is deferred, eg from `resource_view_create`
resource = logic_auth.get_resource_object(context, data_dict)
package_id = resource.package_id
if not package_id:
raise logic.NotFound(
_('No dataset id provided, cannot check auth.')
)
# check authentication against package
pkg = model.Package.get(package_id)
if not pkg:
raise logic.NotFound(
_('No package found for this resource, cannot check auth.')
)
pkg_dict = {'id': pkg.id}
authorized = authz.is_authorized('package_update', context, pkg_dict).get('success')
if not authorized:
return {'success': False,
'msg': _('User %s not authorized to create resources on dataset %s') %
(str(user), package_id)}
else:
return {'success': True}
def resource_view_create(context, data_dict):
return authz.is_authorized('resource_create', context, {'id': data_dict['resource_id']})
def resource_create_default_resource_views(context, data_dict):
return authz.is_authorized('resource_create', context, {'id': data_dict['resource']['id']})
def package_create_default_resource_views(context, data_dict):
return authz.is_authorized('package_update', context,
data_dict['package'])
def package_relationship_create(context, data_dict):
user = context['user']
id = data_dict['subject']
id2 = data_dict['object']
# If we can update each package we can see the relationships
authorized1 = authz.is_authorized_boolean(
'package_update', context, {'id': id})
authorized2 = authz.is_authorized_boolean(
'package_update', context, {'id': id2})
if not authorized1 and authorized2:
return {'success': False, 'msg': _('User %s not authorized to edit these packages') % user}
else:
return {'success': True}
def group_create(context, data_dict=None):
user = context['user']
user = authz.get_user_id_for_username(user, allow_none=True)
if user and authz.check_config_permission('user_create_groups'):
return {'success': True}
return {'success': False,
'msg': _('User %s not authorized to create groups') % user}
def organization_create(context, data_dict=None):
user = context['user']
user = authz.get_user_id_for_username(user, allow_none=True)
if user and authz.check_config_permission('user_create_organizations'):
return {'success': True}
return {'success': False,
'msg': _('User %s not authorized to create organizations') % user}
def rating_create(context, data_dict):
# No authz check in the logic function
return {'success': True}
@logic.auth_allow_anonymous_access
def user_create(context, data_dict=None):
using_api = 'api_version' in context
create_user_via_api = authz.check_config_permission(
'create_user_via_api')
create_user_via_web = authz.check_config_permission(
'create_user_via_web')
if using_api and not create_user_via_api:
return {'success': False, 'msg': _('User {user} not authorized to '
'create users via the API').format(user=context.get('user'))}
if not using_api and not create_user_via_web:
return {'success': False, 'msg': _('Not authorized to '
'create users')}
return {'success': True}
def user_invite(context, data_dict):
data_dict['id'] = data_dict['group_id']
return group_member_create(context, data_dict)
def _check_group_auth(context, data_dict):
'''Has this user got update permission for all of the given groups?
If there is a package in the context then ignore that package's groups.
(owner_org is checked elsewhere.)
:returns: False if not allowed to update one (or more) of the given groups.
True otherwise. i.e. True is the default. A blank data_dict
mentions no groups, so it returns True.
'''
# FIXME This code is shared amoung other logic.auth files and should be
# somewhere better
if not data_dict:
return True
model = context['model']
user = context['user']
pkg = context.get("package")
api_version = context.get('api_version') or '1'
group_blobs = data_dict.get('groups', [])
groups = set()
for group_blob in group_blobs:
# group_blob might be a dict or a group_ref
if isinstance(group_blob, dict):
# use group id by default, but we can accept name as well
id = group_blob.get('id') or group_blob.get('name')
if not id:
continue
else:
id = group_blob
grp = model.Group.get(id)
if grp is None:
raise logic.NotFound(_('Group was not found.'))
groups.add(grp)
if pkg:
pkg_groups = pkg.get_groups()
groups = groups - set(pkg_groups)
for group in groups:
if not authz.has_user_permission_for_group_or_org(group.id, user, 'update'):
return False
return True
## Modifications for rest api
def package_create_rest(context, data_dict):
model = context['model']
user = context['user']
if not user:
return {'success': False, 'msg': _('Valid API key needed to create a package')}
return authz.is_authorized('package_create', context, data_dict)
def group_create_rest(context, data_dict):
model = context['model']
user = context['user']
if not user:
return {'success': False, 'msg': _('Valid API key needed to create a group')}
return authz.is_authorized('group_create', context, data_dict)
def vocabulary_create(context, data_dict):
# sysadmins only
return {'success': False}
def activity_create(context, data_dict):
# sysadmins only
return {'success': False}
def tag_create(context, data_dict):
# sysadmins only
return {'success': False}
def _group_or_org_member_create(context, data_dict):
user = context['user']
|
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]
def _group_or_org_member_create(context, data_dict):
user = context['user']
Cheatsheet (for next line):
- We are in _group_or_org_member_create(), which is a function that seems to be related to creating a group or organization member.
- user is a variable that holds the current user.
- The function is likely checking permissions or creating a new member.
- [Relevant lines: function header, variable user]
Based on the context, the next line of code might be related to checking permissions or creating a new member. However, without more information about the expected behavior, it's difficult to provide a specific next line of code.
However, considering the function name and the variable user, a possible next line could be:
- Checking if the user has permission to create a new member: `if authz.has_user_permission_for_group_or_org(data_dict['id'], user, 'create_member'):`
Please note that this is just a possible next line of code and might not be the actual correct implementation.
|
|
Please complete the code given below.
/**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.learner.meta;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.set.Partition;
import com.rapidminer.example.set.SplittedExampleSet;
import com.rapidminer.operator.Model;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.learner.PredictionModel;
/**
* This model of the hierarchical learner. This stores single models at each step to divide the
* examples into the single branches of the binary model tree.
*
* @author Tobias Malbrecht, Sebastian Land
*/
public class HierarchicalMultiClassModel extends PredictionModel implements MetaModel {
public static class Node implements Serializable {
private static final long serialVersionUID = 1L;
private final String className;
private int partitionId;
private final LinkedHashMap<String, Node> children = new LinkedHashMap<String, Node>();
private final List<Node> childrenList = new ArrayList<Node>();
private Node parent = null;
private Model model = null;
public Node(String className) {
this.className = className;
}
/**
* Returns the children in order of insertion
*/
public List<Node> getChildren() {
return childrenList;
}
/**
* Adds a child node.
*/
public void addChild(Node child) {
childrenList.add(child);
children.put(child.getClassName(), child);
child.setParent(this);
}
/**
* Sets the parent of this node. Only the root node may have a null parent.
*/
public void setParent(Node parent) {
this.parent = parent;
}
public boolean isRoot() {
return parent == null;
}
public void setPartitionId(int partition) {
this.partitionId = partition;
}
public int getPartitionId() {
return partitionId;
}
public Node getParent() {
return this.parent;
}
public String getClassName() {
return this.className;
}
public boolean isLeaf() {
return children.isEmpty();
}
public void setModel(Model model) {
this.model = model;
}
public Model getModel() {
return this.model;
}
public Node getChild(String label) {
return children.get(label);
}
}
private static final long serialVersionUID = -5792943818860734082L;
private final Node root;
public HierarchicalMultiClassModel(ExampleSet exampleSet, Node root) {
super(exampleSet, null, null);
this.root = root;
}
@Override
public ExampleSet performPrediction(ExampleSet exampleSet, Attribute predictedLabel) throws OperatorException {
ExampleSet applySet = (ExampleSet) exampleSet.clone();
// defining arrays for transferring information over recursive calls
double[] confidences = new double[applySet.size()];
int[] outcomes = new int[applySet.size()];
int[] depths = new int[applySet.size()];
Arrays.fill(outcomes, root.getPartitionId());
Arrays.fill(confidences, 1d);
// applying predictions recursively
performPredictionRecursivly(applySet, root, confidences, outcomes, depths, 0, root.getPartitionId() + 1);
// retrieving prediction attributes
Attribute labelAttribute = getTrainingHeader().getAttributes().getLabel();
int numberOfLabels = labelAttribute.getMapping().size();
Attribute[] confidenceAttributes = new Attribute[numberOfLabels];
for (int i = 0; i < numberOfLabels; i++) {
confidenceAttributes[i] = exampleSet.getAttributes().getConfidence(labelAttribute.getMapping().mapIndex(i));
}
// assigning final outcome and confidences
int i = 0;
for (Example example : exampleSet) {
// setting label according to outcome
example.setValue(predictedLabel, outcomes[i]);
// calculating confidences
double confidence = Math.pow(confidences[i], 1d / depths[i]);
double defaultConfidence = (1d - confidence) / numberOfLabels;
// setting confidences
for (int j = 0; j < numberOfLabels; j++) {
example.setValue(confidenceAttributes[j], defaultConfidence);
}
example.setValue(confidenceAttributes[outcomes[i]], confidence);
i++;
}
return exampleSet;
}
/**
* This method will apply all the nodes recursively. For each node it will be called when
* descending the learner hierarchy. The outcomes array stores the information to which node
* each example of the applySet has been assigned. Each node's model will be applied to the
* subset of a partitioned example set according to the node's partition id. After the
* classification has been performed, the examples will be assigned the partion id's of the
* child nodes, to whose class the examples where classified.
*
* It is very important that after each application the predicted label and the confidences are
* removed explicitly to avoid a memory leak in the memory table!
*
* Confidences are multiplied with the outcome every application.
*/
private void performPredictionRecursivly(ExampleSet applySet, Node node, double[] confidences, int[] outcomes,
int[] depths, int depth, int numberOfPartitions) throws OperatorException {
if (!node.isLeaf()) {
// creating partitioned example set
SplittedExampleSet splittedSet = new SplittedExampleSet(applySet, new Partition(outcomes, numberOfPartitions));
splittedSet.selectSingleSubset(node.getPartitionId());
// applying
ExampleSet currentResultSet = node.getModel().apply(splittedSet);
// assign each example a child node regarding to the classification outcome
int resultIndex = 0;
Attribute predictionAttribute = currentResultSet.getAttributes().getPredictedLabel();
for (Example example : currentResultSet) {
int parentIndex = splittedSet.getActualParentIndex(resultIndex);
// extracting data
|
[
"\t\t\t\tString label = example.getValueAsString(predictionAttribute);"
] | 784
|
lcc
|
java
| null |
d2fab0055348069f0d8e88dc8cdb2f46840753245d44d77d
| 52
|
Your task is code completion.
/**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.learner.meta;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.set.Partition;
import com.rapidminer.example.set.SplittedExampleSet;
import com.rapidminer.operator.Model;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.learner.PredictionModel;
/**
* This model of the hierarchical learner. This stores single models at each step to divide the
* examples into the single branches of the binary model tree.
*
* @author Tobias Malbrecht, Sebastian Land
*/
public class HierarchicalMultiClassModel extends PredictionModel implements MetaModel {
public static class Node implements Serializable {
private static final long serialVersionUID = 1L;
private final String className;
private int partitionId;
private final LinkedHashMap<String, Node> children = new LinkedHashMap<String, Node>();
private final List<Node> childrenList = new ArrayList<Node>();
private Node parent = null;
private Model model = null;
public Node(String className) {
this.className = className;
}
/**
* Returns the children in order of insertion
*/
public List<Node> getChildren() {
return childrenList;
}
/**
* Adds a child node.
*/
public void addChild(Node child) {
childrenList.add(child);
children.put(child.getClassName(), child);
child.setParent(this);
}
/**
* Sets the parent of this node. Only the root node may have a null parent.
*/
public void setParent(Node parent) {
this.parent = parent;
}
public boolean isRoot() {
return parent == null;
}
public void setPartitionId(int partition) {
this.partitionId = partition;
}
public int getPartitionId() {
return partitionId;
}
public Node getParent() {
return this.parent;
}
public String getClassName() {
return this.className;
}
public boolean isLeaf() {
return children.isEmpty();
}
public void setModel(Model model) {
this.model = model;
}
public Model getModel() {
return this.model;
}
public Node getChild(String label) {
return children.get(label);
}
}
private static final long serialVersionUID = -5792943818860734082L;
private final Node root;
public HierarchicalMultiClassModel(ExampleSet exampleSet, Node root) {
super(exampleSet, null, null);
this.root = root;
}
@Override
public ExampleSet performPrediction(ExampleSet exampleSet, Attribute predictedLabel) throws OperatorException {
ExampleSet applySet = (ExampleSet) exampleSet.clone();
// defining arrays for transferring information over recursive calls
double[] confidences = new double[applySet.size()];
int[] outcomes = new int[applySet.size()];
int[] depths = new int[applySet.size()];
Arrays.fill(outcomes, root.getPartitionId());
Arrays.fill(confidences, 1d);
// applying predictions recursively
performPredictionRecursivly(applySet, root, confidences, outcomes, depths, 0, root.getPartitionId() + 1);
// retrieving prediction attributes
Attribute labelAttribute = getTrainingHeader().getAttributes().getLabel();
int numberOfLabels = labelAttribute.getMapping().size();
Attribute[] confidenceAttributes = new Attribute[numberOfLabels];
for (int i = 0; i < numberOfLabels; i++) {
confidenceAttributes[i] = exampleSet.getAttributes().getConfidence(labelAttribute.getMapping().mapIndex(i));
}
// assigning final outcome and confidences
int i = 0;
for (Example example : exampleSet) {
// setting label according to outcome
example.setValue(predictedLabel, outcomes[i]);
// calculating confidences
double confidence = Math.pow(confidences[i], 1d / depths[i]);
double defaultConfidence = (1d - confidence) / numberOfLabels;
// setting confidences
for (int j = 0; j < numberOfLabels; j++) {
example.setValue(confidenceAttributes[j], defaultConfidence);
}
example.setValue(confidenceAttributes[outcomes[i]], confidence);
i++;
}
return exampleSet;
}
/**
* This method will apply all the nodes recursively. For each node it will be called when
* descending the learner hierarchy. The outcomes array stores the information to which node
* each example of the applySet has been assigned. Each node's model will be applied to the
* subset of a partitioned example set according to the node's partition id. After the
* classification has been performed, the examples will be assigned the partion id's of the
* child nodes, to whose class the examples where classified.
*
* It is very important that after each application the predicted label and the confidences are
* removed explicitly to avoid a memory leak in the memory table!
*
* Confidences are multiplied with the outcome every application.
*/
private void performPredictionRecursivly(ExampleSet applySet, Node node, double[] confidences, int[] outcomes,
int[] depths, int depth, int numberOfPartitions) throws OperatorException {
if (!node.isLeaf()) {
// creating partitioned example set
SplittedExampleSet splittedSet = new SplittedExampleSet(applySet, new Partition(outcomes, numberOfPartitions));
splittedSet.selectSingleSubset(node.getPartitionId());
// applying
ExampleSet currentResultSet = node.getModel().apply(splittedSet);
// assign each example a child node regarding to the classification outcome
int resultIndex = 0;
Attribute predictionAttribute = currentResultSet.getAttributes().getPredictedLabel();
for (Example example : currentResultSet) {
int parentIndex = splittedSet.getActualParentIndex(resultIndex);
// extracting data
|
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]
private void performPredictionRecursivly(ExampleSet applySet, Node node, double[] confidences, int[] outcomes,
int[] depths, int depth, int numberOfPartitions) throws OperatorException {
if (!node.isLeaf()) {
// creating partitioned example set
SplittedExampleSet splittedSet = new SplittedExampleSet(applySet, new Partition(outcomes, numberOfPartitions));
splittedSet.selectSingleSubset(node.getPartitionId());
// applying
ExampleSet currentResultSet = node.getModel().apply(splittedSet);
// assign each example a child node regarding to the classification outcome
int resultIndex = 0;
Attribute predictionAttribute = currentResultSet.getAttributes().getPredictedLabel();
for (Example example : currentResultSet) {
int parentIndex = splittedSet.getActualParentIndex(resultIndex);
// extracting data
// ...
Cheatsheet (for next line):
- We are in a for loop iterating over the examples in currentResultSet.
- The goal is to assign each example a child node based on the classification outcome.
- The classification outcome is stored in the predictedLabel attribute of the example.
- The parentIndex is the index of the parent node in the outcomes array.
- The node's children are stored in a LinkedHashMap called children.
- The node's children are also stored in a List called childrenList.
- The node's class name is stored in the className field.
- The node's partition ID is stored in the partitionId field.
- The node's parent is stored in the parent field.
- The node's model is stored in the model field.
- The node's child nodes are accessed using the getChild() method.
- The node's children are iterated over using the getChildren() method.
- The node's class name is accessed using the getClassName() method.
- The node's partition ID is accessed using the getPartitionId() method.
- The node's parent is accessed using the getParent() method.
- The node's model is accessed using the getModel() method.
Next line will likely be:
```java
Node child = node.getChild(predictionAttribute.mapIndex(parentIndex));
```
|
|
Please complete the code given below.
// ---------------------------------
// <copyright file="AbstractTrados2007LanguageDirection.cs" company="SDL International">
// Copyright 2011 All Right Reserved
// </copyright>
// <author>Kostiantyn Lukianets</author>
// <email>klukianets@sdl.com</email>
// <date>2011-11-08</date>
// ---------------------------------
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Sdl.Community.Trados2007
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Sdl.LanguagePlatform.Core;
using Sdl.LanguagePlatform.TranslationMemory;
using Sdl.LanguagePlatform.TranslationMemoryApi;
using Trados.Interop.TMAccess;
using Action = Sdl.LanguagePlatform.TranslationMemory.Action;
using SearchResult = Sdl.LanguagePlatform.TranslationMemory.SearchResult;
using Sdl.LanguagePlatform.Lingua.TermRecognition;
/// <summary>
/// Abstract base class for file- and server-based Trados 2007 language directions.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1623:PropertySummaryDocumentationMustMatchAccessors",
Justification = "By original SDL API design.")]
public abstract class AbstractTrados2007LanguageDirection : ITranslationProviderLanguageDirection
{
#region Fields
protected readonly object locker = new object();
/// <summary>
/// Stores Trados 2007 Translation Provider that owns this particular Language Direction.
/// </summary>
private readonly AbstractTrados2007TranslationProvider translationProvider;
/// <summary>
/// Stores languages direction.
/// </summary>
private readonly LanguagePair languageDirection;
#endregion // Fields
/// <summary>
/// Initializes a new instance of the <see cref="AbstractTrados2007LanguageDirection"/> class.
/// </summary>
/// <param name="translationProvider">The Trados 2007 translation provider.</param>
protected AbstractTrados2007LanguageDirection(AbstractTrados2007TranslationProvider translationProvider)
{
if (translationProvider == null)
{
throw new ArgumentNullException("translationProvider");
}
// Trados 2007 TP supports only one language direction, regardless file- or -server based
this.translationProvider = translationProvider;
this.languageDirection = translationProvider.LanguageDirection;
}
#region Properties
/// <summary>
/// The translation provider to which this language direction belongs.
/// </summary>
ITranslationProvider ITranslationProviderLanguageDirection.TranslationProvider
{
get
{
return this.translationProvider;
}
}
/// <summary>
/// Gets the source language.
/// </summary>
public CultureInfo SourceLanguage
{
get
{
return this.languageDirection.SourceCulture;
}
}
/// <summary>
/// Gets the target language.
/// </summary>
public CultureInfo TargetLanguage
{
get
{
return this.languageDirection.TargetCulture;
}
}
/// <summary>
/// Gets a flag which indicates whether the translation provider supports
/// searches in the reversed language direction.
/// </summary>
public bool CanReverseLanguageDirection
{
get
{
return false;
}
}
/// <summary>
/// The translation provider to which this language direction belongs.
/// </summary>
protected AbstractTrados2007TranslationProvider TranslationProvider
{
get
{
return this.translationProvider;
}
}
#endregion // Properties
#region Methods
/// <summary>
/// Adds a translation unit to the database. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </summary>
/// <param name="translationUnit">The translation unit.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> which represents the status of the operation (succeeded, ignored, etc).
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult AddTranslationUnit(TranslationUnit translationUnit, ImportSettings settings)
{
return new ImportResult { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation };
}
/// <summary>
/// Adds an array of translation units to the database. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddTranslationUnits(TranslationUnit[] translationUnits, ImportSettings settings)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Adds an array of translation units to the database. If hash codes of the previous translations are provided,
/// a found translation will be overwritten. If none is found, or the hash is 0 or the collection is <c>null</c>,
/// the operation behaves identical to <see cref="M:Sdl.LanguagePlatform.TranslationMemoryApi.ITranslationProviderLanguageDirection.AddTranslationUnits(Sdl.LanguagePlatform.TranslationMemory.TranslationUnit[],Sdl.LanguagePlatform.TranslationMemory.ImportSettings)"/>.
/// <para>
/// If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </para>
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="previousTranslationHashes">If provided, a corresponding array of a the hash code of a previous translation.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddOrUpdateTranslationUnits(TranslationUnit[] translationUnits, int[] previousTranslationHashes, ImportSettings settings)
{
int count = translationUnits.Length;
var result = new ImportResult[count];
var err = new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation };
for (int i = 0; i < count; i++)
{
result[i] = err;
}
return result;
}
/// <summary>
/// Adds an array of translation units to the database, but will only add those
/// for which the corresponding mask field is <c>true</c>. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable ImportResult but should not throw an exception.
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="settings">The settings used for this operation.</param><param name="mask">A boolean array with the same cardinality as the TU array, specifying which TUs to add.</param>
/// <returns>
/// An array of ImportResult objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddTranslationUnitsMasked(TranslationUnit[] translationUnits, ImportSettings settings, bool[] mask)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Adds an array of translation units to the database, but will only add those
/// for which the corresponding mask field is true. If the previous translation hashes are provided,
/// existing translations will be updated if the target segment hash changed.
/// <para>
/// If the provider doesn't support adding/updating, the
/// implementation should return a reasonable ImportResult but should not throw an exception.
/// </para>
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="previousTranslationHashes">Corresponding hash codes of a previous translation (0 if unknown). The parameter may be null.</param><param name="settings">The settings used for this operation.</param><param name="mask">A boolean array with the same cardinality as the TU array, specifying which TUs to add.</param>
/// <returns>
/// An array of ImportResult objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddOrUpdateTranslationUnitsMasked(TranslationUnit[] translationUnits, int[] previousTranslationHashes, ImportSettings settings, bool[] mask)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Performs a search for an array of segments.
/// </summary>
/// <param name="settings">The settings that define the search parameters.</param><param name="segments">The array containing the segments to search for.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.SearchResults"/> objects, which mirrors the segments array. It has the exact same size and contains the
/// search results for each segment with the same index within the segments array.
/// </returns>
public virtual SearchResults[] SearchSegments(SearchSettings settings, Segment[] segments)
{
|
[
" var searchResultsArray = new SearchResults[segments.Length];"
] | 1,172
|
lcc
|
csharp
| null |
39981401e38829b7087717c9452de413a3ec15cf21ca091f
| 53
|
Your task is code completion.
// ---------------------------------
// <copyright file="AbstractTrados2007LanguageDirection.cs" company="SDL International">
// Copyright 2011 All Right Reserved
// </copyright>
// <author>Kostiantyn Lukianets</author>
// <email>klukianets@sdl.com</email>
// <date>2011-11-08</date>
// ---------------------------------
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Sdl.Community.Trados2007
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Sdl.LanguagePlatform.Core;
using Sdl.LanguagePlatform.TranslationMemory;
using Sdl.LanguagePlatform.TranslationMemoryApi;
using Trados.Interop.TMAccess;
using Action = Sdl.LanguagePlatform.TranslationMemory.Action;
using SearchResult = Sdl.LanguagePlatform.TranslationMemory.SearchResult;
using Sdl.LanguagePlatform.Lingua.TermRecognition;
/// <summary>
/// Abstract base class for file- and server-based Trados 2007 language directions.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1623:PropertySummaryDocumentationMustMatchAccessors",
Justification = "By original SDL API design.")]
public abstract class AbstractTrados2007LanguageDirection : ITranslationProviderLanguageDirection
{
#region Fields
protected readonly object locker = new object();
/// <summary>
/// Stores Trados 2007 Translation Provider that owns this particular Language Direction.
/// </summary>
private readonly AbstractTrados2007TranslationProvider translationProvider;
/// <summary>
/// Stores languages direction.
/// </summary>
private readonly LanguagePair languageDirection;
#endregion // Fields
/// <summary>
/// Initializes a new instance of the <see cref="AbstractTrados2007LanguageDirection"/> class.
/// </summary>
/// <param name="translationProvider">The Trados 2007 translation provider.</param>
protected AbstractTrados2007LanguageDirection(AbstractTrados2007TranslationProvider translationProvider)
{
if (translationProvider == null)
{
throw new ArgumentNullException("translationProvider");
}
// Trados 2007 TP supports only one language direction, regardless file- or -server based
this.translationProvider = translationProvider;
this.languageDirection = translationProvider.LanguageDirection;
}
#region Properties
/// <summary>
/// The translation provider to which this language direction belongs.
/// </summary>
ITranslationProvider ITranslationProviderLanguageDirection.TranslationProvider
{
get
{
return this.translationProvider;
}
}
/// <summary>
/// Gets the source language.
/// </summary>
public CultureInfo SourceLanguage
{
get
{
return this.languageDirection.SourceCulture;
}
}
/// <summary>
/// Gets the target language.
/// </summary>
public CultureInfo TargetLanguage
{
get
{
return this.languageDirection.TargetCulture;
}
}
/// <summary>
/// Gets a flag which indicates whether the translation provider supports
/// searches in the reversed language direction.
/// </summary>
public bool CanReverseLanguageDirection
{
get
{
return false;
}
}
/// <summary>
/// The translation provider to which this language direction belongs.
/// </summary>
protected AbstractTrados2007TranslationProvider TranslationProvider
{
get
{
return this.translationProvider;
}
}
#endregion // Properties
#region Methods
/// <summary>
/// Adds a translation unit to the database. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </summary>
/// <param name="translationUnit">The translation unit.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> which represents the status of the operation (succeeded, ignored, etc).
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult AddTranslationUnit(TranslationUnit translationUnit, ImportSettings settings)
{
return new ImportResult { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation };
}
/// <summary>
/// Adds an array of translation units to the database. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddTranslationUnits(TranslationUnit[] translationUnits, ImportSettings settings)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Adds an array of translation units to the database. If hash codes of the previous translations are provided,
/// a found translation will be overwritten. If none is found, or the hash is 0 or the collection is <c>null</c>,
/// the operation behaves identical to <see cref="M:Sdl.LanguagePlatform.TranslationMemoryApi.ITranslationProviderLanguageDirection.AddTranslationUnits(Sdl.LanguagePlatform.TranslationMemory.TranslationUnit[],Sdl.LanguagePlatform.TranslationMemory.ImportSettings)"/>.
/// <para>
/// If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </para>
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="previousTranslationHashes">If provided, a corresponding array of a the hash code of a previous translation.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddOrUpdateTranslationUnits(TranslationUnit[] translationUnits, int[] previousTranslationHashes, ImportSettings settings)
{
int count = translationUnits.Length;
var result = new ImportResult[count];
var err = new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation };
for (int i = 0; i < count; i++)
{
result[i] = err;
}
return result;
}
/// <summary>
/// Adds an array of translation units to the database, but will only add those
/// for which the corresponding mask field is <c>true</c>. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable ImportResult but should not throw an exception.
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="settings">The settings used for this operation.</param><param name="mask">A boolean array with the same cardinality as the TU array, specifying which TUs to add.</param>
/// <returns>
/// An array of ImportResult objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddTranslationUnitsMasked(TranslationUnit[] translationUnits, ImportSettings settings, bool[] mask)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Adds an array of translation units to the database, but will only add those
/// for which the corresponding mask field is true. If the previous translation hashes are provided,
/// existing translations will be updated if the target segment hash changed.
/// <para>
/// If the provider doesn't support adding/updating, the
/// implementation should return a reasonable ImportResult but should not throw an exception.
/// </para>
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="previousTranslationHashes">Corresponding hash codes of a previous translation (0 if unknown). The parameter may be null.</param><param name="settings">The settings used for this operation.</param><param name="mask">A boolean array with the same cardinality as the TU array, specifying which TUs to add.</param>
/// <returns>
/// An array of ImportResult objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddOrUpdateTranslationUnitsMasked(TranslationUnit[] translationUnits, int[] previousTranslationHashes, ImportSettings settings, bool[] mask)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Performs a search for an array of segments.
/// </summary>
/// <param name="settings">The settings that define the search parameters.</param><param name="segments">The array containing the segments to search for.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.SearchResults"/> objects, which mirrors the segments array. It has the exact same size and contains the
/// search results for each segment with the same index within the segments array.
/// </returns>
public virtual SearchResults[] SearchSegments(SearchSettings settings, Segment[] segments)
{
|
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]
public abstract class AbstractTrados2007LanguageDirection : ITranslationProviderLanguageDirection
{
#region Fields
protected readonly object locker = new object();
/// <summary>
/// Stores Trados 2007 Translation Provider that owns this particular Language Direction.
/// </summary>
private readonly AbstractTrados2007TranslationProvider translationProvider;
/// <summary>
/// Stores languages direction.
/// </summary>
private readonly LanguagePair languageDirection;
#endregion // Fields
/// <summary>
/// Initializes a new instance of the <see cref="AbstractTrados2007LanguageDirection"/> class.
/// </summary>
/// <param name="translationProvider">The Trados 2007 translation provider.</param>
protected AbstractTrados2007LanguageDirection(AbstractTrados2007TranslationProvider translationProvider)
{
if (translationProvider == null)
{
throw new ArgumentNullException("translationProvider");
}
// Trados 2007 TP supports only one language direction, regardless file- or -server based
this.translationProvider = translationProvider;
this.languageDirection = translationProvider.LanguageDirection;
}
#region Properties
/// <summary>
/// The translation provider to which this language direction belongs.
/// </summary>
ITranslationProvider ITranslationProviderLanguageDirection.TranslationProvider
{
get
{
return this.translationProvider;
}
}
/// <summary>
/// Gets the source language.
/// </summary>
public CultureInfo SourceLanguage
{
get
{
return this.languageDirection.SourceCulture;
}
}
/// <summary>
/// Gets the target language.
/// </summary>
public CultureInfo TargetLanguage
{
get
{
return this.languageDirection.TargetCulture;
}
}
/// <summary>
/// Gets a flag which indicates whether the translation provider supports
/// searches in the reversed language direction.
/// </summary>
public bool CanReverseLanguageDirection
{
get
{
return false;
}
}
/// <summary>
/// The translation provider to which this language direction belongs.
/// </summary>
protected AbstractTrados2007TranslationProvider TranslationProvider
{
get
{
return this.translationProvider;
}
}
#endregion // Properties
#region Methods
/// <summary>
/// Adds a translation unit to the database. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </summary>
/// <param name="translationUnit">The translation unit.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> which represents the status of the operation (succeeded, ignored, etc).
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult AddTranslationUnit(TranslationUnit translationUnit, ImportSettings settings)
{
return new ImportResult { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation };
}
/// <summary>
/// Adds an array of translation units to the database. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddTranslationUnits(TranslationUnit[] translationUnits, ImportSettings settings)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Adds an array of translation units to the database. If hash codes of the previous translations are provided,
/// a found translation will be overwritten. If none is found, or the hash is 0 or the collection is <c>null</c>,
/// the operation behaves identical to <see cref="M:Sdl.LanguagePlatform.TranslationMemoryApi.ITranslationProviderLanguageDirection.AddTranslationUnits(Sdl.LanguagePlatform.TranslationMemory.TranslationUnit[],Sdl.LanguagePlatform.TranslationMemory.ImportSettings)"/>.
/// <para>
/// If the provider doesn't support adding/updating, the
/// implementation should return a reasonable <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> but should not throw an exception.
/// </para>
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="previousTranslationHashes">If provided, a corresponding array of a the hash code of a previous translation.</param><param name="settings">The settings used for this operation.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.ImportResult"/> objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddOrUpdateTranslationUnits(TranslationUnit[] translationUnits, int[] previousTranslationHashes, ImportSettings settings)
{
int count = translationUnits.Length;
var result = new ImportResult[count];
var err = new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation };
for (int i = 0; i < count; i++)
{
result[i] = err;
}
return result;
}
/// <summary>
/// Adds an array of translation units to the database, but will only add those
/// for which the corresponding mask field is <c>true</c>. If the provider doesn't support adding/updating, the
/// implementation should return a reasonable ImportResult but should not throw an exception.
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="settings">The settings used for this operation.</param><param name="mask">A boolean array with the same cardinality as the TU array, specifying which TUs to add.</param>
/// <returns>
/// An array of ImportResult objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddTranslationUnitsMasked(TranslationUnit[] translationUnits, ImportSettings settings, bool[] mask)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Adds an array of translation units to the database, but will only add those
/// for which the corresponding mask field is true. If the previous translation hashes are provided,
/// existing translations will be updated if the target segment hash changed.
/// <para>
/// If the provider doesn't support adding/updating, the
/// implementation should return a reasonable ImportResult but should not throw an exception.
/// </para>
/// </summary>
/// <param name="translationUnits">An arrays of translation units to be added.</param><param name="previousTranslationHashes">Corresponding hash codes of a previous translation (0 if unknown). The parameter may be null.</param><param name="settings">The settings used for this operation.</param><param name="mask">A boolean array with the same cardinality as the TU array, specifying which TUs to add.</param>
/// <returns>
/// An array of ImportResult objects, which mirrors the translation unit array. It has the exact same size and contains the
/// status of each add operation for each particular translation unit with the same index within the array.
/// </returns>
[Obsolete(@"Trados 2007 Translation Provider does not support adding\editing.")]
public virtual ImportResult[] AddOrUpdateTranslationUnitsMasked(TranslationUnit[] translationUnits, int[] previousTranslationHashes, ImportSettings settings, bool[] mask)
{
return new[] { new ImportResult() { Action = Action.Add, ErrorCode = ErrorCode.InvalidOperation } };
}
/// <summary>
/// Performs a search for an array of segments.
/// </summary>
/// <param name="settings">The settings that define the search parameters.</param><param name="segments">The array containing the segments to search for.</param>
/// <returns>
/// An array of <see cref="T:Sdl.LanguagePlatform.TranslationMemory.SearchResults"/> objects, which mirrors the segments array. It has the exact same size
|
|
Please complete the code given below.
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.lib.regexp;
import java.util.*;
import com.caucho.util.*;
import com.caucho.quercus.env.StringValue;
class RegexpNode {
private static final L10N L = new L10N(RegexpNode.class);
static final int RC_END = 0;
static final int RC_NULL = 1;
static final int RC_STRING = 2;
static final int RC_SET = 3;
static final int RC_NSET = 4;
static final int RC_BEG_GROUP = 5;
static final int RC_END_GROUP = 6;
static final int RC_GROUP_REF = 7;
static final int RC_LOOP = 8;
static final int RC_LOOP_INIT = 9;
static final int RC_LOOP_SHORT = 10;
static final int RC_LOOP_UNIQUE = 11;
static final int RC_LOOP_SHORT_UNIQUE = 12;
static final int RC_LOOP_LONG = 13;
static final int RC_OR = 64;
static final int RC_OR_UNIQUE = 65;
static final int RC_POS_LOOKAHEAD = 66;
static final int RC_NEG_LOOKAHEAD = 67;
static final int RC_POS_LOOKBEHIND = 68;
static final int RC_NEG_LOOKBEHIND = 69;
static final int RC_LOOKBEHIND_OR = 70;
static final int RC_WORD = 73;
static final int RC_NWORD = 74;
static final int RC_BLINE = 75;
static final int RC_ELINE = 76;
static final int RC_BSTRING = 77;
static final int RC_ESTRING = 78;
static final int RC_ENSTRING = 79;
static final int RC_GSTRING = 80;
// conditionals
static final int RC_COND = 81;
// ignore case
static final int RC_STRING_I = 128;
static final int RC_SET_I = 129;
static final int RC_NSET_I = 130;
static final int RC_GROUP_REF_I = 131;
static final int RC_LEXEME = 256;
// unicode properties
static final int RC_UNICODE = 512;
static final int RC_NUNICODE = 513;
// unicode properties sets
static final int RC_C = 1024;
static final int RC_L = 1025;
static final int RC_M = 1026;
static final int RC_N = 1027;
static final int RC_P = 1028;
static final int RC_S = 1029;
static final int RC_Z = 1030;
// negated unicode properties sets
static final int RC_NC = 1031;
static final int RC_NL = 1032;
static final int RC_NM = 1033;
static final int RC_NN = 1034;
static final int RC_NP = 1035;
// POSIX character classes
static final int RC_CHAR_CLASS = 2048;
static final int RC_ALNUM = 1;
static final int RC_ALPHA = 2;
static final int RC_BLANK = 3;
static final int RC_CNTRL = 4;
static final int RC_DIGIT = 5;
static final int RC_GRAPH = 6;
static final int RC_LOWER = 7;
static final int RC_PRINT = 8;
static final int RC_PUNCT = 9;
static final int RC_SPACE = 10;
static final int RC_UPPER = 11;
static final int RC_XDIGIT = 12;
// #2526, possible JIT/OS issue with Integer.MAX_VALUE
private static final int INTEGER_MAX = Integer.MAX_VALUE - 1;
public static final int FAIL = -1;
public static final int SUCCESS = 0;
static final RegexpNode N_END = new End();
static final RegexpNode ANY_CHAR;
/**
* Creates a node with a code
*/
protected RegexpNode() {
}
//
// parsing constructors
//
RegexpNode concat(RegexpNode next) {
return new Concat(this, next);
}
/**
* '?' operator
*/
RegexpNode createOptional(Regcomp parser) {
return createLoop(parser, 0, 1);
}
/**
* '*' operator
*/
RegexpNode createStar(Regcomp parser) {
return createLoop(parser, 0, INTEGER_MAX);
}
/**
* '+' operator
*/
RegexpNode createPlus(Regcomp parser) {
return createLoop(parser, 1, INTEGER_MAX);
}
/**
* Any loop
*/
RegexpNode createLoop(Regcomp parser, int min, int max) {
return new LoopHead(parser, this, min, max);
}
/**
* Any loop
*/
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
return new LoopHeadUngreedy(parser, this, min, max);
}
/**
* Possessive loop
*/
RegexpNode createPossessiveLoop(int min, int max) {
return new PossessiveLoop(getHead(), min, max);
}
/**
* Create an or expression
*/
RegexpNode createOr(RegexpNode node) {
return Or.create(this, node);
}
/**
* Create a not expression
*/
RegexpNode createNot() {
return Not.create(this);
}
//
// optimization functions
//
int minLength() {
return 0;
}
String prefix() {
return "";
}
int firstChar() {
return -1;
}
boolean isNullable() {
return false;
}
boolean[] firstSet(boolean[] firstSet) {
return null;
}
boolean isAnchorBegin() {
return false;
}
RegexpNode getTail() {
return this;
}
RegexpNode getHead() {
return this;
}
//
// matching
//
int match(StringValue string, int length, int offset, RegexpState state) {
throw new UnsupportedOperationException(getClass().getName());
}
@Override
public String toString() {
Map<RegexpNode, Integer> map = new IdentityHashMap<RegexpNode, Integer>();
StringBuilder sb = new StringBuilder();
toString(sb, map);
return sb.toString();
}
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName()).append("[]");
}
protected boolean toStringAdd(StringBuilder sb, Map<RegexpNode, Integer> map) {
Integer v = map.get(this);
if (v != null) {
sb.append("#").append(v);
return true;
}
map.put(this, map.size());
return false;
}
protected String toStringName() {
String name = getClass().getName();
int p = name.lastIndexOf('$');
if (p < 0) {
p = name.lastIndexOf('.');
}
return name.substring(p + 1);
}
/**
* A node with exactly one character matches.
*/
static class AbstractCharNode extends RegexpNode {
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
return new CharLoop(this, min, max);
}
@Override
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
return new CharUngreedyLoop(this, min, max);
}
@Override
int minLength() {
return 1;
}
}
static class CharNode extends AbstractCharNode {
private char _ch;
CharNode(char ch) {
_ch = ch;
}
@Override
int firstChar() {
return _ch;
}
@Override
boolean[] firstSet(boolean[] firstSet) {
if (firstSet != null && _ch < firstSet.length) {
firstSet[_ch] = true;
return firstSet;
} else {
return null;
}
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset < length && string.charAt(offset) == _ch) {
return offset + 1;
} else {
return -1;
}
}
}
static final AnchorBegin ANCHOR_BEGIN = new AnchorBegin();
static final AnchorBeginOrNewline ANCHOR_BEGIN_OR_NEWLINE = new AnchorBeginOrNewline();
static final AnchorBeginRelative ANCHOR_BEGIN_RELATIVE = new AnchorBeginRelative();
static final AnchorEnd ANCHOR_END = new AnchorEnd();
static final AnchorEndOnly ANCHOR_END_ONLY = new AnchorEndOnly();
static final AnchorEndOrNewline ANCHOR_END_OR_NEWLINE = new AnchorEndOrNewline();
static class AnchorBegin extends NullableNode {
@Override
boolean isAnchorBegin() {
return true;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset == 0) {
return offset;
} else {
return -1;
}
}
}
private static class AnchorBeginOrNewline extends NullableNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset == 0 || string.charAt(offset - 1) == '\n') {
return offset;
} else {
return -1;
}
}
}
static class AnchorBeginRelative extends NullableNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset == state._start) {
return offset;
} else {
return -1;
}
}
}
private static class AnchorEnd extends NullableNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset == strlen
|| offset + 1 == strlen && string.charAt(offset) == '\n') {
return offset;
} else {
return -1;
}
}
}
private static class AnchorEndOnly extends NullableNode {
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset == length) {
return offset;
} else {
return -1;
}
}
}
private static class AnchorEndOrNewline extends NullableNode {
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset == length || string.charAt(offset) == '\n') {
return offset;
} else {
return -1;
}
}
}
static final RegexpNode DIGIT = RegexpSet.DIGIT.createNode();
static final RegexpNode NOT_DIGIT = RegexpSet.DIGIT.createNotNode();
static final RegexpNode DOT = RegexpSet.DOT.createNotNode();
static final RegexpNode NOT_DOT = RegexpSet.DOT.createNode();
static final RegexpNode SPACE = RegexpSet.SPACE.createNode();
static final RegexpNode NOT_SPACE = RegexpSet.SPACE.createNotNode();
static final RegexpNode S_WORD = RegexpSet.WORD.createNode();
static final RegexpNode NOT_S_WORD = RegexpSet.WORD.createNotNode();
static class AsciiSet extends AbstractCharNode {
private final boolean[] _set;
AsciiSet() {
_set = new boolean[128];
}
AsciiSet(boolean[] set) {
_set = set;
}
@Override
boolean[] firstSet(boolean[] firstSet) {
if (firstSet == null) {
return null;
}
for (int i = 0; i < _set.length; i++) {
if (_set[i]) {
firstSet[i] = true;
}
}
return firstSet;
}
void setChar(char ch) {
_set[ch] = true;
}
void clearChar(char ch) {
_set[ch] = false;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (length <= offset) {
return -1;
}
char ch = string.charAt(offset);
if (ch < 128 && _set[ch]) {
return offset + 1;
} else {
return -1;
}
}
}
static class AsciiNotSet extends AbstractCharNode {
private final boolean[] _set;
AsciiNotSet() {
_set = new boolean[128];
}
AsciiNotSet(boolean[] set) {
_set = set;
}
void setChar(char ch) {
_set[ch] = true;
}
void clearChar(char ch) {
_set[ch] = false;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (length <= offset) {
return -1;
}
char ch = string.charAt(offset);
if (ch < 128 && _set[ch]) {
return -1;
} else {
return offset + 1;
}
}
}
static class CharLoop extends RegexpNode {
private final RegexpNode _node;
private RegexpNode _next = N_END;
private int _min;
private int _max;
CharLoop(RegexpNode node, int min, int max) {
_node = node.getHead();
_min = min;
_max = max;
if (_min < 0) {
throw new IllegalStateException();
}
}
@Override
RegexpNode concat(RegexpNode next) {
if (next == null) {
throw new NullPointerException();
}
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next.getHead();
}
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
@Override
int minLength() {
return _min;
}
@Override
boolean[] firstSet(boolean[] firstSet) {
firstSet = _node.firstSet(firstSet);
if (_min > 0 && !_node.isNullable()) {
return firstSet;
}
firstSet = _next.firstSet(firstSet);
return firstSet;
}
//
// match functions
//
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
RegexpNode next = _next;
RegexpNode node = _node;
int min = _min;
int max = _max;
int i;
int tail;
for (i = 0; i < min; i++) {
tail = node.match(string, length, offset + i, state);
if (tail < 0) {
return tail;
}
}
for (; i < max; i++) {
if (node.match(string, length, offset + i, state) < 0) {
break;
}
}
for (; min <= i; i--) {
tail = next.match(string, length, offset + i, state);
if (tail >= 0) {
return tail;
}
}
return -1;
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[").append(_min).append(", ").append(_max).append(", ");
_node.toString(sb, map);
sb.append(", ");
_next.toString(sb, map);
sb.append("]");
}
}
static class CharUngreedyLoop extends RegexpNode {
private final RegexpNode _node;
private RegexpNode _next = N_END;
private int _min;
private int _max;
CharUngreedyLoop(RegexpNode node, int min, int max) {
_node = node.getHead();
_min = min;
_max = max;
if (_min < 0) {
throw new IllegalStateException();
}
}
@Override
RegexpNode concat(RegexpNode next) {
if (next == null) {
throw new NullPointerException();
}
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next.getHead();
}
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
@Override
int minLength() {
return _min;
}
@Override
boolean[] firstSet(boolean[] firstSet) {
firstSet = _node.firstSet(firstSet);
if (_min > 0 && !_node.isNullable()) {
return firstSet;
}
firstSet = _next.firstSet(firstSet);
return firstSet;
}
//
// match functions
//
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
RegexpNode next = _next;
RegexpNode node = _node;
int min = _min;
int max = _max;
int i;
int tail;
for (i = 0; i < min; i++) {
tail = node.match(string, length, offset + i, state);
if (tail < 0) {
return tail;
}
}
for (; i <= max; i++) {
tail = next.match(string, length, offset + i, state);
if (tail >= 0) {
return tail;
}
if (node.match(string, length, offset + i, state) < 0) {
return -1;
}
}
return -1;
}
@Override
public String toString() {
return "CharUngreedyLoop[" + _min + ", "
+ _max + ", " + _node + ", " + _next + "]";
}
}
final static class Concat extends RegexpNode {
private final RegexpNode _head;
private RegexpNode _next;
Concat(RegexpNode head, RegexpNode next) {
if (head == null || next == null) {
throw new NullPointerException();
}
_head = head;
_next = next;
}
@Override
RegexpNode concat(RegexpNode next) {
_next = _next.concat(next);
return this;
}
//
// optim functions
//
@Override
int minLength() {
return _head.minLength() + _next.minLength();
}
@Override
int firstChar() {
return _head.firstChar();
}
@Override
boolean[] firstSet(boolean[] firstSet) {
firstSet = _head.firstSet(firstSet);
if (_head.isNullable()) {
firstSet = _next.firstSet(firstSet);
}
return firstSet;
}
@Override
String prefix() {
return _head.prefix();
}
@Override
boolean isAnchorBegin() {
return _head.isAnchorBegin();
}
RegexpNode getConcatHead() {
return _head;
}
RegexpNode getConcatNext() {
return _next;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
offset = _head.match(string, length, offset, state);
if (offset < 0) {
return -1;
} else {
return _next.match(string, length, offset, state);
}
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[");
_head.toString(sb, map);
sb.append(", ");
_next.toString(sb, map);
sb.append("]");
}
}
static class ConditionalHead extends RegexpNode {
private RegexpNode _first;
private RegexpNode _second;
private RegexpNode _tail;
private final int _group;
ConditionalHead(int group) {
_group = group;
_tail = new ConditionalTail(this);
}
void setFirst(RegexpNode first) {
_first = first;
}
void setSecond(RegexpNode second) {
_second = second;
}
void setTail(RegexpNode tail) {
_tail = tail;
}
@Override
RegexpNode getTail() {
return _tail;
}
@Override
RegexpNode concat(RegexpNode next) {
_tail.concat(next);
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
return _tail.createLoop(parser, min, max);
}
/**
* Create an or expression
*/
@Override
RegexpNode createOr(RegexpNode node) {
return _tail.createOr(node);
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
int begin = state.getBegin(_group);
int end = state.getEnd(_group);
if (_group <= state.getLength() && begin >= 0 && begin <= end) {
int match = _first.match(string, length, offset, state);
return match;
} else if (_second != null) {
return _second.match(string, length, offset, state);
} else {
return _tail.match(string, length, offset, state);
}
}
@Override
public String toString() {
return (getClass().getSimpleName()
+ "[" + _group
+ "," + _first
+ "," + _tail
+ "]");
}
}
static class ConditionalTail extends RegexpNode {
private RegexpNode _head;
private RegexpNode _next;
ConditionalTail(ConditionalHead head) {
_next = N_END;
_head = head;
head.setTail(this);
}
@Override
RegexpNode getHead() {
return _head;
}
@Override
RegexpNode concat(RegexpNode next) {
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
return _head;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
LoopHead head = new LoopHead(parser, _head, min, max);
_next = _next.concat(head.getTail());
return head;
}
@Override
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
LoopHeadUngreedy head = new LoopHeadUngreedy(parser, _head, min, max);
_next = _next.concat(head.getTail());
return head;
}
/**
* Create an or expression
*/
@Override
RegexpNode createOr(RegexpNode node) {
_next = _next.createOr(node);
return getHead();
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
return _next.match(string, length, offset, state);
}
}
final static EmptyNode EMPTY = new EmptyNode();
/**
* Matches an empty production
*/
static class EmptyNode extends RegexpNode {
// needed for php/4e6b
EmptyNode() {
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
return offset;
}
}
static class End extends RegexpNode {
@Override
RegexpNode concat(RegexpNode next) {
return next;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
return offset;
}
}
static class Group extends RegexpNode {
private final RegexpNode _node;
private final int _group;
Group(RegexpNode node, int group) {
_node = node.getHead();
_group = group;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
int oldBegin = state.getBegin(_group);
state.setBegin(_group, offset);
int tail = _node.match(string, length, offset, state);
if (tail >= 0) {
state.setEnd(_group, tail);
return tail;
} else {
state.setBegin(_group, oldBegin);
return -1;
}
}
}
static class GroupHead extends RegexpNode {
private RegexpNode _node;
private RegexpNode _tail;
private final int _group;
GroupHead(int group) {
_group = group;
_tail = new GroupTail(group, this);
}
void setNode(RegexpNode node) {
_node = node.getHead();
// php/4eh1
if (_node == this) {
_node = _tail;
}
}
@Override
RegexpNode getTail() {
return _tail;
}
@Override
RegexpNode concat(RegexpNode next) {
_tail.concat(next);
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
return _tail.createLoop(parser, min, max);
}
@Override
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
return _tail.createLoopUngreedy(parser, min, max);
}
@Override
int minLength() {
return _node.minLength();
}
@Override
int firstChar() {
return _node.firstChar();
}
@Override
boolean[] firstSet(boolean[] firstSet) {
return _node.firstSet(firstSet);
}
@Override
String prefix() {
return _node.prefix();
}
@Override
boolean isAnchorBegin() {
return _node.isAnchorBegin();
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
int oldBegin = state.getBegin(_group);
state.setBegin(_group, offset);
int tail = _node.match(string, length, offset, state);
if (tail >= 0) {
return tail;
} else {
state.setBegin(_group, oldBegin);
return tail;
}
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[");
sb.append(_group);
sb.append(", ");
_node.toString(sb, map);
sb.append("]");
}
}
static class GroupTail extends RegexpNode {
private RegexpNode _head;
private RegexpNode _next;
private final int _group;
private GroupTail(int group, GroupHead head) {
_next = N_END;
_head = head;
_group = group;
}
@Override
RegexpNode getHead() {
return _head;
}
@Override
RegexpNode concat(RegexpNode next) {
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
return _head;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
LoopHead head = new LoopHead(parser, _head, min, max);
_next = head.getTail();
return head;
}
@Override
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
LoopHeadUngreedy head = new LoopHeadUngreedy(parser, _head, min, max);
_next = head.getTail();
return head;
}
/**
* Create an or expression
*/
// php/4e6b
/*
@Override
RegexpNode createOr(RegexpNode node)
{
_next = _next.createOr(node);
return getHead();
}
*/
@Override
int minLength() {
return _next.minLength();
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
int oldEnd = state.getEnd(_group);
int oldLength = state.getLength();
if (_group > 0) {
state.setEnd(_group, offset);
if (oldLength < _group) {
state.setLength(_group);
}
}
int tail = _next.match(string, length, offset, state);
if (tail < 0) {
state.setEnd(_group, oldEnd);
state.setLength(oldLength);
return -1;
} else {
return tail;
}
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[");
sb.append(_group);
sb.append(", ");
_next.toString(sb, map);
sb.append("]");
}
}
static class GroupRef extends RegexpNode {
private final int _group;
GroupRef(int group) {
_group = group;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (state.getLength() < _group) {
return -1;
}
int groupBegin = state.getBegin(_group);
int groupLength = state.getEnd(_group) - groupBegin;
if (string.regionMatches(offset, string, groupBegin, groupLength)) {
return offset + groupLength;
} else {
return -1;
}
}
}
static class Lookahead extends RegexpNode {
private final RegexpNode _head;
Lookahead(RegexpNode head) {
_head = head;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (_head.match(string, length, offset, state) >= 0) {
return offset;
} else {
return -1;
}
}
}
static class NotLookahead extends RegexpNode {
private final RegexpNode _head;
NotLookahead(RegexpNode head) {
_head = head;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (_head.match(string, length, offset, state) < 0) {
return offset;
} else {
return -1;
}
}
}
static class Lookbehind extends RegexpNode {
private final RegexpNode _head;
Lookbehind(RegexpNode head) {
_head = head.getHead();
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int length = _head.minLength();
if (offset < length) {
return -1;
} else if (_head.match(string, strlen, offset - length, state) >= 0) {
return offset;
} else {
return -1;
}
}
}
static class NotLookbehind extends RegexpNode {
private final RegexpNode _head;
NotLookbehind(RegexpNode head) {
_head = head;
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int length = _head.minLength();
if (offset < length) {
return offset;
} else if (_head.match(string, strlen, offset - length, state) < 0) {
return offset;
} else {
return -1;
}
}
}
/**
* A nullable node can match an empty string.
*/
abstract static class NullableNode extends RegexpNode {
@Override
boolean isNullable() {
return true;
}
}
static class LoopHead extends RegexpNode {
private final int _index;
final RegexpNode _node;
private final RegexpNode _tail;
private int _min;
private int _max;
LoopHead(Regcomp parser, RegexpNode node, int min, int max) {
_index = parser.nextLoopIndex();
_tail = new LoopTail(_index, this);
_node = node.concat(_tail).getHead();
_min = min;
_max = max;
}
@Override
RegexpNode getTail() {
return _tail;
}
@Override
RegexpNode concat(RegexpNode next) {
_tail.concat(next);
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
@Override
int minLength() {
return _min * _node.minLength() + _tail.minLength();
}
@Override
boolean[] firstSet(boolean[] firstSet) {
firstSet = _node.firstSet(firstSet);
if (_min > 0 && !_node.isNullable()) {
return firstSet;
}
firstSet = _tail.firstSet(firstSet);
return firstSet;
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
state._loopCount[_index] = 0;
RegexpNode node = _node;
int min = _min;
int i;
for (i = 0; i < min - 1; i++) {
state._loopCount[_index] = i;
offset = node.match(string, strlen, offset, state);
if (offset < 0) {
return offset;
}
}
state._loopCount[_index] = i;
state._loopOffset[_index] = offset;
int tail = node.match(string, strlen, offset, state);
if (tail >= 0) {
return tail;
} else if (state._loopCount[_index] < _min) {
return tail;
} else {
return _tail.match(string, strlen, offset, state);
}
}
@Override
public String toString() {
return "LoopHead[" + _min + ", " + _max + ", " + _node + "]";
}
}
static class LoopTail extends RegexpNode {
private final int _index;
private LoopHead _head;
private RegexpNode _next;
LoopTail(int index, LoopHead head) {
_index = index;
_head = head;
_next = N_END;
}
@Override
RegexpNode getHead() {
return _head;
}
@Override
RegexpNode concat(RegexpNode next) {
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
if (_next == this) {
throw new IllegalStateException();
}
return this;
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int oldCount = state._loopCount[_index];
if (oldCount + 1 < _head._min) {
return offset;
} else if (oldCount + 1 < _head._max) {
int oldOffset = state._loopOffset[_index];
if (oldOffset != offset) {
state._loopCount[_index] = oldCount + 1;
state._loopOffset[_index] = offset;
int tail = _head._node.match(string, strlen, offset, state);
if (tail >= 0) {
return tail;
}
state._loopCount[_index] = oldCount;
state._loopOffset[_index] = oldOffset;
}
}
return _next.match(string, strlen, offset, state);
}
@Override
public String toString() {
return "LoopTail[" + _next + "]";
}
}
static class LoopHeadUngreedy extends RegexpNode {
private final int _index;
final RegexpNode _node;
private final LoopTailUngreedy _tail;
private int _min;
private int _max;
LoopHeadUngreedy(Regcomp parser, RegexpNode node, int min, int max) {
_index = parser.nextLoopIndex();
_min = min;
_max = max;
_tail = new LoopTailUngreedy(_index, this);
_node = node.getTail().concat(_tail).getHead();
}
@Override
RegexpNode getTail() {
return _tail;
}
@Override
RegexpNode concat(RegexpNode next) {
_tail.concat(next);
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
@Override
int minLength() {
return _min * _node.minLength() + _tail.minLength();
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
state._loopCount[_index] = 0;
RegexpNode node = _node;
int min = _min;
for (int i = 0; i < min; i++) {
state._loopCount[_index] = i;
state._loopOffset[_index] = offset;
offset = node.match(string, strlen, offset, state);
if (offset < 0) {
return -1;
}
}
int tail = _tail._next.match(string, strlen, offset, state);
if (tail >= 0) {
return tail;
}
if (min < _max) {
state._loopCount[_index] = min;
state._loopOffset[_index] = offset;
return node.match(string, strlen, offset, state);
} else {
return -1;
}
}
@Override
public String toString() {
return "LoopHeadUngreedy[" + _min + ", " + _max + ", " + _node + "]";
}
}
static class LoopTailUngreedy extends RegexpNode {
private final int _index;
private LoopHeadUngreedy _head;
private RegexpNode _next;
LoopTailUngreedy(int index, LoopHeadUngreedy head) {
_index = index;
_head = head;
_next = N_END;
}
@Override
RegexpNode getHead() {
return _head;
}
@Override
RegexpNode concat(RegexpNode next) {
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
if (_next == this) {
throw new IllegalStateException();
}
return this;
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int i = state._loopCount[_index];
int oldOffset = state._loopOffset[_index];
if (i < _head._min) {
return offset;
}
if (offset == oldOffset) {
return -1;
}
int tail = _next.match(string, strlen, offset, state);
if (tail >= 0) {
return tail;
}
if (i + 1 < _head._max) {
state._loopCount[_index] = i + 1;
state._loopOffset[_index] = offset;
tail = _head._node.match(string, strlen, offset, state);
state._loopCount[_index] = i;
state._loopOffset[_index] = oldOffset;
return tail;
} else {
return -1;
}
}
@Override
public String toString() {
return "LoopTailUngreedy[" + _next + "]";
}
}
static class Not extends RegexpNode {
private RegexpNode _node;
private Not(RegexpNode node) {
_node = node;
}
static Not create(RegexpNode node) {
return new Not(node);
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int result = _node.match(string, strlen, offset, state);
if (result >= 0) {
return -1;
} else {
return offset + 1;
}
}
}
final static class Or extends RegexpNode {
private final RegexpNode _left;
private Or _right;
private Or(RegexpNode left, Or right) {
_left = left;
_right = right;
}
static Or create(RegexpNode left, RegexpNode right) {
if (left instanceof Or) {
return ((Or) left).append(right);
} else if (right instanceof Or) {
return new Or(left, (Or) right);
} else {
return new Or(left, new Or(right, null));
}
}
private Or append(RegexpNode right) {
if (_right != null) {
_right = _right.append(right);
} else if (right instanceof Or) {
_right = (Or) right;
} else {
_right = new Or(right, null);
}
return this;
}
@Override
int minLength() {
if (_right != null) {
return Math.min(_left.minLength(), _right.minLength());
} else {
return _left.minLength();
}
}
@Override
int firstChar() {
if (_right == null) {
return _left.firstChar();
}
int leftChar = _left.firstChar();
int rightChar = _right.firstChar();
if (leftChar == rightChar) {
return leftChar;
} else {
return -1;
}
}
@Override
boolean[] firstSet(boolean[] firstSet) {
if (_right == null) {
return _left.firstSet(firstSet);
}
firstSet = _left.firstSet(firstSet);
firstSet = _right.firstSet(firstSet);
return firstSet;
}
@Override
boolean isAnchorBegin() {
return _left.isAnchorBegin() && _right != null && _right.isAnchorBegin();
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
for (Or ptr = this; ptr != null; ptr = ptr._right) {
int value = ptr._left.match(string, strlen, offset, state);
if (value >= 0) {
return value;
}
}
return -1;
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[");
_left.toString(sb, map);
for (Or ptr = _right; ptr != null; ptr = ptr._right) {
sb.append(",");
ptr._left.toString(sb, map);
}
sb.append("]");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Or[");
sb.append(_left);
for (Or ptr = _right; ptr != null; ptr = ptr._right) {
sb.append(",");
sb.append(ptr._left);
}
sb.append("]");
return sb.toString();
}
}
static class PossessiveLoop extends RegexpNode {
private final RegexpNode _node;
private RegexpNode _next = N_END;
private int _min;
private int _max;
PossessiveLoop(RegexpNode node, int min, int max) {
_node = node.getHead();
_min = min;
_max = max;
}
@Override
RegexpNode concat(RegexpNode next) {
if (next == null) {
throw new NullPointerException();
}
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
RegexpNode node = _node;
int min = _min;
int max = _max;
int i;
for (i = 0; i < min; i++) {
offset = node.match(string, strlen, offset, state);
if (offset < 0) {
return -1;
}
}
for (; i < max; i++) {
int tail = node.match(string, strlen, offset, state);
if (tail < 0 || tail == offset) {
return _next.match(string, strlen, offset, state);
}
offset = tail;
}
return _next.match(string, strlen, offset, state);
}
@Override
public String toString() {
return "PossessiveLoop[" + _min + ", "
+ _max + ", " + _node + ", " + _next + "]";
}
}
static final PropC PROP_C = new PropC();
static final PropNotC PROP_NOT_C = new PropNotC();
static final Prop PROP_Cc = new Prop(Character.CONTROL);
static final PropNot PROP_NOT_Cc = new PropNot(Character.CONTROL);
static final Prop PROP_Cf = new Prop(Character.FORMAT);
static final PropNot PROP_NOT_Cf = new PropNot(Character.FORMAT);
static final Prop PROP_Cn = new Prop(Character.UNASSIGNED);
static final PropNot PROP_NOT_Cn = new PropNot(Character.UNASSIGNED);
static final Prop PROP_Co = new Prop(Character.PRIVATE_USE);
static final PropNot PROP_NOT_Co = new PropNot(Character.PRIVATE_USE);
static final Prop PROP_Cs = new Prop(Character.SURROGATE);
static final PropNot PROP_NOT_Cs = new PropNot(Character.SURROGATE);
static final PropL PROP_L = new PropL();
static final PropNotL PROP_NOT_L = new PropNotL();
static final Prop PROP_Ll = new Prop(Character.LOWERCASE_LETTER);
static final PropNot PROP_NOT_Ll = new PropNot(Character.LOWERCASE_LETTER);
static final Prop PROP_Lm = new Prop(Character.MODIFIER_LETTER);
static final PropNot PROP_NOT_Lm = new PropNot(Character.MODIFIER_LETTER);
static final Prop PROP_Lo = new Prop(Character.OTHER_LETTER);
static final PropNot PROP_NOT_Lo = new PropNot(Character.OTHER_LETTER);
static final Prop PROP_Lt = new Prop(Character.TITLECASE_LETTER);
static final PropNot PROP_NOT_Lt = new PropNot(Character.TITLECASE_LETTER);
static final Prop PROP_Lu = new Prop(Character.UPPERCASE_LETTER);
static final PropNot PROP_NOT_Lu = new PropNot(Character.UPPERCASE_LETTER);
static final PropM PROP_M = new PropM();
static final PropNotM PROP_NOT_M = new PropNotM();
static final Prop PROP_Mc = new Prop(Character.COMBINING_SPACING_MARK);
static final PropNot PROP_NOT_Mc = new PropNot(Character.COMBINING_SPACING_MARK);
static final Prop PROP_Me = new Prop(Character.ENCLOSING_MARK);
static final PropNot PROP_NOT_Me = new PropNot(Character.ENCLOSING_MARK);
static final Prop PROP_Mn = new Prop(Character.NON_SPACING_MARK);
static final PropNot PROP_NOT_Mn = new PropNot(Character.NON_SPACING_MARK);
static final PropN PROP_N = new PropN();
static final PropNotN PROP_NOT_N = new PropNotN();
static final Prop PROP_Nd = new Prop(Character.DECIMAL_DIGIT_NUMBER);
static final PropNot PROP_NOT_Nd = new PropNot(Character.DECIMAL_DIGIT_NUMBER);
static final Prop PROP_Nl = new Prop(Character.LETTER_NUMBER);
static final PropNot PROP_NOT_Nl = new PropNot(Character.LETTER_NUMBER);
static final Prop PROP_No = new Prop(Character.OTHER_NUMBER);
static final PropNot PROP_NOT_No = new PropNot(Character.OTHER_NUMBER);
static final PropP PROP_P = new PropP();
static final PropNotP PROP_NOT_P = new PropNotP();
static final Prop PROP_Pc = new Prop(Character.CONNECTOR_PUNCTUATION);
static final PropNot PROP_NOT_Pc = new PropNot(Character.CONNECTOR_PUNCTUATION);
static final Prop PROP_Pd = new Prop(Character.DASH_PUNCTUATION);
static final PropNot PROP_NOT_Pd = new PropNot(Character.DASH_PUNCTUATION);
static final Prop PROP_Pe = new Prop(Character.END_PUNCTUATION);
static final PropNot PROP_NOT_Pe = new PropNot(Character.END_PUNCTUATION);
static final Prop PROP_Pf = new Prop(Character.FINAL_QUOTE_PUNCTUATION);
static final PropNot PROP_NOT_Pf = new PropNot(Character.FINAL_QUOTE_PUNCTUATION);
static final Prop PROP_Pi = new Prop(Character.INITIAL_QUOTE_PUNCTUATION);
static final PropNot PROP_NOT_Pi = new PropNot(Character.INITIAL_QUOTE_PUNCTUATION);
static final Prop PROP_Po = new Prop(Character.OTHER_PUNCTUATION);
static final PropNot PROP_NOT_Po = new PropNot(Character.OTHER_PUNCTUATION);
static final Prop PROP_Ps = new Prop(Character.START_PUNCTUATION);
static final PropNot PROP_NOT_Ps = new PropNot(Character.START_PUNCTUATION);
static final PropS PROP_S = new PropS();
static final PropNotS PROP_NOT_S = new PropNotS();
static final Prop PROP_Sc = new Prop(Character.CURRENCY_SYMBOL);
static final PropNot PROP_NOT_Sc = new PropNot(Character.CURRENCY_SYMBOL);
static final Prop PROP_Sk = new Prop(Character.MODIFIER_SYMBOL);
static final PropNot PROP_NOT_Sk = new PropNot(Character.MODIFIER_SYMBOL);
static final Prop PROP_Sm = new Prop(Character.MATH_SYMBOL);
static final PropNot PROP_NOT_Sm = new PropNot(Character.MATH_SYMBOL);
static final Prop PROP_So = new Prop(Character.OTHER_SYMBOL);
static final PropNot PROP_NOT_So = new PropNot(Character.OTHER_SYMBOL);
static final PropZ PROP_Z = new PropZ();
static final PropNotZ PROP_NOT_Z = new PropNotZ();
static final Prop PROP_Zl = new Prop(Character.LINE_SEPARATOR);
static final PropNot PROP_NOT_Zl = new PropNot(Character.LINE_SEPARATOR);
static final Prop PROP_Zp = new Prop(Character.PARAGRAPH_SEPARATOR);
static final PropNot PROP_NOT_Zp = new PropNot(Character.PARAGRAPH_SEPARATOR);
static final Prop PROP_Zs = new Prop(Character.SPACE_SEPARATOR);
static final PropNot PROP_NOT_Zs = new PropNot(Character.SPACE_SEPARATOR);
private static class Prop extends AbstractCharNode {
private final int _category;
Prop(int category) {
_category = category;
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
if (Character.getType(ch) == _category) {
return offset + 1;
}
}
return -1;
}
}
private static class PropNot extends AbstractCharNode {
private final int _category;
PropNot(int category) {
_category = category;
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
if (Character.getType(ch) != _category) {
return offset + 1;
}
}
return -1;
}
}
static class PropC extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.CONTROL
|| value == Character.FORMAT
|| value == Character.UNASSIGNED
|| value == Character.PRIVATE_USE
|| value == Character.SURROGATE) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotC extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.CONTROL
|| value == Character.FORMAT
|| value == Character.UNASSIGNED
|| value == Character.PRIVATE_USE
|| value == Character.SURROGATE)) {
return offset + 1;
}
}
return -1;
}
}
static class PropL extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.LOWERCASE_LETTER
|| value == Character.MODIFIER_LETTER
|| value == Character.OTHER_LETTER
|| value == Character.TITLECASE_LETTER
|| value == Character.UPPERCASE_LETTER) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotL extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.LOWERCASE_LETTER
|| value == Character.MODIFIER_LETTER
|| value == Character.OTHER_LETTER
|| value == Character.TITLECASE_LETTER
|| value == Character.UPPERCASE_LETTER)) {
return offset + 1;
}
}
return -1;
}
}
static class PropM extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.COMBINING_SPACING_MARK
|| value == Character.ENCLOSING_MARK
|| value == Character.NON_SPACING_MARK) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotM extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.COMBINING_SPACING_MARK
|| value == Character.ENCLOSING_MARK
|| value == Character.NON_SPACING_MARK)) {
return offset + 1;
}
}
return -1;
}
}
static class PropN extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.DECIMAL_DIGIT_NUMBER
|| value == Character.LETTER_NUMBER
|| value == Character.OTHER_NUMBER) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotN extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.DECIMAL_DIGIT_NUMBER
|| value == Character.LETTER_NUMBER
|| value == Character.OTHER_NUMBER)) {
return offset + 1;
}
}
return -1;
}
}
static class PropP extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.CONNECTOR_PUNCTUATION
|| value == Character.DASH_PUNCTUATION
|| value == Character.END_PUNCTUATION
|| value == Character.FINAL_QUOTE_PUNCTUATION
|| value == Character.INITIAL_QUOTE_PUNCTUATION
|| value == Character.OTHER_PUNCTUATION
|| value == Character.START_PUNCTUATION) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotP extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.CONNECTOR_PUNCTUATION
|| value == Character.DASH_PUNCTUATION
|| value == Character.END_PUNCTUATION
|| value == Character.FINAL_QUOTE_PUNCTUATION
|| value == Character.INITIAL_QUOTE_PUNCTUATION
|| value == Character.OTHER_PUNCTUATION
|| value == Character.START_PUNCTUATION)) {
return offset + 1;
}
}
return -1;
}
}
static class PropS extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.CURRENCY_SYMBOL
|| value == Character.MODIFIER_SYMBOL
|| value == Character.MATH_SYMBOL
|| value == Character.OTHER_SYMBOL) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotS extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.CURRENCY_SYMBOL
|| value == Character.MODIFIER_SYMBOL
|| value == Character.MATH_SYMBOL
|| value == Character.OTHER_SYMBOL)) {
return offset + 1;
}
}
return -1;
}
}
static class PropZ extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.LINE_SEPARATOR
|| value == Character.PARAGRAPH_SEPARATOR
|| value == Character.SPACE_SEPARATOR) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotZ extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.LINE_SEPARATOR
|| value == Character.PARAGRAPH_SEPARATOR
|| value == Character.SPACE_SEPARATOR)) {
return offset + 1;
}
}
return -1;
}
}
static class Recursive extends RegexpNode {
private RegexpNode _top;
Recursive() {
}
void setTop(RegexpNode top) {
_top = top;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
return _top.match(string, length, offset, state);
}
}
static class Set extends AbstractCharNode {
private final boolean[] _asciiSet;
private final IntSet _range;
Set(boolean[] set, IntSet range) {
_asciiSet = set;
_range = range;
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (strlen <= offset) {
return -1;
}
char ch = string.charAt(offset++);
if (ch < 128) {
return _asciiSet[ch] ? offset : -1;
}
int codePoint = ch;
if ('\uD800' <= ch && ch <= '\uDBFF' && offset < strlen) {
|
[
" char low = string.charAt(offset++);"
] | 6,474
|
lcc
|
java
| null |
d616bbc2ccc30cab16459d0300a1d8c933b33e1455e3aa84
| 54
|
Your task is code completion.
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.lib.regexp;
import java.util.*;
import com.caucho.util.*;
import com.caucho.quercus.env.StringValue;
class RegexpNode {
private static final L10N L = new L10N(RegexpNode.class);
static final int RC_END = 0;
static final int RC_NULL = 1;
static final int RC_STRING = 2;
static final int RC_SET = 3;
static final int RC_NSET = 4;
static final int RC_BEG_GROUP = 5;
static final int RC_END_GROUP = 6;
static final int RC_GROUP_REF = 7;
static final int RC_LOOP = 8;
static final int RC_LOOP_INIT = 9;
static final int RC_LOOP_SHORT = 10;
static final int RC_LOOP_UNIQUE = 11;
static final int RC_LOOP_SHORT_UNIQUE = 12;
static final int RC_LOOP_LONG = 13;
static final int RC_OR = 64;
static final int RC_OR_UNIQUE = 65;
static final int RC_POS_LOOKAHEAD = 66;
static final int RC_NEG_LOOKAHEAD = 67;
static final int RC_POS_LOOKBEHIND = 68;
static final int RC_NEG_LOOKBEHIND = 69;
static final int RC_LOOKBEHIND_OR = 70;
static final int RC_WORD = 73;
static final int RC_NWORD = 74;
static final int RC_BLINE = 75;
static final int RC_ELINE = 76;
static final int RC_BSTRING = 77;
static final int RC_ESTRING = 78;
static final int RC_ENSTRING = 79;
static final int RC_GSTRING = 80;
// conditionals
static final int RC_COND = 81;
// ignore case
static final int RC_STRING_I = 128;
static final int RC_SET_I = 129;
static final int RC_NSET_I = 130;
static final int RC_GROUP_REF_I = 131;
static final int RC_LEXEME = 256;
// unicode properties
static final int RC_UNICODE = 512;
static final int RC_NUNICODE = 513;
// unicode properties sets
static final int RC_C = 1024;
static final int RC_L = 1025;
static final int RC_M = 1026;
static final int RC_N = 1027;
static final int RC_P = 1028;
static final int RC_S = 1029;
static final int RC_Z = 1030;
// negated unicode properties sets
static final int RC_NC = 1031;
static final int RC_NL = 1032;
static final int RC_NM = 1033;
static final int RC_NN = 1034;
static final int RC_NP = 1035;
// POSIX character classes
static final int RC_CHAR_CLASS = 2048;
static final int RC_ALNUM = 1;
static final int RC_ALPHA = 2;
static final int RC_BLANK = 3;
static final int RC_CNTRL = 4;
static final int RC_DIGIT = 5;
static final int RC_GRAPH = 6;
static final int RC_LOWER = 7;
static final int RC_PRINT = 8;
static final int RC_PUNCT = 9;
static final int RC_SPACE = 10;
static final int RC_UPPER = 11;
static final int RC_XDIGIT = 12;
// #2526, possible JIT/OS issue with Integer.MAX_VALUE
private static final int INTEGER_MAX = Integer.MAX_VALUE - 1;
public static final int FAIL = -1;
public static final int SUCCESS = 0;
static final RegexpNode N_END = new End();
static final RegexpNode ANY_CHAR;
/**
* Creates a node with a code
*/
protected RegexpNode() {
}
//
// parsing constructors
//
RegexpNode concat(RegexpNode next) {
return new Concat(this, next);
}
/**
* '?' operator
*/
RegexpNode createOptional(Regcomp parser) {
return createLoop(parser, 0, 1);
}
/**
* '*' operator
*/
RegexpNode createStar(Regcomp parser) {
return createLoop(parser, 0, INTEGER_MAX);
}
/**
* '+' operator
*/
RegexpNode createPlus(Regcomp parser) {
return createLoop(parser, 1, INTEGER_MAX);
}
/**
* Any loop
*/
RegexpNode createLoop(Regcomp parser, int min, int max) {
return new LoopHead(parser, this, min, max);
}
/**
* Any loop
*/
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
return new LoopHeadUngreedy(parser, this, min, max);
}
/**
* Possessive loop
*/
RegexpNode createPossessiveLoop(int min, int max) {
return new PossessiveLoop(getHead(), min, max);
}
/**
* Create an or expression
*/
RegexpNode createOr(RegexpNode node) {
return Or.create(this, node);
}
/**
* Create a not expression
*/
RegexpNode createNot() {
return Not.create(this);
}
//
// optimization functions
//
int minLength() {
return 0;
}
String prefix() {
return "";
}
int firstChar() {
return -1;
}
boolean isNullable() {
return false;
}
boolean[] firstSet(boolean[] firstSet) {
return null;
}
boolean isAnchorBegin() {
return false;
}
RegexpNode getTail() {
return this;
}
RegexpNode getHead() {
return this;
}
//
// matching
//
int match(StringValue string, int length, int offset, RegexpState state) {
throw new UnsupportedOperationException(getClass().getName());
}
@Override
public String toString() {
Map<RegexpNode, Integer> map = new IdentityHashMap<RegexpNode, Integer>();
StringBuilder sb = new StringBuilder();
toString(sb, map);
return sb.toString();
}
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName()).append("[]");
}
protected boolean toStringAdd(StringBuilder sb, Map<RegexpNode, Integer> map) {
Integer v = map.get(this);
if (v != null) {
sb.append("#").append(v);
return true;
}
map.put(this, map.size());
return false;
}
protected String toStringName() {
String name = getClass().getName();
int p = name.lastIndexOf('$');
if (p < 0) {
p = name.lastIndexOf('.');
}
return name.substring(p + 1);
}
/**
* A node with exactly one character matches.
*/
static class AbstractCharNode extends RegexpNode {
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
return new CharLoop(this, min, max);
}
@Override
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
return new CharUngreedyLoop(this, min, max);
}
@Override
int minLength() {
return 1;
}
}
static class CharNode extends AbstractCharNode {
private char _ch;
CharNode(char ch) {
_ch = ch;
}
@Override
int firstChar() {
return _ch;
}
@Override
boolean[] firstSet(boolean[] firstSet) {
if (firstSet != null && _ch < firstSet.length) {
firstSet[_ch] = true;
return firstSet;
} else {
return null;
}
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset < length && string.charAt(offset) == _ch) {
return offset + 1;
} else {
return -1;
}
}
}
static final AnchorBegin ANCHOR_BEGIN = new AnchorBegin();
static final AnchorBeginOrNewline ANCHOR_BEGIN_OR_NEWLINE = new AnchorBeginOrNewline();
static final AnchorBeginRelative ANCHOR_BEGIN_RELATIVE = new AnchorBeginRelative();
static final AnchorEnd ANCHOR_END = new AnchorEnd();
static final AnchorEndOnly ANCHOR_END_ONLY = new AnchorEndOnly();
static final AnchorEndOrNewline ANCHOR_END_OR_NEWLINE = new AnchorEndOrNewline();
static class AnchorBegin extends NullableNode {
@Override
boolean isAnchorBegin() {
return true;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset == 0) {
return offset;
} else {
return -1;
}
}
}
private static class AnchorBeginOrNewline extends NullableNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset == 0 || string.charAt(offset - 1) == '\n') {
return offset;
} else {
return -1;
}
}
}
static class AnchorBeginRelative extends NullableNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset == state._start) {
return offset;
} else {
return -1;
}
}
}
private static class AnchorEnd extends NullableNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset == strlen
|| offset + 1 == strlen && string.charAt(offset) == '\n') {
return offset;
} else {
return -1;
}
}
}
private static class AnchorEndOnly extends NullableNode {
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset == length) {
return offset;
} else {
return -1;
}
}
}
private static class AnchorEndOrNewline extends NullableNode {
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset == length || string.charAt(offset) == '\n') {
return offset;
} else {
return -1;
}
}
}
static final RegexpNode DIGIT = RegexpSet.DIGIT.createNode();
static final RegexpNode NOT_DIGIT = RegexpSet.DIGIT.createNotNode();
static final RegexpNode DOT = RegexpSet.DOT.createNotNode();
static final RegexpNode NOT_DOT = RegexpSet.DOT.createNode();
static final RegexpNode SPACE = RegexpSet.SPACE.createNode();
static final RegexpNode NOT_SPACE = RegexpSet.SPACE.createNotNode();
static final RegexpNode S_WORD = RegexpSet.WORD.createNode();
static final RegexpNode NOT_S_WORD = RegexpSet.WORD.createNotNode();
static class AsciiSet extends AbstractCharNode {
private final boolean[] _set;
AsciiSet() {
_set = new boolean[128];
}
AsciiSet(boolean[] set) {
_set = set;
}
@Override
boolean[] firstSet(boolean[] firstSet) {
if (firstSet == null) {
return null;
}
for (int i = 0; i < _set.length; i++) {
if (_set[i]) {
firstSet[i] = true;
}
}
return firstSet;
}
void setChar(char ch) {
_set[ch] = true;
}
void clearChar(char ch) {
_set[ch] = false;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (length <= offset) {
return -1;
}
char ch = string.charAt(offset);
if (ch < 128 && _set[ch]) {
return offset + 1;
} else {
return -1;
}
}
}
static class AsciiNotSet extends AbstractCharNode {
private final boolean[] _set;
AsciiNotSet() {
_set = new boolean[128];
}
AsciiNotSet(boolean[] set) {
_set = set;
}
void setChar(char ch) {
_set[ch] = true;
}
void clearChar(char ch) {
_set[ch] = false;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (length <= offset) {
return -1;
}
char ch = string.charAt(offset);
if (ch < 128 && _set[ch]) {
return -1;
} else {
return offset + 1;
}
}
}
static class CharLoop extends RegexpNode {
private final RegexpNode _node;
private RegexpNode _next = N_END;
private int _min;
private int _max;
CharLoop(RegexpNode node, int min, int max) {
_node = node.getHead();
_min = min;
_max = max;
if (_min < 0) {
throw new IllegalStateException();
}
}
@Override
RegexpNode concat(RegexpNode next) {
if (next == null) {
throw new NullPointerException();
}
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next.getHead();
}
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
@Override
int minLength() {
return _min;
}
@Override
boolean[] firstSet(boolean[] firstSet) {
firstSet = _node.firstSet(firstSet);
if (_min > 0 && !_node.isNullable()) {
return firstSet;
}
firstSet = _next.firstSet(firstSet);
return firstSet;
}
//
// match functions
//
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
RegexpNode next = _next;
RegexpNode node = _node;
int min = _min;
int max = _max;
int i;
int tail;
for (i = 0; i < min; i++) {
tail = node.match(string, length, offset + i, state);
if (tail < 0) {
return tail;
}
}
for (; i < max; i++) {
if (node.match(string, length, offset + i, state) < 0) {
break;
}
}
for (; min <= i; i--) {
tail = next.match(string, length, offset + i, state);
if (tail >= 0) {
return tail;
}
}
return -1;
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[").append(_min).append(", ").append(_max).append(", ");
_node.toString(sb, map);
sb.append(", ");
_next.toString(sb, map);
sb.append("]");
}
}
static class CharUngreedyLoop extends RegexpNode {
private final RegexpNode _node;
private RegexpNode _next = N_END;
private int _min;
private int _max;
CharUngreedyLoop(RegexpNode node, int min, int max) {
_node = node.getHead();
_min = min;
_max = max;
if (_min < 0) {
throw new IllegalStateException();
}
}
@Override
RegexpNode concat(RegexpNode next) {
if (next == null) {
throw new NullPointerException();
}
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next.getHead();
}
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
@Override
int minLength() {
return _min;
}
@Override
boolean[] firstSet(boolean[] firstSet) {
firstSet = _node.firstSet(firstSet);
if (_min > 0 && !_node.isNullable()) {
return firstSet;
}
firstSet = _next.firstSet(firstSet);
return firstSet;
}
//
// match functions
//
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
RegexpNode next = _next;
RegexpNode node = _node;
int min = _min;
int max = _max;
int i;
int tail;
for (i = 0; i < min; i++) {
tail = node.match(string, length, offset + i, state);
if (tail < 0) {
return tail;
}
}
for (; i <= max; i++) {
tail = next.match(string, length, offset + i, state);
if (tail >= 0) {
return tail;
}
if (node.match(string, length, offset + i, state) < 0) {
return -1;
}
}
return -1;
}
@Override
public String toString() {
return "CharUngreedyLoop[" + _min + ", "
+ _max + ", " + _node + ", " + _next + "]";
}
}
final static class Concat extends RegexpNode {
private final RegexpNode _head;
private RegexpNode _next;
Concat(RegexpNode head, RegexpNode next) {
if (head == null || next == null) {
throw new NullPointerException();
}
_head = head;
_next = next;
}
@Override
RegexpNode concat(RegexpNode next) {
_next = _next.concat(next);
return this;
}
//
// optim functions
//
@Override
int minLength() {
return _head.minLength() + _next.minLength();
}
@Override
int firstChar() {
return _head.firstChar();
}
@Override
boolean[] firstSet(boolean[] firstSet) {
firstSet = _head.firstSet(firstSet);
if (_head.isNullable()) {
firstSet = _next.firstSet(firstSet);
}
return firstSet;
}
@Override
String prefix() {
return _head.prefix();
}
@Override
boolean isAnchorBegin() {
return _head.isAnchorBegin();
}
RegexpNode getConcatHead() {
return _head;
}
RegexpNode getConcatNext() {
return _next;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
offset = _head.match(string, length, offset, state);
if (offset < 0) {
return -1;
} else {
return _next.match(string, length, offset, state);
}
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[");
_head.toString(sb, map);
sb.append(", ");
_next.toString(sb, map);
sb.append("]");
}
}
static class ConditionalHead extends RegexpNode {
private RegexpNode _first;
private RegexpNode _second;
private RegexpNode _tail;
private final int _group;
ConditionalHead(int group) {
_group = group;
_tail = new ConditionalTail(this);
}
void setFirst(RegexpNode first) {
_first = first;
}
void setSecond(RegexpNode second) {
_second = second;
}
void setTail(RegexpNode tail) {
_tail = tail;
}
@Override
RegexpNode getTail() {
return _tail;
}
@Override
RegexpNode concat(RegexpNode next) {
_tail.concat(next);
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
return _tail.createLoop(parser, min, max);
}
/**
* Create an or expression
*/
@Override
RegexpNode createOr(RegexpNode node) {
return _tail.createOr(node);
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
int begin = state.getBegin(_group);
int end = state.getEnd(_group);
if (_group <= state.getLength() && begin >= 0 && begin <= end) {
int match = _first.match(string, length, offset, state);
return match;
} else if (_second != null) {
return _second.match(string, length, offset, state);
} else {
return _tail.match(string, length, offset, state);
}
}
@Override
public String toString() {
return (getClass().getSimpleName()
+ "[" + _group
+ "," + _first
+ "," + _tail
+ "]");
}
}
static class ConditionalTail extends RegexpNode {
private RegexpNode _head;
private RegexpNode _next;
ConditionalTail(ConditionalHead head) {
_next = N_END;
_head = head;
head.setTail(this);
}
@Override
RegexpNode getHead() {
return _head;
}
@Override
RegexpNode concat(RegexpNode next) {
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
return _head;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
LoopHead head = new LoopHead(parser, _head, min, max);
_next = _next.concat(head.getTail());
return head;
}
@Override
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
LoopHeadUngreedy head = new LoopHeadUngreedy(parser, _head, min, max);
_next = _next.concat(head.getTail());
return head;
}
/**
* Create an or expression
*/
@Override
RegexpNode createOr(RegexpNode node) {
_next = _next.createOr(node);
return getHead();
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
return _next.match(string, length, offset, state);
}
}
final static EmptyNode EMPTY = new EmptyNode();
/**
* Matches an empty production
*/
static class EmptyNode extends RegexpNode {
// needed for php/4e6b
EmptyNode() {
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
return offset;
}
}
static class End extends RegexpNode {
@Override
RegexpNode concat(RegexpNode next) {
return next;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
return offset;
}
}
static class Group extends RegexpNode {
private final RegexpNode _node;
private final int _group;
Group(RegexpNode node, int group) {
_node = node.getHead();
_group = group;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
int oldBegin = state.getBegin(_group);
state.setBegin(_group, offset);
int tail = _node.match(string, length, offset, state);
if (tail >= 0) {
state.setEnd(_group, tail);
return tail;
} else {
state.setBegin(_group, oldBegin);
return -1;
}
}
}
static class GroupHead extends RegexpNode {
private RegexpNode _node;
private RegexpNode _tail;
private final int _group;
GroupHead(int group) {
_group = group;
_tail = new GroupTail(group, this);
}
void setNode(RegexpNode node) {
_node = node.getHead();
// php/4eh1
if (_node == this) {
_node = _tail;
}
}
@Override
RegexpNode getTail() {
return _tail;
}
@Override
RegexpNode concat(RegexpNode next) {
_tail.concat(next);
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
return _tail.createLoop(parser, min, max);
}
@Override
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
return _tail.createLoopUngreedy(parser, min, max);
}
@Override
int minLength() {
return _node.minLength();
}
@Override
int firstChar() {
return _node.firstChar();
}
@Override
boolean[] firstSet(boolean[] firstSet) {
return _node.firstSet(firstSet);
}
@Override
String prefix() {
return _node.prefix();
}
@Override
boolean isAnchorBegin() {
return _node.isAnchorBegin();
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
int oldBegin = state.getBegin(_group);
state.setBegin(_group, offset);
int tail = _node.match(string, length, offset, state);
if (tail >= 0) {
return tail;
} else {
state.setBegin(_group, oldBegin);
return tail;
}
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[");
sb.append(_group);
sb.append(", ");
_node.toString(sb, map);
sb.append("]");
}
}
static class GroupTail extends RegexpNode {
private RegexpNode _head;
private RegexpNode _next;
private final int _group;
private GroupTail(int group, GroupHead head) {
_next = N_END;
_head = head;
_group = group;
}
@Override
RegexpNode getHead() {
return _head;
}
@Override
RegexpNode concat(RegexpNode next) {
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
return _head;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
LoopHead head = new LoopHead(parser, _head, min, max);
_next = head.getTail();
return head;
}
@Override
RegexpNode createLoopUngreedy(Regcomp parser, int min, int max) {
LoopHeadUngreedy head = new LoopHeadUngreedy(parser, _head, min, max);
_next = head.getTail();
return head;
}
/**
* Create an or expression
*/
// php/4e6b
/*
@Override
RegexpNode createOr(RegexpNode node)
{
_next = _next.createOr(node);
return getHead();
}
*/
@Override
int minLength() {
return _next.minLength();
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
int oldEnd = state.getEnd(_group);
int oldLength = state.getLength();
if (_group > 0) {
state.setEnd(_group, offset);
if (oldLength < _group) {
state.setLength(_group);
}
}
int tail = _next.match(string, length, offset, state);
if (tail < 0) {
state.setEnd(_group, oldEnd);
state.setLength(oldLength);
return -1;
} else {
return tail;
}
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[");
sb.append(_group);
sb.append(", ");
_next.toString(sb, map);
sb.append("]");
}
}
static class GroupRef extends RegexpNode {
private final int _group;
GroupRef(int group) {
_group = group;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (state.getLength() < _group) {
return -1;
}
int groupBegin = state.getBegin(_group);
int groupLength = state.getEnd(_group) - groupBegin;
if (string.regionMatches(offset, string, groupBegin, groupLength)) {
return offset + groupLength;
} else {
return -1;
}
}
}
static class Lookahead extends RegexpNode {
private final RegexpNode _head;
Lookahead(RegexpNode head) {
_head = head;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (_head.match(string, length, offset, state) >= 0) {
return offset;
} else {
return -1;
}
}
}
static class NotLookahead extends RegexpNode {
private final RegexpNode _head;
NotLookahead(RegexpNode head) {
_head = head;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (_head.match(string, length, offset, state) < 0) {
return offset;
} else {
return -1;
}
}
}
static class Lookbehind extends RegexpNode {
private final RegexpNode _head;
Lookbehind(RegexpNode head) {
_head = head.getHead();
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int length = _head.minLength();
if (offset < length) {
return -1;
} else if (_head.match(string, strlen, offset - length, state) >= 0) {
return offset;
} else {
return -1;
}
}
}
static class NotLookbehind extends RegexpNode {
private final RegexpNode _head;
NotLookbehind(RegexpNode head) {
_head = head;
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int length = _head.minLength();
if (offset < length) {
return offset;
} else if (_head.match(string, strlen, offset - length, state) < 0) {
return offset;
} else {
return -1;
}
}
}
/**
* A nullable node can match an empty string.
*/
abstract static class NullableNode extends RegexpNode {
@Override
boolean isNullable() {
return true;
}
}
static class LoopHead extends RegexpNode {
private final int _index;
final RegexpNode _node;
private final RegexpNode _tail;
private int _min;
private int _max;
LoopHead(Regcomp parser, RegexpNode node, int min, int max) {
_index = parser.nextLoopIndex();
_tail = new LoopTail(_index, this);
_node = node.concat(_tail).getHead();
_min = min;
_max = max;
}
@Override
RegexpNode getTail() {
return _tail;
}
@Override
RegexpNode concat(RegexpNode next) {
_tail.concat(next);
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
@Override
int minLength() {
return _min * _node.minLength() + _tail.minLength();
}
@Override
boolean[] firstSet(boolean[] firstSet) {
firstSet = _node.firstSet(firstSet);
if (_min > 0 && !_node.isNullable()) {
return firstSet;
}
firstSet = _tail.firstSet(firstSet);
return firstSet;
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
state._loopCount[_index] = 0;
RegexpNode node = _node;
int min = _min;
int i;
for (i = 0; i < min - 1; i++) {
state._loopCount[_index] = i;
offset = node.match(string, strlen, offset, state);
if (offset < 0) {
return offset;
}
}
state._loopCount[_index] = i;
state._loopOffset[_index] = offset;
int tail = node.match(string, strlen, offset, state);
if (tail >= 0) {
return tail;
} else if (state._loopCount[_index] < _min) {
return tail;
} else {
return _tail.match(string, strlen, offset, state);
}
}
@Override
public String toString() {
return "LoopHead[" + _min + ", " + _max + ", " + _node + "]";
}
}
static class LoopTail extends RegexpNode {
private final int _index;
private LoopHead _head;
private RegexpNode _next;
LoopTail(int index, LoopHead head) {
_index = index;
_head = head;
_next = N_END;
}
@Override
RegexpNode getHead() {
return _head;
}
@Override
RegexpNode concat(RegexpNode next) {
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
if (_next == this) {
throw new IllegalStateException();
}
return this;
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int oldCount = state._loopCount[_index];
if (oldCount + 1 < _head._min) {
return offset;
} else if (oldCount + 1 < _head._max) {
int oldOffset = state._loopOffset[_index];
if (oldOffset != offset) {
state._loopCount[_index] = oldCount + 1;
state._loopOffset[_index] = offset;
int tail = _head._node.match(string, strlen, offset, state);
if (tail >= 0) {
return tail;
}
state._loopCount[_index] = oldCount;
state._loopOffset[_index] = oldOffset;
}
}
return _next.match(string, strlen, offset, state);
}
@Override
public String toString() {
return "LoopTail[" + _next + "]";
}
}
static class LoopHeadUngreedy extends RegexpNode {
private final int _index;
final RegexpNode _node;
private final LoopTailUngreedy _tail;
private int _min;
private int _max;
LoopHeadUngreedy(Regcomp parser, RegexpNode node, int min, int max) {
_index = parser.nextLoopIndex();
_min = min;
_max = max;
_tail = new LoopTailUngreedy(_index, this);
_node = node.getTail().concat(_tail).getHead();
}
@Override
RegexpNode getTail() {
return _tail;
}
@Override
RegexpNode concat(RegexpNode next) {
_tail.concat(next);
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
@Override
int minLength() {
return _min * _node.minLength() + _tail.minLength();
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
state._loopCount[_index] = 0;
RegexpNode node = _node;
int min = _min;
for (int i = 0; i < min; i++) {
state._loopCount[_index] = i;
state._loopOffset[_index] = offset;
offset = node.match(string, strlen, offset, state);
if (offset < 0) {
return -1;
}
}
int tail = _tail._next.match(string, strlen, offset, state);
if (tail >= 0) {
return tail;
}
if (min < _max) {
state._loopCount[_index] = min;
state._loopOffset[_index] = offset;
return node.match(string, strlen, offset, state);
} else {
return -1;
}
}
@Override
public String toString() {
return "LoopHeadUngreedy[" + _min + ", " + _max + ", " + _node + "]";
}
}
static class LoopTailUngreedy extends RegexpNode {
private final int _index;
private LoopHeadUngreedy _head;
private RegexpNode _next;
LoopTailUngreedy(int index, LoopHeadUngreedy head) {
_index = index;
_head = head;
_next = N_END;
}
@Override
RegexpNode getHead() {
return _head;
}
@Override
RegexpNode concat(RegexpNode next) {
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
if (_next == this) {
throw new IllegalStateException();
}
return this;
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int i = state._loopCount[_index];
int oldOffset = state._loopOffset[_index];
if (i < _head._min) {
return offset;
}
if (offset == oldOffset) {
return -1;
}
int tail = _next.match(string, strlen, offset, state);
if (tail >= 0) {
return tail;
}
if (i + 1 < _head._max) {
state._loopCount[_index] = i + 1;
state._loopOffset[_index] = offset;
tail = _head._node.match(string, strlen, offset, state);
state._loopCount[_index] = i;
state._loopOffset[_index] = oldOffset;
return tail;
} else {
return -1;
}
}
@Override
public String toString() {
return "LoopTailUngreedy[" + _next + "]";
}
}
static class Not extends RegexpNode {
private RegexpNode _node;
private Not(RegexpNode node) {
_node = node;
}
static Not create(RegexpNode node) {
return new Not(node);
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
int result = _node.match(string, strlen, offset, state);
if (result >= 0) {
return -1;
} else {
return offset + 1;
}
}
}
final static class Or extends RegexpNode {
private final RegexpNode _left;
private Or _right;
private Or(RegexpNode left, Or right) {
_left = left;
_right = right;
}
static Or create(RegexpNode left, RegexpNode right) {
if (left instanceof Or) {
return ((Or) left).append(right);
} else if (right instanceof Or) {
return new Or(left, (Or) right);
} else {
return new Or(left, new Or(right, null));
}
}
private Or append(RegexpNode right) {
if (_right != null) {
_right = _right.append(right);
} else if (right instanceof Or) {
_right = (Or) right;
} else {
_right = new Or(right, null);
}
return this;
}
@Override
int minLength() {
if (_right != null) {
return Math.min(_left.minLength(), _right.minLength());
} else {
return _left.minLength();
}
}
@Override
int firstChar() {
if (_right == null) {
return _left.firstChar();
}
int leftChar = _left.firstChar();
int rightChar = _right.firstChar();
if (leftChar == rightChar) {
return leftChar;
} else {
return -1;
}
}
@Override
boolean[] firstSet(boolean[] firstSet) {
if (_right == null) {
return _left.firstSet(firstSet);
}
firstSet = _left.firstSet(firstSet);
firstSet = _right.firstSet(firstSet);
return firstSet;
}
@Override
boolean isAnchorBegin() {
return _left.isAnchorBegin() && _right != null && _right.isAnchorBegin();
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
for (Or ptr = this; ptr != null; ptr = ptr._right) {
int value = ptr._left.match(string, strlen, offset, state);
if (value >= 0) {
return value;
}
}
return -1;
}
@Override
protected void toString(StringBuilder sb, Map<RegexpNode, Integer> map) {
if (toStringAdd(sb, map)) {
return;
}
sb.append(toStringName());
sb.append("[");
_left.toString(sb, map);
for (Or ptr = _right; ptr != null; ptr = ptr._right) {
sb.append(",");
ptr._left.toString(sb, map);
}
sb.append("]");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Or[");
sb.append(_left);
for (Or ptr = _right; ptr != null; ptr = ptr._right) {
sb.append(",");
sb.append(ptr._left);
}
sb.append("]");
return sb.toString();
}
}
static class PossessiveLoop extends RegexpNode {
private final RegexpNode _node;
private RegexpNode _next = N_END;
private int _min;
private int _max;
PossessiveLoop(RegexpNode node, int min, int max) {
_node = node.getHead();
_min = min;
_max = max;
}
@Override
RegexpNode concat(RegexpNode next) {
if (next == null) {
throw new NullPointerException();
}
if (_next != null) {
_next = _next.concat(next);
} else {
_next = next;
}
return this;
}
@Override
RegexpNode createLoop(Regcomp parser, int min, int max) {
if (min == 0 && max == 1) {
_min = 0;
return this;
} else {
return new LoopHead(parser, this, min, max);
}
}
//
// match functions
//
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
RegexpNode node = _node;
int min = _min;
int max = _max;
int i;
for (i = 0; i < min; i++) {
offset = node.match(string, strlen, offset, state);
if (offset < 0) {
return -1;
}
}
for (; i < max; i++) {
int tail = node.match(string, strlen, offset, state);
if (tail < 0 || tail == offset) {
return _next.match(string, strlen, offset, state);
}
offset = tail;
}
return _next.match(string, strlen, offset, state);
}
@Override
public String toString() {
return "PossessiveLoop[" + _min + ", "
+ _max + ", " + _node + ", " + _next + "]";
}
}
static final PropC PROP_C = new PropC();
static final PropNotC PROP_NOT_C = new PropNotC();
static final Prop PROP_Cc = new Prop(Character.CONTROL);
static final PropNot PROP_NOT_Cc = new PropNot(Character.CONTROL);
static final Prop PROP_Cf = new Prop(Character.FORMAT);
static final PropNot PROP_NOT_Cf = new PropNot(Character.FORMAT);
static final Prop PROP_Cn = new Prop(Character.UNASSIGNED);
static final PropNot PROP_NOT_Cn = new PropNot(Character.UNASSIGNED);
static final Prop PROP_Co = new Prop(Character.PRIVATE_USE);
static final PropNot PROP_NOT_Co = new PropNot(Character.PRIVATE_USE);
static final Prop PROP_Cs = new Prop(Character.SURROGATE);
static final PropNot PROP_NOT_Cs = new PropNot(Character.SURROGATE);
static final PropL PROP_L = new PropL();
static final PropNotL PROP_NOT_L = new PropNotL();
static final Prop PROP_Ll = new Prop(Character.LOWERCASE_LETTER);
static final PropNot PROP_NOT_Ll = new PropNot(Character.LOWERCASE_LETTER);
static final Prop PROP_Lm = new Prop(Character.MODIFIER_LETTER);
static final PropNot PROP_NOT_Lm = new PropNot(Character.MODIFIER_LETTER);
static final Prop PROP_Lo = new Prop(Character.OTHER_LETTER);
static final PropNot PROP_NOT_Lo = new PropNot(Character.OTHER_LETTER);
static final Prop PROP_Lt = new Prop(Character.TITLECASE_LETTER);
static final PropNot PROP_NOT_Lt = new PropNot(Character.TITLECASE_LETTER);
static final Prop PROP_Lu = new Prop(Character.UPPERCASE_LETTER);
static final PropNot PROP_NOT_Lu = new PropNot(Character.UPPERCASE_LETTER);
static final PropM PROP_M = new PropM();
static final PropNotM PROP_NOT_M = new PropNotM();
static final Prop PROP_Mc = new Prop(Character.COMBINING_SPACING_MARK);
static final PropNot PROP_NOT_Mc = new PropNot(Character.COMBINING_SPACING_MARK);
static final Prop PROP_Me = new Prop(Character.ENCLOSING_MARK);
static final PropNot PROP_NOT_Me = new PropNot(Character.ENCLOSING_MARK);
static final Prop PROP_Mn = new Prop(Character.NON_SPACING_MARK);
static final PropNot PROP_NOT_Mn = new PropNot(Character.NON_SPACING_MARK);
static final PropN PROP_N = new PropN();
static final PropNotN PROP_NOT_N = new PropNotN();
static final Prop PROP_Nd = new Prop(Character.DECIMAL_DIGIT_NUMBER);
static final PropNot PROP_NOT_Nd = new PropNot(Character.DECIMAL_DIGIT_NUMBER);
static final Prop PROP_Nl = new Prop(Character.LETTER_NUMBER);
static final PropNot PROP_NOT_Nl = new PropNot(Character.LETTER_NUMBER);
static final Prop PROP_No = new Prop(Character.OTHER_NUMBER);
static final PropNot PROP_NOT_No = new PropNot(Character.OTHER_NUMBER);
static final PropP PROP_P = new PropP();
static final PropNotP PROP_NOT_P = new PropNotP();
static final Prop PROP_Pc = new Prop(Character.CONNECTOR_PUNCTUATION);
static final PropNot PROP_NOT_Pc = new PropNot(Character.CONNECTOR_PUNCTUATION);
static final Prop PROP_Pd = new Prop(Character.DASH_PUNCTUATION);
static final PropNot PROP_NOT_Pd = new PropNot(Character.DASH_PUNCTUATION);
static final Prop PROP_Pe = new Prop(Character.END_PUNCTUATION);
static final PropNot PROP_NOT_Pe = new PropNot(Character.END_PUNCTUATION);
static final Prop PROP_Pf = new Prop(Character.FINAL_QUOTE_PUNCTUATION);
static final PropNot PROP_NOT_Pf = new PropNot(Character.FINAL_QUOTE_PUNCTUATION);
static final Prop PROP_Pi = new Prop(Character.INITIAL_QUOTE_PUNCTUATION);
static final PropNot PROP_NOT_Pi = new PropNot(Character.INITIAL_QUOTE_PUNCTUATION);
static final Prop PROP_Po = new Prop(Character.OTHER_PUNCTUATION);
static final PropNot PROP_NOT_Po = new PropNot(Character.OTHER_PUNCTUATION);
static final Prop PROP_Ps = new Prop(Character.START_PUNCTUATION);
static final PropNot PROP_NOT_Ps = new PropNot(Character.START_PUNCTUATION);
static final PropS PROP_S = new PropS();
static final PropNotS PROP_NOT_S = new PropNotS();
static final Prop PROP_Sc = new Prop(Character.CURRENCY_SYMBOL);
static final PropNot PROP_NOT_Sc = new PropNot(Character.CURRENCY_SYMBOL);
static final Prop PROP_Sk = new Prop(Character.MODIFIER_SYMBOL);
static final PropNot PROP_NOT_Sk = new PropNot(Character.MODIFIER_SYMBOL);
static final Prop PROP_Sm = new Prop(Character.MATH_SYMBOL);
static final PropNot PROP_NOT_Sm = new PropNot(Character.MATH_SYMBOL);
static final Prop PROP_So = new Prop(Character.OTHER_SYMBOL);
static final PropNot PROP_NOT_So = new PropNot(Character.OTHER_SYMBOL);
static final PropZ PROP_Z = new PropZ();
static final PropNotZ PROP_NOT_Z = new PropNotZ();
static final Prop PROP_Zl = new Prop(Character.LINE_SEPARATOR);
static final PropNot PROP_NOT_Zl = new PropNot(Character.LINE_SEPARATOR);
static final Prop PROP_Zp = new Prop(Character.PARAGRAPH_SEPARATOR);
static final PropNot PROP_NOT_Zp = new PropNot(Character.PARAGRAPH_SEPARATOR);
static final Prop PROP_Zs = new Prop(Character.SPACE_SEPARATOR);
static final PropNot PROP_NOT_Zs = new PropNot(Character.SPACE_SEPARATOR);
private static class Prop extends AbstractCharNode {
private final int _category;
Prop(int category) {
_category = category;
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
if (Character.getType(ch) == _category) {
return offset + 1;
}
}
return -1;
}
}
private static class PropNot extends AbstractCharNode {
private final int _category;
PropNot(int category) {
_category = category;
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
if (Character.getType(ch) != _category) {
return offset + 1;
}
}
return -1;
}
}
static class PropC extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.CONTROL
|| value == Character.FORMAT
|| value == Character.UNASSIGNED
|| value == Character.PRIVATE_USE
|| value == Character.SURROGATE) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotC extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.CONTROL
|| value == Character.FORMAT
|| value == Character.UNASSIGNED
|| value == Character.PRIVATE_USE
|| value == Character.SURROGATE)) {
return offset + 1;
}
}
return -1;
}
}
static class PropL extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.LOWERCASE_LETTER
|| value == Character.MODIFIER_LETTER
|| value == Character.OTHER_LETTER
|| value == Character.TITLECASE_LETTER
|| value == Character.UPPERCASE_LETTER) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotL extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.LOWERCASE_LETTER
|| value == Character.MODIFIER_LETTER
|| value == Character.OTHER_LETTER
|| value == Character.TITLECASE_LETTER
|| value == Character.UPPERCASE_LETTER)) {
return offset + 1;
}
}
return -1;
}
}
static class PropM extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.COMBINING_SPACING_MARK
|| value == Character.ENCLOSING_MARK
|| value == Character.NON_SPACING_MARK) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotM extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.COMBINING_SPACING_MARK
|| value == Character.ENCLOSING_MARK
|| value == Character.NON_SPACING_MARK)) {
return offset + 1;
}
}
return -1;
}
}
static class PropN extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.DECIMAL_DIGIT_NUMBER
|| value == Character.LETTER_NUMBER
|| value == Character.OTHER_NUMBER) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotN extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.DECIMAL_DIGIT_NUMBER
|| value == Character.LETTER_NUMBER
|| value == Character.OTHER_NUMBER)) {
return offset + 1;
}
}
return -1;
}
}
static class PropP extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.CONNECTOR_PUNCTUATION
|| value == Character.DASH_PUNCTUATION
|| value == Character.END_PUNCTUATION
|| value == Character.FINAL_QUOTE_PUNCTUATION
|| value == Character.INITIAL_QUOTE_PUNCTUATION
|| value == Character.OTHER_PUNCTUATION
|| value == Character.START_PUNCTUATION) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotP extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.CONNECTOR_PUNCTUATION
|| value == Character.DASH_PUNCTUATION
|| value == Character.END_PUNCTUATION
|| value == Character.FINAL_QUOTE_PUNCTUATION
|| value == Character.INITIAL_QUOTE_PUNCTUATION
|| value == Character.OTHER_PUNCTUATION
|| value == Character.START_PUNCTUATION)) {
return offset + 1;
}
}
return -1;
}
}
static class PropS extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.CURRENCY_SYMBOL
|| value == Character.MODIFIER_SYMBOL
|| value == Character.MATH_SYMBOL
|| value == Character.OTHER_SYMBOL) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotS extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.CURRENCY_SYMBOL
|| value == Character.MODIFIER_SYMBOL
|| value == Character.MATH_SYMBOL
|| value == Character.OTHER_SYMBOL)) {
return offset + 1;
}
}
return -1;
}
}
static class PropZ extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (value == Character.LINE_SEPARATOR
|| value == Character.PARAGRAPH_SEPARATOR
|| value == Character.SPACE_SEPARATOR) {
return offset + 1;
}
}
return -1;
}
}
static class PropNotZ extends AbstractCharNode {
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (offset < strlen) {
char ch = string.charAt(offset);
int value = Character.getType(ch);
if (!(value == Character.LINE_SEPARATOR
|| value == Character.PARAGRAPH_SEPARATOR
|| value == Character.SPACE_SEPARATOR)) {
return offset + 1;
}
}
return -1;
}
}
static class Recursive extends RegexpNode {
private RegexpNode _top;
Recursive() {
}
void setTop(RegexpNode top) {
_top = top;
}
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
return _top.match(string, length, offset, state);
}
}
static class Set extends AbstractCharNode {
private final boolean[] _asciiSet;
private final IntSet _range;
Set(boolean[] set, IntSet range) {
_asciiSet = set;
_range = range;
}
@Override
int match(StringValue string, int strlen, int offset, RegexpState state) {
if (strlen <= offset) {
return -1;
}
char ch = string.charAt(offset++);
if (ch < 128) {
return _asciiSet[ch] ? offset : -1;
}
int codePoint = ch;
if ('\uD800' <= ch && ch <= '\uDBFF' && offset < strlen) {
|
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 RegexpNode {
// ... ~10,000 lines omitted for brevity
public static final int FAIL = -1;
public static final int SUCCESS = 0;
// ... ~10,000 lines omitted for brevity
public static final RegexpNode N_END = new End();
// ... ~10,000 lines omitted for brevity
public static class CharNode extends AbstractCharNode {
// ... ~10,000 lines omitted for brevity
@Override
int match(StringValue string, int length, int offset, RegexpState state) {
if (offset < length && string.charAt(offset) == _ch) {
return offset + 1;
} else {
return -1;
}
}
// ... ~10,000 lines omitted for brevity
}
// ... ~10,000 lines omitted for brevity
public static class RegexpState {
// ... ~10,000 lines omitted for brevity
public int getBegin(int group) {
// ... ~10,000 lines omitted for brevity
}
public void setBegin(int group, int begin) {
// ... ~10,000 lines omitted for brevity
}
public int getEnd(int group) {
// ... ~10,000 lines omitted for brevity
}
public void setEnd(int group, int end) {
// ... ~10,000 lines omitted for brevity
}
public int getLength() {
// ... ~10,000 lines omitted for brevity
}
public void setLength(int length) {
// ... ~10,000 lines omitted for brevity
}
// ... ~10,000 lines omitted for brevity
}
// ... ~10,000 lines omitted for brevity
}
Cheatsheet (for next line):
- We are in the match() method of a RegexpNode subclass (e.g., CharNode).
- The method takes four parameters: string, length, offset, and state.
- The method should return the index of the matched character or -1 if no match is found.
- The state object has methods to get and set the begin and end indices of a group, as well as the length of the string.
- The current implementation of match() in CharNode returns -1 if the character at the current offset does not match the character _ch.
- The next line should likely return the index of the matched character or -1 if no match is found.
Next line will likely be: return offset + 1;
|
|
Please complete the code given below.
/**
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* The Original Code is OpenELIS code.
*
* Copyright (C) The Minnesota Department of Health. All Rights Reserved.
*
* Contributor(s): CIRG, University of Washington, Seattle WA.
*/
package us.mn.state.health.lims.common.provider.validation;
import static us.mn.state.health.lims.common.provider.validation.IAccessionNumberValidator.ValidationResults.PATIENT_STATUS_FAIL;
import static us.mn.state.health.lims.common.provider.validation.IAccessionNumberValidator.ValidationResults.SAMPLE_FOUND;
import static us.mn.state.health.lims.common.provider.validation.IAccessionNumberValidator.ValidationResults.SAMPLE_STATUS_FAIL;
import java.util.List;
import org.apache.commons.validator.GenericValidator;
import us.mn.state.health.lims.common.action.IActionConstants;
import us.mn.state.health.lims.common.services.StatusService;
import us.mn.state.health.lims.common.services.StatusService.RecordStatus;
import us.mn.state.health.lims.common.services.StatusSet;
import us.mn.state.health.lims.common.util.StringUtil;
import us.mn.state.health.lims.observationhistory.dao.ObservationHistoryDAO;
import us.mn.state.health.lims.observationhistory.daoimpl.ObservationHistoryDAOImpl;
import us.mn.state.health.lims.observationhistory.valueholder.ObservationHistory;
import us.mn.state.health.lims.observationhistorytype.ObservationHistoryTypeMap;
import us.mn.state.health.lims.patient.valueholder.Patient;
import us.mn.state.health.lims.project.dao.ProjectDAO;
import us.mn.state.health.lims.project.daoimpl.ProjectDAOImpl;
import us.mn.state.health.lims.project.valueholder.Project;
import us.mn.state.health.lims.sample.dao.SampleDAO;
import us.mn.state.health.lims.sample.daoimpl.SampleDAOImpl;
import us.mn.state.health.lims.sample.util.AccessionNumberUtil;
import us.mn.state.health.lims.sample.valueholder.Sample;
public class ProgramAccessionValidator implements IAccessionNumberValidator {
private static final String INCREMENT_STARTING_VALUE = "00001";
private static final int UPPER_INC_RANGE = 99999;
private static final int INCREMENT_START = 4;
private static final int PROGRAM_START = 0;
private static final int PROGRAM_END = 4;
private static final int LENGTH = 9;
private static final boolean NEED_PROGRAM_CODE = true;
private static ProjectDAO projectDAO;
public boolean needProgramCode() {
return NEED_PROGRAM_CODE;
}
public String createFirstAccessionNumber(String programCode) {
return programCode + INCREMENT_STARTING_VALUE;
}
public String incrementAccessionNumber(String currentHighAccessionNumber) {
int increment = Integer.parseInt(currentHighAccessionNumber.substring(INCREMENT_START));
String incrementAsString = INCREMENT_STARTING_VALUE;
if( increment < UPPER_INC_RANGE){
increment++;
incrementAsString = String.format("%05d", increment);
}else{
throw new IllegalArgumentException("AccessionNumber has no next value");
}
StringBuilder builder = new StringBuilder( currentHighAccessionNumber.substring(PROGRAM_START, PROGRAM_END).toUpperCase());
builder.append(incrementAsString);
return builder.toString();
}
public ValidationResults validFormat(String accessionNumber, boolean checkDate) {
// The rule is 4 digit program code and 4 incremented numbers
if (accessionNumber.length() != LENGTH) {
return ValidationResults.LENGTH_FAIL;
}
String programCode = accessionNumber.substring(PROGRAM_START, PROGRAM_END).toUpperCase();
//check program code validity
ProjectDAO projectDAO = getProjectDAO();
List<Project> programCodes = projectDAO.getAllProjects();
boolean found = false;
for ( Project code: programCodes ){
if ( programCode.equals(code.getProgramCode())){
found = true;
break;
}
}
if ( !found ) {
return ValidationResults.PROGRAM_FAIL;
}
try {
Integer.parseInt(accessionNumber.substring(INCREMENT_START));
} catch (NumberFormatException e) {
return ValidationResults.FORMAT_FAIL;
}
return ValidationResults.SUCCESS;
}
public String getInvalidMessage(ValidationResults results){
switch(results){
case LENGTH_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.length");
case USED_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.used");
case PROGRAM_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.program");
case FORMAT_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.format");
case REQUIRED_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.required");
case PATIENT_STATUS_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.patientRecordStatus");
case SAMPLE_STATUS_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.sampleRecordStatus");
default: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number");
}
}
public String getInvalidFormatMessage( ValidationResults results ){
return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.format");
}
public String getNextAvailableAccessionNumber(String prefix){
String nextAccessionNumber = null;
SampleDAO sampleDAO = new SampleDAOImpl();
String curLargestAccessionNumber = sampleDAO.getLargestAccessionNumberWithPrefix(prefix);
if( curLargestAccessionNumber == null){
nextAccessionNumber = createFirstAccessionNumber(prefix);
}else{
nextAccessionNumber = incrementAccessionNumber(curLargestAccessionNumber);
}
return nextAccessionNumber;
}
public boolean accessionNumberIsUsed(String accessionNumber, String recordType) {
boolean accessionNumberUsed = new SampleDAOImpl().getSampleByAccessionNumber(accessionNumber) != null;
if( recordType == null){
return accessionNumberUsed;
}
StatusSet statusSet = StatusService.getInstance().getStatusSetForAccessionNumber(accessionNumber);
String recordStatus = new String();
boolean isSampleEntry = recordType.contains("Sample");
boolean isPatientEntry = recordType.contains("Patient");
boolean isInitial = recordType.contains("initial");
boolean isDouble = recordType.contains("double");
if (accessionNumberUsed) {
// sample entry, get SampleRecordStatus
if (isSampleEntry){
recordStatus = statusSet.getSampleRecordStatus().toString();
}
// patient entry, get PatientRecordStatus
else if (isPatientEntry) {
recordStatus = statusSet.getPatientRecordStatus().toString();
}
// initial entry, the status must be NotRegistered
String notRegistered = RecordStatus.NotRegistered.toString();
String initialReg = RecordStatus.InitialRegistration.toString();
if (isInitial){
if(!notRegistered.equals(recordStatus) ){
return true;
}
}
// double entry, the status must be InitialRegistration
else if (isDouble) {
if ( !initialReg.equals(recordStatus) ) {
return false;
}
else {
return true;
}
}
}
return false;
}
public int getMaxAccessionLength() {
return LENGTH;
}
/**
* There are many possible samples with various status, only some of which are valid during certain entry steps.
* This method provides validation results identifying whether a given sample is appropriate given all the information.
* @param accessionNumber the number for the sample
* @param recordType initialPatient, initialSample, doublePatient (double entry for patient), doubleSample
* @param isRequired the step being done expects the sample to exist. This is used generate appropriate results, either
* REQUIRED_FAIL vs SAMPLE_NOT_FOUND
* @param studyFormName - an additional
* @return
*/
public ValidationResults checkAccessionNumberValidity(String accessionNumber, String recordType,
String isRequired, String studyFormName) {
ValidationResults results = validFormat(accessionNumber, true);
SampleDAO sampleDAO = new SampleDAOImpl();
boolean accessionUsed = (sampleDAO.getSampleByAccessionNumber(accessionNumber) != null);
if (results == ValidationResults.SUCCESS) {
if (IActionConstants.TRUE.equals(isRequired) && !accessionUsed) {
results = ValidationResults.REQUIRED_FAIL;
return results;
} else {
if (recordType == null) {
results = ValidationResults.USED_FAIL;
}
// record Type specified, so work out the detailed response to report
if (accessionUsed) {
if (recordType.contains("initial")) {
if (recordType.contains("Patient")) {
results = AccessionNumberUtil.isPatientStatusValid(accessionNumber,
RecordStatus.NotRegistered);
if (results != PATIENT_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, false);
}
} else if (recordType.contains("Sample")) {
results = AccessionNumberUtil.isSampleStatusValid(accessionNumber,
RecordStatus.NotRegistered);
if (results != SAMPLE_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, false);
}
}
} else if (recordType.contains("double")) {
if (recordType.contains("Patient")) {
results = AccessionNumberUtil.isPatientStatusValid(accessionNumber,
RecordStatus.InitialRegistration);
if (results != PATIENT_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, true);
}
} else if (recordType.contains("Sample")) {
results = AccessionNumberUtil.isSampleStatusValid(accessionNumber,
RecordStatus.InitialRegistration);
if (results != SAMPLE_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, true);
}
}
} else if (recordType.contains("orderModify")) {
results = ValidationResults.USED_FAIL;
}
} else {
if (recordType.contains("initial")) {
results = ValidationResults.SAMPLE_NOT_FOUND; // initial entry not used is good
} else if (recordType.contains("double")) {
results = ValidationResults.REQUIRED_FAIL; // double entry not existing is a
// problem
} else if (recordType.contains("orderModify")) {
results = ValidationResults.SAMPLE_NOT_FOUND; // modify order page
}
}
}
}
return results;
}
/**
* Can the existing accession number be used in the given form?
* This method is useful when we have an existing accessionNumber and want to ask the question.
* @param accessionNumber
* @param existingRequired true => it is required that there is an existing studyFormName?
* @return
*/
private static ValidationResults matchExistingStudyFormName(String accessionNumber, String studyFormName, boolean existingRequired) {
|
[
" if (GenericValidator.isBlankOrNull(studyFormName)) {"
] | 945
|
lcc
|
java
| null |
5d56dd41743ce710c9b0986b24ec730ba947774b15696336
| 55
|
Your task is code completion.
/**
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* The Original Code is OpenELIS code.
*
* Copyright (C) The Minnesota Department of Health. All Rights Reserved.
*
* Contributor(s): CIRG, University of Washington, Seattle WA.
*/
package us.mn.state.health.lims.common.provider.validation;
import static us.mn.state.health.lims.common.provider.validation.IAccessionNumberValidator.ValidationResults.PATIENT_STATUS_FAIL;
import static us.mn.state.health.lims.common.provider.validation.IAccessionNumberValidator.ValidationResults.SAMPLE_FOUND;
import static us.mn.state.health.lims.common.provider.validation.IAccessionNumberValidator.ValidationResults.SAMPLE_STATUS_FAIL;
import java.util.List;
import org.apache.commons.validator.GenericValidator;
import us.mn.state.health.lims.common.action.IActionConstants;
import us.mn.state.health.lims.common.services.StatusService;
import us.mn.state.health.lims.common.services.StatusService.RecordStatus;
import us.mn.state.health.lims.common.services.StatusSet;
import us.mn.state.health.lims.common.util.StringUtil;
import us.mn.state.health.lims.observationhistory.dao.ObservationHistoryDAO;
import us.mn.state.health.lims.observationhistory.daoimpl.ObservationHistoryDAOImpl;
import us.mn.state.health.lims.observationhistory.valueholder.ObservationHistory;
import us.mn.state.health.lims.observationhistorytype.ObservationHistoryTypeMap;
import us.mn.state.health.lims.patient.valueholder.Patient;
import us.mn.state.health.lims.project.dao.ProjectDAO;
import us.mn.state.health.lims.project.daoimpl.ProjectDAOImpl;
import us.mn.state.health.lims.project.valueholder.Project;
import us.mn.state.health.lims.sample.dao.SampleDAO;
import us.mn.state.health.lims.sample.daoimpl.SampleDAOImpl;
import us.mn.state.health.lims.sample.util.AccessionNumberUtil;
import us.mn.state.health.lims.sample.valueholder.Sample;
public class ProgramAccessionValidator implements IAccessionNumberValidator {
private static final String INCREMENT_STARTING_VALUE = "00001";
private static final int UPPER_INC_RANGE = 99999;
private static final int INCREMENT_START = 4;
private static final int PROGRAM_START = 0;
private static final int PROGRAM_END = 4;
private static final int LENGTH = 9;
private static final boolean NEED_PROGRAM_CODE = true;
private static ProjectDAO projectDAO;
public boolean needProgramCode() {
return NEED_PROGRAM_CODE;
}
public String createFirstAccessionNumber(String programCode) {
return programCode + INCREMENT_STARTING_VALUE;
}
public String incrementAccessionNumber(String currentHighAccessionNumber) {
int increment = Integer.parseInt(currentHighAccessionNumber.substring(INCREMENT_START));
String incrementAsString = INCREMENT_STARTING_VALUE;
if( increment < UPPER_INC_RANGE){
increment++;
incrementAsString = String.format("%05d", increment);
}else{
throw new IllegalArgumentException("AccessionNumber has no next value");
}
StringBuilder builder = new StringBuilder( currentHighAccessionNumber.substring(PROGRAM_START, PROGRAM_END).toUpperCase());
builder.append(incrementAsString);
return builder.toString();
}
public ValidationResults validFormat(String accessionNumber, boolean checkDate) {
// The rule is 4 digit program code and 4 incremented numbers
if (accessionNumber.length() != LENGTH) {
return ValidationResults.LENGTH_FAIL;
}
String programCode = accessionNumber.substring(PROGRAM_START, PROGRAM_END).toUpperCase();
//check program code validity
ProjectDAO projectDAO = getProjectDAO();
List<Project> programCodes = projectDAO.getAllProjects();
boolean found = false;
for ( Project code: programCodes ){
if ( programCode.equals(code.getProgramCode())){
found = true;
break;
}
}
if ( !found ) {
return ValidationResults.PROGRAM_FAIL;
}
try {
Integer.parseInt(accessionNumber.substring(INCREMENT_START));
} catch (NumberFormatException e) {
return ValidationResults.FORMAT_FAIL;
}
return ValidationResults.SUCCESS;
}
public String getInvalidMessage(ValidationResults results){
switch(results){
case LENGTH_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.length");
case USED_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.used");
case PROGRAM_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.program");
case FORMAT_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.format");
case REQUIRED_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.required");
case PATIENT_STATUS_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.patientRecordStatus");
case SAMPLE_STATUS_FAIL: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.sampleRecordStatus");
default: return StringUtil.getMessageForKey("sample.entry.invalid.accession.number");
}
}
public String getInvalidFormatMessage( ValidationResults results ){
return StringUtil.getMessageForKey("sample.entry.invalid.accession.number.format");
}
public String getNextAvailableAccessionNumber(String prefix){
String nextAccessionNumber = null;
SampleDAO sampleDAO = new SampleDAOImpl();
String curLargestAccessionNumber = sampleDAO.getLargestAccessionNumberWithPrefix(prefix);
if( curLargestAccessionNumber == null){
nextAccessionNumber = createFirstAccessionNumber(prefix);
}else{
nextAccessionNumber = incrementAccessionNumber(curLargestAccessionNumber);
}
return nextAccessionNumber;
}
public boolean accessionNumberIsUsed(String accessionNumber, String recordType) {
boolean accessionNumberUsed = new SampleDAOImpl().getSampleByAccessionNumber(accessionNumber) != null;
if( recordType == null){
return accessionNumberUsed;
}
StatusSet statusSet = StatusService.getInstance().getStatusSetForAccessionNumber(accessionNumber);
String recordStatus = new String();
boolean isSampleEntry = recordType.contains("Sample");
boolean isPatientEntry = recordType.contains("Patient");
boolean isInitial = recordType.contains("initial");
boolean isDouble = recordType.contains("double");
if (accessionNumberUsed) {
// sample entry, get SampleRecordStatus
if (isSampleEntry){
recordStatus = statusSet.getSampleRecordStatus().toString();
}
// patient entry, get PatientRecordStatus
else if (isPatientEntry) {
recordStatus = statusSet.getPatientRecordStatus().toString();
}
// initial entry, the status must be NotRegistered
String notRegistered = RecordStatus.NotRegistered.toString();
String initialReg = RecordStatus.InitialRegistration.toString();
if (isInitial){
if(!notRegistered.equals(recordStatus) ){
return true;
}
}
// double entry, the status must be InitialRegistration
else if (isDouble) {
if ( !initialReg.equals(recordStatus) ) {
return false;
}
else {
return true;
}
}
}
return false;
}
public int getMaxAccessionLength() {
return LENGTH;
}
/**
* There are many possible samples with various status, only some of which are valid during certain entry steps.
* This method provides validation results identifying whether a given sample is appropriate given all the information.
* @param accessionNumber the number for the sample
* @param recordType initialPatient, initialSample, doublePatient (double entry for patient), doubleSample
* @param isRequired the step being done expects the sample to exist. This is used generate appropriate results, either
* REQUIRED_FAIL vs SAMPLE_NOT_FOUND
* @param studyFormName - an additional
* @return
*/
public ValidationResults checkAccessionNumberValidity(String accessionNumber, String recordType,
String isRequired, String studyFormName) {
ValidationResults results = validFormat(accessionNumber, true);
SampleDAO sampleDAO = new SampleDAOImpl();
boolean accessionUsed = (sampleDAO.getSampleByAccessionNumber(accessionNumber) != null);
if (results == ValidationResults.SUCCESS) {
if (IActionConstants.TRUE.equals(isRequired) && !accessionUsed) {
results = ValidationResults.REQUIRED_FAIL;
return results;
} else {
if (recordType == null) {
results = ValidationResults.USED_FAIL;
}
// record Type specified, so work out the detailed response to report
if (accessionUsed) {
if (recordType.contains("initial")) {
if (recordType.contains("Patient")) {
results = AccessionNumberUtil.isPatientStatusValid(accessionNumber,
RecordStatus.NotRegistered);
if (results != PATIENT_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, false);
}
} else if (recordType.contains("Sample")) {
results = AccessionNumberUtil.isSampleStatusValid(accessionNumber,
RecordStatus.NotRegistered);
if (results != SAMPLE_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, false);
}
}
} else if (recordType.contains("double")) {
if (recordType.contains("Patient")) {
results = AccessionNumberUtil.isPatientStatusValid(accessionNumber,
RecordStatus.InitialRegistration);
if (results != PATIENT_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, true);
}
} else if (recordType.contains("Sample")) {
results = AccessionNumberUtil.isSampleStatusValid(accessionNumber,
RecordStatus.InitialRegistration);
if (results != SAMPLE_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, true);
}
}
} else if (recordType.contains("orderModify")) {
results = ValidationResults.USED_FAIL;
}
} else {
if (recordType.contains("initial")) {
results = ValidationResults.SAMPLE_NOT_FOUND; // initial entry not used is good
} else if (recordType.contains("double")) {
results = ValidationResults.REQUIRED_FAIL; // double entry not existing is a
// problem
} else if (recordType.contains("orderModify")) {
results = ValidationResults.SAMPLE_NOT_FOUND; // modify order page
}
}
}
}
return results;
}
/**
* Can the existing accession number be used in the given form?
* This method is useful when we have an existing accessionNumber and want to ask the question.
* @param accessionNumber
* @param existingRequired true => it is required that there is an existing studyFormName?
* @return
*/
private static ValidationResults matchExistingStudyFormName(String accessionNumber, String studyFormName, boolean existingRequired) {
|
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 ProgramAccessionValidator implements IAccessionNumberValidator {
// ... (many lines of code)
public ValidationResults checkAccessionNumberValidity(String accessionNumber, String recordType,
String isRequired, String studyFormName) {
// ... (many lines of code)
if (recordType.contains("initial")) {
if (recordType.contains("Patient")) {
results = AccessionNumberUtil.isPatientStatusValid(accessionNumber,
RecordStatus.NotRegistered);
if (results != PATIENT_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, false);
}
} else if (recordType.contains("Sample")) {
results = AccessionNumberUtil.isSampleStatusValid(accessionNumber,
RecordStatus.NotRegistered);
if (results != SAMPLE_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, false);
}
}
} else if (recordType.contains("double")) {
if (recordType.contains("Patient")) {
results = AccessionNumberUtil.isPatientStatusValid(accessionNumber,
RecordStatus.InitialRegistration);
if (results != PATIENT_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, true);
}
} else if (recordType.contains("Sample")) {
results = AccessionNumberUtil.isSampleStatusValid(accessionNumber,
RecordStatus.InitialRegistration);
if (results != SAMPLE_STATUS_FAIL) {
results = matchExistingStudyFormName(accessionNumber, studyFormName, true);
}
}
} else if (recordType.contains("orderModify")) {
results = ValidationResults.USED_FAIL;
}
}
/**
* Can the existing accession number be used in the given form?
* This method is useful when we have an existing accessionNumber and want to ask the question.
* @param accessionNumber
* @param existingRequired true => it is required that there is an existing studyFormName?
* @return
*/
private static ValidationResults matchExistingStudyFormName(String accessionNumber, String studyFormName, boolean existingRequired) {
// ... (many lines of code)
}
}
Cheatsheet (for next line):
- We are in matchExistingStudyFormName(), which is a private method of ProgramAccessionValidator.
- The method takes three parameters: accessionNumber, studyFormName, and existingRequired.
- The method is used to determine if an existing accession number can be used in a given form.
- The method returns a ValidationResults object.
- The existingRequired parameter is a boolean indicating whether it is required that there is an existing studyFormName.
- The method has a similar structure to checkAccessionNumberValidity(), which suggests that it may perform a similar validation.
- The method is called from checkAccessionNumberValidity() when the recordType is "initial" or "double".
- The method is also called from checkAccessionNumberValidity() when the recordType is "orderModify", but in this case, it returns USED_FAIL.
Next line will likely be:
- Since the method is called from checkAccessionNumberValidity() when the recordType is "initial" or "double", it should perform a similar validation to checkAccessionNumberValidity().
- The method should check if the existing studyFormName matches the studyFormName passed as a parameter.
- The method should return a ValidationResults object indicating whether the existing accession number can be used in the given form.
However, since the method is also called from checkAccessionNumberValidity() when the recordType is "orderModify", it should return USED_FAIL in this case.
So, the next line of code could be:
```java
if (existingRequired && !studyFormName.equals(studyFormName)) {
return ValidationResults.USED_FAIL;
}
```
But this is not the only possible solution. The exact implementation will depend on the specific requirements of the method.
|
|
Please complete the code given below.
#region Copyright & License Information
/*
* Copyright 2007-2017 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using OpenRA.Graphics;
using OpenRA.Network;
using OpenRA.Primitives;
using OpenRA.Support;
namespace OpenRA.Server
{
public enum ServerState
{
WaitingPlayers = 1,
GameStarted = 2,
ShuttingDown = 3
}
public class Server
{
public readonly string TwoHumansRequiredText = "This server requires at least two human players to start a match.";
public readonly IPAddress Ip;
public readonly int Port;
public readonly MersenneTwister Random = new MersenneTwister();
public readonly bool Dedicated;
// Valid player connections
public List<Connection> Conns = new List<Connection>();
// Pre-verified player connections
public List<Connection> PreConns = new List<Connection>();
public Session LobbyInfo;
public ServerSettings Settings;
public ModData ModData;
public List<string> TempBans = new List<string>();
// Managed by LobbyCommands
public MapPreview Map;
readonly int randomSeed;
readonly TcpListener listener;
readonly TypeDictionary serverTraits = new TypeDictionary();
protected volatile ServerState internalState = ServerState.WaitingPlayers;
public ServerState State
{
get { return internalState; }
protected set { internalState = value; }
}
public static void SyncClientToPlayerReference(Session.Client c, PlayerReference pr)
{
if (pr == null)
return;
if (pr.LockFaction)
c.Faction = pr.Faction;
if (pr.LockSpawn)
c.SpawnPoint = pr.Spawn;
if (pr.LockTeam)
c.Team = pr.Team;
c.Color = pr.LockColor ? pr.Color : c.PreferredColor;
}
static void SendData(Socket s, byte[] data)
{
var start = 0;
var length = data.Length;
// Non-blocking sends are free to send only part of the data
while (start < length)
{
SocketError error;
var sent = s.Send(data, start, length - start, SocketFlags.None, out error);
if (error == SocketError.WouldBlock)
{
Log.Write("server", "Non-blocking send of {0} bytes failed. Falling back to blocking send.", length - start);
s.Blocking = true;
sent = s.Send(data, start, length - start, SocketFlags.None);
s.Blocking = false;
}
else if (error != SocketError.Success)
throw new SocketException((int)error);
start += sent;
}
}
public void Shutdown()
{
State = ServerState.ShuttingDown;
}
public void EndGame()
{
foreach (var t in serverTraits.WithInterface<IEndGame>())
t.GameEnded(this);
}
public Server(IPEndPoint endpoint, ServerSettings settings, ModData modData, bool dedicated)
{
Log.AddChannel("server", "server.log");
listener = new TcpListener(endpoint);
listener.Start();
var localEndpoint = (IPEndPoint)listener.LocalEndpoint;
Ip = localEndpoint.Address;
Port = localEndpoint.Port;
Dedicated = dedicated;
Settings = settings;
Settings.Name = OpenRA.Settings.SanitizedServerName(Settings.Name);
ModData = modData;
randomSeed = (int)DateTime.Now.ToBinary();
if (UPnP.Status == UPnPStatus.Enabled)
UPnP.ForwardPort(Settings.ListenPort, Settings.ExternalPort).Wait();
foreach (var trait in modData.Manifest.ServerTraits)
serverTraits.Add(modData.ObjectCreator.CreateObject<ServerTrait>(trait));
LobbyInfo = new Session
{
GlobalSettings =
{
RandomSeed = randomSeed,
Map = settings.Map,
ServerName = settings.Name,
EnableSingleplayer = settings.EnableSingleplayer || !dedicated,
GameUid = Guid.NewGuid().ToString()
}
};
new Thread(_ =>
{
foreach (var t in serverTraits.WithInterface<INotifyServerStart>())
t.ServerStarted(this);
Log.Write("server", "Initial mod: {0}", ModData.Manifest.Id);
Log.Write("server", "Initial map: {0}", LobbyInfo.GlobalSettings.Map);
var timeout = serverTraits.WithInterface<ITick>().Min(t => t.TickTimeout);
for (;;)
{
var checkRead = new List<Socket>();
if (State == ServerState.WaitingPlayers)
checkRead.Add(listener.Server);
checkRead.AddRange(Conns.Select(c => c.Socket));
checkRead.AddRange(PreConns.Select(c => c.Socket));
if (checkRead.Count > 0)
Socket.Select(checkRead, null, null, timeout);
if (State == ServerState.ShuttingDown)
{
EndGame();
break;
}
foreach (var s in checkRead)
{
if (s == listener.Server)
{
AcceptConnection();
continue;
}
var preConn = PreConns.SingleOrDefault(c => c.Socket == s);
if (preConn != null)
{
preConn.ReadData(this);
continue;
}
var conn = Conns.SingleOrDefault(c => c.Socket == s);
if (conn != null)
conn.ReadData(this);
}
foreach (var t in serverTraits.WithInterface<ITick>())
t.Tick(this);
if (State == ServerState.ShuttingDown)
{
EndGame();
if (UPnP.Status == UPnPStatus.Enabled)
UPnP.RemovePortForward().Wait();
break;
}
}
foreach (var t in serverTraits.WithInterface<INotifyServerShutdown>())
t.ServerShutdown(this);
PreConns.Clear();
Conns.Clear();
try { listener.Stop(); }
catch { }
}) { IsBackground = true }.Start();
}
int nextPlayerIndex;
public int ChooseFreePlayerIndex()
{
return nextPlayerIndex++;
}
void AcceptConnection()
{
Socket newSocket;
try
{
if (!listener.Server.IsBound)
return;
newSocket = listener.AcceptSocket();
}
catch (Exception e)
{
/* TODO: Could have an exception here when listener 'goes away' when calling AcceptConnection! */
/* Alternative would be to use locking but the listener doesn't go away without a reason. */
Log.Write("server", "Accepting the connection failed.", e);
return;
}
var newConn = new Connection { Socket = newSocket };
try
{
newConn.Socket.Blocking = false;
newConn.Socket.NoDelay = true;
// assign the player number.
newConn.PlayerIndex = ChooseFreePlayerIndex();
SendData(newConn.Socket, BitConverter.GetBytes(ProtocolVersion.Version));
SendData(newConn.Socket, BitConverter.GetBytes(newConn.PlayerIndex));
PreConns.Add(newConn);
// Dispatch a handshake order
var request = new HandshakeRequest
{
Mod = ModData.Manifest.Id,
Version = ModData.Manifest.Metadata.Version,
Map = LobbyInfo.GlobalSettings.Map
};
DispatchOrdersToClient(newConn, 0, 0, new ServerOrder("HandshakeRequest", request.Serialize()).Serialize());
}
catch (Exception e)
{
DropClient(newConn);
Log.Write("server", "Dropping client {0} because handshake failed: {1}", newConn.PlayerIndex.ToString(CultureInfo.InvariantCulture), e);
}
}
void ValidateClient(Connection newConn, string data)
{
try
{
if (State == ServerState.GameStarted)
{
Log.Write("server", "Rejected connection from {0}; game is already started.",
newConn.Socket.RemoteEndPoint);
SendOrderTo(newConn, "ServerError", "The game has already started");
DropClient(newConn);
return;
}
var handshake = HandshakeResponse.Deserialize(data);
if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password)
{
var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password";
|
[
"\t\t\t\t\tSendOrderTo(newConn, \"AuthenticationError\", message);"
] | 807
|
lcc
|
csharp
| null |
cb8ef7b164c1f9b4d27225f6b8e45ea33c8096c073d82e27
| 56
|
Your task is code completion.
#region Copyright & License Information
/*
* Copyright 2007-2017 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using OpenRA.Graphics;
using OpenRA.Network;
using OpenRA.Primitives;
using OpenRA.Support;
namespace OpenRA.Server
{
public enum ServerState
{
WaitingPlayers = 1,
GameStarted = 2,
ShuttingDown = 3
}
public class Server
{
public readonly string TwoHumansRequiredText = "This server requires at least two human players to start a match.";
public readonly IPAddress Ip;
public readonly int Port;
public readonly MersenneTwister Random = new MersenneTwister();
public readonly bool Dedicated;
// Valid player connections
public List<Connection> Conns = new List<Connection>();
// Pre-verified player connections
public List<Connection> PreConns = new List<Connection>();
public Session LobbyInfo;
public ServerSettings Settings;
public ModData ModData;
public List<string> TempBans = new List<string>();
// Managed by LobbyCommands
public MapPreview Map;
readonly int randomSeed;
readonly TcpListener listener;
readonly TypeDictionary serverTraits = new TypeDictionary();
protected volatile ServerState internalState = ServerState.WaitingPlayers;
public ServerState State
{
get { return internalState; }
protected set { internalState = value; }
}
public static void SyncClientToPlayerReference(Session.Client c, PlayerReference pr)
{
if (pr == null)
return;
if (pr.LockFaction)
c.Faction = pr.Faction;
if (pr.LockSpawn)
c.SpawnPoint = pr.Spawn;
if (pr.LockTeam)
c.Team = pr.Team;
c.Color = pr.LockColor ? pr.Color : c.PreferredColor;
}
static void SendData(Socket s, byte[] data)
{
var start = 0;
var length = data.Length;
// Non-blocking sends are free to send only part of the data
while (start < length)
{
SocketError error;
var sent = s.Send(data, start, length - start, SocketFlags.None, out error);
if (error == SocketError.WouldBlock)
{
Log.Write("server", "Non-blocking send of {0} bytes failed. Falling back to blocking send.", length - start);
s.Blocking = true;
sent = s.Send(data, start, length - start, SocketFlags.None);
s.Blocking = false;
}
else if (error != SocketError.Success)
throw new SocketException((int)error);
start += sent;
}
}
public void Shutdown()
{
State = ServerState.ShuttingDown;
}
public void EndGame()
{
foreach (var t in serverTraits.WithInterface<IEndGame>())
t.GameEnded(this);
}
public Server(IPEndPoint endpoint, ServerSettings settings, ModData modData, bool dedicated)
{
Log.AddChannel("server", "server.log");
listener = new TcpListener(endpoint);
listener.Start();
var localEndpoint = (IPEndPoint)listener.LocalEndpoint;
Ip = localEndpoint.Address;
Port = localEndpoint.Port;
Dedicated = dedicated;
Settings = settings;
Settings.Name = OpenRA.Settings.SanitizedServerName(Settings.Name);
ModData = modData;
randomSeed = (int)DateTime.Now.ToBinary();
if (UPnP.Status == UPnPStatus.Enabled)
UPnP.ForwardPort(Settings.ListenPort, Settings.ExternalPort).Wait();
foreach (var trait in modData.Manifest.ServerTraits)
serverTraits.Add(modData.ObjectCreator.CreateObject<ServerTrait>(trait));
LobbyInfo = new Session
{
GlobalSettings =
{
RandomSeed = randomSeed,
Map = settings.Map,
ServerName = settings.Name,
EnableSingleplayer = settings.EnableSingleplayer || !dedicated,
GameUid = Guid.NewGuid().ToString()
}
};
new Thread(_ =>
{
foreach (var t in serverTraits.WithInterface<INotifyServerStart>())
t.ServerStarted(this);
Log.Write("server", "Initial mod: {0}", ModData.Manifest.Id);
Log.Write("server", "Initial map: {0}", LobbyInfo.GlobalSettings.Map);
var timeout = serverTraits.WithInterface<ITick>().Min(t => t.TickTimeout);
for (;;)
{
var checkRead = new List<Socket>();
if (State == ServerState.WaitingPlayers)
checkRead.Add(listener.Server);
checkRead.AddRange(Conns.Select(c => c.Socket));
checkRead.AddRange(PreConns.Select(c => c.Socket));
if (checkRead.Count > 0)
Socket.Select(checkRead, null, null, timeout);
if (State == ServerState.ShuttingDown)
{
EndGame();
break;
}
foreach (var s in checkRead)
{
if (s == listener.Server)
{
AcceptConnection();
continue;
}
var preConn = PreConns.SingleOrDefault(c => c.Socket == s);
if (preConn != null)
{
preConn.ReadData(this);
continue;
}
var conn = Conns.SingleOrDefault(c => c.Socket == s);
if (conn != null)
conn.ReadData(this);
}
foreach (var t in serverTraits.WithInterface<ITick>())
t.Tick(this);
if (State == ServerState.ShuttingDown)
{
EndGame();
if (UPnP.Status == UPnPStatus.Enabled)
UPnP.RemovePortForward().Wait();
break;
}
}
foreach (var t in serverTraits.WithInterface<INotifyServerShutdown>())
t.ServerShutdown(this);
PreConns.Clear();
Conns.Clear();
try { listener.Stop(); }
catch { }
}) { IsBackground = true }.Start();
}
int nextPlayerIndex;
public int ChooseFreePlayerIndex()
{
return nextPlayerIndex++;
}
void AcceptConnection()
{
Socket newSocket;
try
{
if (!listener.Server.IsBound)
return;
newSocket = listener.AcceptSocket();
}
catch (Exception e)
{
/* TODO: Could have an exception here when listener 'goes away' when calling AcceptConnection! */
/* Alternative would be to use locking but the listener doesn't go away without a reason. */
Log.Write("server", "Accepting the connection failed.", e);
return;
}
var newConn = new Connection { Socket = newSocket };
try
{
newConn.Socket.Blocking = false;
newConn.Socket.NoDelay = true;
// assign the player number.
newConn.PlayerIndex = ChooseFreePlayerIndex();
SendData(newConn.Socket, BitConverter.GetBytes(ProtocolVersion.Version));
SendData(newConn.Socket, BitConverter.GetBytes(newConn.PlayerIndex));
PreConns.Add(newConn);
// Dispatch a handshake order
var request = new HandshakeRequest
{
Mod = ModData.Manifest.Id,
Version = ModData.Manifest.Metadata.Version,
Map = LobbyInfo.GlobalSettings.Map
};
DispatchOrdersToClient(newConn, 0, 0, new ServerOrder("HandshakeRequest", request.Serialize()).Serialize());
}
catch (Exception e)
{
DropClient(newConn);
Log.Write("server", "Dropping client {0} because handshake failed: {1}", newConn.PlayerIndex.ToString(CultureInfo.InvariantCulture), e);
}
}
void ValidateClient(Connection newConn, string data)
{
try
{
if (State == ServerState.GameStarted)
{
Log.Write("server", "Rejected connection from {0}; game is already started.",
newConn.Socket.RemoteEndPoint);
SendOrderTo(newConn, "ServerError", "The game has already started");
DropClient(newConn);
return;
}
var handshake = HandshakeResponse.Deserialize(data);
if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password)
{
var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password";
|
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]
void ValidateClient(Connection newConn, string data)
{
try
{
if (State == ServerState.GameStarted)
{
Log.Write("server", "Rejected connection from {0}; game is already started.",
newConn.Socket.RemoteEndPoint);
SendOrderTo(newConn, "ServerError", "The game has already started");
DropClient(newConn);
return;
}
var handshake = HandshakeResponse.Deserialize(data);
if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password)
{
var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password";
Cheatsheet (for next line):
- We are in the ValidateClient method, which is validating a client connection.
- The client's password is being checked against the server's password.
- The handshake object has been deserialized from the client's data.
- The Settings object contains the server's password.
- The message variable contains the error message to be sent to the client.
- The client will be dropped if the password is incorrect.
- [Relevant lines: password check, message creation, DropClient call]
Next line will likely be: DropClient(newConn);
|
|
Please complete the code given below.
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to RefMan.CatsReferral business object (ID: 1004100035).
*/
public class CatsReferralPendingEmergencyNonEDAdmissionListVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<CatsReferralPendingEmergencyNonEDAdmissionListVo>, ims.vo.interfaces.IPendingAdmissionCollection
{
private static final long serialVersionUID = 1L;
private ArrayList<CatsReferralPendingEmergencyNonEDAdmissionListVo> col = new ArrayList<CatsReferralPendingEmergencyNonEDAdmissionListVo>();
public String getBoClassName()
{
return "ims.RefMan.domain.objects.CatsReferral";
}
public boolean add(CatsReferralPendingEmergencyNonEDAdmissionListVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, CatsReferralPendingEmergencyNonEDAdmissionListVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(CatsReferralPendingEmergencyNonEDAdmissionListVo instance)
{
return col.indexOf(instance);
}
public CatsReferralPendingEmergencyNonEDAdmissionListVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, CatsReferralPendingEmergencyNonEDAdmissionListVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(CatsReferralPendingEmergencyNonEDAdmissionListVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(CatsReferralPendingEmergencyNonEDAdmissionListVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
CatsReferralPendingEmergencyNonEDAdmissionListVoCollection clone = new CatsReferralPendingEmergencyNonEDAdmissionListVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((CatsReferralPendingEmergencyNonEDAdmissionListVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort(SortOrder order)
{
return sort(new CatsReferralPendingEmergencyNonEDAdmissionListVoComparator(order));
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new CatsReferralPendingEmergencyNonEDAdmissionListVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.RefMan.vo.CatsReferralRefVoCollection toRefVoCollection()
{
ims.RefMan.vo.CatsReferralRefVoCollection result = new ims.RefMan.vo.CatsReferralRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public CatsReferralPendingEmergencyNonEDAdmissionListVo[] toArray()
{
CatsReferralPendingEmergencyNonEDAdmissionListVo[] arr = new CatsReferralPendingEmergencyNonEDAdmissionListVo[col.size()];
col.toArray(arr);
return arr;
}
public ims.vo.interfaces.IPendingAdmission[] toIPendingAdmissionArray()
{
ims.vo.interfaces.IPendingAdmission[] arr = new ims.vo.interfaces.IPendingAdmission[col.size()];
col.toArray(arr);
return arr;
}
public ims.vo.interfaces.IPendingAdmissionDetails[] toIPendingAdmissionDetailsArray()
{
ims.vo.interfaces.IPendingAdmissionDetails[] arr = new ims.vo.interfaces.IPendingAdmissionDetails[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<CatsReferralPendingEmergencyNonEDAdmissionListVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class CatsReferralPendingEmergencyNonEDAdmissionListVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public CatsReferralPendingEmergencyNonEDAdmissionListVoComparator()
{
this(SortOrder.ASCENDING);
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
CatsReferralPendingEmergencyNonEDAdmissionListVo voObj1 = (CatsReferralPendingEmergencyNonEDAdmissionListVo)obj1;
CatsReferralPendingEmergencyNonEDAdmissionListVo voObj2 = (CatsReferralPendingEmergencyNonEDAdmissionListVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] getBeanCollectionArray()
{
ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] result = new ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
CatsReferralPendingEmergencyNonEDAdmissionListVo vo = ((CatsReferralPendingEmergencyNonEDAdmissionListVo)col.get(i));
result[i] = (ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean)vo.getBean();
}
return result;
}
public static CatsReferralPendingEmergencyNonEDAdmissionListVoCollection buildFromBeanCollection(java.util.Collection beans)
{
CatsReferralPendingEmergencyNonEDAdmissionListVoCollection coll = new CatsReferralPendingEmergencyNonEDAdmissionListVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean)iter.next()).buildVo());
}
return coll;
}
public static CatsReferralPendingEmergencyNonEDAdmissionListVoCollection buildFromBeanCollection(ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] beans)
{
CatsReferralPendingEmergencyNonEDAdmissionListVoCollection coll = new CatsReferralPendingEmergencyNonEDAdmissionListVoCollection();
|
[
"\t\tif(beans == null)"
] | 833
|
lcc
|
java
| null |
6e13c44c01f4116cb114d1ed362252ac9e0da0ef7331a74b
| 57
|
Your task is code completion.
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to RefMan.CatsReferral business object (ID: 1004100035).
*/
public class CatsReferralPendingEmergencyNonEDAdmissionListVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<CatsReferralPendingEmergencyNonEDAdmissionListVo>, ims.vo.interfaces.IPendingAdmissionCollection
{
private static final long serialVersionUID = 1L;
private ArrayList<CatsReferralPendingEmergencyNonEDAdmissionListVo> col = new ArrayList<CatsReferralPendingEmergencyNonEDAdmissionListVo>();
public String getBoClassName()
{
return "ims.RefMan.domain.objects.CatsReferral";
}
public boolean add(CatsReferralPendingEmergencyNonEDAdmissionListVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, CatsReferralPendingEmergencyNonEDAdmissionListVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(CatsReferralPendingEmergencyNonEDAdmissionListVo instance)
{
return col.indexOf(instance);
}
public CatsReferralPendingEmergencyNonEDAdmissionListVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, CatsReferralPendingEmergencyNonEDAdmissionListVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(CatsReferralPendingEmergencyNonEDAdmissionListVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(CatsReferralPendingEmergencyNonEDAdmissionListVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
CatsReferralPendingEmergencyNonEDAdmissionListVoCollection clone = new CatsReferralPendingEmergencyNonEDAdmissionListVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((CatsReferralPendingEmergencyNonEDAdmissionListVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort(SortOrder order)
{
return sort(new CatsReferralPendingEmergencyNonEDAdmissionListVoComparator(order));
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new CatsReferralPendingEmergencyNonEDAdmissionListVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public CatsReferralPendingEmergencyNonEDAdmissionListVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.RefMan.vo.CatsReferralRefVoCollection toRefVoCollection()
{
ims.RefMan.vo.CatsReferralRefVoCollection result = new ims.RefMan.vo.CatsReferralRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public CatsReferralPendingEmergencyNonEDAdmissionListVo[] toArray()
{
CatsReferralPendingEmergencyNonEDAdmissionListVo[] arr = new CatsReferralPendingEmergencyNonEDAdmissionListVo[col.size()];
col.toArray(arr);
return arr;
}
public ims.vo.interfaces.IPendingAdmission[] toIPendingAdmissionArray()
{
ims.vo.interfaces.IPendingAdmission[] arr = new ims.vo.interfaces.IPendingAdmission[col.size()];
col.toArray(arr);
return arr;
}
public ims.vo.interfaces.IPendingAdmissionDetails[] toIPendingAdmissionDetailsArray()
{
ims.vo.interfaces.IPendingAdmissionDetails[] arr = new ims.vo.interfaces.IPendingAdmissionDetails[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<CatsReferralPendingEmergencyNonEDAdmissionListVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class CatsReferralPendingEmergencyNonEDAdmissionListVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public CatsReferralPendingEmergencyNonEDAdmissionListVoComparator()
{
this(SortOrder.ASCENDING);
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public CatsReferralPendingEmergencyNonEDAdmissionListVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
CatsReferralPendingEmergencyNonEDAdmissionListVo voObj1 = (CatsReferralPendingEmergencyNonEDAdmissionListVo)obj1;
CatsReferralPendingEmergencyNonEDAdmissionListVo voObj2 = (CatsReferralPendingEmergencyNonEDAdmissionListVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] getBeanCollectionArray()
{
ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] result = new ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
CatsReferralPendingEmergencyNonEDAdmissionListVo vo = ((CatsReferralPendingEmergencyNonEDAdmissionListVo)col.get(i));
result[i] = (ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean)vo.getBean();
}
return result;
}
public static CatsReferralPendingEmergencyNonEDAdmissionListVoCollection buildFromBeanCollection(java.util.Collection beans)
{
CatsReferralPendingEmergencyNonEDAdmissionListVoCollection coll = new CatsReferralPendingEmergencyNonEDAdmissionListVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean)iter.next()).buildVo());
}
return coll;
}
public static CatsReferralPendingEmergencyNonEDAdmissionListVoCollection buildFromBeanCollection(ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] beans)
{
CatsReferralPendingEmergencyNonEDAdmissionListVoCollection coll = new CatsReferralPendingEmergencyNonEDAdmissionListVoCollection();
|
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]
public class CatsReferralPendingEmergencyNonEDAdmissionListVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<CatsReferralPendingEmergencyNonEDAdmissionListVo>, ims.vo.interfaces.IPendingAdmissionCollection
{
// ... (many lines omitted for brevity)
public static CatsReferralPendingEmergencyNonEDAdmissionListVoCollection buildFromBeanCollection(ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean[] beans)
{
CatsReferralPendingEmergencyNonEDAdmissionListVoCollection coll = new CatsReferralPendingEmergencyNonEDAdmissionListVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.core.vo.beans.CatsReferralPendingEmergencyNonEDAdmissionListVoBean)iter.next()).buildVo());
}
return coll;
}
// ... (many lines omitted for brevity)
Cheatsheet (for next line):
- We are in the buildFromBeanCollection method, which creates a new CatsReferralPendingEmergencyNonEDAdmissionListVoCollection from an array of beans.
- The method iterates over the beans using an iterator and adds each bean to the collection using the add method.
- The add method takes a CatsReferralPendingEmergencyNonEDAdmissionListVo object as an argument.
- The buildVo method is called on each bean to convert it to a CatsReferralPendingEmergencyNonEDAdmissionListVo object.
- The collection is returned at the end of the method.
- [Relevant lines: method header, loop, add method call]
Next line will likely be: return coll;
|
|
Please complete the code given below.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# This script is based on script.randomitems & script.watchlist
# Thanks to their original authors
import os
import re
import sys
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import random
import urllib
import shutil
import glob, os
import time
__addon__ = xbmcaddon.Addon('skin.qonfluence')
__addonid__ = __addon__.getAddonInfo('id')
__language__ = __addon__.getLocalizedString
addonPath = xbmcaddon.Addon('skin.qonfluence').getAddonInfo("path")
image = os.path.join(addonPath,'notification.png')
dialog = xbmcgui.Dialog()
localtxt2 = __language__(32007)
localtxt3 = __language__(32008)
localtxt8 = __language__(32014)
localtxt9 = __language__(32028)
localtxt10 = __language__(32040)
prnum=""
try:
prnum= sys.argv[ 1 ]
except:
pass
def cache():
localtxt1 = __language__(32006)+__language__(32000)
destpath=xbmc.translatePath(os.path.join('special://temp',''))
if dialog.yesno(localtxt1, localtxt3):
shutil.rmtree(destpath)
os.mkdir(destpath)
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt2+", 5000, %s)" % (image))
#-------------------
def packages():
localtxt1 = __language__(32006)+__language__(32002)
path=xbmc.translatePath(os.path.join('special://home/addons/packages',''))
if dialog.yesno(localtxt1, localtxt3):
shutil.rmtree(path)
os.mkdir(path)
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt2+", 5000, %s)" % (image))
#-------------------
def musicdb():
localtxt1 = __language__(32006)+__language__(32005)
path = xbmc.translatePath(os.path.join('special://profile/Database',''))
if dialog.yesno(localtxt1, localtxt3):
database = os.path.join(path, 'MyMusic*.db')
print database
filelist = glob.glob(database)
print filelist
if filelist != []:
for f in filelist:
print f
os.remove(f)
xbmc.executebuiltin("Notification("+localtxt2+","+localtxt8+")")
time.sleep(3)
xbmc.executebuiltin("Reboot")
else:
print 'merdaa'
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def videodb():
localtxt1 = __language__(32006)+__language__(32004)
path = xbmc.translatePath(os.path.join('special://profile/Database',''))
if dialog.yesno(localtxt1, localtxt3):
database = os.path.join(path, 'MyVideos*.db')
print database
filelist = glob.glob(database)
print filelist
if filelist != []:
for f in filelist:
print f
os.remove(f)
xbmc.executebuiltin("Notification("+localtxt2+","+localtxt8+")")
time.sleep(3)
xbmc.executebuiltin("Reboot")
else:
print 'merdaa'
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def thumbs():
localtxt1 = __language__(32006)+__language__(32001)
thumbnails=xbmc.translatePath(os.path.join('special://profile/Thumbnails',''))
path=xbmc.translatePath(os.path.join('special://profile/Database',''))
dialog = xbmcgui.Dialog()
if dialog.yesno(localtxt1, localtxt3):
shutil.rmtree(thumbnails)
os.mkdir(thumbnails)
database = os.path.join(path, 'Textures*.db')
print database
filelist = glob.glob(database)
print filelist
if filelist != []:
for f in filelist:
print f
os.remove(f)
xbmc.executebuiltin("Notification("+localtxt2+","+localtxt8+", 5000, %s)" % (image))
time.sleep(3)
xbmc.executebuiltin("Reboot")
else:
print 'merdaa'
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def advanced():
localtxt1 = __language__(32006)+__language__(32003)
dialog = xbmcgui.Dialog()
if dialog.yesno(localtxt1, localtxt3):
path = xbmc.translatePath(os.path.join('special://profile/userdata',''))
advance=os.path.join(path, 'advancedsettings.xml')
try:
os.remove(advance)
xbmc.executebuiltin("Notification(,"+localtxt2+")")
except:
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def viewsdb():
localtxt1 = __language__(32006)+__language__(32011)
path = xbmc.translatePath(os.path.join('special://profile/Database',''))
if dialog.yesno(localtxt1, localtxt3):
database = os.path.join(path, 'ViewModes*.db')
print database
filelist = glob.glob(database)
print filelist
if filelist != []:
for f in filelist:
print f
os.remove(f)
xbmc.executebuiltin("Notification("+localtxt2+","+localtxt8+", 5000, %s)" % (image))
time.sleep(3)
xbmc.executebuiltin("Reboot")
else:
print 'merdaa'
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def date():
localtxt1 = __language__(32012)
localtxt4 = __language__(32013)
localtxt5 = __language__(32014)
destpath=xbmc.translatePath(os.path.join('/storage/.cache/connman',''))
if dialog.yesno(localtxt1, localtxt3):
shutil.rmtree(destpath)
os.mkdir(destpath)
xbmc.executebuiltin("Notification("+localtxt4+","+localtxt5+", 5000, %s)" % (image))
xbmc.sleep(1000)
xbmc.restart()
#-------------------
def notify(header="", message="", icon=image, time=5000, sound=True):
dialog = xbmcgui.Dialog()
dialog.notification(heading="Service Clean Up", message="This Addon needs arguments to run", icon=icon, time=time, sound=sound)
#-------------------
def donate():
localtxt1 = __language__(32929)
localtxt2 = __language__(32930)
localtxt3 = __language__(32931)
localtxt4 = __language__(32932)
localtxt5 = __language__(32933)
localtxt6 = __language__(32934)
xbmc.executebuiltin("Notification("+localtxt1+","+localtxt2+",7000)")
time.sleep(7)
xbmc.executebuiltin("Notification("+localtxt3+","+localtxt4+",7000)")
time.sleep(7)
xbmc.executebuiltin("Notification("+localtxt5+","+localtxt6+",7000)")
time.sleep(7)
#-------------------
if prnum == 'cache':
cache()
elif prnum == 'packages':
packages()
elif prnum == 'videodb':
videodb()
elif prnum == 'musicdb':
musicdb()
elif prnum == 'thumbs':
thumbs()
|
[
"elif prnum == 'advanced':"
] | 549
|
lcc
|
python
| null |
73fefc41fc5fa1c47966c4abc5dc1e78bb36629f5e868c89
| 58
|
Your task is code completion.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# This script is based on script.randomitems & script.watchlist
# Thanks to their original authors
import os
import re
import sys
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import random
import urllib
import shutil
import glob, os
import time
__addon__ = xbmcaddon.Addon('skin.qonfluence')
__addonid__ = __addon__.getAddonInfo('id')
__language__ = __addon__.getLocalizedString
addonPath = xbmcaddon.Addon('skin.qonfluence').getAddonInfo("path")
image = os.path.join(addonPath,'notification.png')
dialog = xbmcgui.Dialog()
localtxt2 = __language__(32007)
localtxt3 = __language__(32008)
localtxt8 = __language__(32014)
localtxt9 = __language__(32028)
localtxt10 = __language__(32040)
prnum=""
try:
prnum= sys.argv[ 1 ]
except:
pass
def cache():
localtxt1 = __language__(32006)+__language__(32000)
destpath=xbmc.translatePath(os.path.join('special://temp',''))
if dialog.yesno(localtxt1, localtxt3):
shutil.rmtree(destpath)
os.mkdir(destpath)
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt2+", 5000, %s)" % (image))
#-------------------
def packages():
localtxt1 = __language__(32006)+__language__(32002)
path=xbmc.translatePath(os.path.join('special://home/addons/packages',''))
if dialog.yesno(localtxt1, localtxt3):
shutil.rmtree(path)
os.mkdir(path)
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt2+", 5000, %s)" % (image))
#-------------------
def musicdb():
localtxt1 = __language__(32006)+__language__(32005)
path = xbmc.translatePath(os.path.join('special://profile/Database',''))
if dialog.yesno(localtxt1, localtxt3):
database = os.path.join(path, 'MyMusic*.db')
print database
filelist = glob.glob(database)
print filelist
if filelist != []:
for f in filelist:
print f
os.remove(f)
xbmc.executebuiltin("Notification("+localtxt2+","+localtxt8+")")
time.sleep(3)
xbmc.executebuiltin("Reboot")
else:
print 'merdaa'
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def videodb():
localtxt1 = __language__(32006)+__language__(32004)
path = xbmc.translatePath(os.path.join('special://profile/Database',''))
if dialog.yesno(localtxt1, localtxt3):
database = os.path.join(path, 'MyVideos*.db')
print database
filelist = glob.glob(database)
print filelist
if filelist != []:
for f in filelist:
print f
os.remove(f)
xbmc.executebuiltin("Notification("+localtxt2+","+localtxt8+")")
time.sleep(3)
xbmc.executebuiltin("Reboot")
else:
print 'merdaa'
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def thumbs():
localtxt1 = __language__(32006)+__language__(32001)
thumbnails=xbmc.translatePath(os.path.join('special://profile/Thumbnails',''))
path=xbmc.translatePath(os.path.join('special://profile/Database',''))
dialog = xbmcgui.Dialog()
if dialog.yesno(localtxt1, localtxt3):
shutil.rmtree(thumbnails)
os.mkdir(thumbnails)
database = os.path.join(path, 'Textures*.db')
print database
filelist = glob.glob(database)
print filelist
if filelist != []:
for f in filelist:
print f
os.remove(f)
xbmc.executebuiltin("Notification("+localtxt2+","+localtxt8+", 5000, %s)" % (image))
time.sleep(3)
xbmc.executebuiltin("Reboot")
else:
print 'merdaa'
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def advanced():
localtxt1 = __language__(32006)+__language__(32003)
dialog = xbmcgui.Dialog()
if dialog.yesno(localtxt1, localtxt3):
path = xbmc.translatePath(os.path.join('special://profile/userdata',''))
advance=os.path.join(path, 'advancedsettings.xml')
try:
os.remove(advance)
xbmc.executebuiltin("Notification(,"+localtxt2+")")
except:
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def viewsdb():
localtxt1 = __language__(32006)+__language__(32011)
path = xbmc.translatePath(os.path.join('special://profile/Database',''))
if dialog.yesno(localtxt1, localtxt3):
database = os.path.join(path, 'ViewModes*.db')
print database
filelist = glob.glob(database)
print filelist
if filelist != []:
for f in filelist:
print f
os.remove(f)
xbmc.executebuiltin("Notification("+localtxt2+","+localtxt8+", 5000, %s)" % (image))
time.sleep(3)
xbmc.executebuiltin("Reboot")
else:
print 'merdaa'
xbmc.executebuiltin("Notification("+localtxt9+","+localtxt10+", 5000, %s)" % (image))
#-------------------
def date():
localtxt1 = __language__(32012)
localtxt4 = __language__(32013)
localtxt5 = __language__(32014)
destpath=xbmc.translatePath(os.path.join('/storage/.cache/connman',''))
if dialog.yesno(localtxt1, localtxt3):
shutil.rmtree(destpath)
os.mkdir(destpath)
xbmc.executebuiltin("Notification("+localtxt4+","+localtxt5+", 5000, %s)" % (image))
xbmc.sleep(1000)
xbmc.restart()
#-------------------
def notify(header="", message="", icon=image, time=5000, sound=True):
dialog = xbmcgui.Dialog()
dialog.notification(heading="Service Clean Up", message="This Addon needs arguments to run", icon=icon, time=time, sound=sound)
#-------------------
def donate():
localtxt1 = __language__(32929)
localtxt2 = __language__(32930)
localtxt3 = __language__(32931)
localtxt4 = __language__(32932)
localtxt5 = __language__(32933)
localtxt6 = __language__(32934)
xbmc.executebuiltin("Notification("+localtxt1+","+localtxt2+",7000)")
time.sleep(7)
xbmc.executebuiltin("Notification("+localtxt3+","+localtxt4+",7000)")
time.sleep(7)
xbmc.executebuiltin("Notification("+localtxt5+","+localtxt6+",7000)")
time.sleep(7)
#-------------------
if prnum == 'cache':
cache()
elif prnum == 'packages':
packages()
elif prnum == 'videodb':
videodb()
elif prnum == 'musicdb':
musicdb()
elif prnum == 'thumbs':
thumbs()
|
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 Code Completion Task:
**Context:**
The given code is a script for a Kodi add-on that provides various cleaning options for the Kodi media center. The script includes functions for clearing cache, packages, music database, video database, thumbnails, advanced settings, view modes database, and date. The script also includes a notification function and a donate function.
**Relevant Variables and Functions:**
- `prnum`: a variable that stores the parameter passed to the script (e.g., 'cache', 'packages', etc.)
- `cache()`, `packages()`, `musicdb()`, `videodb()`, `thumbs()`, `advanced()`, `viewsdb()`, `date()`: functions that perform specific cleaning tasks
- `notify()`: a function for displaying notifications
- `donate()`: a function for displaying a donation notification
**Cheat Sheet:**
- We are at the end of the script, and we need to add an `elif` statement to handle the case where `prnum` is 'thumbs'.
- The `thumbs()` function is already defined, and we need to call it when `prnum` is 'thumbs'.
- The script should handle the case where `prnum` is not one of the specified values (e.g., 'cache', 'packages', etc.).
**Next Line(s) of Code:**
```python
elif prnum == 'thumbs':
thumbs()
elif prnum not in ['cache', 'packages', 'musicdb', 'videodb', 'thumbs', 'advanced', 'viewsdb', 'date']:
notify(header="Invalid Parameter", message="This Addon needs arguments to run", icon=image, time=5000, sound=True)
```
This code adds an `elif` statement to call the `thumbs()` function when `prnum` is 'thumbs'. It also adds an `elif` statement to display a notification when `prnum` is not one of the specified values.
|
|
Please complete the code given below.
//////////////////////////////////////////////////////////////////
// //
// This is an auto - manipulated source file. //
// Edits inside regions of HYCALPER AUTO GENERATED CODE //
// will be lost and overwritten on the next build! //
// //
//////////////////////////////////////////////////////////////////
#region LGPL License
/*
This file is part of ILNumerics.Net Core Module.
ILNumerics.Net Core Module is free software: you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
ILNumerics.Net Core Module is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ILNumerics.Net Core Module.
If not, see <http://www.gnu.org/licenses/>.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using ILNumerics;
using ILNumerics.Exceptions;
using ILNumerics.Storage;
using ILNumerics.Misc;
namespace ILNumerics.BuiltInFunctions {
public partial class ILMath {
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<double> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<float> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<complex> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<fcomplex> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<Int16> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<Int32> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<Int64> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<UInt16> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<UInt32> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<UInt64> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<char> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
|
[
" int [] ret = new int[A.Dimensions.NumberOfDimensions]; "
] | 1,174
|
lcc
|
csharp
| null |
5f7f8ad03839f70553f1bf1189d38d53af0f00c6db0c9584
| 59
|
Your task is code completion.
//////////////////////////////////////////////////////////////////
// //
// This is an auto - manipulated source file. //
// Edits inside regions of HYCALPER AUTO GENERATED CODE //
// will be lost and overwritten on the next build! //
// //
//////////////////////////////////////////////////////////////////
#region LGPL License
/*
This file is part of ILNumerics.Net Core Module.
ILNumerics.Net Core Module is free software: you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
ILNumerics.Net Core Module is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ILNumerics.Net Core Module.
If not, see <http://www.gnu.org/licenses/>.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using ILNumerics;
using ILNumerics.Exceptions;
using ILNumerics.Storage;
using ILNumerics.Misc;
namespace ILNumerics.BuiltInFunctions {
public partial class ILMath {
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<double> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<float> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<complex> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<fcomplex> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<Int16> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<Int32> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<Int64> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<UInt16> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<UInt32> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<UInt64> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
}
/// <summary>
/// convert sequential index into subscript indices
/// </summary>
/// <param name="A">input array</param>
/// <param name="seqindex">sequential index</param>
/// <returns>subscript indices</returns>
/// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
/// <para>if A is null or empty array, the return value will be of length 0</para>
/// </remarks>
/// <exception cref="System.IndexOutOfRangeException">if seqindex is < 0 or > numel(A)</exception>
public static int[] ind2sub(ILArray<char> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
|
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... ~20 lines omitted for brevity]
public static int[] ind2sub(ILArray<T> A, int seqindex) {
if (object.Equals(A,null) || A.IsEmpty)
return new int[0];
int [] ret = new int[A.Dimensions.NumberOfDimensions];
A.GetValueSeq(seqindex,ref ret);
return ret;
Cheatsheet (for next line):
- We are in the ind2sub method, which is a generic method that takes an ILArray of any type T and returns an array of integers.
- The method is currently handling the case where A is null or empty, and returning an empty array.
- The method is then creating an array of integers with the same number of dimensions as the input array A.
- The method is calling the GetValueSeq method on A, passing in the seqindex and a reference to the ret array.
- The method is returning the ret array.
- The type T is not specified, but it is one of the following types: double, float, complex, fcomplex, Int16, Int32, Int64, UInt16, UInt32, or UInt64.
- The method is throwing an IndexOutOfRangeException if seqindex is less than 0 or greater than the number of elements in A.
Relevant lines:
- Method header
- Type T
- Creation of ret array
- Call to GetValueSeq method
- Return statement
Next line will likely be: return ret;
|
|
Please complete the code given below.
import logging
import datetime
import simplejson
import tempfile
try:
from hashlib import md5
except:
from md5 import md5
from dirac.lib.base import *
from dirac.lib.diset import getRPCClient, getTransferClient
from dirac.lib.credentials import getUsername, getSelectedGroup, getSelectedSetup
from DIRAC import S_OK, S_ERROR, gLogger, gConfig
from DIRAC.Core.Utilities import Time, List
from DIRAC.Core.Utilities.DictCache import DictCache
from DIRAC.Core.Security import CS
from DIRAC.AccountingSystem.Client.ReportsClient import ReportsClient
from dirac.lib.webBase import defaultRedirect
log = logging.getLogger( __name__ )
class AccountingplotsController( BaseController ):
__keysCache = DictCache()
def __getUniqueKeyValues( self, typeName ):
userGroup = getSelectedGroup()
if 'NormalUser' in CS.getPropertiesForGroup( userGroup ):
cacheKey = ( getUsername(), userGroup, getSelectedSetup(), typeName )
else:
cacheKey = ( userGroup, getSelectedSetup(), typeName )
data = AccountingplotsController.__keysCache.get( cacheKey )
if not data:
rpcClient = getRPCClient( "Accounting/ReportGenerator" )
retVal = rpcClient.listUniqueKeyValues( typeName )
if 'rpcStub' in retVal:
del( retVal[ 'rpcStub' ] )
if not retVal[ 'OK' ]:
return retVal
#Site ordering based on TierLevel / alpha
if 'Site' in retVal[ 'Value' ]:
siteLevel = {}
for siteName in retVal[ 'Value' ][ 'Site' ]:
sitePrefix = siteName.split( "." )[0].strip()
level = gConfig.getValue( "/Resources/Sites/%s/%s/MoUTierLevel" % ( sitePrefix, siteName ), 10 )
if level not in siteLevel:
siteLevel[ level ] = []
siteLevel[ level ].append( siteName )
orderedSites = []
for level in sorted( siteLevel ):
orderedSites.extend( sorted( siteLevel[ level ] ) )
retVal[ 'Value' ][ 'Site' ] = orderedSites
data = retVal
AccountingplotsController.__keysCache.add( cacheKey, 300, data )
return data
def index( self ):
# Return a rendered template
# return render('/some/template.mako')
# or, Return a response
return defaultRedirect()
def dataOperation( self ):
return self.__showPlotPage( "DataOperation", "/systems/accounting/dataOperation.mako" )
def job( self ):
return self.__showPlotPage( "Job", "/systems/accounting/job.mako" )
def WMSHistory( self ):
return self.__showPlotPage( "WMSHistory", "/systems/accounting/WMSHistory.mako" )
def pilot( self ):
return self.__showPlotPage( "Pilot", "/systems/accounting/Pilot.mako" )
def SRMSpaceTokenDeployment( self ):
return self.__showPlotPage( "SRMSpaceTokenDeployment", "/systems/accounting/SRMSpaceTokenDeployment.mako" )
def plotPage( self ):
try:
typeName = str( request.params[ 'typeName' ] )
except:
c.errorMessage = "Oops. missing type"
return render( "/error.mako" )
return self.__showPlotPage( typeName , "/systems/accounting/%s.mako" % typeName )
def __showPlotPage( self, typeName, templateFile ):
#Get unique key values
retVal = self.__getUniqueKeyValues( typeName )
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render ( "/error.mako" )
c.selectionValues = simplejson.dumps( retVal[ 'Value' ] )
#Cache for plotsList?
data = AccountingplotsController.__keysCache.get( "reportsList:%s" % typeName )
if not data:
repClient = ReportsClient( rpcClient = getRPCClient( "Accounting/ReportGenerator" ) )
retVal = repClient.listReports( typeName )
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render ( "/error.mako" )
data = simplejson.dumps( retVal[ 'Value' ] )
AccountingplotsController.__keysCache.add( "reportsList:%s" % typeName, 300, data )
c.plotsList = data
return render ( templateFile )
@jsonify
def getKeyValuesForType( self ):
try:
typeName = str( request.params[ 'typeName' ] )
except:
return S_ERROR( "Missing or invalid type name!" )
retVal = self.__getUniqueKeyValues( typeName )
if not retVal[ 'OK' ] and 'rpcStub' in retVal:
del( retVal[ 'rpcStub' ] )
return retVal
def __parseFormParams(self):
params = request.params
return parseFormParams(params)
def __translateToExpectedExtResult( self, retVal ):
if retVal[ 'OK' ]:
return { 'success' : True, 'data' : retVal[ 'Value' ][ 'plot' ] }
else:
return { 'success' : False, 'errors' : retVal[ 'Message' ] }
def __queryForPlot( self ):
retVal = self.__parseFormParams()
if not retVal[ 'OK' ]:
return retVal
params = retVal[ 'Value' ]
repClient = ReportsClient( rpcClient = getRPCClient( "Accounting/ReportGenerator" ) )
retVal = repClient.generateDelayedPlot( *params )
return retVal
def getPlotData( self ):
retVal = self.__parseFormParams()
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render( "/error.mako" )
params = retVal[ 'Value' ]
repClient = ReportsClient( rpcClient = getRPCClient( "Accounting/ReportGenerator" ) )
retVal = repClient.getReport( *params )
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render( "/error.mako" )
rawData = retVal[ 'Value' ]
groupKeys = rawData[ 'data' ].keys()
groupKeys.sort()
if 'granularity' in rawData:
granularity = rawData[ 'granularity' ]
data = rawData['data']
tS = int( Time.toEpoch( params[2] ) )
timeStart = tS - tS % granularity
strData = "epoch,%s\n" % ",".join( groupKeys )
for timeSlot in range( timeStart, int( Time.toEpoch( params[3] ) ), granularity ):
lineData = [ str( timeSlot ) ]
for key in groupKeys:
if timeSlot in data[ key ]:
lineData.append( str( data[ key ][ timeSlot ] ) )
else:
lineData.append( "" )
strData += "%s\n" % ",".join( lineData )
else:
strData = "%s\n" % ",".join( groupKeys )
strData += ",".join( [ str( rawData[ 'data' ][ k ] ) for k in groupKeys ] )
response.headers['Content-type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment; filename="%s.csv"' % md5( str( params ) ).hexdigest()
response.headers['Content-Length'] = len( strData )
return strData
@jsonify
def generatePlot( self ):
return self.__translateToExpectedExtResult( self.__queryForPlot() )
def generatePlotAndGetHTML( self ):
retVal = self.__queryForPlot()
if not retVal[ 'OK' ]:
return "<h2>Can't regenerate plot: %s</h2>" % retVal[ 'Message' ]
return "<img src='getPlotImg?file=%s'/>" % retVal[ 'Value' ][ 'plot' ]
def getPlotImg( self ):
"""
Get plot image
"""
if 'file' not in request.params:
c.error = "Maybe you forgot the file?"
return render( "/error.mako" )
plotImageFile = str( request.params[ 'file' ] )
if plotImageFile.find( ".png" ) < -1:
c.error = "Not a valid image!"
return render( "/error.mako" )
transferClient = getTransferClient( "Accounting/ReportGenerator" )
tempFile = tempfile.TemporaryFile()
retVal = transferClient.receiveFile( tempFile, plotImageFile )
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render( "/error.mako" )
tempFile.seek( 0 )
data = tempFile.read()
response.headers['Content-type'] = 'image/png'
response.headers['Content-Disposition'] = 'attachment; filename="%s.png"' % md5( plotImageFile ).hexdigest()
response.headers['Content-Length'] = len( data )
response.headers['Content-Transfer-Encoding'] = 'Binary'
response.headers['Cache-Control'] = "no-cache, no-store, must-revalidate, max-age=0"
response.headers['Pragma'] = "no-cache"
response.headers['Expires'] = ( datetime.datetime.utcnow() - datetime.timedelta( minutes = -10 ) ).strftime( "%d %b %Y %H:%M:%S GMT" )
return data
@jsonify
def getPlotListAndSelectionValues(self):
result = {}
try:
typeName = str( request.params[ 'typeName' ] )
except:
return S_ERROR( "Missing or invalid type name!" )
retVal = self.__getUniqueKeyValues( typeName )
if not retVal[ 'OK' ] and 'rpcStub' in retVal:
del( retVal[ 'rpcStub' ] )
return retVal
selectionValues = retVal['Value']
data = AccountingplotsController.__keysCache.get( "reportsList:%s" % typeName )
if not data:
repClient = ReportsClient( rpcClient = getRPCClient( "Accounting/ReportGenerator" ) )
retVal = repClient.listReports( typeName )
if not retVal[ 'OK' ]:
return retVal
data = simplejson.dumps( retVal[ 'Value' ] )
AccountingplotsController.__keysCache.add( "reportsList:%s" % typeName, 300, data )
try:
plotsList = eval(data)
except:
return S_ERROR('Failed to convert a string to a list!')
return S_OK({'SelectionData':selectionValues, 'PlotList':plotsList})
def parseFormParams(params):
pD = {}
extraParams = {}
pinDates = False
for name in params:
if name.find( "_" ) != 0:
continue
value = params[ name ]
name = name[1:]
pD[ name ] = str( value )
#Personalized title?
if 'plotTitle' in pD:
extraParams[ 'plotTitle' ] = pD[ 'plotTitle' ]
del( pD[ 'plotTitle' ] )
#Pin dates?
if 'pinDates' in pD:
pinDates = pD[ 'pinDates' ]
del( pD[ 'pinDates' ] )
pinDates = pinDates.lower() in ( "yes", "y", "true", "1" )
#Get plotname
if not 'grouping' in pD:
return S_ERROR( "Missing grouping!" )
grouping = pD[ 'grouping' ]
#Get plotname
if not 'typeName' in pD:
return S_ERROR( "Missing type name!" )
typeName = pD[ 'typeName' ]
del( pD[ 'typeName' ] )
#Get plotname
if not 'plotName' in pD:
return S_ERROR( "Missing plot name!" )
|
[
" reportName = pD[ 'plotName' ]"
] | 1,147
|
lcc
|
python
| null |
6f5d658cc2b84c64bf49c302dee4078f60fd158ed24b7b19
| 60
|
Your task is code completion.
import logging
import datetime
import simplejson
import tempfile
try:
from hashlib import md5
except:
from md5 import md5
from dirac.lib.base import *
from dirac.lib.diset import getRPCClient, getTransferClient
from dirac.lib.credentials import getUsername, getSelectedGroup, getSelectedSetup
from DIRAC import S_OK, S_ERROR, gLogger, gConfig
from DIRAC.Core.Utilities import Time, List
from DIRAC.Core.Utilities.DictCache import DictCache
from DIRAC.Core.Security import CS
from DIRAC.AccountingSystem.Client.ReportsClient import ReportsClient
from dirac.lib.webBase import defaultRedirect
log = logging.getLogger( __name__ )
class AccountingplotsController( BaseController ):
__keysCache = DictCache()
def __getUniqueKeyValues( self, typeName ):
userGroup = getSelectedGroup()
if 'NormalUser' in CS.getPropertiesForGroup( userGroup ):
cacheKey = ( getUsername(), userGroup, getSelectedSetup(), typeName )
else:
cacheKey = ( userGroup, getSelectedSetup(), typeName )
data = AccountingplotsController.__keysCache.get( cacheKey )
if not data:
rpcClient = getRPCClient( "Accounting/ReportGenerator" )
retVal = rpcClient.listUniqueKeyValues( typeName )
if 'rpcStub' in retVal:
del( retVal[ 'rpcStub' ] )
if not retVal[ 'OK' ]:
return retVal
#Site ordering based on TierLevel / alpha
if 'Site' in retVal[ 'Value' ]:
siteLevel = {}
for siteName in retVal[ 'Value' ][ 'Site' ]:
sitePrefix = siteName.split( "." )[0].strip()
level = gConfig.getValue( "/Resources/Sites/%s/%s/MoUTierLevel" % ( sitePrefix, siteName ), 10 )
if level not in siteLevel:
siteLevel[ level ] = []
siteLevel[ level ].append( siteName )
orderedSites = []
for level in sorted( siteLevel ):
orderedSites.extend( sorted( siteLevel[ level ] ) )
retVal[ 'Value' ][ 'Site' ] = orderedSites
data = retVal
AccountingplotsController.__keysCache.add( cacheKey, 300, data )
return data
def index( self ):
# Return a rendered template
# return render('/some/template.mako')
# or, Return a response
return defaultRedirect()
def dataOperation( self ):
return self.__showPlotPage( "DataOperation", "/systems/accounting/dataOperation.mako" )
def job( self ):
return self.__showPlotPage( "Job", "/systems/accounting/job.mako" )
def WMSHistory( self ):
return self.__showPlotPage( "WMSHistory", "/systems/accounting/WMSHistory.mako" )
def pilot( self ):
return self.__showPlotPage( "Pilot", "/systems/accounting/Pilot.mako" )
def SRMSpaceTokenDeployment( self ):
return self.__showPlotPage( "SRMSpaceTokenDeployment", "/systems/accounting/SRMSpaceTokenDeployment.mako" )
def plotPage( self ):
try:
typeName = str( request.params[ 'typeName' ] )
except:
c.errorMessage = "Oops. missing type"
return render( "/error.mako" )
return self.__showPlotPage( typeName , "/systems/accounting/%s.mako" % typeName )
def __showPlotPage( self, typeName, templateFile ):
#Get unique key values
retVal = self.__getUniqueKeyValues( typeName )
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render ( "/error.mako" )
c.selectionValues = simplejson.dumps( retVal[ 'Value' ] )
#Cache for plotsList?
data = AccountingplotsController.__keysCache.get( "reportsList:%s" % typeName )
if not data:
repClient = ReportsClient( rpcClient = getRPCClient( "Accounting/ReportGenerator" ) )
retVal = repClient.listReports( typeName )
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render ( "/error.mako" )
data = simplejson.dumps( retVal[ 'Value' ] )
AccountingplotsController.__keysCache.add( "reportsList:%s" % typeName, 300, data )
c.plotsList = data
return render ( templateFile )
@jsonify
def getKeyValuesForType( self ):
try:
typeName = str( request.params[ 'typeName' ] )
except:
return S_ERROR( "Missing or invalid type name!" )
retVal = self.__getUniqueKeyValues( typeName )
if not retVal[ 'OK' ] and 'rpcStub' in retVal:
del( retVal[ 'rpcStub' ] )
return retVal
def __parseFormParams(self):
params = request.params
return parseFormParams(params)
def __translateToExpectedExtResult( self, retVal ):
if retVal[ 'OK' ]:
return { 'success' : True, 'data' : retVal[ 'Value' ][ 'plot' ] }
else:
return { 'success' : False, 'errors' : retVal[ 'Message' ] }
def __queryForPlot( self ):
retVal = self.__parseFormParams()
if not retVal[ 'OK' ]:
return retVal
params = retVal[ 'Value' ]
repClient = ReportsClient( rpcClient = getRPCClient( "Accounting/ReportGenerator" ) )
retVal = repClient.generateDelayedPlot( *params )
return retVal
def getPlotData( self ):
retVal = self.__parseFormParams()
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render( "/error.mako" )
params = retVal[ 'Value' ]
repClient = ReportsClient( rpcClient = getRPCClient( "Accounting/ReportGenerator" ) )
retVal = repClient.getReport( *params )
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render( "/error.mako" )
rawData = retVal[ 'Value' ]
groupKeys = rawData[ 'data' ].keys()
groupKeys.sort()
if 'granularity' in rawData:
granularity = rawData[ 'granularity' ]
data = rawData['data']
tS = int( Time.toEpoch( params[2] ) )
timeStart = tS - tS % granularity
strData = "epoch,%s\n" % ",".join( groupKeys )
for timeSlot in range( timeStart, int( Time.toEpoch( params[3] ) ), granularity ):
lineData = [ str( timeSlot ) ]
for key in groupKeys:
if timeSlot in data[ key ]:
lineData.append( str( data[ key ][ timeSlot ] ) )
else:
lineData.append( "" )
strData += "%s\n" % ",".join( lineData )
else:
strData = "%s\n" % ",".join( groupKeys )
strData += ",".join( [ str( rawData[ 'data' ][ k ] ) for k in groupKeys ] )
response.headers['Content-type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment; filename="%s.csv"' % md5( str( params ) ).hexdigest()
response.headers['Content-Length'] = len( strData )
return strData
@jsonify
def generatePlot( self ):
return self.__translateToExpectedExtResult( self.__queryForPlot() )
def generatePlotAndGetHTML( self ):
retVal = self.__queryForPlot()
if not retVal[ 'OK' ]:
return "<h2>Can't regenerate plot: %s</h2>" % retVal[ 'Message' ]
return "<img src='getPlotImg?file=%s'/>" % retVal[ 'Value' ][ 'plot' ]
def getPlotImg( self ):
"""
Get plot image
"""
if 'file' not in request.params:
c.error = "Maybe you forgot the file?"
return render( "/error.mako" )
plotImageFile = str( request.params[ 'file' ] )
if plotImageFile.find( ".png" ) < -1:
c.error = "Not a valid image!"
return render( "/error.mako" )
transferClient = getTransferClient( "Accounting/ReportGenerator" )
tempFile = tempfile.TemporaryFile()
retVal = transferClient.receiveFile( tempFile, plotImageFile )
if not retVal[ 'OK' ]:
c.error = retVal[ 'Message' ]
return render( "/error.mako" )
tempFile.seek( 0 )
data = tempFile.read()
response.headers['Content-type'] = 'image/png'
response.headers['Content-Disposition'] = 'attachment; filename="%s.png"' % md5( plotImageFile ).hexdigest()
response.headers['Content-Length'] = len( data )
response.headers['Content-Transfer-Encoding'] = 'Binary'
response.headers['Cache-Control'] = "no-cache, no-store, must-revalidate, max-age=0"
response.headers['Pragma'] = "no-cache"
response.headers['Expires'] = ( datetime.datetime.utcnow() - datetime.timedelta( minutes = -10 ) ).strftime( "%d %b %Y %H:%M:%S GMT" )
return data
@jsonify
def getPlotListAndSelectionValues(self):
result = {}
try:
typeName = str( request.params[ 'typeName' ] )
except:
return S_ERROR( "Missing or invalid type name!" )
retVal = self.__getUniqueKeyValues( typeName )
if not retVal[ 'OK' ] and 'rpcStub' in retVal:
del( retVal[ 'rpcStub' ] )
return retVal
selectionValues = retVal['Value']
data = AccountingplotsController.__keysCache.get( "reportsList:%s" % typeName )
if not data:
repClient = ReportsClient( rpcClient = getRPCClient( "Accounting/ReportGenerator" ) )
retVal = repClient.listReports( typeName )
if not retVal[ 'OK' ]:
return retVal
data = simplejson.dumps( retVal[ 'Value' ] )
AccountingplotsController.__keysCache.add( "reportsList:%s" % typeName, 300, data )
try:
plotsList = eval(data)
except:
return S_ERROR('Failed to convert a string to a list!')
return S_OK({'SelectionData':selectionValues, 'PlotList':plotsList})
def parseFormParams(params):
pD = {}
extraParams = {}
pinDates = False
for name in params:
if name.find( "_" ) != 0:
continue
value = params[ name ]
name = name[1:]
pD[ name ] = str( value )
#Personalized title?
if 'plotTitle' in pD:
extraParams[ 'plotTitle' ] = pD[ 'plotTitle' ]
del( pD[ 'plotTitle' ] )
#Pin dates?
if 'pinDates' in pD:
pinDates = pD[ 'pinDates' ]
del( pD[ 'pinDates' ] )
pinDates = pinDates.lower() in ( "yes", "y", "true", "1" )
#Get plotname
if not 'grouping' in pD:
return S_ERROR( "Missing grouping!" )
grouping = pD[ 'grouping' ]
#Get plotname
if not 'typeName' in pD:
return S_ERROR( "Missing type name!" )
typeName = pD[ 'typeName' ]
del( pD[ 'typeName' ] )
#Get plotname
if not 'plotName' in pD:
return S_ERROR( "Missing plot name!" )
|
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 parseFormParams(params):
pD = {}
extraParams = {}
pinDates = False
for name in params:
if name.find( "_" ) != 0:
continue
value = params[ name ]
name = name[1:]
pD[ name ] = str( value )
#Personalized title?
if 'plotTitle' in pD:
extraParams[ 'plotTitle' ] = pD[ 'plotTitle' ]
del( pD[ 'plotTitle' ] )
#Pin dates?
if 'pinDates' in pD:
pinDates = pD[ 'pinDates' ]
del( pD[ 'pinDates' ] )
pinDates = pinDates.lower() in ( "yes", "y", "true", "1" )
#Get plotname
if not 'grouping' in pD:
return S_ERROR( "Missing grouping!" )
grouping = pD[ 'grouping' ]
#Get plotname
if not 'typeName' in pD:
return S_ERROR( "Missing type name!" )
typeName = pD[ 'typeName' ]
del( pD[ 'typeName' ] )
#Get plotname
if not 'plotName' in pD:
return S_ERROR( "Missing plot name!" )
Cheatsheet (for next line):
- We are in the if-else block for 'plotName' in pD.
- The function is returning an error if 'plotName' is missing.
- The error message is a string.
- [Relevant lines: error message, return statement]
The next line will likely be: return S_ERROR( "Missing plot name!" )
|
|
Please complete the code given below.
#region Copyright & License Information
/*
* Copyright 2007-2021 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
[Desc("Manages AI base construction.")]
public class BaseBuilderBotModuleInfo : ConditionalTraitInfo
{
[Desc("Tells the AI what building types are considered construction yards.")]
public readonly HashSet<string> ConstructionYardTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered vehicle production facilities.")]
public readonly HashSet<string> VehiclesFactoryTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered refineries.")]
public readonly HashSet<string> RefineryTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered power plants.")]
public readonly HashSet<string> PowerTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered infantry production facilities.")]
public readonly HashSet<string> BarracksTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered production facilities.")]
public readonly HashSet<string> ProductionTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered naval production facilities.")]
public readonly HashSet<string> NavalProductionTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered silos (resource storage).")]
public readonly HashSet<string> SiloTypes = new HashSet<string>();
[Desc("Production queues AI uses for buildings.")]
public readonly HashSet<string> BuildingQueues = new HashSet<string> { "Building" };
[Desc("Production queues AI uses for defenses.")]
public readonly HashSet<string> DefenseQueues = new HashSet<string> { "Defense" };
[Desc("Minimum distance in cells from center of the base when checking for building placement.")]
public readonly int MinBaseRadius = 2;
[Desc("Radius in cells around the center of the base to expand.")]
public readonly int MaxBaseRadius = 20;
[Desc("Minimum excess power the AI should try to maintain.")]
public readonly int MinimumExcessPower = 0;
[Desc("The targeted excess power the AI tries to maintain cannot rise above this.")]
public readonly int MaximumExcessPower = 0;
[Desc("Increase maintained excess power by this amount for every ExcessPowerIncreaseThreshold of base buildings.")]
public readonly int ExcessPowerIncrement = 0;
[Desc("Increase maintained excess power by ExcessPowerIncrement for every N base buildings.")]
public readonly int ExcessPowerIncreaseThreshold = 1;
[Desc("Number of refineries to build before building a barracks.")]
public readonly int InititalMinimumRefineryCount = 1;
[Desc("Number of refineries to build additionally after building a barracks.")]
public readonly int AdditionalMinimumRefineryCount = 1;
[Desc("Additional delay (in ticks) between structure production checks when there is no active production.",
"StructureProductionRandomBonusDelay is added to this.")]
public readonly int StructureProductionInactiveDelay = 125;
[Desc("Additional delay (in ticks) added between structure production checks when actively building things.",
"Note: this should be at least as large as the typical order latency to avoid duplicated build choices.")]
public readonly int StructureProductionActiveDelay = 25;
[Desc("A random delay (in ticks) of up to this is added to active/inactive production delays.")]
public readonly int StructureProductionRandomBonusDelay = 10;
[Desc("Delay (in ticks) until retrying to build structure after the last 3 consecutive attempts failed.")]
public readonly int StructureProductionResumeDelay = 1500;
[Desc("After how many failed attempts to place a structure should AI give up and wait",
"for StructureProductionResumeDelay before retrying.")]
public readonly int MaximumFailedPlacementAttempts = 3;
[Desc("How many randomly chosen cells with resources to check when deciding refinery placement.")]
public readonly int MaxResourceCellsToCheck = 3;
[Desc("Delay (in ticks) until rechecking for new BaseProviders.")]
public readonly int CheckForNewBasesDelay = 1500;
[Desc("Chance that the AI will place the defenses in the direction of the closest enemy building.")]
public readonly int PlaceDefenseTowardsEnemyChance = 100;
[Desc("Minimum range at which to build defensive structures near a combat hotspot.")]
public readonly int MinimumDefenseRadius = 5;
[Desc("Maximum range at which to build defensive structures near a combat hotspot.")]
public readonly int MaximumDefenseRadius = 20;
[Desc("Try to build another production building if there is too much cash.")]
public readonly int NewProductionCashThreshold = 5000;
[Desc("Radius in cells around a factory scanned for rally points by the AI.")]
public readonly int RallyPointScanRadius = 8;
[Desc("Radius in cells around each building with ProvideBuildableArea",
"to check for a 3x3 area of water where naval structures can be built.",
"Should match maximum adjacency of naval structures.")]
public readonly int CheckForWaterRadius = 8;
[Desc("Terrain types which are considered water for base building purposes.")]
public readonly HashSet<string> WaterTerrainTypes = new HashSet<string> { "Water" };
[Desc("What buildings to the AI should build.", "What integer percentage of the total base must be this type of building.")]
public readonly Dictionary<string, int> BuildingFractions = null;
[Desc("What buildings should the AI have a maximum limit to build.")]
public readonly Dictionary<string, int> BuildingLimits = null;
[Desc("When should the AI start building specific buildings.")]
public readonly Dictionary<string, int> BuildingDelays = null;
public override object Create(ActorInitializer init) { return new BaseBuilderBotModule(init.Self, this); }
}
public class BaseBuilderBotModule : ConditionalTrait<BaseBuilderBotModuleInfo>, IGameSaveTraitData,
IBotTick, IBotPositionsUpdated, IBotRespondToAttack, IBotRequestPauseUnitProduction
{
public CPos GetRandomBaseCenter()
{
var randomConstructionYard = world.Actors.Where(a => a.Owner == player &&
Info.ConstructionYardTypes.Contains(a.Info.Name))
.RandomOrDefault(world.LocalRandom);
return randomConstructionYard?.Location ?? initialBaseCenter;
}
public CPos DefenseCenter => defenseCenter;
readonly World world;
readonly Player player;
PowerManager playerPower;
PlayerResources playerResources;
IResourceLayer resourceLayer;
IBotPositionsUpdated[] positionsUpdatedModules;
CPos initialBaseCenter;
CPos defenseCenter;
List<BaseBuilderQueueManager> builders = new List<BaseBuilderQueueManager>();
public BaseBuilderBotModule(Actor self, BaseBuilderBotModuleInfo info)
: base(info)
{
world = self.World;
player = self.Owner;
}
protected override void Created(Actor self)
{
playerPower = self.Owner.PlayerActor.TraitOrDefault<PowerManager>();
playerResources = self.Owner.PlayerActor.Trait<PlayerResources>();
resourceLayer = self.World.WorldActor.TraitOrDefault<IResourceLayer>();
positionsUpdatedModules = self.Owner.PlayerActor.TraitsImplementing<IBotPositionsUpdated>().ToArray();
}
protected override void TraitEnabled(Actor self)
{
foreach (var building in Info.BuildingQueues)
builders.Add(new BaseBuilderQueueManager(this, building, player, playerPower, playerResources, resourceLayer));
foreach (var defense in Info.DefenseQueues)
builders.Add(new BaseBuilderQueueManager(this, defense, player, playerPower, playerResources, resourceLayer));
}
void IBotPositionsUpdated.UpdatedBaseCenter(CPos newLocation)
{
initialBaseCenter = newLocation;
}
void IBotPositionsUpdated.UpdatedDefenseCenter(CPos newLocation)
{
defenseCenter = newLocation;
}
bool IBotRequestPauseUnitProduction.PauseUnitProduction => !IsTraitDisabled && !HasAdequateRefineryCount;
void IBotTick.BotTick(IBot bot)
{
SetRallyPointsForNewProductionBuildings(bot);
foreach (var b in builders)
b.Tick(bot);
}
void IBotRespondToAttack.RespondToAttack(IBot bot, Actor self, AttackInfo e)
{
if (e.Attacker == null || e.Attacker.Disposed)
return;
if (e.Attacker.Owner.RelationshipWith(self.Owner) != PlayerRelationship.Enemy)
return;
if (!e.Attacker.Info.HasTraitInfo<ITargetableInfo>())
return;
// Protect buildings
if (self.Info.HasTraitInfo<BuildingInfo>())
foreach (var n in positionsUpdatedModules)
n.UpdatedDefenseCenter(e.Attacker.Location);
}
void SetRallyPointsForNewProductionBuildings(IBot bot)
{
|
[
"\t\t\tforeach (var rp in world.ActorsWithTrait<RallyPoint>())"
] | 985
|
lcc
|
csharp
| null |
10f9dbc73235c1d307666e6143b4217f1b7b644ae2fe93d6
| 61
|
Your task is code completion.
#region Copyright & License Information
/*
* Copyright 2007-2021 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
[Desc("Manages AI base construction.")]
public class BaseBuilderBotModuleInfo : ConditionalTraitInfo
{
[Desc("Tells the AI what building types are considered construction yards.")]
public readonly HashSet<string> ConstructionYardTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered vehicle production facilities.")]
public readonly HashSet<string> VehiclesFactoryTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered refineries.")]
public readonly HashSet<string> RefineryTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered power plants.")]
public readonly HashSet<string> PowerTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered infantry production facilities.")]
public readonly HashSet<string> BarracksTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered production facilities.")]
public readonly HashSet<string> ProductionTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered naval production facilities.")]
public readonly HashSet<string> NavalProductionTypes = new HashSet<string>();
[Desc("Tells the AI what building types are considered silos (resource storage).")]
public readonly HashSet<string> SiloTypes = new HashSet<string>();
[Desc("Production queues AI uses for buildings.")]
public readonly HashSet<string> BuildingQueues = new HashSet<string> { "Building" };
[Desc("Production queues AI uses for defenses.")]
public readonly HashSet<string> DefenseQueues = new HashSet<string> { "Defense" };
[Desc("Minimum distance in cells from center of the base when checking for building placement.")]
public readonly int MinBaseRadius = 2;
[Desc("Radius in cells around the center of the base to expand.")]
public readonly int MaxBaseRadius = 20;
[Desc("Minimum excess power the AI should try to maintain.")]
public readonly int MinimumExcessPower = 0;
[Desc("The targeted excess power the AI tries to maintain cannot rise above this.")]
public readonly int MaximumExcessPower = 0;
[Desc("Increase maintained excess power by this amount for every ExcessPowerIncreaseThreshold of base buildings.")]
public readonly int ExcessPowerIncrement = 0;
[Desc("Increase maintained excess power by ExcessPowerIncrement for every N base buildings.")]
public readonly int ExcessPowerIncreaseThreshold = 1;
[Desc("Number of refineries to build before building a barracks.")]
public readonly int InititalMinimumRefineryCount = 1;
[Desc("Number of refineries to build additionally after building a barracks.")]
public readonly int AdditionalMinimumRefineryCount = 1;
[Desc("Additional delay (in ticks) between structure production checks when there is no active production.",
"StructureProductionRandomBonusDelay is added to this.")]
public readonly int StructureProductionInactiveDelay = 125;
[Desc("Additional delay (in ticks) added between structure production checks when actively building things.",
"Note: this should be at least as large as the typical order latency to avoid duplicated build choices.")]
public readonly int StructureProductionActiveDelay = 25;
[Desc("A random delay (in ticks) of up to this is added to active/inactive production delays.")]
public readonly int StructureProductionRandomBonusDelay = 10;
[Desc("Delay (in ticks) until retrying to build structure after the last 3 consecutive attempts failed.")]
public readonly int StructureProductionResumeDelay = 1500;
[Desc("After how many failed attempts to place a structure should AI give up and wait",
"for StructureProductionResumeDelay before retrying.")]
public readonly int MaximumFailedPlacementAttempts = 3;
[Desc("How many randomly chosen cells with resources to check when deciding refinery placement.")]
public readonly int MaxResourceCellsToCheck = 3;
[Desc("Delay (in ticks) until rechecking for new BaseProviders.")]
public readonly int CheckForNewBasesDelay = 1500;
[Desc("Chance that the AI will place the defenses in the direction of the closest enemy building.")]
public readonly int PlaceDefenseTowardsEnemyChance = 100;
[Desc("Minimum range at which to build defensive structures near a combat hotspot.")]
public readonly int MinimumDefenseRadius = 5;
[Desc("Maximum range at which to build defensive structures near a combat hotspot.")]
public readonly int MaximumDefenseRadius = 20;
[Desc("Try to build another production building if there is too much cash.")]
public readonly int NewProductionCashThreshold = 5000;
[Desc("Radius in cells around a factory scanned for rally points by the AI.")]
public readonly int RallyPointScanRadius = 8;
[Desc("Radius in cells around each building with ProvideBuildableArea",
"to check for a 3x3 area of water where naval structures can be built.",
"Should match maximum adjacency of naval structures.")]
public readonly int CheckForWaterRadius = 8;
[Desc("Terrain types which are considered water for base building purposes.")]
public readonly HashSet<string> WaterTerrainTypes = new HashSet<string> { "Water" };
[Desc("What buildings to the AI should build.", "What integer percentage of the total base must be this type of building.")]
public readonly Dictionary<string, int> BuildingFractions = null;
[Desc("What buildings should the AI have a maximum limit to build.")]
public readonly Dictionary<string, int> BuildingLimits = null;
[Desc("When should the AI start building specific buildings.")]
public readonly Dictionary<string, int> BuildingDelays = null;
public override object Create(ActorInitializer init) { return new BaseBuilderBotModule(init.Self, this); }
}
public class BaseBuilderBotModule : ConditionalTrait<BaseBuilderBotModuleInfo>, IGameSaveTraitData,
IBotTick, IBotPositionsUpdated, IBotRespondToAttack, IBotRequestPauseUnitProduction
{
public CPos GetRandomBaseCenter()
{
var randomConstructionYard = world.Actors.Where(a => a.Owner == player &&
Info.ConstructionYardTypes.Contains(a.Info.Name))
.RandomOrDefault(world.LocalRandom);
return randomConstructionYard?.Location ?? initialBaseCenter;
}
public CPos DefenseCenter => defenseCenter;
readonly World world;
readonly Player player;
PowerManager playerPower;
PlayerResources playerResources;
IResourceLayer resourceLayer;
IBotPositionsUpdated[] positionsUpdatedModules;
CPos initialBaseCenter;
CPos defenseCenter;
List<BaseBuilderQueueManager> builders = new List<BaseBuilderQueueManager>();
public BaseBuilderBotModule(Actor self, BaseBuilderBotModuleInfo info)
: base(info)
{
world = self.World;
player = self.Owner;
}
protected override void Created(Actor self)
{
playerPower = self.Owner.PlayerActor.TraitOrDefault<PowerManager>();
playerResources = self.Owner.PlayerActor.Trait<PlayerResources>();
resourceLayer = self.World.WorldActor.TraitOrDefault<IResourceLayer>();
positionsUpdatedModules = self.Owner.PlayerActor.TraitsImplementing<IBotPositionsUpdated>().ToArray();
}
protected override void TraitEnabled(Actor self)
{
foreach (var building in Info.BuildingQueues)
builders.Add(new BaseBuilderQueueManager(this, building, player, playerPower, playerResources, resourceLayer));
foreach (var defense in Info.DefenseQueues)
builders.Add(new BaseBuilderQueueManager(this, defense, player, playerPower, playerResources, resourceLayer));
}
void IBotPositionsUpdated.UpdatedBaseCenter(CPos newLocation)
{
initialBaseCenter = newLocation;
}
void IBotPositionsUpdated.UpdatedDefenseCenter(CPos newLocation)
{
defenseCenter = newLocation;
}
bool IBotRequestPauseUnitProduction.PauseUnitProduction => !IsTraitDisabled && !HasAdequateRefineryCount;
void IBotTick.BotTick(IBot bot)
{
SetRallyPointsForNewProductionBuildings(bot);
foreach (var b in builders)
b.Tick(bot);
}
void IBotRespondToAttack.RespondToAttack(IBot bot, Actor self, AttackInfo e)
{
if (e.Attacker == null || e.Attacker.Disposed)
return;
if (e.Attacker.Owner.RelationshipWith(self.Owner) != PlayerRelationship.Enemy)
return;
if (!e.Attacker.Info.HasTraitInfo<ITargetableInfo>())
return;
// Protect buildings
if (self.Info.HasTraitInfo<BuildingInfo>())
foreach (var n in positionsUpdatedModules)
n.UpdatedDefenseCenter(e.Attacker.Location);
}
void SetRallyPointsForNewProductionBuildings(IBot bot)
{
|
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 BaseBuilderBotModule : ConditionalTrait<BaseBuilderBotModuleInfo>, IGameSaveTraitData,
IBotTick, IBotPositionsUpdated, IBotRespondToAttack, IBotRequestPauseUnitProduction
{
// ...
void IBotTick.BotTick(IBot bot)
{
SetRallyPointsForNewProductionBuildings(bot);
foreach (var b in builders)
b.Tick(bot);
}
Cheatsheet (for next line):
- We are in IBotTick.BotTick(), which is a method that gets called every tick.
- The method is supposed to update the bot's state and perform any necessary actions.
- The method is currently calling SetRallyPointsForNewProductionBuildings(bot) and then ticking each builder in the builders list.
- The task is likely to add another action to be performed in this method.
Relevant lines:
- The method header IBotTick.BotTick(IBot bot)
- The existing code inside the method
Next line will likely be: [Insert new action here, e.g., another method call or a conditional statement]
|
|
Please complete the code given below.
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb.planner;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.hsqldb_voltpatches.HSQLInterface;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltcore.utils.Pair;
import org.voltdb.VoltType;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.Statement;
import org.voltdb.catalog.StmtParameter;
import org.voltdb.compiler.DDLCompiler;
import org.voltdb.compiler.DatabaseEstimates;
import org.voltdb.compiler.DeterminismMode;
import org.voltdb.compiler.StatementCompiler;
import org.voltdb.compiler.VoltCompiler;
import org.voltdb.compiler.VoltDDLElementTracker;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.plannodes.PlanNodeList;
import org.voltdb.plannodes.SchemaColumn;
import org.voltdb.types.QueryType;
import org.voltdb.utils.BuildDirectoryUtils;
/**
* Some utility functions to compile SQL statements for plan generation tests.
*/
public class PlannerTestAideDeCamp {
private final Catalog catalog;
private final Procedure proc;
private final HSQLInterface hsql;
private final Database db;
int compileCounter = 0;
private CompiledPlan m_currentPlan = null;
/**
* Loads the schema at ddlurl and setups a voltcompiler / hsql instance.
* @param ddlurl URL to the schema/ddl file.
* @param basename Unique string, JSON plans [basename]-stmt-#_json.txt on disk
* @throws Exception
*/
public PlannerTestAideDeCamp(URL ddlurl, String basename) throws Exception {
catalog = new Catalog();
catalog.execute("add / clusters cluster");
catalog.execute("add /clusters[cluster] databases database");
db = catalog.getClusters().get("cluster").getDatabases().get("database");
proc = db.getProcedures().add(basename);
String schemaPath = URLDecoder.decode(ddlurl.getPath(), "UTF-8");
VoltCompiler compiler = new VoltCompiler();
hsql = HSQLInterface.loadHsqldb();
//hsql.runDDLFile(schemaPath);
VoltDDLElementTracker partitionMap = new VoltDDLElementTracker(compiler);
DDLCompiler ddl_compiler = new DDLCompiler(compiler, hsql, partitionMap, db);
ddl_compiler.loadSchema(schemaPath);
ddl_compiler.compileToCatalog(catalog, db);
}
public void tearDown() {
}
public Catalog getCatalog() {
return catalog;
}
public Database getDatabase() {
return db;
}
/**
* Compile a statement and return the head of the plan.
* @param sql
*/
public CompiledPlan compileAdHocPlan(String sql)
{
compile(sql, 0, null, null, true, false);
return m_currentPlan;
}
/**
* Compile a statement and return the head of the plan.
* @param sql
* @param detMode
*/
public CompiledPlan compileAdHocPlan(String sql, DeterminismMode detMode)
{
compile(sql, 0, null, null, true, false, detMode);
return m_currentPlan;
}
public List<AbstractPlanNode> compile(String sql, int paramCount)
{
return compile(sql, paramCount, false, null);
}
public List<AbstractPlanNode> compile(String sql, int paramCount, boolean singlePartition) {
return compile(sql, paramCount, singlePartition, null);
}
public List<AbstractPlanNode> compile(String sql, int paramCount, boolean singlePartition, String joinOrder) {
Object partitionBy = null;
if (singlePartition) {
partitionBy = "Forced single partitioning";
}
return compile(sql, paramCount, joinOrder, partitionBy, true, false);
}
public List<AbstractPlanNode> compile(String sql, int paramCount, String joinOrder, Object partitionParameter, boolean inferSP, boolean lockInSP) {
return compile(sql, paramCount, joinOrder, partitionParameter, inferSP, lockInSP, DeterminismMode.SAFER);
}
/**
* Compile and cache the statement and plan and return the final plan graph.
*/
public List<AbstractPlanNode> compile(String sql, int paramCount, String joinOrder, Object partitionParameter, boolean inferSP, boolean lockInSP, DeterminismMode detMode)
{
Statement catalogStmt = proc.getStatements().add("stmt-" + String.valueOf(compileCounter++));
catalogStmt.setSqltext(sql);
catalogStmt.setSinglepartition(partitionParameter != null);
catalogStmt.setBatched(false);
catalogStmt.setParamnum(paramCount);
// determine the type of the query
QueryType qtype = QueryType.SELECT;
catalogStmt.setReadonly(true);
if (sql.toLowerCase().startsWith("insert")) {
qtype = QueryType.INSERT;
catalogStmt.setReadonly(false);
}
if (sql.toLowerCase().startsWith("update")) {
qtype = QueryType.UPDATE;
catalogStmt.setReadonly(false);
}
if (sql.toLowerCase().startsWith("delete")) {
qtype = QueryType.DELETE;
catalogStmt.setReadonly(false);
}
catalogStmt.setQuerytype(qtype.getValue());
// name will look like "basename-stmt-#"
String name = catalogStmt.getParent().getTypeName() + "-" + catalogStmt.getTypeName();
DatabaseEstimates estimates = new DatabaseEstimates();
TrivialCostModel costModel = new TrivialCostModel();
PartitioningForStatement partitioning = new PartitioningForStatement(partitionParameter, inferSP, lockInSP);
QueryPlanner planner =
new QueryPlanner(catalogStmt.getSqltext(), catalogStmt.getTypeName(),
catalogStmt.getParent().getTypeName(), catalog.getClusters().get("cluster"),
db, partitioning, hsql, estimates, false, StatementCompiler.DEFAULT_MAX_JOIN_TABLES,
costModel, null, joinOrder, detMode);
CompiledPlan plan = null;
planner.parse();
plan = planner.plan();
assert(plan != null);
// Input Parameters
// We will need to update the system catalogs with this new information
// If this is an adhoc query then there won't be any parameters
for (int i = 0; i < plan.parameters.length; ++i) {
StmtParameter catalogParam = catalogStmt.getParameters().add(String.valueOf(i));
catalogParam.setJavatype(plan.parameters[i].getValue());
catalogParam.setIndex(i);
}
// Output Columns
int index = 0;
for (SchemaColumn col : plan.columns.getColumns())
{
Column catColumn = catalogStmt.getOutput_columns().add(String.valueOf(index));
catColumn.setNullable(false);
catColumn.setIndex(index);
catColumn.setName(col.getColumnName());
catColumn.setType(col.getType().getValue());
catColumn.setSize(col.getSize());
index++;
}
|
[
" List<PlanNodeList> nodeLists = new ArrayList<PlanNodeList>();"
] | 768
|
lcc
|
java
| null |
fc248cbd17650fa9a1b49a55fb76191e355a916d55809db3
| 62
|
Your task is code completion.
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb.planner;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.hsqldb_voltpatches.HSQLInterface;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltcore.utils.Pair;
import org.voltdb.VoltType;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.Statement;
import org.voltdb.catalog.StmtParameter;
import org.voltdb.compiler.DDLCompiler;
import org.voltdb.compiler.DatabaseEstimates;
import org.voltdb.compiler.DeterminismMode;
import org.voltdb.compiler.StatementCompiler;
import org.voltdb.compiler.VoltCompiler;
import org.voltdb.compiler.VoltDDLElementTracker;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.plannodes.PlanNodeList;
import org.voltdb.plannodes.SchemaColumn;
import org.voltdb.types.QueryType;
import org.voltdb.utils.BuildDirectoryUtils;
/**
* Some utility functions to compile SQL statements for plan generation tests.
*/
public class PlannerTestAideDeCamp {
private final Catalog catalog;
private final Procedure proc;
private final HSQLInterface hsql;
private final Database db;
int compileCounter = 0;
private CompiledPlan m_currentPlan = null;
/**
* Loads the schema at ddlurl and setups a voltcompiler / hsql instance.
* @param ddlurl URL to the schema/ddl file.
* @param basename Unique string, JSON plans [basename]-stmt-#_json.txt on disk
* @throws Exception
*/
public PlannerTestAideDeCamp(URL ddlurl, String basename) throws Exception {
catalog = new Catalog();
catalog.execute("add / clusters cluster");
catalog.execute("add /clusters[cluster] databases database");
db = catalog.getClusters().get("cluster").getDatabases().get("database");
proc = db.getProcedures().add(basename);
String schemaPath = URLDecoder.decode(ddlurl.getPath(), "UTF-8");
VoltCompiler compiler = new VoltCompiler();
hsql = HSQLInterface.loadHsqldb();
//hsql.runDDLFile(schemaPath);
VoltDDLElementTracker partitionMap = new VoltDDLElementTracker(compiler);
DDLCompiler ddl_compiler = new DDLCompiler(compiler, hsql, partitionMap, db);
ddl_compiler.loadSchema(schemaPath);
ddl_compiler.compileToCatalog(catalog, db);
}
public void tearDown() {
}
public Catalog getCatalog() {
return catalog;
}
public Database getDatabase() {
return db;
}
/**
* Compile a statement and return the head of the plan.
* @param sql
*/
public CompiledPlan compileAdHocPlan(String sql)
{
compile(sql, 0, null, null, true, false);
return m_currentPlan;
}
/**
* Compile a statement and return the head of the plan.
* @param sql
* @param detMode
*/
public CompiledPlan compileAdHocPlan(String sql, DeterminismMode detMode)
{
compile(sql, 0, null, null, true, false, detMode);
return m_currentPlan;
}
public List<AbstractPlanNode> compile(String sql, int paramCount)
{
return compile(sql, paramCount, false, null);
}
public List<AbstractPlanNode> compile(String sql, int paramCount, boolean singlePartition) {
return compile(sql, paramCount, singlePartition, null);
}
public List<AbstractPlanNode> compile(String sql, int paramCount, boolean singlePartition, String joinOrder) {
Object partitionBy = null;
if (singlePartition) {
partitionBy = "Forced single partitioning";
}
return compile(sql, paramCount, joinOrder, partitionBy, true, false);
}
public List<AbstractPlanNode> compile(String sql, int paramCount, String joinOrder, Object partitionParameter, boolean inferSP, boolean lockInSP) {
return compile(sql, paramCount, joinOrder, partitionParameter, inferSP, lockInSP, DeterminismMode.SAFER);
}
/**
* Compile and cache the statement and plan and return the final plan graph.
*/
public List<AbstractPlanNode> compile(String sql, int paramCount, String joinOrder, Object partitionParameter, boolean inferSP, boolean lockInSP, DeterminismMode detMode)
{
Statement catalogStmt = proc.getStatements().add("stmt-" + String.valueOf(compileCounter++));
catalogStmt.setSqltext(sql);
catalogStmt.setSinglepartition(partitionParameter != null);
catalogStmt.setBatched(false);
catalogStmt.setParamnum(paramCount);
// determine the type of the query
QueryType qtype = QueryType.SELECT;
catalogStmt.setReadonly(true);
if (sql.toLowerCase().startsWith("insert")) {
qtype = QueryType.INSERT;
catalogStmt.setReadonly(false);
}
if (sql.toLowerCase().startsWith("update")) {
qtype = QueryType.UPDATE;
catalogStmt.setReadonly(false);
}
if (sql.toLowerCase().startsWith("delete")) {
qtype = QueryType.DELETE;
catalogStmt.setReadonly(false);
}
catalogStmt.setQuerytype(qtype.getValue());
// name will look like "basename-stmt-#"
String name = catalogStmt.getParent().getTypeName() + "-" + catalogStmt.getTypeName();
DatabaseEstimates estimates = new DatabaseEstimates();
TrivialCostModel costModel = new TrivialCostModel();
PartitioningForStatement partitioning = new PartitioningForStatement(partitionParameter, inferSP, lockInSP);
QueryPlanner planner =
new QueryPlanner(catalogStmt.getSqltext(), catalogStmt.getTypeName(),
catalogStmt.getParent().getTypeName(), catalog.getClusters().get("cluster"),
db, partitioning, hsql, estimates, false, StatementCompiler.DEFAULT_MAX_JOIN_TABLES,
costModel, null, joinOrder, detMode);
CompiledPlan plan = null;
planner.parse();
plan = planner.plan();
assert(plan != null);
// Input Parameters
// We will need to update the system catalogs with this new information
// If this is an adhoc query then there won't be any parameters
for (int i = 0; i < plan.parameters.length; ++i) {
StmtParameter catalogParam = catalogStmt.getParameters().add(String.valueOf(i));
catalogParam.setJavatype(plan.parameters[i].getValue());
catalogParam.setIndex(i);
}
// Output Columns
int index = 0;
for (SchemaColumn col : plan.columns.getColumns())
{
Column catColumn = catalogStmt.getOutput_columns().add(String.valueOf(index));
catColumn.setNullable(false);
catColumn.setIndex(index);
catColumn.setName(col.getColumnName());
catColumn.setType(col.getType().getValue());
catColumn.setSize(col.getSize());
index++;
}
|
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 the brevity]
public class PlannerTestAideDeCamp {
// ...
public List<AbstractPlanNode> compile(String sql, int paramCount, String joinOrder, Object partitionParameter, boolean inferSP, boolean lockInSP, DeterminismMode detMode)
{
// ...
CompiledPlan plan = null;
planner.parse();
plan = planner.plan();
assert(plan != null);
// Input Parameters
// We will need to update the system catalogs with this new information
// If this is an adhoc query then there won't be any parameters
for (int i = 0; i < plan.parameters.length; ++i) {
StmtParameter catalogParam = catalogStmt.getParameters().add(String.valueOf(i));
catalogParam.setJavatype(plan.parameters[i].getValue());
catalogParam.setIndex(i);
}
// Output Columns
int index = 0;
for (SchemaColumn col : plan.columns.getColumns())
{
Column catColumn = catalogStmt.getOutput_columns().add(String.valueOf(index));
catColumn.setNullable(false);
catColumn.setIndex(index);
catColumn.setName(col.getColumnName());
catColumn.setType(col.getType().getValue());
catColumn.setSize(col.getSize());
index++;
}
// ...
Cheatsheet (for next line):
- We are in the compile() method, which is returning a List of AbstractPlanNode.
- plan is a CompiledPlan object that was just created.
- The method is returning the final plan graph.
- The previous lines have added parameters and output columns to the catalog statement.
- [Relevant lines: declaration of plan, previous for loops]
Next line will likely be: return plan.getPlan();
|
|
Please complete the code given below.
/* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 1997-2004 Apple Computer, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Data;
using System.Text;
using Bonjour;
namespace SimpleChat.NET
{
/// <summary>
/// Summary description for Form1.
/// </summary>
///
public class SimpleChat : System.Windows.Forms.Form
{
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private Bonjour.DNSSDEventManager m_eventManager = null;
private Bonjour.DNSSDService m_service = null;
private Bonjour.DNSSDService m_registrar = null;
private Bonjour.DNSSDService m_browser = null;
private Bonjour.DNSSDService m_resolver = null;
private String m_name;
private Socket m_socket = null;
private const int BUFFER_SIZE = 1024;
public byte[] m_buffer = new byte[BUFFER_SIZE];
public bool m_complete = false;
public StringBuilder m_sb = new StringBuilder();
delegate void ReadMessageCallback(String data);
ReadMessageCallback m_readMessageCallback;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.RichTextBox richTextBox1;
// ServiceRegistered
//
// Called by DNSServices core as a result of Register()
// call
//
public void
ServiceRegistered
(
DNSSDService service,
DNSSDFlags flags,
String name,
String regType,
String domain
)
{
m_name = name;
//
// Try to start browsing for other instances of this service
//
try
{
m_browser = m_service.Browse(0, 0, "_p2pchat._udp", null, m_eventManager);
}
catch
{
MessageBox.Show("Browse Failed", "Error");
Application.Exit();
}
}
//
// ServiceFound
//
// Called by DNSServices core as a result of a Browse call
//
public void
ServiceFound
(
DNSSDService sref,
DNSSDFlags flags,
uint ifIndex,
String serviceName,
String regType,
String domain
)
{
if (serviceName != m_name)
{
PeerData peer = new PeerData();
peer.InterfaceIndex = ifIndex;
peer.Name = serviceName;
peer.Type = regType;
peer.Domain = domain;
peer.Address = null;
comboBox1.Items.Add(peer);
if (comboBox1.Items.Count == 1)
{
comboBox1.SelectedIndex = 0;
}
}
}
//
// ServiceLost
//
// Called by DNSServices core as a result of a Browse call
//
public void
ServiceLost
(
DNSSDService sref,
DNSSDFlags flags,
uint ifIndex,
String serviceName,
String regType,
String domain
)
{
PeerData peer = new PeerData();
peer.InterfaceIndex = ifIndex;
peer.Name = serviceName;
peer.Type = regType;
peer.Domain = domain;
peer.Address = null;
comboBox1.Items.Remove(peer);
}
//
// ServiceResolved
//
// Called by DNSServices core as a result of DNSService.Resolve()
// call
//
public void
ServiceResolved
(
DNSSDService sref,
DNSSDFlags flags,
uint ifIndex,
String fullName,
String hostName,
ushort port,
TXTRecord txtRecord
)
{
m_resolver.Stop();
m_resolver = null;
PeerData peer = (PeerData)comboBox1.SelectedItem;
peer.Port = port;
//
// Query for the IP address associated with "hostName"
//
try
{
m_resolver = m_service.QueryRecord(0, ifIndex, hostName, DNSSDRRType.kDNSSDType_A, DNSSDRRClass.kDNSSDClass_IN, m_eventManager );
}
catch
{
MessageBox.Show("QueryRecord Failed", "Error");
Application.Exit();
}
}
//
// QueryAnswered
//
// Called by DNSServices core as a result of DNSService.QueryRecord()
// call
//
public void
QueryAnswered
(
DNSSDService service,
DNSSDFlags flags,
uint ifIndex,
String fullName,
DNSSDRRType rrtype,
DNSSDRRClass rrclass,
Object rdata,
uint ttl
)
{
//
// Stop the resolve to reduce the burden on the network
//
m_resolver.Stop();
m_resolver = null;
PeerData peer = (PeerData) comboBox1.SelectedItem;
uint bits = BitConverter.ToUInt32( (Byte[])rdata, 0);
System.Net.IPAddress address = new System.Net.IPAddress(bits);
peer.Address = address;
}
public void
OperationFailed
(
DNSSDService service,
DNSSDError error
)
{
MessageBox.Show("Operation returned an error code " + error, "Error");
}
//
// OnReadMessage
//
// Called when there is data to be read on a socket
//
// This is called (indirectly) from OnReadSocket()
//
private void
OnReadMessage
(
String msg
)
{
int rgb = 0;
for (int i = 0; i < msg.Length && msg[i] != ':'; i++)
{
rgb = rgb ^ ((int)msg[i] << (i % 3 + 2) * 8);
}
Color color = Color.FromArgb(rgb & 0x007F7FFF);
richTextBox1.SelectionColor = color;
richTextBox1.AppendText(msg + Environment.NewLine);
}
//
// OnReadSocket
//
// Called by the .NET core when there is data to be read on a socket
//
// This is called from a worker thread by the .NET core
//
private void
OnReadSocket
(
IAsyncResult ar
)
{
try
{
int read = m_socket.EndReceive(ar);
if (read > 0)
{
String msg = Encoding.UTF8.GetString(m_buffer, 0, read);
Invoke(m_readMessageCallback, new Object[]{msg});
}
m_socket.BeginReceive(m_buffer, 0, BUFFER_SIZE, 0, new AsyncCallback(OnReadSocket), this);
}
catch
{
}
}
public SimpleChat()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
try
{
m_service = new DNSSDService();
}
catch
{
MessageBox.Show("Bonjour Service is not available", "Error");
Application.Exit();
}
//
// Associate event handlers with all the Bonjour events that the app is interested in.
//
m_eventManager = new DNSSDEventManager();
m_eventManager.ServiceRegistered += new _IDNSSDEvents_ServiceRegisteredEventHandler(this.ServiceRegistered);
m_eventManager.ServiceFound += new _IDNSSDEvents_ServiceFoundEventHandler(this.ServiceFound);
m_eventManager.ServiceLost += new _IDNSSDEvents_ServiceLostEventHandler(this.ServiceLost);
m_eventManager.ServiceResolved += new _IDNSSDEvents_ServiceResolvedEventHandler(this.ServiceResolved);
m_eventManager.QueryRecordAnswered += new _IDNSSDEvents_QueryRecordAnsweredEventHandler(this.QueryAnswered);
m_eventManager.OperationFailed += new _IDNSSDEvents_OperationFailedEventHandler(this.OperationFailed);
//
// Socket read handler
//
m_readMessageCallback = new ReadMessageCallback(OnReadMessage);
this.Load += new System.EventHandler(this.Form1_Load);
this.AcceptButton = button1;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void
Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
if (m_registrar != null)
{
m_registrar.Stop();
}
if (m_browser != null)
{
m_browser.Stop();
}
if (m_resolver != null)
{
m_resolver.Stop();
}
m_eventManager.ServiceFound -= new _IDNSSDEvents_ServiceFoundEventHandler(this.ServiceFound);
m_eventManager.ServiceLost -= new _IDNSSDEvents_ServiceLostEventHandler(this.ServiceLost);
m_eventManager.ServiceResolved -= new _IDNSSDEvents_ServiceResolvedEventHandler(this.ServiceResolved);
m_eventManager.QueryRecordAnswered -= new _IDNSSDEvents_QueryRecordAnsweredEventHandler(this.QueryAnswered);
m_eventManager.OperationFailed -= new _IDNSSDEvents_OperationFailedEventHandler(this.OperationFailed);
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// comboBox1
//
this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.Location = new System.Drawing.Point(59, 208);
this.comboBox1.Name = "comboBox1";
|
[
"\t\t\tthis.comboBox1.Size = new System.Drawing.Size(224, 21);"
] | 1,012
|
lcc
|
csharp
| null |
8f007015b8b3b455a6fcd8f989241324f18ff10327811d5b
| 63
|
Your task is code completion.
/* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 1997-2004 Apple Computer, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Data;
using System.Text;
using Bonjour;
namespace SimpleChat.NET
{
/// <summary>
/// Summary description for Form1.
/// </summary>
///
public class SimpleChat : System.Windows.Forms.Form
{
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private Bonjour.DNSSDEventManager m_eventManager = null;
private Bonjour.DNSSDService m_service = null;
private Bonjour.DNSSDService m_registrar = null;
private Bonjour.DNSSDService m_browser = null;
private Bonjour.DNSSDService m_resolver = null;
private String m_name;
private Socket m_socket = null;
private const int BUFFER_SIZE = 1024;
public byte[] m_buffer = new byte[BUFFER_SIZE];
public bool m_complete = false;
public StringBuilder m_sb = new StringBuilder();
delegate void ReadMessageCallback(String data);
ReadMessageCallback m_readMessageCallback;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.RichTextBox richTextBox1;
// ServiceRegistered
//
// Called by DNSServices core as a result of Register()
// call
//
public void
ServiceRegistered
(
DNSSDService service,
DNSSDFlags flags,
String name,
String regType,
String domain
)
{
m_name = name;
//
// Try to start browsing for other instances of this service
//
try
{
m_browser = m_service.Browse(0, 0, "_p2pchat._udp", null, m_eventManager);
}
catch
{
MessageBox.Show("Browse Failed", "Error");
Application.Exit();
}
}
//
// ServiceFound
//
// Called by DNSServices core as a result of a Browse call
//
public void
ServiceFound
(
DNSSDService sref,
DNSSDFlags flags,
uint ifIndex,
String serviceName,
String regType,
String domain
)
{
if (serviceName != m_name)
{
PeerData peer = new PeerData();
peer.InterfaceIndex = ifIndex;
peer.Name = serviceName;
peer.Type = regType;
peer.Domain = domain;
peer.Address = null;
comboBox1.Items.Add(peer);
if (comboBox1.Items.Count == 1)
{
comboBox1.SelectedIndex = 0;
}
}
}
//
// ServiceLost
//
// Called by DNSServices core as a result of a Browse call
//
public void
ServiceLost
(
DNSSDService sref,
DNSSDFlags flags,
uint ifIndex,
String serviceName,
String regType,
String domain
)
{
PeerData peer = new PeerData();
peer.InterfaceIndex = ifIndex;
peer.Name = serviceName;
peer.Type = regType;
peer.Domain = domain;
peer.Address = null;
comboBox1.Items.Remove(peer);
}
//
// ServiceResolved
//
// Called by DNSServices core as a result of DNSService.Resolve()
// call
//
public void
ServiceResolved
(
DNSSDService sref,
DNSSDFlags flags,
uint ifIndex,
String fullName,
String hostName,
ushort port,
TXTRecord txtRecord
)
{
m_resolver.Stop();
m_resolver = null;
PeerData peer = (PeerData)comboBox1.SelectedItem;
peer.Port = port;
//
// Query for the IP address associated with "hostName"
//
try
{
m_resolver = m_service.QueryRecord(0, ifIndex, hostName, DNSSDRRType.kDNSSDType_A, DNSSDRRClass.kDNSSDClass_IN, m_eventManager );
}
catch
{
MessageBox.Show("QueryRecord Failed", "Error");
Application.Exit();
}
}
//
// QueryAnswered
//
// Called by DNSServices core as a result of DNSService.QueryRecord()
// call
//
public void
QueryAnswered
(
DNSSDService service,
DNSSDFlags flags,
uint ifIndex,
String fullName,
DNSSDRRType rrtype,
DNSSDRRClass rrclass,
Object rdata,
uint ttl
)
{
//
// Stop the resolve to reduce the burden on the network
//
m_resolver.Stop();
m_resolver = null;
PeerData peer = (PeerData) comboBox1.SelectedItem;
uint bits = BitConverter.ToUInt32( (Byte[])rdata, 0);
System.Net.IPAddress address = new System.Net.IPAddress(bits);
peer.Address = address;
}
public void
OperationFailed
(
DNSSDService service,
DNSSDError error
)
{
MessageBox.Show("Operation returned an error code " + error, "Error");
}
//
// OnReadMessage
//
// Called when there is data to be read on a socket
//
// This is called (indirectly) from OnReadSocket()
//
private void
OnReadMessage
(
String msg
)
{
int rgb = 0;
for (int i = 0; i < msg.Length && msg[i] != ':'; i++)
{
rgb = rgb ^ ((int)msg[i] << (i % 3 + 2) * 8);
}
Color color = Color.FromArgb(rgb & 0x007F7FFF);
richTextBox1.SelectionColor = color;
richTextBox1.AppendText(msg + Environment.NewLine);
}
//
// OnReadSocket
//
// Called by the .NET core when there is data to be read on a socket
//
// This is called from a worker thread by the .NET core
//
private void
OnReadSocket
(
IAsyncResult ar
)
{
try
{
int read = m_socket.EndReceive(ar);
if (read > 0)
{
String msg = Encoding.UTF8.GetString(m_buffer, 0, read);
Invoke(m_readMessageCallback, new Object[]{msg});
}
m_socket.BeginReceive(m_buffer, 0, BUFFER_SIZE, 0, new AsyncCallback(OnReadSocket), this);
}
catch
{
}
}
public SimpleChat()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
try
{
m_service = new DNSSDService();
}
catch
{
MessageBox.Show("Bonjour Service is not available", "Error");
Application.Exit();
}
//
// Associate event handlers with all the Bonjour events that the app is interested in.
//
m_eventManager = new DNSSDEventManager();
m_eventManager.ServiceRegistered += new _IDNSSDEvents_ServiceRegisteredEventHandler(this.ServiceRegistered);
m_eventManager.ServiceFound += new _IDNSSDEvents_ServiceFoundEventHandler(this.ServiceFound);
m_eventManager.ServiceLost += new _IDNSSDEvents_ServiceLostEventHandler(this.ServiceLost);
m_eventManager.ServiceResolved += new _IDNSSDEvents_ServiceResolvedEventHandler(this.ServiceResolved);
m_eventManager.QueryRecordAnswered += new _IDNSSDEvents_QueryRecordAnsweredEventHandler(this.QueryAnswered);
m_eventManager.OperationFailed += new _IDNSSDEvents_OperationFailedEventHandler(this.OperationFailed);
//
// Socket read handler
//
m_readMessageCallback = new ReadMessageCallback(OnReadMessage);
this.Load += new System.EventHandler(this.Form1_Load);
this.AcceptButton = button1;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void
Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
if (m_registrar != null)
{
m_registrar.Stop();
}
if (m_browser != null)
{
m_browser.Stop();
}
if (m_resolver != null)
{
m_resolver.Stop();
}
m_eventManager.ServiceFound -= new _IDNSSDEvents_ServiceFoundEventHandler(this.ServiceFound);
m_eventManager.ServiceLost -= new _IDNSSDEvents_ServiceLostEventHandler(this.ServiceLost);
m_eventManager.ServiceResolved -= new _IDNSSDEvents_ServiceResolvedEventHandler(this.ServiceResolved);
m_eventManager.QueryRecordAnswered -= new _IDNSSDEvents_QueryRecordAnsweredEventHandler(this.QueryAnswered);
m_eventManager.OperationFailed -= new _IDNSSDEvents_OperationFailedEventHandler(this.OperationFailed);
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// comboBox1
//
this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.Location = new System.Drawing.Point(59, 208);
this.comboBox1.Name = "comboBox1";
|
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]
public class SimpleChat : System.Windows.Forms.Form
{
// ... (many lines omitted for brevity)
private void InitializeComponent()
{
// ... (many lines omitted for brevity)
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 12);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(260, 190);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
this.richTextBox1.TextChanged += new System.EventHandler(this.richTextBox1_TextChanged);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "SimpleChat";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
Cheatsheet (for next line):
- We are in the Form1_Load event handler, which is called when the form is loaded.
- richTextBox1 is a RichTextBox control on the form.
- richTextBox1_TextChanged is an event handler for the TextChanged event of richTextBox1.
- The form's Load event is a good place to initialize the form's UI or perform other setup tasks.
- [Relevant lines: richTextBox1_TextChanged, Form1_Load]
Next line will likely be: this.richTextBox1.Text = "Connected to " + m_name + " on port " + m_port;
|
|
Please complete the code given below.
//
// System.IO.Ports.WinSerialStream.cs
//
// Authors:
// Carlos Alberto Cortez (calberto.cortez@gmail.com)
//
// (c) Copyright 2006 Novell, Inc. (http://www.novell.com)
//
using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.ComponentModel;
namespace System.IO.Ports
{
class WinSerialStream : Stream, ISerialStream, IDisposable
{
// Windows API Constants
const uint GenericRead = 0x80000000;
const uint GenericWrite = 0x40000000;
const uint OpenExisting = 3;
const uint FileFlagOverlapped = 0x40000000;
const uint PurgeRxClear = 0x0008;
const uint PurgeTxClear = 0x0004;
const uint WinInfiniteTimeout = 0xFFFFFFFF;
const uint FileIOPending = 997;
// Signal constants
const uint SetRts = 3;
const uint ClearRts = 4;
const uint SetDtr = 5;
const uint ClearDtr = 6;
const uint SetBreak = 8;
const uint ClearBreak = 9;
const uint CtsOn = 0x0010;
const uint DsrOn = 0x0020;
const uint RsldOn = 0x0080;
// Event constants
const uint EvRxChar = 0x0001;
const uint EvCts = 0x0008;
const uint EvDsr = 0x0010;
const uint EvRlsd = 0x0020;
const uint EvBreak = 0x0040;
const uint EvErr = 0x0080;
const uint EvRing = 0x0100;
int handle;
int read_timeout;
int write_timeout;
bool disposed;
IntPtr write_overlapped;
IntPtr read_overlapped;
ManualResetEvent read_event;
ManualResetEvent write_event;
Timeouts timeouts;
[DllImport("kernel32", SetLastError = true)]
static extern int CreateFile(string port_name, uint desired_access,
uint share_mode, uint security_attrs, uint creation, uint flags,
uint template);
[DllImport("kernel32", SetLastError = true)]
static extern bool SetupComm(int handle, int read_buffer_size, int write_buffer_size);
[DllImport("kernel32", SetLastError = true)]
static extern bool PurgeComm(int handle, uint flags);
[DllImport("kernel32", SetLastError = true)]
static extern bool SetCommTimeouts(int handle, Timeouts timeouts);
public WinSerialStream (string port_name, int baud_rate, int data_bits, Parity parity, StopBits sb,
bool dtr_enable, bool rts_enable, Handshake hs, int read_timeout, int write_timeout,
int read_buffer_size, int write_buffer_size)
{
handle = CreateFile (port_name != null && !port_name.StartsWith(@"\\.\")
? @"\\.\" + port_name : port_name,
GenericRead | GenericWrite, 0, 0, OpenExisting,
FileFlagOverlapped, 0);
if (handle == -1)
ReportIOError (port_name);
// Set port low level attributes
SetAttributes (baud_rate, parity, data_bits, sb, hs);
// Clean buffers and set sizes
if (!PurgeComm (handle, PurgeRxClear | PurgeTxClear) ||
!SetupComm (handle, read_buffer_size, write_buffer_size))
ReportIOError (null);
// Set timeouts
this.read_timeout = read_timeout;
this.write_timeout = write_timeout;
timeouts = new Timeouts (read_timeout, write_timeout);
if (!SetCommTimeouts(handle, timeouts))
ReportIOError (null);
/// Set DTR and RTS
SetSignal(SerialSignal.Dtr, dtr_enable);
if (hs != Handshake.RequestToSend &&
hs != Handshake.RequestToSendXOnXOff)
SetSignal(SerialSignal.Rts, rts_enable);
// Init overlapped structures
NativeOverlapped wo = new NativeOverlapped ();
write_event = new ManualResetEvent (false);
wo.EventHandle = write_event.Handle;
write_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped)));
Marshal.StructureToPtr (wo, write_overlapped, true);
NativeOverlapped ro = new NativeOverlapped ();
read_event = new ManualResetEvent (false);
ro.EventHandle = read_event.Handle;
read_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped)));
Marshal.StructureToPtr (ro, read_overlapped, true);
}
public override bool CanRead {
get {
return true;
}
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanTimeout {
get {
return true;
}
}
public override bool CanWrite {
get {
return true;
}
}
public override int ReadTimeout {
get {
return read_timeout;
}
set {
if (value < 0 && value != SerialPort.InfiniteTimeout)
throw new ArgumentOutOfRangeException ("value");
timeouts.SetValues (value, write_timeout);
if (!SetCommTimeouts (handle, timeouts))
ReportIOError (null);
read_timeout = value;
}
}
public override int WriteTimeout {
get {
return write_timeout;
}
set
{
if (value < 0 && value != SerialPort.InfiniteTimeout)
throw new ArgumentOutOfRangeException ("value");
timeouts.SetValues (read_timeout, value);
if (!SetCommTimeouts (handle, timeouts))
ReportIOError (null);
write_timeout = value;
}
}
public override long Length {
get {
throw new NotSupportedException ();
}
}
public override long Position {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
[DllImport("kernel32", SetLastError = true)]
static extern bool CloseHandle (int handle);
protected override void Dispose (bool disposing)
{
if (disposed)
return;
disposed = true;
CloseHandle (handle);
Marshal.FreeHGlobal (write_overlapped);
Marshal.FreeHGlobal (read_overlapped);
}
void IDisposable.Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public override void Close ()
{
((IDisposable)this).Dispose ();
}
~WinSerialStream ()
{
Dispose (false);
}
public override void Flush ()
{
CheckDisposed ();
// No dothing by now
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength (long value)
{
throw new NotSupportedException();
}
#if !TARGET_JVM
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool ReadFile (int handle, byte* buffer, int bytes_to_read,
out int bytes_read, IntPtr overlapped);
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool GetOverlappedResult (int handle, IntPtr overlapped,
ref int bytes_transfered, bool wait);
#endif
public override int Read ([In, Out] byte [] buffer, int offset, int count)
{
CheckDisposed ();
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException ("offset or count less than zero.");
if (buffer.Length - offset < count )
throw new ArgumentException ("offset+count",
"The size of the buffer is less than offset + count.");
int bytes_read;
unsafe {
fixed (byte* ptr = buffer) {
if (ReadFile (handle, ptr + offset, count, out bytes_read, read_overlapped))
return bytes_read;
// Test for overlapped behavior
if (Marshal.GetLastWin32Error () != FileIOPending)
ReportIOError (null);
if (!GetOverlappedResult (handle, read_overlapped, ref bytes_read, true))
ReportIOError (null);
}
}
if (bytes_read == 0)
throw new TimeoutException (); // We didn't get any byte
return bytes_read;
}
#if !TARGET_JVM
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool WriteFile (int handle, byte* buffer, int bytes_to_write,
out int bytes_written, IntPtr overlapped);
#endif
public override void Write (byte [] buffer, int offset, int count)
{
CheckDisposed ();
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException ();
if (buffer.Length - offset < count)
throw new ArgumentException ("offset+count",
"The size of the buffer is less than offset + count.");
int bytes_written = 0;
unsafe {
fixed (byte* ptr = buffer) {
if (WriteFile (handle, ptr + offset, count, out bytes_written, write_overlapped))
return;
if (Marshal.GetLastWin32Error() != FileIOPending)
ReportIOError (null);
if (!GetOverlappedResult(handle, write_overlapped, ref bytes_written, true))
ReportIOError (null);
}
}
// If the operation timed out, then
// we transfered less bytes than the requested ones
if (bytes_written < count)
throw new TimeoutException ();
}
[DllImport("kernel32", SetLastError = true)]
static extern bool GetCommState (int handle, [Out] DCB dcb);
[DllImport ("kernel32", SetLastError=true)]
static extern bool SetCommState (int handle, DCB dcb);
public void SetAttributes (int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs)
{
DCB dcb = new DCB ();
if (!GetCommState (handle, dcb))
ReportIOError (null);
|
[
"\t\t\tdcb.SetValues (baud_rate, parity, data_bits, bits, hs);"
] | 1,031
|
lcc
|
csharp
| null |
d356cc0ece3ba9de9fcbb2613757dcabae2d8a589e1f370b
| 64
|
Your task is code completion.
//
// System.IO.Ports.WinSerialStream.cs
//
// Authors:
// Carlos Alberto Cortez (calberto.cortez@gmail.com)
//
// (c) Copyright 2006 Novell, Inc. (http://www.novell.com)
//
using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.ComponentModel;
namespace System.IO.Ports
{
class WinSerialStream : Stream, ISerialStream, IDisposable
{
// Windows API Constants
const uint GenericRead = 0x80000000;
const uint GenericWrite = 0x40000000;
const uint OpenExisting = 3;
const uint FileFlagOverlapped = 0x40000000;
const uint PurgeRxClear = 0x0008;
const uint PurgeTxClear = 0x0004;
const uint WinInfiniteTimeout = 0xFFFFFFFF;
const uint FileIOPending = 997;
// Signal constants
const uint SetRts = 3;
const uint ClearRts = 4;
const uint SetDtr = 5;
const uint ClearDtr = 6;
const uint SetBreak = 8;
const uint ClearBreak = 9;
const uint CtsOn = 0x0010;
const uint DsrOn = 0x0020;
const uint RsldOn = 0x0080;
// Event constants
const uint EvRxChar = 0x0001;
const uint EvCts = 0x0008;
const uint EvDsr = 0x0010;
const uint EvRlsd = 0x0020;
const uint EvBreak = 0x0040;
const uint EvErr = 0x0080;
const uint EvRing = 0x0100;
int handle;
int read_timeout;
int write_timeout;
bool disposed;
IntPtr write_overlapped;
IntPtr read_overlapped;
ManualResetEvent read_event;
ManualResetEvent write_event;
Timeouts timeouts;
[DllImport("kernel32", SetLastError = true)]
static extern int CreateFile(string port_name, uint desired_access,
uint share_mode, uint security_attrs, uint creation, uint flags,
uint template);
[DllImport("kernel32", SetLastError = true)]
static extern bool SetupComm(int handle, int read_buffer_size, int write_buffer_size);
[DllImport("kernel32", SetLastError = true)]
static extern bool PurgeComm(int handle, uint flags);
[DllImport("kernel32", SetLastError = true)]
static extern bool SetCommTimeouts(int handle, Timeouts timeouts);
public WinSerialStream (string port_name, int baud_rate, int data_bits, Parity parity, StopBits sb,
bool dtr_enable, bool rts_enable, Handshake hs, int read_timeout, int write_timeout,
int read_buffer_size, int write_buffer_size)
{
handle = CreateFile (port_name != null && !port_name.StartsWith(@"\\.\")
? @"\\.\" + port_name : port_name,
GenericRead | GenericWrite, 0, 0, OpenExisting,
FileFlagOverlapped, 0);
if (handle == -1)
ReportIOError (port_name);
// Set port low level attributes
SetAttributes (baud_rate, parity, data_bits, sb, hs);
// Clean buffers and set sizes
if (!PurgeComm (handle, PurgeRxClear | PurgeTxClear) ||
!SetupComm (handle, read_buffer_size, write_buffer_size))
ReportIOError (null);
// Set timeouts
this.read_timeout = read_timeout;
this.write_timeout = write_timeout;
timeouts = new Timeouts (read_timeout, write_timeout);
if (!SetCommTimeouts(handle, timeouts))
ReportIOError (null);
/// Set DTR and RTS
SetSignal(SerialSignal.Dtr, dtr_enable);
if (hs != Handshake.RequestToSend &&
hs != Handshake.RequestToSendXOnXOff)
SetSignal(SerialSignal.Rts, rts_enable);
// Init overlapped structures
NativeOverlapped wo = new NativeOverlapped ();
write_event = new ManualResetEvent (false);
wo.EventHandle = write_event.Handle;
write_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped)));
Marshal.StructureToPtr (wo, write_overlapped, true);
NativeOverlapped ro = new NativeOverlapped ();
read_event = new ManualResetEvent (false);
ro.EventHandle = read_event.Handle;
read_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped)));
Marshal.StructureToPtr (ro, read_overlapped, true);
}
public override bool CanRead {
get {
return true;
}
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanTimeout {
get {
return true;
}
}
public override bool CanWrite {
get {
return true;
}
}
public override int ReadTimeout {
get {
return read_timeout;
}
set {
if (value < 0 && value != SerialPort.InfiniteTimeout)
throw new ArgumentOutOfRangeException ("value");
timeouts.SetValues (value, write_timeout);
if (!SetCommTimeouts (handle, timeouts))
ReportIOError (null);
read_timeout = value;
}
}
public override int WriteTimeout {
get {
return write_timeout;
}
set
{
if (value < 0 && value != SerialPort.InfiniteTimeout)
throw new ArgumentOutOfRangeException ("value");
timeouts.SetValues (read_timeout, value);
if (!SetCommTimeouts (handle, timeouts))
ReportIOError (null);
write_timeout = value;
}
}
public override long Length {
get {
throw new NotSupportedException ();
}
}
public override long Position {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
[DllImport("kernel32", SetLastError = true)]
static extern bool CloseHandle (int handle);
protected override void Dispose (bool disposing)
{
if (disposed)
return;
disposed = true;
CloseHandle (handle);
Marshal.FreeHGlobal (write_overlapped);
Marshal.FreeHGlobal (read_overlapped);
}
void IDisposable.Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public override void Close ()
{
((IDisposable)this).Dispose ();
}
~WinSerialStream ()
{
Dispose (false);
}
public override void Flush ()
{
CheckDisposed ();
// No dothing by now
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength (long value)
{
throw new NotSupportedException();
}
#if !TARGET_JVM
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool ReadFile (int handle, byte* buffer, int bytes_to_read,
out int bytes_read, IntPtr overlapped);
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool GetOverlappedResult (int handle, IntPtr overlapped,
ref int bytes_transfered, bool wait);
#endif
public override int Read ([In, Out] byte [] buffer, int offset, int count)
{
CheckDisposed ();
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException ("offset or count less than zero.");
if (buffer.Length - offset < count )
throw new ArgumentException ("offset+count",
"The size of the buffer is less than offset + count.");
int bytes_read;
unsafe {
fixed (byte* ptr = buffer) {
if (ReadFile (handle, ptr + offset, count, out bytes_read, read_overlapped))
return bytes_read;
// Test for overlapped behavior
if (Marshal.GetLastWin32Error () != FileIOPending)
ReportIOError (null);
if (!GetOverlappedResult (handle, read_overlapped, ref bytes_read, true))
ReportIOError (null);
}
}
if (bytes_read == 0)
throw new TimeoutException (); // We didn't get any byte
return bytes_read;
}
#if !TARGET_JVM
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool WriteFile (int handle, byte* buffer, int bytes_to_write,
out int bytes_written, IntPtr overlapped);
#endif
public override void Write (byte [] buffer, int offset, int count)
{
CheckDisposed ();
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException ();
if (buffer.Length - offset < count)
throw new ArgumentException ("offset+count",
"The size of the buffer is less than offset + count.");
int bytes_written = 0;
unsafe {
fixed (byte* ptr = buffer) {
if (WriteFile (handle, ptr + offset, count, out bytes_written, write_overlapped))
return;
if (Marshal.GetLastWin32Error() != FileIOPending)
ReportIOError (null);
if (!GetOverlappedResult(handle, write_overlapped, ref bytes_written, true))
ReportIOError (null);
}
}
// If the operation timed out, then
// we transfered less bytes than the requested ones
if (bytes_written < count)
throw new TimeoutException ();
}
[DllImport("kernel32", SetLastError = true)]
static extern bool GetCommState (int handle, [Out] DCB dcb);
[DllImport ("kernel32", SetLastError=true)]
static extern bool SetCommState (int handle, DCB dcb);
public void SetAttributes (int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs)
{
DCB dcb = new DCB ();
if (!GetCommState (handle, dcb))
ReportIOError (null);
|
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]
public void SetAttributes (int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs)
{
DCB dcb = new DCB ();
if (!GetCommState (handle, dcb))
ReportIOError (null);
Cheatsheet (for next line):
- We are in SetAttributes(), which is setting the attributes of a serial port.
- The method is called with baud_rate, parity, data_bits, bits, and hs as parameters.
- The DCB (Device Control Block) structure is used to store the serial port settings.
- The GetCommState function is used to get the current state of the serial port.
- The ReportIOError method is used to handle any errors that occur.
- The handle variable is the file handle of the serial port.
- The DCB structure has several fields that need to be set based on the input parameters.
- The relevant lines are the method header, the DCB declaration, and the GetCommState function call.
Next line will likely be:
- Setting the baud_rate field of the DCB structure.
- The DCB structure has a field called BaudRate, which is used to set the baud rate of the serial port.
- The BaudRate field is of type DWORD, which is a 32-bit unsigned integer.
Next line will likely be:
dcb.BaudRate = baud_rate;
|
|
Please complete the code given below.
# Copyright (c) 2008-2009 Participatory Culture Foundation
# See LICENSE for details.
import re
from django.core import mail
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from channelguide.testframework import TestCase
from channelguide.cobranding.models import Cobranding
class UserProfileTest(TestCase):
def setUp(self):
TestCase.setUp(self)
self.user = self.make_user('mary')
def login_data(self):
return {'username': 'mary', 'password': 'password',
'which-form': 'login' }
def register_data(self):
"""
Return a dictionary of data used to register a new user.
"""
return {'newusername': u'mike\xf6', 'email': 'mike@mike.com',
'newpassword': u'password\xdf\xdf',
'newpassword2': u'password\xdf\xdf',
'which-form': 'register' }
def register(self):
"""
Return the final response from registering a user.
"""
response = self.post_data("/accounts/register/", self.register_data())
self.assertRedirect(response, '')
response = self.get_page('/')
context = response.context[0]
self.assertEquals(context['request'].notifications[0][0],
_('Thanks for registering!'))
self.assertEquals(context['user'].username, u'mike\xf6')
self.assertEquals(context['user'].email, 'mike@mike.com')
self.assert_(context['user'].check_password(
u'password\xdf\xdf'))
self.assertEquals(context['user'].get_profile().user,
context['user'])
self.assertEquals(context['user'].is_active, True)
return response
def bad_login_data(self):
return {'username': 'mary', 'password': 'badpassword',
'which-form': 'login' }
def test_login(self):
response = self.post_data(settings.LOGIN_URL, self.login_data())
self.assertRedirect(response, '')
response = self.get_page('/')
self.assertEquals(response.context[0]['user'].username,
self.user.username)
def test_login_with_email(self):
data = self.login_data()
data['username'] = self.user.email
response = self.post_data(settings.LOGIN_URL, data)
self.assertRedirect(response, '')
response = self.get_page('/')
self.assertEquals(response.context[0]['user'].username,
self.user.username)
def test_bad_login(self):
response = self.post_data(settings.LOGIN_URL, self.bad_login_data())
self.assert_(not response.context[0]['user'].is_authenticated())
def test_register(self):
self.register()
def test_forgot_password(self):
user = self.make_user('rachel')
data = {'email': user.email}
self.post_data("/accounts/password_reset/", data)
regex = re.compile(r'/accounts/reset/[\w-]+/')
url = regex.search(mail.outbox[0].body).group(0)
data = {'new_password1': 'newpass', 'new_password2': 'badmatch'}
page = self.post_data(url, data=data)
self.assertEquals(page.status_code, 200) # didn't redirect to a new
# page
data['new_password2'] = data['new_password1']
page = self.post_data(url, data=data)
self.assertEquals(page.status_code, 302)
user_check = User.objects.get(pk=user.pk)
self.assert_(user_check.check_password('newpass'))
def test_user_starts_unapproved(self):
"""
Users should start off unapproved.
"""
response = self.register()
user = response.context[0]['request'].user
self.assertEquals(user.get_profile().approved, False)
def test_registration_send_approval_email(self):
"""
Registering a user should send an e-mail to that user letting them
approve their account.
"""
response = self.register()
user = response.context[0]['request'].user
self.check_confirmation_email(user)
def check_confirmation_email(self, user):
email = mail.outbox[-1]
self.assertEquals(email.subject, 'Approve your Miro Guide account')
self.assertEquals(email.recipients(), ['mike@mike.com'])
m = re.match("""
You have requested a new user account on Miro Guide and you specified
this address \((.*?)\) as your e-mail address.
If you did not do this, simply ignore this e-mail. To confirm your
registration, please follow this link:
(.*?)
Your ratings will show up, but won't count towards the average until
you use this confirmation link.
Thanks,
The Miro Guide""", email.body)
self.assert_(m, 'Email does not match:\n%s' % email.body)
self.assertEquals(m.groups()[0], 'mike@mike.com')
self.assertEquals(m.groups()[1],
'%saccounts/confirm/%s/%s' % (settings.BASE_URL_FULL,
user.id, user.get_profile().generate_confirmation_code()))
def test_confirmation_url_confirms_user(self):
"""
When the user visits the confirmation url, it should set the approval
flag to true.
"""
response = self.register()
user = response.context[0]['request'].user
url = user.get_profile().generate_confirmation_url()
response = self.get_page(url[len(settings.BASE_URL_FULL)-1:])
user = User.objects.get(pk=user.pk)
self.assert_(user.get_profile().approved)
def test_no_confirmation_with_bad_code(self):
"""
If the user gives an incorrect code, they should not be confirmed.
"""
response = self.register()
user = response.context[0]['request'].user
url = user.get_profile().generate_confirmation_url()
response = self.get_page(url[len(settings.BASE_URL_FULL)-1:-1])
user = User.objects.get(pk=user.pk)
self.assert_(not user.get_profile().approved)
def test_resend_confirmation_code(self):
"""
/accounts/confirm/<id>/resend should resent the initial confirmation
email.
"""
response = self.register()
user = response.context[0]['request'].user
url = user.get_profile().generate_confirmation_url()
parts = url[len(settings.BASE_URL_FULL)-1:].split('/')
url = '/'.join(parts[:-1]) + '/resend'
mail.outbox = []
response = self.get_page(url)
self.check_confirmation_email(user)
def test_unicode_in_data(self):
"""
The profile page should render even when the user has Unicode elements.
"""
response = self.register()
user = response.context[0]['request'].user
user.city = u'S\u1111o'
user.save()
self.get_page(user.get_absolute_url())
class ModerateUserTest(TestCase):
def setUp(self):
TestCase.setUp(self)
self.jane = self.make_user("jane")
self.jane.is_superuser = True
self.jane.save()
self.bob = self.make_user("bob")
self.cathy = self.make_user("cathy")
self.adrian = self.make_user("adrian")
self.judy = self.make_user("judy")
self.judy.email = 'judy@bob.com'
self.judy.save()
def test_auth(self):
self.login(self.adrian)
response = self.get_page("/accounts/search", data={'query': 'yahoo'})
self.assertLoginRedirect(response)
response = self.post_data("/accounts/profile/",
{'action': 'promote', 'id': self.bob.id})
self.assertLoginRedirect(response)
response = self.post_data("/accounts/profile/",
{'action': 'demote', 'id': self.bob.id})
self.assertLoginRedirect(response)
def check_search(self, query, *correct_results):
response = self.get_page("/accounts/search", data={'query': query})
returned_names = [u.username for u in
response.context[0]['page'].object_list]
correct_names = [u.username for u in correct_results]
self.assertSameSet(returned_names, correct_names)
def test_search_users(self):
self.login(self.jane)
self.check_search('cathy', self.cathy)
self.check_search('bob', self.bob, self.judy)
self.check_search('test.test', self.jane, self.bob, self.cathy,
self.adrian)
self.check_search('blahblah') # no users should be returned
def check_promote_demote(self, user, action, permission=None):
self.post_data("/accounts/profile/%i/" % user.pk, {'action': action})
user = User.objects.get(pk=user.pk)
if permission is not None:
self.assert_(user.has_perm(permission))
else:
self.assert_(not user.get_all_permissions())
return user
def test_promote_user(self):
self.login(self.jane)
user = self.check_promote_demote(self.bob, 'promote',
'user_profile.betatester')
self.assertFalse(user.has_perm('channels.change_channel'))
user = self.check_promote_demote(self.bob, 'promote',
'channels.change_channel')
self.assertFalse(user.has_perm('featured_add_featured_queue'))
self.check_promote_demote(self.bob, 'promote',
'featured.add_featuredqueue')
# no group has this permission, so only superusers should have it
self.check_promote_demote(self.bob, 'promote',
'channels.add_generatedstats')
self.check_promote_demote(self.bob, 'promote',
'channels.add_generatedstats')
def test_demote_user(self):
self.login(self.jane)
for i in range(5):
self.cathy.get_profile().promote()
user = self.check_promote_demote(self.cathy, 'demote',
'featured.add_featuredqueue')
self.assertFalse(user.is_superuser)
user = self.check_promote_demote(self.cathy, 'demote',
'channels.change_channel')
self.assertFalse(user.has_perm('featured.add_featuredqueue'))
user = self.check_promote_demote(self.cathy, 'demote',
'user_profile.betatester')
self.assertFalse(user.has_perm('channels.change_channel'))
user = self.check_promote_demote(self.cathy, 'demote')
self.assertFalse(user.has_perm('user_profile.betatester'))
self.check_promote_demote(self.cathy, 'demote')
class EditUserTest(TestCase):
def setUp(self):
TestCase.setUp(self)
self.user = self.make_user('mary')
self.admin = self.make_user('joe')
self.admin.is_superuser = True
self.admin.save()
self.other_user = self.make_user('bobby',
group='cg_moderator')
def check_can_see_edit_page(self, user, should_see):
page = self.get_page('/accounts/profile/%i/' % self.user.id, user)
if should_see:
self.assertCanAccess(page)
else:
self.assertLoginRedirect(page)
def test_permissions(self):
self.check_can_see_edit_page(self.user, True)
self.check_can_see_edit_page(self.admin, True)
self.check_can_see_edit_page(self.other_user, False)
class UserViewTest(TestCase):
def setUp(self):
TestCase.setUp(self)
self.user = self.make_user('mary')
self.channel = self.make_channel(self.user)
def test_view(self):
page = self.get_page(self.user.get_profile().get_url())
self.assertEquals(page.status_code, 200)
self.assertEquals(page.context['for_user'], self.user)
self.assertEquals(page.context['cobrand'], None)
self.assertEquals(page.context['biggest'].paginator.count, 1)
self.assertEquals(page.context['biggest'].object_list[0], self.channel)
def test_view_with_site(self):
site = self.make_channel(self.user)
site.url = None
site.save()
page = self.get_page(self.user.get_profile().get_url())
self.assertEquals(page.status_code, 200)
self.assertEquals(page.context['for_user'], self.user)
self.assertEquals(page.context['cobrand'], None)
self.assertEquals(page.context['biggest'].paginator.count, 1)
self.assertEquals(page.context['feed_page'].object_list[0],
self.channel)
self.assertEquals(page.context['site_page'].object_list[0], site)
def test_url_with_id_is_redirected(self):
url = reverse('channelguide.user_profile.views.for_user',
args=(self.user.pk,))
page = self.get_page(url)
self.assertRedirect(page, self.user.get_profile().get_url())
def test_inactive_user_gives_404(self):
self.user.is_active = False
self.user.save()
page = self.get_page(self.user.get_profile().get_url())
self.assertEquals(page.status_code, 404)
def test_unknown_user_gives_404(self):
url = reverse('channelguide.user_profile.views.for_user',
args=('unknown_username',))
page = self.get_page(url)
self.assertEquals(page.status_code, 404)
def test_user_with_cobrand(self):
cobrand = Cobranding.objects.create(user=self.user)
page = self.get_page(self.user.get_profile().get_url(),
login_as=self.user)
self.assertEquals(page.context['cobrand'],
cobrand)
def test_user_with_cobrand_admin(self):
admin = self.make_user('admin')
admin.is_superuser = True
admin.save()
cobrand = Cobranding.objects.create(user=self.user)
|
[
" page = self.get_page(self.user.get_profile().get_url(),"
] | 840
|
lcc
|
python
| null |
feedb243436593ce6db6b01f37eaf505c93f329ca6adb4ff
| 65
|
Your task is code completion.
# Copyright (c) 2008-2009 Participatory Culture Foundation
# See LICENSE for details.
import re
from django.core import mail
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from channelguide.testframework import TestCase
from channelguide.cobranding.models import Cobranding
class UserProfileTest(TestCase):
def setUp(self):
TestCase.setUp(self)
self.user = self.make_user('mary')
def login_data(self):
return {'username': 'mary', 'password': 'password',
'which-form': 'login' }
def register_data(self):
"""
Return a dictionary of data used to register a new user.
"""
return {'newusername': u'mike\xf6', 'email': 'mike@mike.com',
'newpassword': u'password\xdf\xdf',
'newpassword2': u'password\xdf\xdf',
'which-form': 'register' }
def register(self):
"""
Return the final response from registering a user.
"""
response = self.post_data("/accounts/register/", self.register_data())
self.assertRedirect(response, '')
response = self.get_page('/')
context = response.context[0]
self.assertEquals(context['request'].notifications[0][0],
_('Thanks for registering!'))
self.assertEquals(context['user'].username, u'mike\xf6')
self.assertEquals(context['user'].email, 'mike@mike.com')
self.assert_(context['user'].check_password(
u'password\xdf\xdf'))
self.assertEquals(context['user'].get_profile().user,
context['user'])
self.assertEquals(context['user'].is_active, True)
return response
def bad_login_data(self):
return {'username': 'mary', 'password': 'badpassword',
'which-form': 'login' }
def test_login(self):
response = self.post_data(settings.LOGIN_URL, self.login_data())
self.assertRedirect(response, '')
response = self.get_page('/')
self.assertEquals(response.context[0]['user'].username,
self.user.username)
def test_login_with_email(self):
data = self.login_data()
data['username'] = self.user.email
response = self.post_data(settings.LOGIN_URL, data)
self.assertRedirect(response, '')
response = self.get_page('/')
self.assertEquals(response.context[0]['user'].username,
self.user.username)
def test_bad_login(self):
response = self.post_data(settings.LOGIN_URL, self.bad_login_data())
self.assert_(not response.context[0]['user'].is_authenticated())
def test_register(self):
self.register()
def test_forgot_password(self):
user = self.make_user('rachel')
data = {'email': user.email}
self.post_data("/accounts/password_reset/", data)
regex = re.compile(r'/accounts/reset/[\w-]+/')
url = regex.search(mail.outbox[0].body).group(0)
data = {'new_password1': 'newpass', 'new_password2': 'badmatch'}
page = self.post_data(url, data=data)
self.assertEquals(page.status_code, 200) # didn't redirect to a new
# page
data['new_password2'] = data['new_password1']
page = self.post_data(url, data=data)
self.assertEquals(page.status_code, 302)
user_check = User.objects.get(pk=user.pk)
self.assert_(user_check.check_password('newpass'))
def test_user_starts_unapproved(self):
"""
Users should start off unapproved.
"""
response = self.register()
user = response.context[0]['request'].user
self.assertEquals(user.get_profile().approved, False)
def test_registration_send_approval_email(self):
"""
Registering a user should send an e-mail to that user letting them
approve their account.
"""
response = self.register()
user = response.context[0]['request'].user
self.check_confirmation_email(user)
def check_confirmation_email(self, user):
email = mail.outbox[-1]
self.assertEquals(email.subject, 'Approve your Miro Guide account')
self.assertEquals(email.recipients(), ['mike@mike.com'])
m = re.match("""
You have requested a new user account on Miro Guide and you specified
this address \((.*?)\) as your e-mail address.
If you did not do this, simply ignore this e-mail. To confirm your
registration, please follow this link:
(.*?)
Your ratings will show up, but won't count towards the average until
you use this confirmation link.
Thanks,
The Miro Guide""", email.body)
self.assert_(m, 'Email does not match:\n%s' % email.body)
self.assertEquals(m.groups()[0], 'mike@mike.com')
self.assertEquals(m.groups()[1],
'%saccounts/confirm/%s/%s' % (settings.BASE_URL_FULL,
user.id, user.get_profile().generate_confirmation_code()))
def test_confirmation_url_confirms_user(self):
"""
When the user visits the confirmation url, it should set the approval
flag to true.
"""
response = self.register()
user = response.context[0]['request'].user
url = user.get_profile().generate_confirmation_url()
response = self.get_page(url[len(settings.BASE_URL_FULL)-1:])
user = User.objects.get(pk=user.pk)
self.assert_(user.get_profile().approved)
def test_no_confirmation_with_bad_code(self):
"""
If the user gives an incorrect code, they should not be confirmed.
"""
response = self.register()
user = response.context[0]['request'].user
url = user.get_profile().generate_confirmation_url()
response = self.get_page(url[len(settings.BASE_URL_FULL)-1:-1])
user = User.objects.get(pk=user.pk)
self.assert_(not user.get_profile().approved)
def test_resend_confirmation_code(self):
"""
/accounts/confirm/<id>/resend should resent the initial confirmation
email.
"""
response = self.register()
user = response.context[0]['request'].user
url = user.get_profile().generate_confirmation_url()
parts = url[len(settings.BASE_URL_FULL)-1:].split('/')
url = '/'.join(parts[:-1]) + '/resend'
mail.outbox = []
response = self.get_page(url)
self.check_confirmation_email(user)
def test_unicode_in_data(self):
"""
The profile page should render even when the user has Unicode elements.
"""
response = self.register()
user = response.context[0]['request'].user
user.city = u'S\u1111o'
user.save()
self.get_page(user.get_absolute_url())
class ModerateUserTest(TestCase):
def setUp(self):
TestCase.setUp(self)
self.jane = self.make_user("jane")
self.jane.is_superuser = True
self.jane.save()
self.bob = self.make_user("bob")
self.cathy = self.make_user("cathy")
self.adrian = self.make_user("adrian")
self.judy = self.make_user("judy")
self.judy.email = 'judy@bob.com'
self.judy.save()
def test_auth(self):
self.login(self.adrian)
response = self.get_page("/accounts/search", data={'query': 'yahoo'})
self.assertLoginRedirect(response)
response = self.post_data("/accounts/profile/",
{'action': 'promote', 'id': self.bob.id})
self.assertLoginRedirect(response)
response = self.post_data("/accounts/profile/",
{'action': 'demote', 'id': self.bob.id})
self.assertLoginRedirect(response)
def check_search(self, query, *correct_results):
response = self.get_page("/accounts/search", data={'query': query})
returned_names = [u.username for u in
response.context[0]['page'].object_list]
correct_names = [u.username for u in correct_results]
self.assertSameSet(returned_names, correct_names)
def test_search_users(self):
self.login(self.jane)
self.check_search('cathy', self.cathy)
self.check_search('bob', self.bob, self.judy)
self.check_search('test.test', self.jane, self.bob, self.cathy,
self.adrian)
self.check_search('blahblah') # no users should be returned
def check_promote_demote(self, user, action, permission=None):
self.post_data("/accounts/profile/%i/" % user.pk, {'action': action})
user = User.objects.get(pk=user.pk)
if permission is not None:
self.assert_(user.has_perm(permission))
else:
self.assert_(not user.get_all_permissions())
return user
def test_promote_user(self):
self.login(self.jane)
user = self.check_promote_demote(self.bob, 'promote',
'user_profile.betatester')
self.assertFalse(user.has_perm('channels.change_channel'))
user = self.check_promote_demote(self.bob, 'promote',
'channels.change_channel')
self.assertFalse(user.has_perm('featured_add_featured_queue'))
self.check_promote_demote(self.bob, 'promote',
'featured.add_featuredqueue')
# no group has this permission, so only superusers should have it
self.check_promote_demote(self.bob, 'promote',
'channels.add_generatedstats')
self.check_promote_demote(self.bob, 'promote',
'channels.add_generatedstats')
def test_demote_user(self):
self.login(self.jane)
for i in range(5):
self.cathy.get_profile().promote()
user = self.check_promote_demote(self.cathy, 'demote',
'featured.add_featuredqueue')
self.assertFalse(user.is_superuser)
user = self.check_promote_demote(self.cathy, 'demote',
'channels.change_channel')
self.assertFalse(user.has_perm('featured.add_featuredqueue'))
user = self.check_promote_demote(self.cathy, 'demote',
'user_profile.betatester')
self.assertFalse(user.has_perm('channels.change_channel'))
user = self.check_promote_demote(self.cathy, 'demote')
self.assertFalse(user.has_perm('user_profile.betatester'))
self.check_promote_demote(self.cathy, 'demote')
class EditUserTest(TestCase):
def setUp(self):
TestCase.setUp(self)
self.user = self.make_user('mary')
self.admin = self.make_user('joe')
self.admin.is_superuser = True
self.admin.save()
self.other_user = self.make_user('bobby',
group='cg_moderator')
def check_can_see_edit_page(self, user, should_see):
page = self.get_page('/accounts/profile/%i/' % self.user.id, user)
if should_see:
self.assertCanAccess(page)
else:
self.assertLoginRedirect(page)
def test_permissions(self):
self.check_can_see_edit_page(self.user, True)
self.check_can_see_edit_page(self.admin, True)
self.check_can_see_edit_page(self.other_user, False)
class UserViewTest(TestCase):
def setUp(self):
TestCase.setUp(self)
self.user = self.make_user('mary')
self.channel = self.make_channel(self.user)
def test_view(self):
page = self.get_page(self.user.get_profile().get_url())
self.assertEquals(page.status_code, 200)
self.assertEquals(page.context['for_user'], self.user)
self.assertEquals(page.context['cobrand'], None)
self.assertEquals(page.context['biggest'].paginator.count, 1)
self.assertEquals(page.context['biggest'].object_list[0], self.channel)
def test_view_with_site(self):
site = self.make_channel(self.user)
site.url = None
site.save()
page = self.get_page(self.user.get_profile().get_url())
self.assertEquals(page.status_code, 200)
self.assertEquals(page.context['for_user'], self.user)
self.assertEquals(page.context['cobrand'], None)
self.assertEquals(page.context['biggest'].paginator.count, 1)
self.assertEquals(page.context['feed_page'].object_list[0],
self.channel)
self.assertEquals(page.context['site_page'].object_list[0], site)
def test_url_with_id_is_redirected(self):
url = reverse('channelguide.user_profile.views.for_user',
args=(self.user.pk,))
page = self.get_page(url)
self.assertRedirect(page, self.user.get_profile().get_url())
def test_inactive_user_gives_404(self):
self.user.is_active = False
self.user.save()
page = self.get_page(self.user.get_profile().get_url())
self.assertEquals(page.status_code, 404)
def test_unknown_user_gives_404(self):
url = reverse('channelguide.user_profile.views.for_user',
args=('unknown_username',))
page = self.get_page(url)
self.assertEquals(page.status_code, 404)
def test_user_with_cobrand(self):
cobrand = Cobranding.objects.create(user=self.user)
page = self.get_page(self.user.get_profile().get_url(),
login_as=self.user)
self.assertEquals(page.context['cobrand'],
cobrand)
def test_user_with_cobrand_admin(self):
admin = self.make_user('admin')
admin.is_superuser = True
admin.save()
cobrand = Cobranding.objects.create(user=self.user)
|
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:
**UserProfileTest class**
* The class is testing user profile functionality.
* It has several test methods, including `test_login`, `test_register`, `test_forgot_password`, etc.
* The `register` method tests the registration process and checks various aspects of the registered user's profile.
* The `check_confirmation_email` method checks the email sent to the user after registration.
* The `test_confirmation_url_confirms_user` method tests the confirmation URL and checks if the user's profile is approved after visiting the URL.
**ModerateUserTest class**
* This class tests user moderation functionality.
* It has several test methods, including `test_auth`, `test_search_users`, `test_promote_user`, etc.
* The `check_search` method checks the search results for users.
* The `check_promote_demote` method promotes or demotes a user and checks their permissions.
**EditUserTest class**
* This class tests user editing functionality.
* It has a single test method, `test_permissions`, which checks if a user can see the edit page based on their permissions.
**UserViewTest class**
* This class tests user view functionality.
* It has several test methods, including `test_view`, `test_view_with_site`, `test_url_with_id_is_redirected`, etc.
* The `test_view` method tests the user view page and checks its context.
* The `test_user_with_cobrand` method tests the user view page with a cobrand.
**Relevant variables and methods**
* `self.user`: a user object used in various test methods.
* `self.make_user`: a method to create a new user.
* `self.get_page`: a method to get a page object.
* `self.post_data`: a method to post data to a URL.
* `self.assertRedirect`: a method to check if a response is a redirect.
* `self.assertLoginRedirect`: a method to check if a response is a login redirect.
* `self.assertSameSet`: a method to check if two sets are the same.
* `self.check_can_see_edit_page`: a method to check if a user can see the edit page.
* `self.check_promote_demote`: a method to promote or demote a user and check their permissions.
**Relevant lines and context**
* The `test_user_with_cobrand` method in the `UserViewTest` class is incomplete and needs to be completed.
* The `test_user_with_cobrand_admin` method in the `UserViewTest` class is also incomplete and needs to be completed.
Based on the context and the relevant variables and methods, the next line of code for the `test_user_with_cobrand` method might be:
```python
self.assertEquals(page.context['cobrand'], cobrand)
```
This line checks if the cobrand object is correctly set in the page context.
For the `test_user_with_cobrand_admin` method, the next line of code might be:
```python
self.assertEquals(page.context['cobrand'], cobrand)
```
This line also checks if the cobrand object is correctly set in the page context.
However, considering the method name `test_user_with_cobrand_admin`, it seems that the test should also check if the admin user can see the cobrand. The next line of code might be:
```python
self.check_can_see_edit_page(self.admin, True)
```
This line checks if the admin user can see the edit page.
|
|
Please complete the code given below.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
functional_tests
~~~~~~~~~~~~~~~~
This file contains the functional or acceptance tests for the fetchphotos project.
"""
# Time-stamp: <2015-02-22 14:17:50 bob>
## invoke tests using the call_func_tests.sh script in this directory
#pylint: disable=global-statement, invalid-name
import argparse
from contextlib import contextmanager
import copy
import datetime
import os
import re
import shutil
import string
import subprocess
import sys
import tempfile
import unittest
CF_TEMPLATE = string.Template(u'''
[General]
DIGICAMDIR=$src
DESTINATIONDIR=$dst
#IMAGE_EXTENSIONS= JPG, tiff
VIDEO_EXTENSIONS=mov avi
[File_processing]
ROTATE_PHOTOS=$rot
ADD_TIMESTAMP=$timestamp
LOWERCASE_FILENAME=$lower
''')
CF_DEFAULTS = {'src': '/path-to-images',
'dst': '/path-to-dst',
'rot': True,
'timestamp': True,
'lower': True}
_keep_tempdir = False
# Adapted from: http://stackoverflow.com/a/22434262
@contextmanager
def redirect_stdout_stderr(new_target, capture_stderr=False):
"""Make unit tests be quiet"""
if capture_stderr:
old_stderr, sys.stderr = sys.stderr, new_target # replace sys.stdout
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stdout = old_target # restore to the previous value
if capture_stderr:
sys.stderr = old_stderr
class TestMethods(unittest.TestCase):
"""Acceptance tests for fetchphotos.py.
These tests run the fetchphotos.py script, and do a lot of copying.
"""
def setUp(self):
"""fetchphotos needs logging to be initialized"""
#print "argv is", sys.argv
self.tempdir = tempfile.mkdtemp(dir='./')
self.cfgfile = os.path.join(self.tempdir, u"config.cfg")
self.srcdir = os.path.join(self.tempdir, u"src")
self.dstdir = os.path.join(self.tempdir, u"dst")
self.starttime = datetime.datetime.now()
shutil.copytree(u"./tests/testdata/example_images",
self.srcdir)
os.makedirs(self.dstdir)
#print "temp dir is:", self.tempdir
def tearDown(self):
"""Clean up results of tests"""
if _keep_tempdir is False:
shutil.rmtree(self.tempdir)
def test_check_tempdir(self):
"""Basic happy case with one specified file."""
write_config_file(self.cfgfile, self.tempdir)
subprocess.check_output(["python",
"fetchphotos.py",
"-c",
self.cfgfile,
os.path.join(self.tempdir,
u"src",
u"IMG_0533_normal_top_left.JPG")
],
stderr=subprocess.STDOUT)
dstfile = os.path.join(
self.dstdir,
u"2009-04-22T17.25.35_img_0533_normal_top_left.jpg")
# print "dstfile is", dstfile
self.assertTrue(os.path.isfile(dstfile))
def test_check_nolower(self):
"""Basic case with LOWERCASE_FILENAME=False."""
write_config_file(self.cfgfile, self.tempdir, ('lower', False))
subprocess.check_output(["python",
"fetchphotos.py",
"-c",
self.cfgfile,
os.path.join(self.tempdir,
u"src",
u"IMG_0533_normal_top_left.JPG")
],
stderr=subprocess.STDOUT)
# print "Result is \"{}\"".format(result)
dstfile = os.path.join(
self.dstdir,
u"2009-04-22T17.25.35_IMG_0533_normal_top_left.JPG")
self.assertTrue(os.path.isfile(dstfile))
def test_check_no_metadata(self):
"""Basic case with a file without metadata"""
write_config_file(self.cfgfile, self.tempdir, ('lower', False))
try:
result = subprocess.check_output(["python",
"fetchphotos.py",
"-c",
self.cfgfile,
os.path.join(self.tempdir,
u"src",
u"img_no_metadata.JPG")
],
stderr=subprocess.STDOUT)
#print "Result is \"{}\"".format(result)
except subprocess.CalledProcessError, e:
print "Got exception: \"{}\"".format(e.output)
match = re.match(r'^.*\-\-\>\s+(.*)$', result, re.MULTILINE)
self.assertIsNotNone(match)
if match is None:
return
destfile = match.group(1)
# The time for the new file will be sometime between when the
# tree copy was started and now (unless you're on a networked
# file system and the file server has a different time that
# this machine (unlikely))
# Try making a filename from each of these times until one
# matches.
then = copy.copy(self.starttime).replace(microsecond=0)
now = datetime.datetime.now().replace(microsecond=0)
got_match = False
while then <= now:
filename = os.path.join(
self.dstdir,
then.isoformat().replace(':', '.') + u"_img_no_metadata.JPG")
if filename == destfile:
got_match = True
break
then += datetime.timedelta(seconds=1)
then = then.replace(microsecond=0)
self.assertTrue(got_match)
def test_check_first_time(self):
"""Check what happens the first time fetchphotos is called"""
try:
subprocess.check_output(["python",
"fetchphotos.py",
"-c",
self.cfgfile,
"--generate-configfile"
],
stderr=subprocess.STDOUT)
# print "Result is \"{}\"".format(result)
except subprocess.CalledProcessError, e:
print "Got exception: \"{}\"".format(e.output)
self.assertTrue(os.path.isfile(self.cfgfile))
def write_config_file(fname, tdir, *pairs):
"""Writes a config file for testing.
The path for the src dir must be 'src', as that is what is used in
the setUp() method.
If present, *pairs is a list of key-value pairs that will be put into cf_sub.
"""
cf_sub = copy.copy(CF_DEFAULTS)
for key, value in pairs:
cf_sub[key] = value
cf_sub['src'] = os.path.join(tdir, u'src')
cf_sub['dst'] = os.path.join(tdir, u'dst')
#pprint.pprint(cf_sub)
with open(fname, "w") as out:
out.write(CF_TEMPLATE.substitute(cf_sub))
def main():
"""Main routine for functional unit tests"""
global _keep_tempdir
# This handy code from http://stackoverflow.com/a/17259773
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--keep-tempdir', dest='keep_tempdir',
action='store_true')
|
[
" options, args = parser.parse_known_args()"
] | 555
|
lcc
|
python
| null |
320e62adbcd607acda753d0d1559c566d029796c177de00e
| 66
|
Your task is code completion.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
functional_tests
~~~~~~~~~~~~~~~~
This file contains the functional or acceptance tests for the fetchphotos project.
"""
# Time-stamp: <2015-02-22 14:17:50 bob>
## invoke tests using the call_func_tests.sh script in this directory
#pylint: disable=global-statement, invalid-name
import argparse
from contextlib import contextmanager
import copy
import datetime
import os
import re
import shutil
import string
import subprocess
import sys
import tempfile
import unittest
CF_TEMPLATE = string.Template(u'''
[General]
DIGICAMDIR=$src
DESTINATIONDIR=$dst
#IMAGE_EXTENSIONS= JPG, tiff
VIDEO_EXTENSIONS=mov avi
[File_processing]
ROTATE_PHOTOS=$rot
ADD_TIMESTAMP=$timestamp
LOWERCASE_FILENAME=$lower
''')
CF_DEFAULTS = {'src': '/path-to-images',
'dst': '/path-to-dst',
'rot': True,
'timestamp': True,
'lower': True}
_keep_tempdir = False
# Adapted from: http://stackoverflow.com/a/22434262
@contextmanager
def redirect_stdout_stderr(new_target, capture_stderr=False):
"""Make unit tests be quiet"""
if capture_stderr:
old_stderr, sys.stderr = sys.stderr, new_target # replace sys.stdout
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stdout = old_target # restore to the previous value
if capture_stderr:
sys.stderr = old_stderr
class TestMethods(unittest.TestCase):
"""Acceptance tests for fetchphotos.py.
These tests run the fetchphotos.py script, and do a lot of copying.
"""
def setUp(self):
"""fetchphotos needs logging to be initialized"""
#print "argv is", sys.argv
self.tempdir = tempfile.mkdtemp(dir='./')
self.cfgfile = os.path.join(self.tempdir, u"config.cfg")
self.srcdir = os.path.join(self.tempdir, u"src")
self.dstdir = os.path.join(self.tempdir, u"dst")
self.starttime = datetime.datetime.now()
shutil.copytree(u"./tests/testdata/example_images",
self.srcdir)
os.makedirs(self.dstdir)
#print "temp dir is:", self.tempdir
def tearDown(self):
"""Clean up results of tests"""
if _keep_tempdir is False:
shutil.rmtree(self.tempdir)
def test_check_tempdir(self):
"""Basic happy case with one specified file."""
write_config_file(self.cfgfile, self.tempdir)
subprocess.check_output(["python",
"fetchphotos.py",
"-c",
self.cfgfile,
os.path.join(self.tempdir,
u"src",
u"IMG_0533_normal_top_left.JPG")
],
stderr=subprocess.STDOUT)
dstfile = os.path.join(
self.dstdir,
u"2009-04-22T17.25.35_img_0533_normal_top_left.jpg")
# print "dstfile is", dstfile
self.assertTrue(os.path.isfile(dstfile))
def test_check_nolower(self):
"""Basic case with LOWERCASE_FILENAME=False."""
write_config_file(self.cfgfile, self.tempdir, ('lower', False))
subprocess.check_output(["python",
"fetchphotos.py",
"-c",
self.cfgfile,
os.path.join(self.tempdir,
u"src",
u"IMG_0533_normal_top_left.JPG")
],
stderr=subprocess.STDOUT)
# print "Result is \"{}\"".format(result)
dstfile = os.path.join(
self.dstdir,
u"2009-04-22T17.25.35_IMG_0533_normal_top_left.JPG")
self.assertTrue(os.path.isfile(dstfile))
def test_check_no_metadata(self):
"""Basic case with a file without metadata"""
write_config_file(self.cfgfile, self.tempdir, ('lower', False))
try:
result = subprocess.check_output(["python",
"fetchphotos.py",
"-c",
self.cfgfile,
os.path.join(self.tempdir,
u"src",
u"img_no_metadata.JPG")
],
stderr=subprocess.STDOUT)
#print "Result is \"{}\"".format(result)
except subprocess.CalledProcessError, e:
print "Got exception: \"{}\"".format(e.output)
match = re.match(r'^.*\-\-\>\s+(.*)$', result, re.MULTILINE)
self.assertIsNotNone(match)
if match is None:
return
destfile = match.group(1)
# The time for the new file will be sometime between when the
# tree copy was started and now (unless you're on a networked
# file system and the file server has a different time that
# this machine (unlikely))
# Try making a filename from each of these times until one
# matches.
then = copy.copy(self.starttime).replace(microsecond=0)
now = datetime.datetime.now().replace(microsecond=0)
got_match = False
while then <= now:
filename = os.path.join(
self.dstdir,
then.isoformat().replace(':', '.') + u"_img_no_metadata.JPG")
if filename == destfile:
got_match = True
break
then += datetime.timedelta(seconds=1)
then = then.replace(microsecond=0)
self.assertTrue(got_match)
def test_check_first_time(self):
"""Check what happens the first time fetchphotos is called"""
try:
subprocess.check_output(["python",
"fetchphotos.py",
"-c",
self.cfgfile,
"--generate-configfile"
],
stderr=subprocess.STDOUT)
# print "Result is \"{}\"".format(result)
except subprocess.CalledProcessError, e:
print "Got exception: \"{}\"".format(e.output)
self.assertTrue(os.path.isfile(self.cfgfile))
def write_config_file(fname, tdir, *pairs):
"""Writes a config file for testing.
The path for the src dir must be 'src', as that is what is used in
the setUp() method.
If present, *pairs is a list of key-value pairs that will be put into cf_sub.
"""
cf_sub = copy.copy(CF_DEFAULTS)
for key, value in pairs:
cf_sub[key] = value
cf_sub['src'] = os.path.join(tdir, u'src')
cf_sub['dst'] = os.path.join(tdir, u'dst')
#pprint.pprint(cf_sub)
with open(fname, "w") as out:
out.write(CF_TEMPLATE.substitute(cf_sub))
def main():
"""Main routine for functional unit tests"""
global _keep_tempdir
# This handy code from http://stackoverflow.com/a/17259773
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--keep-tempdir', dest='keep_tempdir',
action='store_true')
|
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 main():
"""Main routine for functional unit tests"""
global _keep_tempdir
# This handy code from http://stackoverflow.com/a/17259773
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--keep-tempdir', dest='keep_tempdir',
action='store_true')
Cheatsheet (for next line):
- We are in the main() function, which is the entry point of the script.
- The script is using the argparse module to parse command-line arguments.
- The parser has already been created and configured.
- The '--keep-tempdir' argument is being added to the parser.
- The 'store_true' action means that the argument will be stored as a boolean value.
- The 'dest' argument specifies the name of the attribute that will be added to the parser's namespace.
- The 'action' argument specifies how the argument will be handled.
- The script is likely expecting the user to pass the '--keep-tempdir' argument when running the script.
- The global variable _keep_tempdir is being modified based on the value of the '--keep-tempdir' argument.
Next line will likely be:
args = parser.parse_args()
|
|
Please complete the code given below.
from enigma import eTimer, eEnv
from Screens.Screen import Screen
from Components.ActionMap import ActionMap, NumberActionMap
from Components.Pixmap import Pixmap, MultiPixmap
from Components.Label import Label
from Components.Sources.StaticText import StaticText
from Components.Sources.List import List
from Components.config import config, ConfigYesNo, NoSave, ConfigSubsection, ConfigText, ConfigSelection, ConfigPassword
from Components.Network import iNetwork
from Components.Console import Console
from Plugins.Plugin import PluginDescriptor
from Tools.Directories import resolveFilename, SCOPE_SKIN_IMAGE
from Tools.LoadPixmap import LoadPixmap
from Wlan import iWlan, iStatus, getWlanConfigName, existBcmWifi
from time import time
import re
plugin_path = eEnv.resolve("${libdir}/enigma2/python/Plugins/SystemPlugins/WirelessLan")
list = ["Unencrypted", "WEP", "WPA", "WPA/WPA2", "WPA2"]
weplist = ["ASCII", "HEX"]
config.plugins.wlan = ConfigSubsection()
config.plugins.wlan.essid = NoSave(ConfigText(default="", fixed_size=False))
config.plugins.wlan.hiddenessid = NoSave(ConfigYesNo(default=False))
config.plugins.wlan.encryption = NoSave(ConfigSelection(list, default="WPA2"))
config.plugins.wlan.wepkeytype = NoSave(ConfigSelection(weplist, default="ASCII"))
config.plugins.wlan.psk = NoSave(ConfigPassword(default="", fixed_size=False))
class WlanStatus(Screen):
skin = """
<screen name="WlanStatus" position="center,center" size="560,400" title="Wireless network status" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="LabelBSSID" render="Label" position="10,60" size="200,25" valign="left" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelESSID" render="Label" position="10,100" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelQuality" render="Label" position="10,140" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelSignal" render="Label" position="10,180" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelBitrate" render="Label" position="10,220" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelEnc" render="Label" position="10,260" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="BSSID" render="Label" position="220,60" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="ESSID" render="Label" position="220,100" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="quality" render="Label" position="220,140" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="signal" render="Label" position="220,180" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="bitrate" render="Label" position="220,220" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="enc" render="Label" position="220,260" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<ePixmap pixmap="div-h.png" position="0,350" zPosition="1" size="560,2" />
<widget source="IFtext" render="Label" position="10,355" size="120,21" zPosition="10" font="Regular;20" halign="left" backgroundColor="#25062748" transparent="1" />
<widget source="IF" render="Label" position="120,355" size="400,21" zPosition="10" font="Regular;20" halign="left" backgroundColor="#25062748" transparent="1" />
<widget source="Statustext" render="Label" position="10,375" size="115,21" zPosition="10" font="Regular;20" halign="left" backgroundColor="#25062748" transparent="1"/>
<widget name="statuspic" pixmaps="buttons/button_green.png,buttons/button_green_off.png" position="130,380" zPosition="10" size="15,16" transparent="1" alphatest="on"/>
</screen>"""
def __init__(self, session, iface):
Screen.__init__(self, session)
self.session = session
self.iface = iface
self["LabelBSSID"] = StaticText(_('Accesspoint:'))
self["LabelESSID"] = StaticText(_('SSID:'))
self["LabelQuality"] = StaticText(_('Link quality:'))
self["LabelSignal"] = StaticText(_('Signal strength:'))
self["LabelBitrate"] = StaticText(_('Bitrate:'))
self["LabelEnc"] = StaticText(_('Encryption:'))
self["BSSID"] = StaticText()
self["ESSID"] = StaticText()
self["quality"] = StaticText()
self["signal"] = StaticText()
self["bitrate"] = StaticText()
self["enc"] = StaticText()
self["IFtext"] = StaticText()
self["IF"] = StaticText()
self["Statustext"] = StaticText()
self["statuspic"] = MultiPixmap()
self["statuspic"].hide()
self["key_red"] = StaticText(_("Close"))
self.resetList()
self.updateStatusbar()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions", "ShortcutActions"],
{
"ok": self.exit,
"back": self.exit,
"red": self.exit,
}, -1)
self.timer = eTimer()
self.timer.timeout.get().append(self.resetList)
self.onShown.append(lambda: self.timer.start(8000))
self.onLayoutFinish.append(self.layoutFinished)
self.onClose.append(self.cleanup)
def cleanup(self):
iStatus.stopWlanConsole()
def layoutFinished(self):
self.setTitle(_("Wireless network state"))
def resetList(self):
iStatus.getDataForInterface(self.iface, self.getInfoCB)
def getInfoCB(self, data, status):
if data is not None:
if data is True:
if status is not None:
if status[self.iface]["essid"] == "off":
essid = _("No Connection")
else:
essid = status[self.iface]["essid"]
if status[self.iface]["accesspoint"] == "Not-Associated":
accesspoint = _("Not associated")
essid = _("No Connection")
else:
accesspoint = status[self.iface]["accesspoint"]
if "BSSID" in self:
self["BSSID"].setText(accesspoint)
if "ESSID" in self:
self["ESSID"].setText(essid)
quality = status[self.iface]["quality"]
if "quality" in self:
self["quality"].setText(quality)
if status[self.iface]["bitrate"] == '0':
bitrate = _("Unsupported")
else:
bitrate = str(status[self.iface]["bitrate"]) + " Mb/s"
if "bitrate" in self:
self["bitrate"].setText(bitrate)
signal = status[self.iface]["signal"]
if "signal" in self:
self["signal"].setText(signal)
if status[self.iface]["encryption"] == "off":
if accesspoint == "Not-Associated":
encryption = _("Disabled")
else:
encryption = _("off or wpa2 on")
else:
encryption = _("Enabled")
if "enc" in self:
self["enc"].setText(encryption)
self.updateStatusLink(status)
def exit(self):
self.timer.stop()
self.close(True)
def updateStatusbar(self):
wait_txt = _("Please wait...")
self["BSSID"].setText(wait_txt)
self["ESSID"].setText(wait_txt)
self["quality"].setText(wait_txt)
self["signal"].setText(wait_txt)
self["bitrate"].setText(wait_txt)
self["enc"].setText(wait_txt)
self["IFtext"].setText(_("Network:"))
self["IF"].setText(iNetwork.getFriendlyAdapterName(self.iface))
self["Statustext"].setText(_("Link:"))
def updateStatusLink(self, status):
if status is not None:
if status[self.iface]["essid"] == "off" or status[self.iface]["accesspoint"] == "Not-Associated" or status[self.iface]["accesspoint"] == False:
self["statuspic"].setPixmapNum(1)
else:
self["statuspic"].setPixmapNum(0)
self["statuspic"].show()
class WlanScan(Screen):
skin = """
<screen name="WlanScan" position="center,center" size="560,400" title="Select a wireless network" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="list" render="Listbox" position="5,40" size="550,300" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (0, 0), size = (550, 30), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the essid
MultiContentEntryText(pos = (0, 30), size = (175, 20), font=1, flags = RT_HALIGN_LEFT, text = 5), # index 5 is the interface
MultiContentEntryText(pos = (175, 30), size = (175, 20), font=1, flags = RT_HALIGN_LEFT, text = 4), # index 0 is the encryption
MultiContentEntryText(pos = (350, 0), size = (200, 20), font=1, flags = RT_HALIGN_LEFT, text = 2), # index 0 is the signal
MultiContentEntryText(pos = (350, 30), size = (200, 20), font=1, flags = RT_HALIGN_LEFT, text = 3), # index 0 is the maxrate
MultiContentEntryPixmapAlphaTest(pos = (0, 52), size = (550, 2), png = 6), # index 6 is the div pixmap
],
"fonts": [gFont("Regular", 28),gFont("Regular", 18)],
"itemHeight": 54
}
</convert>
</widget>
<ePixmap pixmap="div-h.png" position="0,340" zPosition="1" size="560,2" />
<widget source="info" render="Label" position="0,350" size="560,50" font="Regular;24" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
</screen>"""
def __init__(self, session, iface):
Screen.__init__(self, session)
self.session = session
self.iface = iface
self.skin_path = plugin_path
self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
self.APList = None
self.newAPList = None
self.WlanList = None
self.cleanList = None
self.oldlist = {}
self.listLength = None
self.divpng = LoadPixmap(path=resolveFilename(SCOPE_SKIN_IMAGE, "div-h.png"))
self.rescanTimer = eTimer()
self.rescanTimer.callback.append(self.rescanTimerFired)
self["info"] = StaticText()
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Connect"))
self["key_yellow"] = StaticText()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions"],
{
"ok": self.select,
"back": self.cancel,
}, -1)
self["shortcuts"] = ActionMap(["ShortcutActions"],
{
"red": self.cancel,
"green": self.select,
})
iWlan.setInterface(self.iface)
self.w = iWlan.getInterface()
self.onLayoutFinish.append(self.layoutFinished)
self.getAccessPoints(refresh=False)
def layoutFinished(self):
self.setTitle(_("Select a wireless network"))
def select(self):
cur = self["list"].getCurrent()
if cur is not None:
iWlan.stopGetNetworkList()
self.rescanTimer.stop()
del self.rescanTimer
if cur[0] is not None:
self.close(cur[0])
else:
self.close(None)
else:
iWlan.stopGetNetworkList()
self.rescanTimer.stop()
del self.rescanTimer
self.close(None)
def cancel(self):
iWlan.stopGetNetworkList()
self.rescanTimer.stop()
del self.rescanTimer
self.close(None)
def rescanTimerFired(self):
self.rescanTimer.stop()
self.updateAPList()
def buildEntryComponent(self, essid, bssid, encrypted, iface, maxrate, signal):
encryption = encrypted and _("Yes") or _("No")
return((essid, bssid, _("Signal: ") + str(signal), _("Max. bitrate: ") + str(maxrate), _("Encrypted: ") + encryption, _("Interface: ") + str(iface), self.divpng))
def updateAPList(self):
newList = []
newList = self.getAccessPoints(refresh=True)
self.newAPList = []
tmpList = []
newListIndex = None
currentListEntry = None
currentListIndex = None
for ap in self.oldlist.keys():
data = self.oldlist[ap]['data']
if data is not None:
tmpList.append(data)
if len(tmpList):
for entry in tmpList:
self.newAPList.append(self.buildEntryComponent(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5]))
|
[
"\t\t\tcurrentListEntry = self[\"list\"].getCurrent()"
] | 1,024
|
lcc
|
python
| null |
544c63cee98145e32800b86cdc53d87ba73f46da8aeafade
| 67
|
Your task is code completion.
from enigma import eTimer, eEnv
from Screens.Screen import Screen
from Components.ActionMap import ActionMap, NumberActionMap
from Components.Pixmap import Pixmap, MultiPixmap
from Components.Label import Label
from Components.Sources.StaticText import StaticText
from Components.Sources.List import List
from Components.config import config, ConfigYesNo, NoSave, ConfigSubsection, ConfigText, ConfigSelection, ConfigPassword
from Components.Network import iNetwork
from Components.Console import Console
from Plugins.Plugin import PluginDescriptor
from Tools.Directories import resolveFilename, SCOPE_SKIN_IMAGE
from Tools.LoadPixmap import LoadPixmap
from Wlan import iWlan, iStatus, getWlanConfigName, existBcmWifi
from time import time
import re
plugin_path = eEnv.resolve("${libdir}/enigma2/python/Plugins/SystemPlugins/WirelessLan")
list = ["Unencrypted", "WEP", "WPA", "WPA/WPA2", "WPA2"]
weplist = ["ASCII", "HEX"]
config.plugins.wlan = ConfigSubsection()
config.plugins.wlan.essid = NoSave(ConfigText(default="", fixed_size=False))
config.plugins.wlan.hiddenessid = NoSave(ConfigYesNo(default=False))
config.plugins.wlan.encryption = NoSave(ConfigSelection(list, default="WPA2"))
config.plugins.wlan.wepkeytype = NoSave(ConfigSelection(weplist, default="ASCII"))
config.plugins.wlan.psk = NoSave(ConfigPassword(default="", fixed_size=False))
class WlanStatus(Screen):
skin = """
<screen name="WlanStatus" position="center,center" size="560,400" title="Wireless network status" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="LabelBSSID" render="Label" position="10,60" size="200,25" valign="left" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelESSID" render="Label" position="10,100" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelQuality" render="Label" position="10,140" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelSignal" render="Label" position="10,180" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelBitrate" render="Label" position="10,220" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="LabelEnc" render="Label" position="10,260" size="200,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="BSSID" render="Label" position="220,60" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="ESSID" render="Label" position="220,100" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="quality" render="Label" position="220,140" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="signal" render="Label" position="220,180" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="bitrate" render="Label" position="220,220" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<widget source="enc" render="Label" position="220,260" size="330,25" valign="center" font="Regular;20" transparent="1" foregroundColor="#FFFFFF" />
<ePixmap pixmap="div-h.png" position="0,350" zPosition="1" size="560,2" />
<widget source="IFtext" render="Label" position="10,355" size="120,21" zPosition="10" font="Regular;20" halign="left" backgroundColor="#25062748" transparent="1" />
<widget source="IF" render="Label" position="120,355" size="400,21" zPosition="10" font="Regular;20" halign="left" backgroundColor="#25062748" transparent="1" />
<widget source="Statustext" render="Label" position="10,375" size="115,21" zPosition="10" font="Regular;20" halign="left" backgroundColor="#25062748" transparent="1"/>
<widget name="statuspic" pixmaps="buttons/button_green.png,buttons/button_green_off.png" position="130,380" zPosition="10" size="15,16" transparent="1" alphatest="on"/>
</screen>"""
def __init__(self, session, iface):
Screen.__init__(self, session)
self.session = session
self.iface = iface
self["LabelBSSID"] = StaticText(_('Accesspoint:'))
self["LabelESSID"] = StaticText(_('SSID:'))
self["LabelQuality"] = StaticText(_('Link quality:'))
self["LabelSignal"] = StaticText(_('Signal strength:'))
self["LabelBitrate"] = StaticText(_('Bitrate:'))
self["LabelEnc"] = StaticText(_('Encryption:'))
self["BSSID"] = StaticText()
self["ESSID"] = StaticText()
self["quality"] = StaticText()
self["signal"] = StaticText()
self["bitrate"] = StaticText()
self["enc"] = StaticText()
self["IFtext"] = StaticText()
self["IF"] = StaticText()
self["Statustext"] = StaticText()
self["statuspic"] = MultiPixmap()
self["statuspic"].hide()
self["key_red"] = StaticText(_("Close"))
self.resetList()
self.updateStatusbar()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions", "ShortcutActions"],
{
"ok": self.exit,
"back": self.exit,
"red": self.exit,
}, -1)
self.timer = eTimer()
self.timer.timeout.get().append(self.resetList)
self.onShown.append(lambda: self.timer.start(8000))
self.onLayoutFinish.append(self.layoutFinished)
self.onClose.append(self.cleanup)
def cleanup(self):
iStatus.stopWlanConsole()
def layoutFinished(self):
self.setTitle(_("Wireless network state"))
def resetList(self):
iStatus.getDataForInterface(self.iface, self.getInfoCB)
def getInfoCB(self, data, status):
if data is not None:
if data is True:
if status is not None:
if status[self.iface]["essid"] == "off":
essid = _("No Connection")
else:
essid = status[self.iface]["essid"]
if status[self.iface]["accesspoint"] == "Not-Associated":
accesspoint = _("Not associated")
essid = _("No Connection")
else:
accesspoint = status[self.iface]["accesspoint"]
if "BSSID" in self:
self["BSSID"].setText(accesspoint)
if "ESSID" in self:
self["ESSID"].setText(essid)
quality = status[self.iface]["quality"]
if "quality" in self:
self["quality"].setText(quality)
if status[self.iface]["bitrate"] == '0':
bitrate = _("Unsupported")
else:
bitrate = str(status[self.iface]["bitrate"]) + " Mb/s"
if "bitrate" in self:
self["bitrate"].setText(bitrate)
signal = status[self.iface]["signal"]
if "signal" in self:
self["signal"].setText(signal)
if status[self.iface]["encryption"] == "off":
if accesspoint == "Not-Associated":
encryption = _("Disabled")
else:
encryption = _("off or wpa2 on")
else:
encryption = _("Enabled")
if "enc" in self:
self["enc"].setText(encryption)
self.updateStatusLink(status)
def exit(self):
self.timer.stop()
self.close(True)
def updateStatusbar(self):
wait_txt = _("Please wait...")
self["BSSID"].setText(wait_txt)
self["ESSID"].setText(wait_txt)
self["quality"].setText(wait_txt)
self["signal"].setText(wait_txt)
self["bitrate"].setText(wait_txt)
self["enc"].setText(wait_txt)
self["IFtext"].setText(_("Network:"))
self["IF"].setText(iNetwork.getFriendlyAdapterName(self.iface))
self["Statustext"].setText(_("Link:"))
def updateStatusLink(self, status):
if status is not None:
if status[self.iface]["essid"] == "off" or status[self.iface]["accesspoint"] == "Not-Associated" or status[self.iface]["accesspoint"] == False:
self["statuspic"].setPixmapNum(1)
else:
self["statuspic"].setPixmapNum(0)
self["statuspic"].show()
class WlanScan(Screen):
skin = """
<screen name="WlanScan" position="center,center" size="560,400" title="Select a wireless network" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="list" render="Listbox" position="5,40" size="550,300" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (0, 0), size = (550, 30), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the essid
MultiContentEntryText(pos = (0, 30), size = (175, 20), font=1, flags = RT_HALIGN_LEFT, text = 5), # index 5 is the interface
MultiContentEntryText(pos = (175, 30), size = (175, 20), font=1, flags = RT_HALIGN_LEFT, text = 4), # index 0 is the encryption
MultiContentEntryText(pos = (350, 0), size = (200, 20), font=1, flags = RT_HALIGN_LEFT, text = 2), # index 0 is the signal
MultiContentEntryText(pos = (350, 30), size = (200, 20), font=1, flags = RT_HALIGN_LEFT, text = 3), # index 0 is the maxrate
MultiContentEntryPixmapAlphaTest(pos = (0, 52), size = (550, 2), png = 6), # index 6 is the div pixmap
],
"fonts": [gFont("Regular", 28),gFont("Regular", 18)],
"itemHeight": 54
}
</convert>
</widget>
<ePixmap pixmap="div-h.png" position="0,340" zPosition="1" size="560,2" />
<widget source="info" render="Label" position="0,350" size="560,50" font="Regular;24" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
</screen>"""
def __init__(self, session, iface):
Screen.__init__(self, session)
self.session = session
self.iface = iface
self.skin_path = plugin_path
self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
self.APList = None
self.newAPList = None
self.WlanList = None
self.cleanList = None
self.oldlist = {}
self.listLength = None
self.divpng = LoadPixmap(path=resolveFilename(SCOPE_SKIN_IMAGE, "div-h.png"))
self.rescanTimer = eTimer()
self.rescanTimer.callback.append(self.rescanTimerFired)
self["info"] = StaticText()
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Connect"))
self["key_yellow"] = StaticText()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions"],
{
"ok": self.select,
"back": self.cancel,
}, -1)
self["shortcuts"] = ActionMap(["ShortcutActions"],
{
"red": self.cancel,
"green": self.select,
})
iWlan.setInterface(self.iface)
self.w = iWlan.getInterface()
self.onLayoutFinish.append(self.layoutFinished)
self.getAccessPoints(refresh=False)
def layoutFinished(self):
self.setTitle(_("Select a wireless network"))
def select(self):
cur = self["list"].getCurrent()
if cur is not None:
iWlan.stopGetNetworkList()
self.rescanTimer.stop()
del self.rescanTimer
if cur[0] is not None:
self.close(cur[0])
else:
self.close(None)
else:
iWlan.stopGetNetworkList()
self.rescanTimer.stop()
del self.rescanTimer
self.close(None)
def cancel(self):
iWlan.stopGetNetworkList()
self.rescanTimer.stop()
del self.rescanTimer
self.close(None)
def rescanTimerFired(self):
self.rescanTimer.stop()
self.updateAPList()
def buildEntryComponent(self, essid, bssid, encrypted, iface, maxrate, signal):
encryption = encrypted and _("Yes") or _("No")
return((essid, bssid, _("Signal: ") + str(signal), _("Max. bitrate: ") + str(maxrate), _("Encrypted: ") + encryption, _("Interface: ") + str(iface), self.divpng))
def updateAPList(self):
newList = []
newList = self.getAccessPoints(refresh=True)
self.newAPList = []
tmpList = []
newListIndex = None
currentListEntry = None
currentListIndex = None
for ap in self.oldlist.keys():
data = self.oldlist[ap]['data']
if data is not None:
tmpList.append(data)
if len(tmpList):
for entry in tmpList:
self.newAPList.append(self.buildEntryComponent(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5]))
|
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 WlanScan(Screen):
def __init__(self, session, iface):
...
self.skin_path = plugin_path
self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
self.APList = None
self.newAPList = None
self.WlanList = None
self.cleanList = None
self.oldlist = {}
self.listLength = None
self.divpng = LoadPixmap(path=resolveFilename(SCOPE_SKIN_IMAGE, "div-h.png"))
self.rescanTimer = eTimer()
self.rescanTimer.callback.append(self.rescanTimerFired)
self["info"] = StaticText()
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Connect"))
self["key_yellow"] = StaticText()
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions"],
{
"ok": self.select,
"back": self.cancel,
}, -1)
self["shortcuts"] = ActionMap(["ShortcutActions"],
{
"red": self.cancel,
"green": self.select,
})
iWlan.setInterface(self.iface)
self.w = iWlan.getInterface()
self.onLayoutFinish.append(self.layoutFinished)
self.getAccessPoints(refresh=False)
**Cheat sheet (for next line):**
- We are in the __init__ method of the WlanScan class.
- The self.skin_path variable is assigned a value.
- The self.oldInterfaceState variable is assigned a value using iNetwork.getAdapterAttribute.
- The self.APList, self.newAPList, self.WlanList, self.cleanList, and self.oldlist variables are initialized as None.
- The self.listLength variable is initialized as None.
- The self.divpng variable is assigned a value using LoadPixmap.
- The self.rescanTimer variable is assigned an eTimer object.
- The self.rescanTimer.callback list is appended with self.rescanTimerFired.
- The self.info variable is assigned a StaticText object.
- The self.list variable is initialized as an empty list.
- The self.list variable is assigned to the "list" widget.
- The self.key_red, self.key_green, and self.key_yellow variables are assigned StaticText objects.
- The self.actions variable is assigned a NumberActionMap object.
- The self.shortcuts variable is assigned an ActionMap object.
- iWlan.setInterface is called with self.iface as an argument.
- The self.w variable is assigned the result of iWlan.getInterface.
- The self.onLayoutFinish list is appended with self.layoutFinished.
- The self.getAccessPoints method is called with refresh=False.
**Relevant lines:**
- self.skin_path = plugin_path
- self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
- self.APList = None
- self.newAPList = None
- self.WlanList = None
- self.cleanList = None
- self.oldlist = {}
- self.listLength = None
- self.divpng = LoadPixmap(path=resolveFilename(SCOPE_SKIN_IMAGE, "div-h.png"))
- self.rescanTimer = eTimer()
- self.rescanTimer.callback.append(self.rescanTimerFired)
- self["info"] = StaticText()
- self.list = []
- self["list"] = List(self.list)
- self["key_red"] = StaticText(_("Close"))
- self["key_green"] = StaticText(_("Connect"))
- self["key_yellow"] = StaticText()
- self["actions"] = NumberActionMap(["WizardActions", "InputActions", "EPGSelectActions"],
- self["shortcuts"] = ActionMap(["ShortcutActions"],
- iWlan.setInterface(self.iface)
- self.w = iWlan.getInterface()
- self.onLayoutFinish.append(self.layoutFinished)
- self.getAccessPoints(refresh=False)
**Next line will likely be:**
self.getAccessPoints(refresh=True)
|
|
Please complete the code given below.
using System;
using iTextSharp.text;
/*
* $Id: Barcode39.cs,v 1.5 2006/09/17 15:58:51 psoares33 Exp $
*
* Copyright 2002-2006 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
namespace iTextSharp.text.pdf {
/** Implements the code 39 and code 39 extended. The default parameters are:
* <pre>
*x = 0.8f;
*n = 2;
*font = BaseFont.CreateFont("Helvetica", "winansi", false);
*size = 8;
*baseline = size;
*barHeight = size * 3;
*textint= Element.ALIGN_CENTER;
*generateChecksum = false;
*checksumText = false;
*startStopText = true;
*extended = false;
* </pre>
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public class Barcode39 : Barcode {
/** The bars to generate the code.
*/
private static readonly byte[][] BARS =
{
new byte[] {0,0,0,1,1,0,1,0,0},
new byte[] {1,0,0,1,0,0,0,0,1},
new byte[] {0,0,1,1,0,0,0,0,1},
new byte[] {1,0,1,1,0,0,0,0,0},
new byte[] {0,0,0,1,1,0,0,0,1},
new byte[] {1,0,0,1,1,0,0,0,0},
new byte[] {0,0,1,1,1,0,0,0,0},
new byte[] {0,0,0,1,0,0,1,0,1},
new byte[] {1,0,0,1,0,0,1,0,0},
new byte[] {0,0,1,1,0,0,1,0,0},
new byte[] {1,0,0,0,0,1,0,0,1},
new byte[] {0,0,1,0,0,1,0,0,1},
new byte[] {1,0,1,0,0,1,0,0,0},
new byte[] {0,0,0,0,1,1,0,0,1},
new byte[] {1,0,0,0,1,1,0,0,0},
new byte[] {0,0,1,0,1,1,0,0,0},
new byte[] {0,0,0,0,0,1,1,0,1},
new byte[] {1,0,0,0,0,1,1,0,0},
new byte[] {0,0,1,0,0,1,1,0,0},
new byte[] {0,0,0,0,1,1,1,0,0},
new byte[] {1,0,0,0,0,0,0,1,1},
new byte[] {0,0,1,0,0,0,0,1,1},
new byte[] {1,0,1,0,0,0,0,1,0},
new byte[] {0,0,0,0,1,0,0,1,1},
new byte[] {1,0,0,0,1,0,0,1,0},
new byte[] {0,0,1,0,1,0,0,1,0},
new byte[] {0,0,0,0,0,0,1,1,1},
new byte[] {1,0,0,0,0,0,1,1,0},
new byte[] {0,0,1,0,0,0,1,1,0},
new byte[] {0,0,0,0,1,0,1,1,0},
new byte[] {1,1,0,0,0,0,0,0,1},
new byte[] {0,1,1,0,0,0,0,0,1},
new byte[] {1,1,1,0,0,0,0,0,0},
new byte[] {0,1,0,0,1,0,0,0,1},
new byte[] {1,1,0,0,1,0,0,0,0},
new byte[] {0,1,1,0,1,0,0,0,0},
new byte[] {0,1,0,0,0,0,1,0,1},
new byte[] {1,1,0,0,0,0,1,0,0},
new byte[] {0,1,1,0,0,0,1,0,0},
new byte[] {0,1,0,1,0,1,0,0,0},
new byte[] {0,1,0,1,0,0,0,1,0},
new byte[] {0,1,0,0,0,1,0,1,0},
new byte[] {0,0,0,1,0,1,0,1,0},
new byte[] {0,1,0,0,1,0,1,0,0}
};
/** The index chars to <CODE>BARS</CODE>.
*/
private const string CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*";
/** The character combinations to make the code 39 extended.
*/
private const string EXTENDED = "%U" +
"$A$B$C$D$E$F$G$H$I$J$K$L$M$N$O$P$Q$R$S$T$U$V$W$X$Y$Z" +
"%A%B%C%D%E /A/B/C/D/E/F/G/H/I/J/K/L - ./O" +
" 0 1 2 3 4 5 6 7 8 9/Z%F%G%H%I%J%V" +
" A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" +
"%K%L%M%N%O%W" +
"+A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z" +
"%P%Q%R%S%T";
/** Creates a new Barcode39.
*/
public Barcode39() {
x = 0.8f;
n = 2;
font = BaseFont.CreateFont("Helvetica", "winansi", false);
size = 8;
baseline = size;
barHeight = size * 3;
textAlignment = Element.ALIGN_CENTER;
generateChecksum = false;
checksumText = false;
startStopText = true;
extended = false;
}
/** Creates the bars.
* @param text the text to create the bars. This text does not include the start and
* stop characters
* @return the bars
*/
public static byte[] GetBarsCode39(string text) {
text = "*" + text + "*";
byte[] bars = new byte[text.Length * 10 - 1];
for (int k = 0; k < text.Length; ++k) {
int idx = CHARS.IndexOf(text[k]);
if (idx < 0)
throw new ArgumentException("The character '" + text[k] + "' is illegal in code 39.");
Array.Copy(BARS[idx], 0, bars, k * 10, 9);
}
return bars;
}
/** Converts the extended text into a normal, escaped text,
* ready to generate bars.
* @param text the extended text
* @return the escaped text
*/
public static string GetCode39Ex(string text) {
string ret = "";
for (int k = 0; k < text.Length; ++k) {
char c = text[k];
if (c > 127)
throw new ArgumentException("The character '" + c + "' is illegal in code 39 extended.");
char c1 = EXTENDED[c * 2];
char c2 = EXTENDED[c * 2 + 1];
if (c1 != ' ')
ret += c1;
ret += c2;
}
return ret;
}
/** Calculates the checksum.
* @param text the text
* @return the checksum
*/
internal static char GetChecksum(string text) {
int chk = 0;
for (int k = 0; k < text.Length; ++k) {
int idx = CHARS.IndexOf(text[k]);
if (idx < 0)
throw new ArgumentException("The character '" + text[k] + "' is illegal in code 39.");
chk += idx;
}
return CHARS[chk % 43];
}
/** Gets the maximum area that the barcode and the text, if
* any, will occupy. The lower left corner is always (0, 0).
* @return the size the barcode occupies.
*/
public override Rectangle BarcodeSize {
get {
float fontX = 0;
float fontY = 0;
if (font != null) {
if (baseline > 0)
fontY = baseline - font.GetFontDescriptor(BaseFont.DESCENT, size);
else
fontY = -baseline + size;
string fullCode = code;
if (generateChecksum && checksumText)
fullCode += GetChecksum(fullCode);
if (startStopText)
fullCode = "*" + fullCode + "*";
fontX = font.GetWidthPoint(altText != null ? altText : fullCode, size);
}
string fCode = code;
if (extended)
fCode = GetCode39Ex(code);
|
[
" int len = fCode.Length + 2;"
] | 1,163
|
lcc
|
csharp
| null |
5c41dbe75be69a522492a261348f685fcc83189eb876ce02
| 68
|
Your task is code completion.
using System;
using iTextSharp.text;
/*
* $Id: Barcode39.cs,v 1.5 2006/09/17 15:58:51 psoares33 Exp $
*
* Copyright 2002-2006 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
namespace iTextSharp.text.pdf {
/** Implements the code 39 and code 39 extended. The default parameters are:
* <pre>
*x = 0.8f;
*n = 2;
*font = BaseFont.CreateFont("Helvetica", "winansi", false);
*size = 8;
*baseline = size;
*barHeight = size * 3;
*textint= Element.ALIGN_CENTER;
*generateChecksum = false;
*checksumText = false;
*startStopText = true;
*extended = false;
* </pre>
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public class Barcode39 : Barcode {
/** The bars to generate the code.
*/
private static readonly byte[][] BARS =
{
new byte[] {0,0,0,1,1,0,1,0,0},
new byte[] {1,0,0,1,0,0,0,0,1},
new byte[] {0,0,1,1,0,0,0,0,1},
new byte[] {1,0,1,1,0,0,0,0,0},
new byte[] {0,0,0,1,1,0,0,0,1},
new byte[] {1,0,0,1,1,0,0,0,0},
new byte[] {0,0,1,1,1,0,0,0,0},
new byte[] {0,0,0,1,0,0,1,0,1},
new byte[] {1,0,0,1,0,0,1,0,0},
new byte[] {0,0,1,1,0,0,1,0,0},
new byte[] {1,0,0,0,0,1,0,0,1},
new byte[] {0,0,1,0,0,1,0,0,1},
new byte[] {1,0,1,0,0,1,0,0,0},
new byte[] {0,0,0,0,1,1,0,0,1},
new byte[] {1,0,0,0,1,1,0,0,0},
new byte[] {0,0,1,0,1,1,0,0,0},
new byte[] {0,0,0,0,0,1,1,0,1},
new byte[] {1,0,0,0,0,1,1,0,0},
new byte[] {0,0,1,0,0,1,1,0,0},
new byte[] {0,0,0,0,1,1,1,0,0},
new byte[] {1,0,0,0,0,0,0,1,1},
new byte[] {0,0,1,0,0,0,0,1,1},
new byte[] {1,0,1,0,0,0,0,1,0},
new byte[] {0,0,0,0,1,0,0,1,1},
new byte[] {1,0,0,0,1,0,0,1,0},
new byte[] {0,0,1,0,1,0,0,1,0},
new byte[] {0,0,0,0,0,0,1,1,1},
new byte[] {1,0,0,0,0,0,1,1,0},
new byte[] {0,0,1,0,0,0,1,1,0},
new byte[] {0,0,0,0,1,0,1,1,0},
new byte[] {1,1,0,0,0,0,0,0,1},
new byte[] {0,1,1,0,0,0,0,0,1},
new byte[] {1,1,1,0,0,0,0,0,0},
new byte[] {0,1,0,0,1,0,0,0,1},
new byte[] {1,1,0,0,1,0,0,0,0},
new byte[] {0,1,1,0,1,0,0,0,0},
new byte[] {0,1,0,0,0,0,1,0,1},
new byte[] {1,1,0,0,0,0,1,0,0},
new byte[] {0,1,1,0,0,0,1,0,0},
new byte[] {0,1,0,1,0,1,0,0,0},
new byte[] {0,1,0,1,0,0,0,1,0},
new byte[] {0,1,0,0,0,1,0,1,0},
new byte[] {0,0,0,1,0,1,0,1,0},
new byte[] {0,1,0,0,1,0,1,0,0}
};
/** The index chars to <CODE>BARS</CODE>.
*/
private const string CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*";
/** The character combinations to make the code 39 extended.
*/
private const string EXTENDED = "%U" +
"$A$B$C$D$E$F$G$H$I$J$K$L$M$N$O$P$Q$R$S$T$U$V$W$X$Y$Z" +
"%A%B%C%D%E /A/B/C/D/E/F/G/H/I/J/K/L - ./O" +
" 0 1 2 3 4 5 6 7 8 9/Z%F%G%H%I%J%V" +
" A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" +
"%K%L%M%N%O%W" +
"+A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z" +
"%P%Q%R%S%T";
/** Creates a new Barcode39.
*/
public Barcode39() {
x = 0.8f;
n = 2;
font = BaseFont.CreateFont("Helvetica", "winansi", false);
size = 8;
baseline = size;
barHeight = size * 3;
textAlignment = Element.ALIGN_CENTER;
generateChecksum = false;
checksumText = false;
startStopText = true;
extended = false;
}
/** Creates the bars.
* @param text the text to create the bars. This text does not include the start and
* stop characters
* @return the bars
*/
public static byte[] GetBarsCode39(string text) {
text = "*" + text + "*";
byte[] bars = new byte[text.Length * 10 - 1];
for (int k = 0; k < text.Length; ++k) {
int idx = CHARS.IndexOf(text[k]);
if (idx < 0)
throw new ArgumentException("The character '" + text[k] + "' is illegal in code 39.");
Array.Copy(BARS[idx], 0, bars, k * 10, 9);
}
return bars;
}
/** Converts the extended text into a normal, escaped text,
* ready to generate bars.
* @param text the extended text
* @return the escaped text
*/
public static string GetCode39Ex(string text) {
string ret = "";
for (int k = 0; k < text.Length; ++k) {
char c = text[k];
if (c > 127)
throw new ArgumentException("The character '" + c + "' is illegal in code 39 extended.");
char c1 = EXTENDED[c * 2];
char c2 = EXTENDED[c * 2 + 1];
if (c1 != ' ')
ret += c1;
ret += c2;
}
return ret;
}
/** Calculates the checksum.
* @param text the text
* @return the checksum
*/
internal static char GetChecksum(string text) {
int chk = 0;
for (int k = 0; k < text.Length; ++k) {
int idx = CHARS.IndexOf(text[k]);
if (idx < 0)
throw new ArgumentException("The character '" + text[k] + "' is illegal in code 39.");
chk += idx;
}
return CHARS[chk % 43];
}
/** Gets the maximum area that the barcode and the text, if
* any, will occupy. The lower left corner is always (0, 0).
* @return the size the barcode occupies.
*/
public override Rectangle BarcodeSize {
get {
float fontX = 0;
float fontY = 0;
if (font != null) {
if (baseline > 0)
fontY = baseline - font.GetFontDescriptor(BaseFont.DESCENT, size);
else
fontY = -baseline + size;
string fullCode = code;
if (generateChecksum && checksumText)
fullCode += GetChecksum(fullCode);
if (startStopText)
fullCode = "*" + fullCode + "*";
fontX = font.GetWidthPoint(altText != null ? altText : fullCode, size);
}
string fCode = code;
if (extended)
fCode = GetCode39Ex(code);
|
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 Barcode39 : Barcode {
// ...
public override Rectangle BarcodeSize {
get {
float fontX = 0;
float fontY = 0;
if (font != null) {
if (baseline > 0)
fontY = baseline - font.GetFontDescriptor(BaseFont.DESCENT, size);
else
fontY = -baseline + size;
string fullCode = code;
if (generateChecksum && checksumText)
fullCode += GetChecksum(fullCode);
if (startStopText)
fullCode = "*" + fullCode + "*";
fontX = font.GetWidthPoint(altText != null ? altText : fullCode, size);
}
string fCode = code;
if (extended)
fCode = GetCode39Ex(code);
Cheatsheet (for next line):
- We are in the BarcodeSize property, which should return the size of the barcode.
- The size is calculated based on the font and the code.
- The size is represented by a Rectangle object.
- The Rectangle object has properties for the lower left corner (x, y), width, and height.
- The size is calculated based on the font and the code, so we need to return a Rectangle object with the correct dimensions.
- [Relevant lines: declaration of BarcodeSize, calculation of fontX and fontY]
Next line will likely be:
return new Rectangle(fontX, fontY, fontX, fontY);
|
|
Please complete the code given below.
package edu.stanford.nlp.util;
import java.io.PrintStream;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
public class PropertiesUtils {
private PropertiesUtils() {}
/**
* Returns true iff the given Properties contains a property with the given
* key (name), and its value is not "false" or "no" or "off".
*
* @param props Properties object
* @param key The key to test
* @return true iff the given Properties contains a property with the given
* key (name), and its value is not "false" or "no" or "off".
*/
public static boolean hasProperty(Properties props, String key) {
String value = props.getProperty(key);
if (value == null) {
return false;
}
value = value.toLowerCase();
return ! (value.equals("false") || value.equals("no") || value.equals("off"));
}
// printing -------------------------------------------------------------------
public static void printProperties(String message, Properties properties,
PrintStream stream) {
if (message != null) {
stream.println(message);
}
if (properties.isEmpty()) {
stream.println(" [empty]");
} else {
List<Map.Entry<String, String>> entries = getSortedEntries(properties);
for (Map.Entry<String, String> entry : entries) {
if ( ! "".equals(entry.getKey())) {
stream.format(" %-30s = %s%n", entry.getKey(), entry.getValue());
}
}
}
stream.println();
}
public static void printProperties(String message, Properties properties) {
printProperties(message, properties, System.out);
}
/**
* Tired of Properties not behaving like Map<String,String>s? This method will solve that problem for you.
*/
public static Map<String, String> asMap(Properties properties) {
Map<String, String> map = Generics.newHashMap();
for (Entry<Object, Object> entry : properties.entrySet()) {
map.put((String)entry.getKey(), (String)entry.getValue());
}
return map;
}
public static List<Map.Entry<String, String>> getSortedEntries(Properties properties) {
return Maps.sortedEntries(asMap(properties));
}
/**
* Checks to make sure that all properties specified in <code>properties</code>
* are known to the program by checking that each simply overrides
* a default value
* @param properties Current properties
* @param defaults Default properties which lists all known keys
*/
@SuppressWarnings("unchecked")
public static void checkProperties(Properties properties, Properties defaults) {
Set<String> names = Generics.newHashSet();
for (Enumeration<String> e = (Enumeration<String>) properties.propertyNames();
e.hasMoreElements(); ) {
names.add(e.nextElement());
}
for (Enumeration<String> e = (Enumeration<String>) defaults.propertyNames();
e.hasMoreElements(); ) {
names.remove(e.nextElement());
}
if (!names.isEmpty()) {
if (names.size() == 1) {
throw new IllegalArgumentException("Unknown property: " + names.iterator().next());
} else {
throw new IllegalArgumentException("Unknown properties: " + names);
}
}
}
/**
* Get the value of a property and automatically cast it to a specific type.
* This differs from the original Properties.getProperty() method in that you
* need to specify the desired type (e.g. Double.class) and the default value
* is an object of that type, i.e. a double 0.0 instead of the String "0.0".
*/
@SuppressWarnings("unchecked")
public static <E> E get(Properties props, String key, E defaultValue, Type type) {
String value = props.getProperty(key);
if (value == null) {
return defaultValue;
} else {
return (E) MetaClass.cast(value, type);
}
}
/**
* Load an integer property. If the key is not present, returns 0.
*/
public static int getInt(Properties props, String key) {
return getInt(props, key, 0);
}
/**
* Load an integer property. If the key is not present, returns defaultValue.
*/
public static int getInt(Properties props, String key, int defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Integer.parseInt(value);
} else {
return defaultValue;
}
}
/**
* Load an integer property as a long.
* If the key is not present, returns defaultValue.
*/
public static long getLong(Properties props, String key, long defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Long.parseLong(value);
} else {
return defaultValue;
}
}
/**
* Load a double property. If the key is not present, returns 0.0.
*/
public static double getDouble(Properties props, String key) {
return getDouble(props, key, 0.0);
}
/**
* Load a double property. If the key is not present, returns defaultValue.
*/
public static double getDouble(Properties props, String key, double defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Double.parseDouble(value);
} else {
return defaultValue;
}
}
/**
* Load a boolean property. If the key is not present, returns false.
*/
public static boolean getBool(Properties props, String key) {
return getBool(props, key, false);
}
/**
* Load a boolean property. If the key is not present, returns defaultValue.
*/
public static boolean getBool(Properties props, String key,
boolean defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Boolean.parseBoolean(value);
} else {
return defaultValue;
}
}
/**
* Loads a comma-separated list of integers from Properties. The list cannot include any whitespace.
*/
public static int[] getIntArray(Properties props, String key) {
Integer[] result = MetaClass.cast(props.getProperty(key), Integer [].class);
return ArrayUtils.toPrimitive(result);
}
/**
* Loads a comma-separated list of doubles from Properties. The list cannot include any whitespace.
*/
public static double[] getDoubleArray(Properties props, String key) {
Double[] result = MetaClass.cast(props.getProperty(key), Double [].class);
return ArrayUtils.toPrimitive(result);
}
/**
* Loads a comma-separated list of strings from Properties. Commas may be quoted if needed, e.g.:
* property1 = value1,value2,"a quoted value",'another quoted value'
*
* getStringArray(props, "property1") should return the same thing as
* new String[] { "value1", "value2", "a quoted value", "another quoted value" };
*/
public static String[] getStringArray(Properties props, String key) {
String[] results = MetaClass.cast(props.getProperty(key), String [].class);
|
[
" if (results == null) {"
] | 840
|
lcc
|
java
| null |
cdd96b1a6cdd32b52402ed8afa5c640bc81a206da183fee0
| 69
|
Your task is code completion.
package edu.stanford.nlp.util;
import java.io.PrintStream;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
public class PropertiesUtils {
private PropertiesUtils() {}
/**
* Returns true iff the given Properties contains a property with the given
* key (name), and its value is not "false" or "no" or "off".
*
* @param props Properties object
* @param key The key to test
* @return true iff the given Properties contains a property with the given
* key (name), and its value is not "false" or "no" or "off".
*/
public static boolean hasProperty(Properties props, String key) {
String value = props.getProperty(key);
if (value == null) {
return false;
}
value = value.toLowerCase();
return ! (value.equals("false") || value.equals("no") || value.equals("off"));
}
// printing -------------------------------------------------------------------
public static void printProperties(String message, Properties properties,
PrintStream stream) {
if (message != null) {
stream.println(message);
}
if (properties.isEmpty()) {
stream.println(" [empty]");
} else {
List<Map.Entry<String, String>> entries = getSortedEntries(properties);
for (Map.Entry<String, String> entry : entries) {
if ( ! "".equals(entry.getKey())) {
stream.format(" %-30s = %s%n", entry.getKey(), entry.getValue());
}
}
}
stream.println();
}
public static void printProperties(String message, Properties properties) {
printProperties(message, properties, System.out);
}
/**
* Tired of Properties not behaving like Map<String,String>s? This method will solve that problem for you.
*/
public static Map<String, String> asMap(Properties properties) {
Map<String, String> map = Generics.newHashMap();
for (Entry<Object, Object> entry : properties.entrySet()) {
map.put((String)entry.getKey(), (String)entry.getValue());
}
return map;
}
public static List<Map.Entry<String, String>> getSortedEntries(Properties properties) {
return Maps.sortedEntries(asMap(properties));
}
/**
* Checks to make sure that all properties specified in <code>properties</code>
* are known to the program by checking that each simply overrides
* a default value
* @param properties Current properties
* @param defaults Default properties which lists all known keys
*/
@SuppressWarnings("unchecked")
public static void checkProperties(Properties properties, Properties defaults) {
Set<String> names = Generics.newHashSet();
for (Enumeration<String> e = (Enumeration<String>) properties.propertyNames();
e.hasMoreElements(); ) {
names.add(e.nextElement());
}
for (Enumeration<String> e = (Enumeration<String>) defaults.propertyNames();
e.hasMoreElements(); ) {
names.remove(e.nextElement());
}
if (!names.isEmpty()) {
if (names.size() == 1) {
throw new IllegalArgumentException("Unknown property: " + names.iterator().next());
} else {
throw new IllegalArgumentException("Unknown properties: " + names);
}
}
}
/**
* Get the value of a property and automatically cast it to a specific type.
* This differs from the original Properties.getProperty() method in that you
* need to specify the desired type (e.g. Double.class) and the default value
* is an object of that type, i.e. a double 0.0 instead of the String "0.0".
*/
@SuppressWarnings("unchecked")
public static <E> E get(Properties props, String key, E defaultValue, Type type) {
String value = props.getProperty(key);
if (value == null) {
return defaultValue;
} else {
return (E) MetaClass.cast(value, type);
}
}
/**
* Load an integer property. If the key is not present, returns 0.
*/
public static int getInt(Properties props, String key) {
return getInt(props, key, 0);
}
/**
* Load an integer property. If the key is not present, returns defaultValue.
*/
public static int getInt(Properties props, String key, int defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Integer.parseInt(value);
} else {
return defaultValue;
}
}
/**
* Load an integer property as a long.
* If the key is not present, returns defaultValue.
*/
public static long getLong(Properties props, String key, long defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Long.parseLong(value);
} else {
return defaultValue;
}
}
/**
* Load a double property. If the key is not present, returns 0.0.
*/
public static double getDouble(Properties props, String key) {
return getDouble(props, key, 0.0);
}
/**
* Load a double property. If the key is not present, returns defaultValue.
*/
public static double getDouble(Properties props, String key, double defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Double.parseDouble(value);
} else {
return defaultValue;
}
}
/**
* Load a boolean property. If the key is not present, returns false.
*/
public static boolean getBool(Properties props, String key) {
return getBool(props, key, false);
}
/**
* Load a boolean property. If the key is not present, returns defaultValue.
*/
public static boolean getBool(Properties props, String key,
boolean defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Boolean.parseBoolean(value);
} else {
return defaultValue;
}
}
/**
* Loads a comma-separated list of integers from Properties. The list cannot include any whitespace.
*/
public static int[] getIntArray(Properties props, String key) {
Integer[] result = MetaClass.cast(props.getProperty(key), Integer [].class);
return ArrayUtils.toPrimitive(result);
}
/**
* Loads a comma-separated list of doubles from Properties. The list cannot include any whitespace.
*/
public static double[] getDoubleArray(Properties props, String key) {
Double[] result = MetaClass.cast(props.getProperty(key), Double [].class);
return ArrayUtils.toPrimitive(result);
}
/**
* Loads a comma-separated list of strings from Properties. Commas may be quoted if needed, e.g.:
* property1 = value1,value2,"a quoted value",'another quoted value'
*
* getStringArray(props, "property1") should return the same thing as
* new String[] { "value1", "value2", "a quoted value", "another quoted value" };
*/
public static String[] getStringArray(Properties props, String key) {
String[] results = MetaClass.cast(props.getProperty(key), String [].class);
|
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]
public class PropertiesUtils {
// ... existing code ...
/**
* Loads a boolean property. If the key is not present, returns defaultValue.
*/
public static boolean getBool(Properties props, String key,
boolean defaultValue) {
String value = props.getProperty(key);
if (value != null) {
return Boolean.parseBoolean(value);
} else {
return defaultValue;
}
}
// ... existing code ...
Cheatsheet (for next line):
- We are in a method that loads a boolean property.
- The method is similar to getBool(Properties props, String key), but it should return a boolean array instead of a single boolean value.
- The method should handle the case where the key is not present in the properties.
- Convention: The method name should be similar to the existing getBool method, but with an array suffix (e.g., getBoolArray).
Next line will likely be:
public static boolean[] getBoolArray(Properties props, String key, boolean[] defaultValue)
|
|
Please complete the code given below.
# Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""Integration tests for :mod:`iris.analysis.trajectory`."""
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests # isort:skip
import numpy as np
import iris
from iris._lazy_data import as_lazy_data
from iris.analysis.trajectory import Trajectory
from iris.analysis.trajectory import interpolate as traj_interpolate
import iris.tests.stock as istk
@tests.skip_data
class TestColpex(tests.IrisTest):
def setUp(self):
# Load the COLPEX data => TZYX
path = tests.get_data_path(
["PP", "COLPEX", "theta_and_orog_subset.pp"]
)
cube = iris.load_cube(path, "air_potential_temperature")
cube.coord("grid_latitude").bounds = None
cube.coord("grid_longitude").bounds = None
# TODO: Workaround until regrid can handle factories
cube.remove_aux_factory(cube.aux_factories[0])
cube.remove_coord("surface_altitude")
self.cube = cube
def test_trajectory_extraction(self):
# Pull out a single point - no interpolation required
single_point = traj_interpolate(
self.cube,
[("grid_latitude", [-0.1188]), ("grid_longitude", [359.57958984])],
)
expected = self.cube[..., 10, 0].data
self.assertArrayAllClose(
single_point[..., 0].data, expected, rtol=2.0e-7
)
self.assertCML(
single_point, ("trajectory", "single_point.cml"), checksum=False
)
def test_trajectory_extraction_calc(self):
# Pull out another point and test against a manually calculated result.
single_point = [
["grid_latitude", [-0.1188]],
["grid_longitude", [359.584090412]],
]
scube = self.cube[0, 0, 10:11, 4:6]
x0 = scube.coord("grid_longitude")[0].points
x1 = scube.coord("grid_longitude")[1].points
y0 = scube.data[0, 0]
y1 = scube.data[0, 1]
expected = y0 + ((y1 - y0) * ((359.584090412 - x0) / (x1 - x0)))
trajectory_cube = traj_interpolate(scube, single_point)
self.assertArrayAllClose(trajectory_cube.data, expected, rtol=2.0e-7)
def _traj_to_sample_points(self, trajectory):
sample_points = []
src_points = trajectory.sampled_points
for name in src_points[0].keys():
values = [point[name] for point in src_points]
sample_points.append((name, values))
return sample_points
def test_trajectory_extraction_axis_aligned(self):
# Extract a simple, axis-aligned trajectory that is similar to an
# indexing operation.
# (It's not exactly the same because the source cube doesn't have
# regular spacing.)
waypoints = [
{"grid_latitude": -0.1188, "grid_longitude": 359.57958984},
{"grid_latitude": -0.1188, "grid_longitude": 359.66870117},
]
trajectory = Trajectory(waypoints, sample_count=100)
sample_points = self._traj_to_sample_points(trajectory)
trajectory_cube = traj_interpolate(self.cube, sample_points)
self.assertCML(
trajectory_cube, ("trajectory", "constant_latitude.cml")
)
def test_trajectory_extraction_zigzag(self):
# Extract a zig-zag trajectory
waypoints = [
{"grid_latitude": -0.1188, "grid_longitude": 359.5886},
{"grid_latitude": -0.0828, "grid_longitude": 359.6606},
{"grid_latitude": -0.0468, "grid_longitude": 359.6246},
]
trajectory = Trajectory(waypoints, sample_count=20)
sample_points = self._traj_to_sample_points(trajectory)
trajectory_cube = traj_interpolate(self.cube[0, 0], sample_points)
expected = np.array(
[
287.95953369,
287.9190979,
287.95550537,
287.93240356,
287.83850098,
287.87869263,
287.90942383,
287.9463501,
287.74365234,
287.68856812,
287.75588989,
287.54611206,
287.48522949,
287.53356934,
287.60217285,
287.43795776,
287.59701538,
287.52468872,
287.45025635,
287.52716064,
],
dtype=np.float32,
)
self.assertCML(
trajectory_cube, ("trajectory", "zigzag.cml"), checksum=False
)
self.assertArrayAllClose(trajectory_cube.data, expected, rtol=2.0e-7)
def test_colpex__nearest(self):
# Check a smallish nearest-neighbour interpolation against a result
# snapshot.
test_cube = self.cube[0][0]
# Test points on a regular grid, a bit larger than the source region.
xmin, xmax = [
fn(test_cube.coord(axis="x").points) for fn in (np.min, np.max)
]
ymin, ymax = [
fn(test_cube.coord(axis="x").points) for fn in (np.min, np.max)
]
fractions = [-0.23, -0.01, 0.27, 0.624, 0.983, 1.052, 1.43]
x_points = [xmin + frac * (xmax - xmin) for frac in fractions]
y_points = [ymin + frac * (ymax - ymin) for frac in fractions]
x_points, y_points = np.meshgrid(x_points, y_points)
sample_points = [
("grid_longitude", x_points.flatten()),
("grid_latitude", y_points.flatten()),
]
result = traj_interpolate(test_cube, sample_points, method="nearest")
expected = [
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
]
self.assertArrayAllClose(result.data, expected)
@tests.skip_data
class TestTriPolar(tests.IrisTest):
def setUp(self):
# load data
cubes = iris.load(
tests.get_data_path(["NetCDF", "ORCA2", "votemper.nc"])
)
cube = cubes[0]
# The netCDF file has different data types for the points and
# bounds of 'depth'. This wasn't previously supported, so we
# emulate that old behaviour.
b32 = cube.coord("depth").bounds.astype(np.float32)
cube.coord("depth").bounds = b32
self.cube = cube
# define a latitude trajectory (put coords in a different order
# to the cube, just to be awkward)
latitudes = list(range(-90, 90, 2))
longitudes = [-90] * len(latitudes)
self.sample_points = [
("longitude", longitudes),
("latitude", latitudes),
]
def test_tri_polar(self):
# extract
sampled_cube = traj_interpolate(self.cube, self.sample_points)
self.assertCML(
sampled_cube, ("trajectory", "tri_polar_latitude_slice.cml")
)
def test_tri_polar_method_linear_fails(self):
# Try to request linear interpolation.
# Not allowed, as we have multi-dimensional coords.
self.assertRaises(
iris.exceptions.CoordinateMultiDimError,
traj_interpolate,
self.cube,
self.sample_points,
method="linear",
)
def test_tri_polar_method_unknown_fails(self):
# Try to request unknown interpolation.
self.assertRaises(
ValueError,
traj_interpolate,
self.cube,
self.sample_points,
method="linekar",
)
def test_tri_polar__nearest(self):
# Check a smallish nearest-neighbour interpolation against a result
# snapshot.
test_cube = self.cube
# Use just one 2d layer, just to be faster.
test_cube = test_cube[0][0]
# Fix the fill value of the data to zero, just so that we get the same
# result under numpy < 1.11 as with 1.11.
# NOTE: numpy<1.11 *used* to assign missing data points into an
# unmasked array as =0.0, now =fill-value.
# TODO: arguably, we should support masked data properly in the
# interpolation routine. In the legacy code, that is unfortunately
# just not the case.
test_cube.data.fill_value = 0
# Test points on a regular global grid, with unrelated steps + offsets
# and an extended range of longitude values.
x_points = np.arange(-185.23, +360.0, 73.123)
|
[
" y_points = np.arange(-89.12, +90.0, 42.847)"
] | 819
|
lcc
|
python
| null |
f199ac4b782288ef2a374c11cfb7bee86753f53493876247
| 70
|
Your task is code completion.
# Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""Integration tests for :mod:`iris.analysis.trajectory`."""
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests # isort:skip
import numpy as np
import iris
from iris._lazy_data import as_lazy_data
from iris.analysis.trajectory import Trajectory
from iris.analysis.trajectory import interpolate as traj_interpolate
import iris.tests.stock as istk
@tests.skip_data
class TestColpex(tests.IrisTest):
def setUp(self):
# Load the COLPEX data => TZYX
path = tests.get_data_path(
["PP", "COLPEX", "theta_and_orog_subset.pp"]
)
cube = iris.load_cube(path, "air_potential_temperature")
cube.coord("grid_latitude").bounds = None
cube.coord("grid_longitude").bounds = None
# TODO: Workaround until regrid can handle factories
cube.remove_aux_factory(cube.aux_factories[0])
cube.remove_coord("surface_altitude")
self.cube = cube
def test_trajectory_extraction(self):
# Pull out a single point - no interpolation required
single_point = traj_interpolate(
self.cube,
[("grid_latitude", [-0.1188]), ("grid_longitude", [359.57958984])],
)
expected = self.cube[..., 10, 0].data
self.assertArrayAllClose(
single_point[..., 0].data, expected, rtol=2.0e-7
)
self.assertCML(
single_point, ("trajectory", "single_point.cml"), checksum=False
)
def test_trajectory_extraction_calc(self):
# Pull out another point and test against a manually calculated result.
single_point = [
["grid_latitude", [-0.1188]],
["grid_longitude", [359.584090412]],
]
scube = self.cube[0, 0, 10:11, 4:6]
x0 = scube.coord("grid_longitude")[0].points
x1 = scube.coord("grid_longitude")[1].points
y0 = scube.data[0, 0]
y1 = scube.data[0, 1]
expected = y0 + ((y1 - y0) * ((359.584090412 - x0) / (x1 - x0)))
trajectory_cube = traj_interpolate(scube, single_point)
self.assertArrayAllClose(trajectory_cube.data, expected, rtol=2.0e-7)
def _traj_to_sample_points(self, trajectory):
sample_points = []
src_points = trajectory.sampled_points
for name in src_points[0].keys():
values = [point[name] for point in src_points]
sample_points.append((name, values))
return sample_points
def test_trajectory_extraction_axis_aligned(self):
# Extract a simple, axis-aligned trajectory that is similar to an
# indexing operation.
# (It's not exactly the same because the source cube doesn't have
# regular spacing.)
waypoints = [
{"grid_latitude": -0.1188, "grid_longitude": 359.57958984},
{"grid_latitude": -0.1188, "grid_longitude": 359.66870117},
]
trajectory = Trajectory(waypoints, sample_count=100)
sample_points = self._traj_to_sample_points(trajectory)
trajectory_cube = traj_interpolate(self.cube, sample_points)
self.assertCML(
trajectory_cube, ("trajectory", "constant_latitude.cml")
)
def test_trajectory_extraction_zigzag(self):
# Extract a zig-zag trajectory
waypoints = [
{"grid_latitude": -0.1188, "grid_longitude": 359.5886},
{"grid_latitude": -0.0828, "grid_longitude": 359.6606},
{"grid_latitude": -0.0468, "grid_longitude": 359.6246},
]
trajectory = Trajectory(waypoints, sample_count=20)
sample_points = self._traj_to_sample_points(trajectory)
trajectory_cube = traj_interpolate(self.cube[0, 0], sample_points)
expected = np.array(
[
287.95953369,
287.9190979,
287.95550537,
287.93240356,
287.83850098,
287.87869263,
287.90942383,
287.9463501,
287.74365234,
287.68856812,
287.75588989,
287.54611206,
287.48522949,
287.53356934,
287.60217285,
287.43795776,
287.59701538,
287.52468872,
287.45025635,
287.52716064,
],
dtype=np.float32,
)
self.assertCML(
trajectory_cube, ("trajectory", "zigzag.cml"), checksum=False
)
self.assertArrayAllClose(trajectory_cube.data, expected, rtol=2.0e-7)
def test_colpex__nearest(self):
# Check a smallish nearest-neighbour interpolation against a result
# snapshot.
test_cube = self.cube[0][0]
# Test points on a regular grid, a bit larger than the source region.
xmin, xmax = [
fn(test_cube.coord(axis="x").points) for fn in (np.min, np.max)
]
ymin, ymax = [
fn(test_cube.coord(axis="x").points) for fn in (np.min, np.max)
]
fractions = [-0.23, -0.01, 0.27, 0.624, 0.983, 1.052, 1.43]
x_points = [xmin + frac * (xmax - xmin) for frac in fractions]
y_points = [ymin + frac * (ymax - ymin) for frac in fractions]
x_points, y_points = np.meshgrid(x_points, y_points)
sample_points = [
("grid_longitude", x_points.flatten()),
("grid_latitude", y_points.flatten()),
]
result = traj_interpolate(test_cube, sample_points, method="nearest")
expected = [
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
]
self.assertArrayAllClose(result.data, expected)
@tests.skip_data
class TestTriPolar(tests.IrisTest):
def setUp(self):
# load data
cubes = iris.load(
tests.get_data_path(["NetCDF", "ORCA2", "votemper.nc"])
)
cube = cubes[0]
# The netCDF file has different data types for the points and
# bounds of 'depth'. This wasn't previously supported, so we
# emulate that old behaviour.
b32 = cube.coord("depth").bounds.astype(np.float32)
cube.coord("depth").bounds = b32
self.cube = cube
# define a latitude trajectory (put coords in a different order
# to the cube, just to be awkward)
latitudes = list(range(-90, 90, 2))
longitudes = [-90] * len(latitudes)
self.sample_points = [
("longitude", longitudes),
("latitude", latitudes),
]
def test_tri_polar(self):
# extract
sampled_cube = traj_interpolate(self.cube, self.sample_points)
self.assertCML(
sampled_cube, ("trajectory", "tri_polar_latitude_slice.cml")
)
def test_tri_polar_method_linear_fails(self):
# Try to request linear interpolation.
# Not allowed, as we have multi-dimensional coords.
self.assertRaises(
iris.exceptions.CoordinateMultiDimError,
traj_interpolate,
self.cube,
self.sample_points,
method="linear",
)
def test_tri_polar_method_unknown_fails(self):
# Try to request unknown interpolation.
self.assertRaises(
ValueError,
traj_interpolate,
self.cube,
self.sample_points,
method="linekar",
)
def test_tri_polar__nearest(self):
# Check a smallish nearest-neighbour interpolation against a result
# snapshot.
test_cube = self.cube
# Use just one 2d layer, just to be faster.
test_cube = test_cube[0][0]
# Fix the fill value of the data to zero, just so that we get the same
# result under numpy < 1.11 as with 1.11.
# NOTE: numpy<1.11 *used* to assign missing data points into an
# unmasked array as =0.0, now =fill-value.
# TODO: arguably, we should support masked data properly in the
# interpolation routine. In the legacy code, that is unfortunately
# just not the case.
test_cube.data.fill_value = 0
# Test points on a regular global grid, with unrelated steps + offsets
# and an extended range of longitude values.
x_points = np.arange(-185.23, +360.0, 73.123)
|
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 task:
Context:
[Previous code... ~10,000 lines omitted for brevity]
@tests.skip_data
class TestTriPolar(tests.IrisTest):
def setUp(self):
# load data
cubes = iris.load(
tests.get_data_path(["NetCDF", "ORCA2", "votemper.nc"])
)
cube = cubes[0]
# The netCDF file has different data types for the points and
# bounds of 'depth'. This wasn't previously supported, so we
# emulate that old behaviour.
b32 = cube.coord("depth").bounds.astype(np.float32)
cube.coord("depth").bounds = b32
self.cube = cube
# define a latitude trajectory (put coords in a different order
# to the cube, just to be awkward)
latitudes = list(range(-90, 90, 2))
longitudes = [-90] * len(latitudes)
self.sample_points = [
("longitude", longitudes),
("latitude", latitudes),
]
def test_tri_polar(self):
# extract
sampled_cube = traj_interpolate(self.cube, self.sample_points)
self.assertCML(
sampled_cube, ("trajectory", "tri_polar_latitude_slice.cml")
)
def test_tri_polar_method_linear_fails(self):
# Try to request linear interpolation.
# Not allowed, as we have multi-dimensional coords.
self.assertRaises(
iris.exceptions.CoordinateMultiDimError,
traj_interpolate,
self.cube,
self.sample_points,
method="linear",
)
def test_tri_polar_method_unknown_fails(self):
# Try to request unknown interpolation.
self.assertRaises(
ValueError,
traj_interpolate,
self.cube,
self.sample_points,
method="linekar",
)
def test_tri_polar__nearest(self):
# Check a smallish nearest-neighbour interpolation against a result
# snapshot.
test_cube = self.cube
# Use just one 2d layer, just to be faster.
test_cube = test_cube[0][0]
# Fix the fill value of the data to zero, just so that we get the same
# result under numpy < 1.11 as with 1.11.
# NOTE: numpy<1.11 *used* to assign missing data points into an
# unmasked array as =0.0, now =fill-value.
# TODO: arguably, we should support masked data properly in the
# interpolation routine. In the legacy code, that is unfortunately
# just not the case.
test_cube.data.fill_value = 0
# Test points on a regular global grid, with unrelated steps + offsets
# and an extended range of longitude values.
x_points = np.arange(-185.23, +360.0, 73.123)
y_points = np.arange(-90, 91, 2)
sample_points = [
("longitude", x_points),
("latitude", y_points),
]
result = traj_interpolate(test_cube, sample_points, method="nearest")
expected = [
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
288.07168579,
288.07168579,
287.9367981,
287.82736206,
287.78564453,
287.8374939,
287.8374939,
]
self.assertArrayAllClose(result.data, expected)
Cheatsheet (for next line):
- We are in test_tri_polar__nearest, which is testing nearest-neighbour interpolation.
- The test_cube is a 2D layer of the cube.
- The sample_points are defined as a list of tuples, where each tuple contains a coordinate name and a 1D array of values.
- The method parameter is set to "nearest".
- The result is compared to an expected array of values.
- The expected array is a list of 64 float values.
- The test is checking the result of the nearest-neighbour interpolation against a result snapshot.
- The test_cube has a fill value of 0.
Next line will likely be: self.assertArrayAllClose(result.data, expected);
|
|
Please complete the code given below.
// CANAPE Network Testing Tool
// Copyright (C) 2014 Context Information Security
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using CANAPE.Controls;
using CANAPE.Nodes;
using CANAPE.Utils;
namespace CANAPE.Forms
{
internal partial class PacketLogViewerForm : Form
{
int _index;
IList<LogPacket> _packets;
PacketEntry[] _modifiedPackets;
bool _newStyleLogViewer;
private struct PacketEntry
{
public bool modified;
public LogPacket packet;
}
public bool ReadOnly { get; set; }
private bool IsFrameModified()
{
if (_packets.Count == 0)
{
return false;
}
return _modifiedPackets[_index].modified;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
bool ret = true;
switch(keyData)
{
case Keys.Control | Keys.N:
toolStripButtonForward.PerformClick();
break;
case Keys.Control | Keys.P:
toolStripButtonBack.PerformClick();
break;
case Keys.Control | Keys.S:
if (_newStyleLogViewer && IsFrameModified())
{
toolStripButtonSave.PerformClick();
}
break;
default:
ret = base.ProcessCmdKey(ref msg, keyData);
break;
}
return ret;
}
public PacketLogViewerForm(LogPacket curr, IList<LogPacket> packets)
{
for (int i = 0; i < packets.Count; i++)
{
if (packets[i] == curr)
{
_index = i;
break;
}
}
_packets = packets;
_modifiedPackets = new PacketEntry[_packets.Count];
_newStyleLogViewer = GlobalControlConfig.NewStyleLogViewer;
InitializeComponent();
timer.Start();
}
private void SetModifiedFrame()
{
_modifiedPackets[_index].modified = false;
_modifiedPackets[_index].packet = _packets[_index].ClonePacket();
_modifiedPackets[_index].packet.Frame.FrameModified += new EventHandler(_currPacket_FrameModified);
}
private LogPacket GetCurrentPacket()
{
if (_packets.Count == 0)
{
return null;
}
if (_newStyleLogViewer)
{
if (_modifiedPackets[_index].packet == null)
{
SetModifiedFrame();
}
return _modifiedPackets[_index].packet;
}
else
{
return _packets[_index];
}
}
private void OnFrameModified()
{
_modifiedPackets[_index].modified = true;
toolStripButtonSave.Enabled = true;
toolStripButtonRevert.Enabled = true;
}
void _currPacket_FrameModified(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action(OnFrameModified));
}
else
{
OnFrameModified();
}
}
private void UpdatePacketDisplay()
{
LogPacket p = GetCurrentPacket();
if (p == null)
{
return;
}
if (!_newStyleLogViewer)
{
frameEditorControl.ReadOnly = ReadOnly;
}
frameEditorControl.SetFrame(p.Frame, null, ColorValueConverter.ToColor(p.Color));
if (p.Frame.IsBasic || (ReadOnly && !_newStyleLogViewer))
{
toolStripButtonConvertToBytes.Enabled = false;
}
else
{
toolStripButtonConvertToBytes.Enabled = true;
}
if (_newStyleLogViewer)
{
toolStripButtonSave.Enabled = IsFrameModified();
toolStripButtonRevert.Enabled = IsFrameModified();
}
toolStripLabelPosition.Text = String.Format(CANAPE.Properties.Resources.PacketLogViewerForm_Header, _index + 1,
_packets.Count, p.Tag, p.Network, p.Timestamp.ToString());
}
private void LogViewerForm_Load(object sender, EventArgs e)
{
if(_packets.Count == 0)
{
Close();
}
if (!_newStyleLogViewer)
{
Text = !ReadOnly ? CANAPE.Properties.Resources.PacketLogViewerForm_Title
: CANAPE.Properties.Resources.PacketLogViewerForm_TitleReadOnly;
toolStripButtonSave.Visible = false;
toolStripButtonRevert.Visible = false;
}
else
{
Text = CANAPE.Properties.Resources.PacketLogViewerForm_Title;
}
UpdatePacketDisplay();
}
private void toolStripButtonBack_Click(object sender, EventArgs e)
{
_index -= 1;
if (_index < 0)
{
_index = _packets.Count - 1;
}
UpdatePacketDisplay();
}
private void toolStripButtonForward_Click(object sender, EventArgs e)
{
_index++;
if (_index > _packets.Count - 1)
{
_index = 0;
}
UpdatePacketDisplay();
}
private void toolStripButtonCopy_Click(object sender, EventArgs e)
{
LogPacket currPacket = GetCurrentPacket();
|
[
" if (currPacket != null)"
] | 518
|
lcc
|
csharp
| null |
6cbff4b2ab9cd811f4d0b2d6ed54a5ae26c2c9ed95c4d5cb
| 71
|
Your task is code completion.
// CANAPE Network Testing Tool
// Copyright (C) 2014 Context Information Security
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using CANAPE.Controls;
using CANAPE.Nodes;
using CANAPE.Utils;
namespace CANAPE.Forms
{
internal partial class PacketLogViewerForm : Form
{
int _index;
IList<LogPacket> _packets;
PacketEntry[] _modifiedPackets;
bool _newStyleLogViewer;
private struct PacketEntry
{
public bool modified;
public LogPacket packet;
}
public bool ReadOnly { get; set; }
private bool IsFrameModified()
{
if (_packets.Count == 0)
{
return false;
}
return _modifiedPackets[_index].modified;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
bool ret = true;
switch(keyData)
{
case Keys.Control | Keys.N:
toolStripButtonForward.PerformClick();
break;
case Keys.Control | Keys.P:
toolStripButtonBack.PerformClick();
break;
case Keys.Control | Keys.S:
if (_newStyleLogViewer && IsFrameModified())
{
toolStripButtonSave.PerformClick();
}
break;
default:
ret = base.ProcessCmdKey(ref msg, keyData);
break;
}
return ret;
}
public PacketLogViewerForm(LogPacket curr, IList<LogPacket> packets)
{
for (int i = 0; i < packets.Count; i++)
{
if (packets[i] == curr)
{
_index = i;
break;
}
}
_packets = packets;
_modifiedPackets = new PacketEntry[_packets.Count];
_newStyleLogViewer = GlobalControlConfig.NewStyleLogViewer;
InitializeComponent();
timer.Start();
}
private void SetModifiedFrame()
{
_modifiedPackets[_index].modified = false;
_modifiedPackets[_index].packet = _packets[_index].ClonePacket();
_modifiedPackets[_index].packet.Frame.FrameModified += new EventHandler(_currPacket_FrameModified);
}
private LogPacket GetCurrentPacket()
{
if (_packets.Count == 0)
{
return null;
}
if (_newStyleLogViewer)
{
if (_modifiedPackets[_index].packet == null)
{
SetModifiedFrame();
}
return _modifiedPackets[_index].packet;
}
else
{
return _packets[_index];
}
}
private void OnFrameModified()
{
_modifiedPackets[_index].modified = true;
toolStripButtonSave.Enabled = true;
toolStripButtonRevert.Enabled = true;
}
void _currPacket_FrameModified(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action(OnFrameModified));
}
else
{
OnFrameModified();
}
}
private void UpdatePacketDisplay()
{
LogPacket p = GetCurrentPacket();
if (p == null)
{
return;
}
if (!_newStyleLogViewer)
{
frameEditorControl.ReadOnly = ReadOnly;
}
frameEditorControl.SetFrame(p.Frame, null, ColorValueConverter.ToColor(p.Color));
if (p.Frame.IsBasic || (ReadOnly && !_newStyleLogViewer))
{
toolStripButtonConvertToBytes.Enabled = false;
}
else
{
toolStripButtonConvertToBytes.Enabled = true;
}
if (_newStyleLogViewer)
{
toolStripButtonSave.Enabled = IsFrameModified();
toolStripButtonRevert.Enabled = IsFrameModified();
}
toolStripLabelPosition.Text = String.Format(CANAPE.Properties.Resources.PacketLogViewerForm_Header, _index + 1,
_packets.Count, p.Tag, p.Network, p.Timestamp.ToString());
}
private void LogViewerForm_Load(object sender, EventArgs e)
{
if(_packets.Count == 0)
{
Close();
}
if (!_newStyleLogViewer)
{
Text = !ReadOnly ? CANAPE.Properties.Resources.PacketLogViewerForm_Title
: CANAPE.Properties.Resources.PacketLogViewerForm_TitleReadOnly;
toolStripButtonSave.Visible = false;
toolStripButtonRevert.Visible = false;
}
else
{
Text = CANAPE.Properties.Resources.PacketLogViewerForm_Title;
}
UpdatePacketDisplay();
}
private void toolStripButtonBack_Click(object sender, EventArgs e)
{
_index -= 1;
if (_index < 0)
{
_index = _packets.Count - 1;
}
UpdatePacketDisplay();
}
private void toolStripButtonForward_Click(object sender, EventArgs e)
{
_index++;
if (_index > _packets.Count - 1)
{
_index = 0;
}
UpdatePacketDisplay();
}
private void toolStripButtonCopy_Click(object sender, EventArgs e)
{
LogPacket currPacket = GetCurrentPacket();
|
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 PacketLogViewerForm:
**Context:**
[Previous code... ~10,000 lines omitted for brevity]
private void toolStripButtonCopy_Click(object sender, EventArgs e)
{
LogPacket currPacket = GetCurrentPacket();
// [Insert code here]
**Relevant Variables and Methods:**
- `currPacket`: The current packet being displayed, obtained from `GetCurrentPacket()`.
- `GetCurrentPacket()`: Returns the current packet being displayed, either from the original list or the modified list if `newStyleLogViewer` is true.
- `ReadOnly`: A boolean indicating whether the form is in read-only mode.
- `frameEditorControl`: A control used to display the packet frame.
**Expected Behavior:**
- The `toolStripButtonCopy_Click` method should copy the current packet to the clipboard.
- If `ReadOnly` is true, the method should not perform any action.
**Possible Next Lines:**
- `if (!ReadOnly) { ... }` to check if the form is not in read-only mode.
- `Clipboard.SetDataObject(currPacket);` to copy the current packet to the clipboard.
- `frameEditorControl.Copy();` to copy the current packet from the frame editor control.
**Completed Cheat Sheet:**
- We are in `toolStripButtonCopy_Click`, which should copy the current packet to the clipboard.
- `currPacket` is the current packet being displayed.
- `ReadOnly` is a boolean indicating whether the form is in read-only mode.
- `frameEditorControl` is a control used to display the packet frame.
- Convention: If a method is not in read-only mode, it should perform the desired action.
- [Relevant lines: method header, `ReadOnly` field, `frameEditorControl` declaration]
**Next Line:**
```csharp
if (!ReadOnly) {
```
|
|
Please complete the code given below.
import cPickle
import wave
import gzip
import scipy
import scipy.io.wavfile
from matplotlib import pylab
import scipy.io.wavfile
import os
from numpy import *
from pydub import AudioSegment
from pyechonest import track, config
import numpy
import mfcc_diy
class Dataset:
"""Slices, shuffles and manages a small dataset for the HF optimizer."""
def __init__(self, data, batch_size, number_batches=None, targets=None):
'''SequenceDataset __init__
data : list of lists of numpy arrays
Your dataset will be provided as a list (one list for each graph input) of
variable-length tensors that will be used as mini-batches. Typically, each
tensor is a sequence or a set of examples.
batch_size : int or None
If an int, the mini-batches will be further split in chunks of length
`batch_size`. This is useful for slicing subsequences or provide the full
dataset in a single tensor to be split here. All tensors in `data` must
then have the same leading dimension.
number_batches : int
Number of mini-batches over which you iterate to compute a gradient or
Gauss-Newton matrix product. If None, it will iterate over the entire dataset.
minimum_size : int
Reject all mini-batches that end up smaller than this length.'''
self.current_batch = 0
self.number_batches = number_batches
self.items = []
if targets is None:
if batch_size is None:
# self.items.append([data[i][i_sequence] for i in xrange(len(data))])
self.items = [[data[i]] for i in xrange(len(data))]
else:
# self.items = [sequence[i:i+batch_size] for sequence in data for i in xrange(0, len(sequence), batch_size)]
for sequence in data:
num_batches = sequence.shape[0] / float(batch_size)
num_batches = numpy.ceil(num_batches)
for i in xrange(int(num_batches)):
start = i * batch_size
end = (i + 1) * batch_size
if end > sequence.shape[0]:
end = sequence.shape[0]
self.items.append([sequence[start:end]])
else:
if batch_size is None:
self.items = [[data[i], targets[i]] for i in xrange(len(data))]
else:
for sequence, sequence_targets in zip(data, targets):
num_batches = sequence.shape[0] / float(batch_size)
num_batches = numpy.ceil(num_batches)
for i in xrange(int(num_batches)):
start = i * batch_size
end = (i + 1) * batch_size
if end > sequence.shape[0]:
end = sequence.shape[0]
self.items.append([sequence[start:end], sequence_targets[start:end]])
if not self.number_batches:
self.number_batches = len(self.items)
self.num_min_batches = len(self.items)
self.shuffle()
def shuffle(self):
numpy.random.shuffle(self.items)
def iterate(self, update=True):
for b in xrange(self.number_batches):
yield self.items[(self.current_batch + b) % len(self.items)]
if update: self.update()
def update(self):
if self.current_batch + self.number_batches >= len(self.items):
self.shuffle()
self.current_batch = 0
else:
self.current_batch += self.number_batches
def load_audio(song_dir):
file_format = song_dir.split('.')[1]
if 'wav' == file_format:
song = wave.open(song_dir, "rb")
params = song.getparams()
nchannels, samplewidth, framerate, nframes = params[:4] # format info
song_data = song.readframes(nframes)
song.close()
wave_data = numpy.fromstring(song_data, dtype=numpy.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
else:
raise NameError("now just support wav format audio files")
return wave_data
def pickle_dataset(dataset, out_pkl='dataset.pkl'):
# pickle the file and for long time save
pkl_file = file(out_pkl, 'wb')
cPickle.dump(dataset, pkl_file, True)
pkl_file.close()
return 0
def build_song_set(songs_dir):
# save songs and singer lable to pickle file
songs_dataset = []
for parent, dirnames, filenames in os.walk(songs_dir):
for filename in filenames:
song_dir = os.path.join(parent, filename)
audio = load_audio(song_dir)
# change the value as your singer name level in the dir
# eg. short_wav/new_wav/dataset/singer_name so I set 3
singer = song_dir.split('/')[1]
# this value depends on the singer file level in the dir
songs_dataset.append((audio, singer))
pickle_dataset(songs_dataset, 'songs_audio_singer.pkl')
return 0
def load_data(pkl_dir='dataset.pkl'):
# load pickle data file
pkl_dataset = open(pkl_dir, 'rb')
dataset = cPickle.load(pkl_dataset)
pkl_dataset.close()
return dataset
def get_mono_left_right_audio(wavs_dir='mir1k-Wavfile'):
# split a audio to left and right channel
for parent, dirnames, filenames in os.walk(wavs_dir):
for filename in filenames:
audio_dir = os.path.join(parent, filename)
mono_sound_dir = 'mono/' + audio_dir
if not os.path.exists(os.path.split(mono_sound_dir)[0]):
os.makedirs(os.path.split(mono_sound_dir)[0])
left_audio_dir = 'left_right/' + os.path.splitext(mono_sound_dir)[0] + '_left.wav'
if not os.path.exists(os.path.split(left_audio_dir)[0]):
os.makedirs(os.path.split(left_audio_dir)[0])
right_audio_dir = 'left_right/' + os.path.splitext(mono_sound_dir)[0] + '_right.wav'
if not os.path.exists(os.path.split(right_audio_dir)[0]):
os.makedirs(os.path.split(right_audio_dir)[0])
sound = AudioSegment.from_wav(audio_dir)
mono = sound.set_channels(1)
left, right = sound.split_to_mono()
mono.export(mono_sound_dir, format='wav')
left.export(left_audio_dir, format='wav')
right.export(right_audio_dir, format='wav')
return 0
def get_right_voice_audio(wavs_dir='mir1k-Wavfile'):
# get singer voice from the right channel
for parent, dirnames, filenames in os.walk(wavs_dir):
for filename in filenames:
audio_dir = os.path.join(parent, filename)
right_audio_dir = 'right_voices/' + os.path.splitext(audio_dir)[0] + '_right.wav'
if not os.path.exists(os.path.split(right_audio_dir)[0]):
os.makedirs(os.path.split(right_audio_dir)[0])
sound = AudioSegment.from_wav(audio_dir)
left, right = sound.split_to_mono()
right.export(right_audio_dir, format='wav')
return 0
def draw_wav(wav_dir):
'''
draw the wav audio to show
'''
song = wave.open(wav_dir, "rb")
params = song.getparams()
nchannels, samplewidth, framerate, nframes = params[:4] # format info
song_data = song.readframes(nframes)
song.close()
wave_data = numpy.fromstring(song_data, dtype=numpy.short)
wave_data.shape = -1, 1
wave_data = wave_data.T
time = numpy.arange(0, nframes) * (1.0 / framerate)
len_time = len(time)
time = time[0:len_time]
pylab.plot(time, wave_data[0])
pylab.xlabel("time")
pylab.ylabel("wav_data")
pylab.show()
return 0
def get_mfcc(wav_dir):
# mfccs
sample_rate, audio = scipy.io.wavfile.read(wav_dir)
# ceps, mspec, spec = mfcc(audio, nwin=256, fs=8000, nceps=13)
ceps, mspec, spec = mfcc_diy.mfcc(audio, nwin=8000, fs=8000, nceps=13)
mfccs = ceps
return mfccs
def get_raw(wav_dir):
# raw audio data
sample_rate, audio = scipy.io.wavfile.read(wav_dir)
return audio
def filter_nan_inf(mfccss):
# filter the nan and inf data point of mfcc
filter_nan_infs = []
for item in mfccss:
new_item = []
for ii in item:
if numpy.isinf(ii):
ii = 1000
elif numpy.isnan(ii):
ii = -11
else:
ii = ii
new_item.append(ii)
filter_nan_infs.append(new_item)
new_mfcc = numpy.array(filter_nan_infs)
return new_mfcc
def get_timbre_pitches_loudness(wav_dir):
# from echonest capture the timbre and pitches loudness et.al.
config.ECHO_NEST_API_KEY = "BPQ7TEP9JXXDVIXA5" # daleloogn my api key
f = open(wav_dir)
print "process:============ %s =============" % wav_dir
t = track.track_from_file(f, 'wav', 256, force_upload=True)
t.get_analysis()
segments = t.segments # list of dicts :timing,pitch,loudness and timbre for each segment
timbre_pitches_loudness = from_segments_get_timbre_pitch_etal(wav_dir, segments)
timbre_pitches_loudness_file_txt = open('timbre_pitches_loudness_file.txt', 'a')
timbre_pitches_loudness_file_txt.write(wav_dir + '\r\n')
timbre_pitches_loudness_file_txt.write(str(timbre_pitches_loudness))
timbre_pitches_loudness_file_txt.close()
return segments
def draw_segments_from_echonest(wav_dir, starts_point):
# just draw it and show the difference duration of segments
song = wave.open(wav_dir, "rb")
params = song.getparams()
nchannels, samplewidth, framerate, nframes = params[:4] # format info
song_data = song.readframes(nframes)
song.close()
wave_data = numpy.fromstring(song_data, dtype=numpy.short)
wave_data.shape = -1, 1
wave_data = wave_data.T
time = numpy.arange(0, nframes) * (1.0 / framerate)
len_time = len(time)
time = time[0:len_time]
pylab.plot(time, wave_data[0])
num_len = len(starts_point)
pylab.plot(starts_point, [1] * num_len, 'ro')
pylab.xlabel("time")
pylab.ylabel("wav_data")
pylab.show()
return 0
def from_segments_get_timbre_pitch_etal(wav_dir, segments):
# from segments get the feature you want
timbre_pitches_loudness = []
starts_point = []
for segments_item in segments:
timbre = segments_item['timbre']
pitches = segments_item['pitches']
loudness_start = segments_item['loudness_start']
loudness_max_time = segments_item['loudness_max_time']
loudness_max = segments_item['loudness_max']
durarion = segments_item['duration']
start = segments_item['start']
starts_point.append(start)
segments_item_union = timbre + pitches + [loudness_start, loudness_max_time, loudness_max]
timbre_pitches_loudness.append(segments_item_union)
##plot the segments seg
draw_segments_from_echonest(wav_dir, starts_point)
####
return timbre_pitches_loudness
def generate_singer_label(wavs_dir):
# generate the singer to label dict
dict_singer_label = {}
singers = []
for parent, dirnames, filenames in os.walk(wavs_dir):
for filename in filenames:
singer_name = filename.split('_')[0]
singers.append(singer_name)
only_singers = sorted(list(set(singers)))
for item, singer in enumerate(only_singers):
dict_singer_label[singer] = item
# print dict_singer_label
return dict_singer_label
def build_dataset(wavs_dir):
print 'from %s build dataset==============' % wavs_dir
dataset = []
data = []
target = []
dict_singer_label = generate_singer_label(wavs_dir)
for parent, dirnames, filenames in os.walk(wavs_dir):
for filename in filenames:
song_dir = os.path.join(parent, filename)
print"get mfcc of %s ====" % filename
song_feature = get_mfcc(song_dir)
song_feature = filter_nan_inf(song_feature) # feature=======================a song mfcc vector
singer = filename.split('_')[0] # this value depends on the singer file level in the dir
singer_label = dict_singer_label[singer] # target class====================
# song_mfcc_sum_vector = mfcc_sum_vector(song_feature)
# feature=======================a song mfcc vector sum
songs_mfcc_vecto_link = []
for vector_item in song_feature:
vector_item = [x for x in vector_item]
# songs_mfcc_vecto_link.extend(vector_item)
# data.append(songs_mfcc_vecto_link) # feature just a frame
data.append(vector_item)
target.append(singer_label)
dataset.append(data)
# print data[1:50]
dataset.append(target)
print 'pkl_to dataset.pkl'
pickle_dataset(dataset)
return 0
def slice_wav_beigin_one_end_one(wav_dir):
# it used for cut the wav file head and end
new_dir = 'sliced/' + wav_dir
if not os.path.exists(os.path.split(new_dir)[0]):
os.makedirs(os.path.split(new_dir)[0])
audio = AudioSegment.from_wav(wav_dir)
one_seconds = 1 * 1000
first_five_seconds = audio[one_seconds:-2000]
first_five_seconds.export(new_dir, format='wav')
return 0
def slice_wavs_dirs(dirs):
# in batach to slice
for parent, dirnames, filenames in os.walk(dirs):
for filename in filenames:
song_dir = os.path.join(parent, filename)
slice_wav_beigin_one_end_one(song_dir)
return 0
def save_echonest_data_to_txt(wav_dirs):
# cache the data from the internet
for parent, dirnames, filenames in os.walk(wav_dirs):
for filename in filenames:
song_dir = os.path.join(parent, filename)
if not os.path.exists('save_segments.txt'):
segments_file = open('save_segments.txt', 'w')
segments_file.close()
segments_file = open('save_segments.txt', 'r')
all_lines = segments_file.readlines()
segments_file.close()
dirs = []
for line_item in all_lines:
dir_song = line_item.split('@')[0]
dirs.append(dir_song)
if song_dir in dirs:
pass
else:
segments = get_timbre_pitches_loudness(song_dir)
lines = song_dir + '@' + str(segments) + '\r\n'
segments_file = open('save_segments.txt', 'a', )
segments_file.write(lines)
segments_file.close()
return 0
def print_color(color="red or yellow"):
# consloe out color
if color == 'red':
print '\033[1;31;40m'
|
[
" elif color == 'yellow':"
] | 1,319
|
lcc
|
python
| null |
6071885a8ddae41fc3b21de3b7edec8f485b65d210d0a2e3
| 72
|
Your task is code completion.
import cPickle
import wave
import gzip
import scipy
import scipy.io.wavfile
from matplotlib import pylab
import scipy.io.wavfile
import os
from numpy import *
from pydub import AudioSegment
from pyechonest import track, config
import numpy
import mfcc_diy
class Dataset:
"""Slices, shuffles and manages a small dataset for the HF optimizer."""
def __init__(self, data, batch_size, number_batches=None, targets=None):
'''SequenceDataset __init__
data : list of lists of numpy arrays
Your dataset will be provided as a list (one list for each graph input) of
variable-length tensors that will be used as mini-batches. Typically, each
tensor is a sequence or a set of examples.
batch_size : int or None
If an int, the mini-batches will be further split in chunks of length
`batch_size`. This is useful for slicing subsequences or provide the full
dataset in a single tensor to be split here. All tensors in `data` must
then have the same leading dimension.
number_batches : int
Number of mini-batches over which you iterate to compute a gradient or
Gauss-Newton matrix product. If None, it will iterate over the entire dataset.
minimum_size : int
Reject all mini-batches that end up smaller than this length.'''
self.current_batch = 0
self.number_batches = number_batches
self.items = []
if targets is None:
if batch_size is None:
# self.items.append([data[i][i_sequence] for i in xrange(len(data))])
self.items = [[data[i]] for i in xrange(len(data))]
else:
# self.items = [sequence[i:i+batch_size] for sequence in data for i in xrange(0, len(sequence), batch_size)]
for sequence in data:
num_batches = sequence.shape[0] / float(batch_size)
num_batches = numpy.ceil(num_batches)
for i in xrange(int(num_batches)):
start = i * batch_size
end = (i + 1) * batch_size
if end > sequence.shape[0]:
end = sequence.shape[0]
self.items.append([sequence[start:end]])
else:
if batch_size is None:
self.items = [[data[i], targets[i]] for i in xrange(len(data))]
else:
for sequence, sequence_targets in zip(data, targets):
num_batches = sequence.shape[0] / float(batch_size)
num_batches = numpy.ceil(num_batches)
for i in xrange(int(num_batches)):
start = i * batch_size
end = (i + 1) * batch_size
if end > sequence.shape[0]:
end = sequence.shape[0]
self.items.append([sequence[start:end], sequence_targets[start:end]])
if not self.number_batches:
self.number_batches = len(self.items)
self.num_min_batches = len(self.items)
self.shuffle()
def shuffle(self):
numpy.random.shuffle(self.items)
def iterate(self, update=True):
for b in xrange(self.number_batches):
yield self.items[(self.current_batch + b) % len(self.items)]
if update: self.update()
def update(self):
if self.current_batch + self.number_batches >= len(self.items):
self.shuffle()
self.current_batch = 0
else:
self.current_batch += self.number_batches
def load_audio(song_dir):
file_format = song_dir.split('.')[1]
if 'wav' == file_format:
song = wave.open(song_dir, "rb")
params = song.getparams()
nchannels, samplewidth, framerate, nframes = params[:4] # format info
song_data = song.readframes(nframes)
song.close()
wave_data = numpy.fromstring(song_data, dtype=numpy.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
else:
raise NameError("now just support wav format audio files")
return wave_data
def pickle_dataset(dataset, out_pkl='dataset.pkl'):
# pickle the file and for long time save
pkl_file = file(out_pkl, 'wb')
cPickle.dump(dataset, pkl_file, True)
pkl_file.close()
return 0
def build_song_set(songs_dir):
# save songs and singer lable to pickle file
songs_dataset = []
for parent, dirnames, filenames in os.walk(songs_dir):
for filename in filenames:
song_dir = os.path.join(parent, filename)
audio = load_audio(song_dir)
# change the value as your singer name level in the dir
# eg. short_wav/new_wav/dataset/singer_name so I set 3
singer = song_dir.split('/')[1]
# this value depends on the singer file level in the dir
songs_dataset.append((audio, singer))
pickle_dataset(songs_dataset, 'songs_audio_singer.pkl')
return 0
def load_data(pkl_dir='dataset.pkl'):
# load pickle data file
pkl_dataset = open(pkl_dir, 'rb')
dataset = cPickle.load(pkl_dataset)
pkl_dataset.close()
return dataset
def get_mono_left_right_audio(wavs_dir='mir1k-Wavfile'):
# split a audio to left and right channel
for parent, dirnames, filenames in os.walk(wavs_dir):
for filename in filenames:
audio_dir = os.path.join(parent, filename)
mono_sound_dir = 'mono/' + audio_dir
if not os.path.exists(os.path.split(mono_sound_dir)[0]):
os.makedirs(os.path.split(mono_sound_dir)[0])
left_audio_dir = 'left_right/' + os.path.splitext(mono_sound_dir)[0] + '_left.wav'
if not os.path.exists(os.path.split(left_audio_dir)[0]):
os.makedirs(os.path.split(left_audio_dir)[0])
right_audio_dir = 'left_right/' + os.path.splitext(mono_sound_dir)[0] + '_right.wav'
if not os.path.exists(os.path.split(right_audio_dir)[0]):
os.makedirs(os.path.split(right_audio_dir)[0])
sound = AudioSegment.from_wav(audio_dir)
mono = sound.set_channels(1)
left, right = sound.split_to_mono()
mono.export(mono_sound_dir, format='wav')
left.export(left_audio_dir, format='wav')
right.export(right_audio_dir, format='wav')
return 0
def get_right_voice_audio(wavs_dir='mir1k-Wavfile'):
# get singer voice from the right channel
for parent, dirnames, filenames in os.walk(wavs_dir):
for filename in filenames:
audio_dir = os.path.join(parent, filename)
right_audio_dir = 'right_voices/' + os.path.splitext(audio_dir)[0] + '_right.wav'
if not os.path.exists(os.path.split(right_audio_dir)[0]):
os.makedirs(os.path.split(right_audio_dir)[0])
sound = AudioSegment.from_wav(audio_dir)
left, right = sound.split_to_mono()
right.export(right_audio_dir, format='wav')
return 0
def draw_wav(wav_dir):
'''
draw the wav audio to show
'''
song = wave.open(wav_dir, "rb")
params = song.getparams()
nchannels, samplewidth, framerate, nframes = params[:4] # format info
song_data = song.readframes(nframes)
song.close()
wave_data = numpy.fromstring(song_data, dtype=numpy.short)
wave_data.shape = -1, 1
wave_data = wave_data.T
time = numpy.arange(0, nframes) * (1.0 / framerate)
len_time = len(time)
time = time[0:len_time]
pylab.plot(time, wave_data[0])
pylab.xlabel("time")
pylab.ylabel("wav_data")
pylab.show()
return 0
def get_mfcc(wav_dir):
# mfccs
sample_rate, audio = scipy.io.wavfile.read(wav_dir)
# ceps, mspec, spec = mfcc(audio, nwin=256, fs=8000, nceps=13)
ceps, mspec, spec = mfcc_diy.mfcc(audio, nwin=8000, fs=8000, nceps=13)
mfccs = ceps
return mfccs
def get_raw(wav_dir):
# raw audio data
sample_rate, audio = scipy.io.wavfile.read(wav_dir)
return audio
def filter_nan_inf(mfccss):
# filter the nan and inf data point of mfcc
filter_nan_infs = []
for item in mfccss:
new_item = []
for ii in item:
if numpy.isinf(ii):
ii = 1000
elif numpy.isnan(ii):
ii = -11
else:
ii = ii
new_item.append(ii)
filter_nan_infs.append(new_item)
new_mfcc = numpy.array(filter_nan_infs)
return new_mfcc
def get_timbre_pitches_loudness(wav_dir):
# from echonest capture the timbre and pitches loudness et.al.
config.ECHO_NEST_API_KEY = "BPQ7TEP9JXXDVIXA5" # daleloogn my api key
f = open(wav_dir)
print "process:============ %s =============" % wav_dir
t = track.track_from_file(f, 'wav', 256, force_upload=True)
t.get_analysis()
segments = t.segments # list of dicts :timing,pitch,loudness and timbre for each segment
timbre_pitches_loudness = from_segments_get_timbre_pitch_etal(wav_dir, segments)
timbre_pitches_loudness_file_txt = open('timbre_pitches_loudness_file.txt', 'a')
timbre_pitches_loudness_file_txt.write(wav_dir + '\r\n')
timbre_pitches_loudness_file_txt.write(str(timbre_pitches_loudness))
timbre_pitches_loudness_file_txt.close()
return segments
def draw_segments_from_echonest(wav_dir, starts_point):
# just draw it and show the difference duration of segments
song = wave.open(wav_dir, "rb")
params = song.getparams()
nchannels, samplewidth, framerate, nframes = params[:4] # format info
song_data = song.readframes(nframes)
song.close()
wave_data = numpy.fromstring(song_data, dtype=numpy.short)
wave_data.shape = -1, 1
wave_data = wave_data.T
time = numpy.arange(0, nframes) * (1.0 / framerate)
len_time = len(time)
time = time[0:len_time]
pylab.plot(time, wave_data[0])
num_len = len(starts_point)
pylab.plot(starts_point, [1] * num_len, 'ro')
pylab.xlabel("time")
pylab.ylabel("wav_data")
pylab.show()
return 0
def from_segments_get_timbre_pitch_etal(wav_dir, segments):
# from segments get the feature you want
timbre_pitches_loudness = []
starts_point = []
for segments_item in segments:
timbre = segments_item['timbre']
pitches = segments_item['pitches']
loudness_start = segments_item['loudness_start']
loudness_max_time = segments_item['loudness_max_time']
loudness_max = segments_item['loudness_max']
durarion = segments_item['duration']
start = segments_item['start']
starts_point.append(start)
segments_item_union = timbre + pitches + [loudness_start, loudness_max_time, loudness_max]
timbre_pitches_loudness.append(segments_item_union)
##plot the segments seg
draw_segments_from_echonest(wav_dir, starts_point)
####
return timbre_pitches_loudness
def generate_singer_label(wavs_dir):
# generate the singer to label dict
dict_singer_label = {}
singers = []
for parent, dirnames, filenames in os.walk(wavs_dir):
for filename in filenames:
singer_name = filename.split('_')[0]
singers.append(singer_name)
only_singers = sorted(list(set(singers)))
for item, singer in enumerate(only_singers):
dict_singer_label[singer] = item
# print dict_singer_label
return dict_singer_label
def build_dataset(wavs_dir):
print 'from %s build dataset==============' % wavs_dir
dataset = []
data = []
target = []
dict_singer_label = generate_singer_label(wavs_dir)
for parent, dirnames, filenames in os.walk(wavs_dir):
for filename in filenames:
song_dir = os.path.join(parent, filename)
print"get mfcc of %s ====" % filename
song_feature = get_mfcc(song_dir)
song_feature = filter_nan_inf(song_feature) # feature=======================a song mfcc vector
singer = filename.split('_')[0] # this value depends on the singer file level in the dir
singer_label = dict_singer_label[singer] # target class====================
# song_mfcc_sum_vector = mfcc_sum_vector(song_feature)
# feature=======================a song mfcc vector sum
songs_mfcc_vecto_link = []
for vector_item in song_feature:
vector_item = [x for x in vector_item]
# songs_mfcc_vecto_link.extend(vector_item)
# data.append(songs_mfcc_vecto_link) # feature just a frame
data.append(vector_item)
target.append(singer_label)
dataset.append(data)
# print data[1:50]
dataset.append(target)
print 'pkl_to dataset.pkl'
pickle_dataset(dataset)
return 0
def slice_wav_beigin_one_end_one(wav_dir):
# it used for cut the wav file head and end
new_dir = 'sliced/' + wav_dir
if not os.path.exists(os.path.split(new_dir)[0]):
os.makedirs(os.path.split(new_dir)[0])
audio = AudioSegment.from_wav(wav_dir)
one_seconds = 1 * 1000
first_five_seconds = audio[one_seconds:-2000]
first_five_seconds.export(new_dir, format='wav')
return 0
def slice_wavs_dirs(dirs):
# in batach to slice
for parent, dirnames, filenames in os.walk(dirs):
for filename in filenames:
song_dir = os.path.join(parent, filename)
slice_wav_beigin_one_end_one(song_dir)
return 0
def save_echonest_data_to_txt(wav_dirs):
# cache the data from the internet
for parent, dirnames, filenames in os.walk(wav_dirs):
for filename in filenames:
song_dir = os.path.join(parent, filename)
if not os.path.exists('save_segments.txt'):
segments_file = open('save_segments.txt', 'w')
segments_file.close()
segments_file = open('save_segments.txt', 'r')
all_lines = segments_file.readlines()
segments_file.close()
dirs = []
for line_item in all_lines:
dir_song = line_item.split('@')[0]
dirs.append(dir_song)
if song_dir in dirs:
pass
else:
segments = get_timbre_pitches_loudness(song_dir)
lines = song_dir + '@' + str(segments) + '\r\n'
segments_file = open('save_segments.txt', 'a', )
segments_file.write(lines)
segments_file.close()
return 0
def print_color(color="red or yellow"):
# consloe out color
if color == 'red':
print '\033[1;31;40m'
|
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:**
The code is a collection of functions for audio processing and dataset management. The functions are used for tasks such as loading audio files, extracting features (MFCCs), splitting audio files, and building datasets.
**Relevant lines and variables:**
1. `build_dataset(wavs_dir)` function:
* This function builds a dataset from a directory of audio files.
* It uses the `get_mfcc` function to extract MFCC features from each audio file.
* It uses the `filter_nan_inf` function to filter out NaN and inf values in the MFCC features.
* It uses the `generate_singer_label` function to generate a dictionary mapping singer names to labels.
2. `get_mfcc(wav_dir)` function:
* This function extracts MFCC features from an audio file.
* It uses the `scipy.io.wavfile.read` function to read the audio file.
* It uses the `mfcc_diy.mfcc` function to extract MFCC features.
3. `filter_nan_inf(mfccss)` function:
* This function filters out NaN and inf values in a list of MFCC features.
* It uses a list comprehension to iterate over each MFCC feature and replace NaN and inf values with specific values.
4. `generate_singer_label(wavs_dir)` function:
* This function generates a dictionary mapping singer names to labels.
* It uses a list comprehension to extract singer names from file names in the directory.
* It uses the `sorted` function to sort the list of singer names and remove duplicates.
5. `build_song_set(songs_dir)` function:
* This function builds a dataset from a directory of audio files.
* It uses the `load_audio` function to load each audio file.
* It uses the `pickle_dataset` function to save the dataset to a pickle file.
**Task:**
The task is to complete the `build_dataset(wavs_dir)` function to handle the case where the input directory contains subdirectories.
**Cheat sheet:**
* We are in the `build_dataset(wavs_dir)` function.
* The function is designed to handle a directory of audio files.
* The function uses the `os.walk` function to iterate over the directory and its subdirectories.
* The function uses the `generate_singer_label` function to generate a dictionary mapping singer names to labels.
* The function uses the `get_mfcc` function to extract MFCC features from each audio file.
* The function uses the `filter_nan_inf` function to filter out NaN and inf values in the MFCC features.
**Next line:**
The next line should iterate over the subdirectories in the input directory and build the dataset for each subdirectory. The line should use the `os.walk` function to iterate over the subdirectories and the `build_song_set` function to build the dataset for each subdirectory.
```python
for parent, dirnames, filenames in os.walk(wavs_dir):
for dirname in dirnames:
sub_dir = os.path.join(parent, dirname)
build_song_set(sub_dir)
```
However, this is not the complete solution. The `build_song_set` function is not designed to handle subdirectories. We need to modify the `build_song_set` function to handle subdirectories.
**Modified `build_song_set` function:**
```python
def build_song_set(songs_dir):
songs_dataset = []
for parent, dirnames, filenames in os.walk(songs_dir):
for filename in filenames:
song_dir = os.path.join(parent, filename)
audio = load_audio(song_dir)
singer = song_dir.split('/')[1]
songs_dataset.append((audio, singer))
pickle_dataset(songs_dataset, 'songs_audio_singer.pkl')
return 0
```
**Complete solution:**
```python
def build_dataset(wavs_dir):
print 'from %s build dataset==============' % wavs_dir
dataset = []
data = []
target = []
dict_singer_label = generate_singer_label(wavs_dir)
for parent, dirnames, filenames in os.walk(wavs_dir):
for dirname in dirnames:
sub_dir = os.path.join(parent, dirname)
build_song_set(sub_dir)
# ... rest of the function remains the same ...
```
|
|
Please complete the code given below.
///////////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2006-2019 Esper Team. All rights reserved. /
// http://esper.codehaus.org /
// ---------------------------------------------------------------------------------- /
// The software in this package is published under the terms of the GPL license /
// a copy of which has been included with this distribution in the license.txt file. /
///////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
namespace com.espertech.esper.common.@internal.collection
{
/// <summary> reference-counting set based on a HashMap implementation that stores keys and a reference counter for
/// each unique key value. Each time the same key is added, the reference counter increases.
/// Each time a key is removed, the reference counter decreases.
/// </summary>
public class RefCountedSet<TK>
{
private bool _hasNullEntry;
private int _nullEntry;
private readonly IDictionary<TK, int> _refSet;
private int _numValues;
/// <summary>
/// Constructor.
/// </summary>
public RefCountedSet()
{
_refSet = new Dictionary<TK, int>();
}
public RefCountedSet(
IDictionary<TK, int> refSet,
int numValues)
{
_refSet = refSet;
_numValues = numValues;
}
/// <summary>
/// Adds a key to the set, but the key is null. It behaves the same, but has its own
/// variables that need to be incremented.
/// </summary>
private bool AddNull()
{
if (!_hasNullEntry) {
_hasNullEntry = true;
_numValues++;
_nullEntry = 0;
return true;
}
_numValues++;
_nullEntry++;
return false;
}
/// <summary> Add a key to the set. Add with a reference count of one if the key didn't exist in the set.
/// Increase the reference count by one if the key already exists.
/// Return true if this is the first time the key was encountered, or false if key is already in set.
/// </summary>
/// <param name="key">to add
/// </param>
/// <returns> true if the key is not in the set already, false if the key is already in the set
/// </returns>
public virtual bool Add(TK key)
{
if (ReferenceEquals(key, null)) {
return AddNull();
}
int value;
if (!_refSet.TryGetValue(key, out value)) {
_refSet[key] = 1;
_numValues++;
return true;
}
value++;
_numValues++;
_refSet[key] = value;
return false;
}
/// <summary>
/// Removes the null key
/// </summary>
private bool RemoveNull()
{
if (_nullEntry == 1) {
_hasNullEntry = false;
_nullEntry--;
return true;
}
_nullEntry--;
_numValues--;
return false;
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="numReferences">The num references.</param>
public void Add(
TK key,
int numReferences)
{
int value;
if (!_refSet.TryGetValue(key, out value)) {
_refSet[key] = numReferences;
_numValues += numReferences;
return;
}
throw new ArgumentException("Value '" + key + "' already in collection");
}
/// <summary> Removed a key to the set. Removes the key if the reference count is one.
/// Decreases the reference count by one if the reference count is more then one.
/// Return true if the reference count was one and the key thus removed, or false if key is stays in set.
/// </summary>
/// <param name="key">to add
/// </param>
/// <returns> true if the key is removed, false if it stays in the set
/// </returns>
/// <throws> IllegalStateException is a key is removed that wasn't added to the map </throws>
public virtual bool Remove(TK key)
{
if (ReferenceEquals(key, null)) {
return RemoveNull();
}
int value;
if (!_refSet.TryGetValue(key, out value)) {
return true; // ignore duplcate removals
}
if (value == 1) {
_refSet.Remove(key);
_numValues--;
return true;
}
value--;
_refSet[key] = value;
_numValues--;
return false;
}
/// <summary>
/// Remove a key from the set regardless of the number of references.
/// </summary>
/// <param name="key">to add</param>
/// <returns>
/// true if the key is removed, false if the key was not found
/// </returns>
/// <throws>IllegalStateException if a key is removed that wasn't added to the map</throws>
public bool RemoveAll(TK key)
{
return _refSet.Remove(key);
}
/// <summary> Returns an iterator over the entry set.</summary>
/// <returns> entry set iterator
/// </returns>
public IEnumerator<KeyValuePair<TK, int>> GetEnumerator()
{
if (_hasNullEntry) {
yield return new KeyValuePair<TK, int>(default(TK), _nullEntry);
}
foreach (KeyValuePair<TK, int> value in _refSet) {
yield return value;
}
}
/// <summary>
/// Gets the keys.
/// </summary>
/// <value>The keys.</value>
public ICollection<TK> Keys {
get { return _refSet.Keys; }
}
/// <summary> Returns the number of values in the collection.</summary>
/// <returns> size
/// </returns>
public virtual int Count {
get { return _numValues; }
}
/// <summary>
/// Clear out the collection.
/// </summary>
public virtual void Clear()
{
_refSet.Clear();
_numValues = 0;
}
public IDictionary<TK, int> RefSet {
get { return _refSet; }
}
public int NumValues {
get { return _numValues; }
|
[
" set { _numValues = value; }"
] | 743
|
lcc
|
csharp
| null |
90e9975c7f92d8ef21fcbe89fd1500b3a541124b7b4304fb
| 73
|
Your task is code completion.
///////////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2006-2019 Esper Team. All rights reserved. /
// http://esper.codehaus.org /
// ---------------------------------------------------------------------------------- /
// The software in this package is published under the terms of the GPL license /
// a copy of which has been included with this distribution in the license.txt file. /
///////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
namespace com.espertech.esper.common.@internal.collection
{
/// <summary> reference-counting set based on a HashMap implementation that stores keys and a reference counter for
/// each unique key value. Each time the same key is added, the reference counter increases.
/// Each time a key is removed, the reference counter decreases.
/// </summary>
public class RefCountedSet<TK>
{
private bool _hasNullEntry;
private int _nullEntry;
private readonly IDictionary<TK, int> _refSet;
private int _numValues;
/// <summary>
/// Constructor.
/// </summary>
public RefCountedSet()
{
_refSet = new Dictionary<TK, int>();
}
public RefCountedSet(
IDictionary<TK, int> refSet,
int numValues)
{
_refSet = refSet;
_numValues = numValues;
}
/// <summary>
/// Adds a key to the set, but the key is null. It behaves the same, but has its own
/// variables that need to be incremented.
/// </summary>
private bool AddNull()
{
if (!_hasNullEntry) {
_hasNullEntry = true;
_numValues++;
_nullEntry = 0;
return true;
}
_numValues++;
_nullEntry++;
return false;
}
/// <summary> Add a key to the set. Add with a reference count of one if the key didn't exist in the set.
/// Increase the reference count by one if the key already exists.
/// Return true if this is the first time the key was encountered, or false if key is already in set.
/// </summary>
/// <param name="key">to add
/// </param>
/// <returns> true if the key is not in the set already, false if the key is already in the set
/// </returns>
public virtual bool Add(TK key)
{
if (ReferenceEquals(key, null)) {
return AddNull();
}
int value;
if (!_refSet.TryGetValue(key, out value)) {
_refSet[key] = 1;
_numValues++;
return true;
}
value++;
_numValues++;
_refSet[key] = value;
return false;
}
/// <summary>
/// Removes the null key
/// </summary>
private bool RemoveNull()
{
if (_nullEntry == 1) {
_hasNullEntry = false;
_nullEntry--;
return true;
}
_nullEntry--;
_numValues--;
return false;
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="numReferences">The num references.</param>
public void Add(
TK key,
int numReferences)
{
int value;
if (!_refSet.TryGetValue(key, out value)) {
_refSet[key] = numReferences;
_numValues += numReferences;
return;
}
throw new ArgumentException("Value '" + key + "' already in collection");
}
/// <summary> Removed a key to the set. Removes the key if the reference count is one.
/// Decreases the reference count by one if the reference count is more then one.
/// Return true if the reference count was one and the key thus removed, or false if key is stays in set.
/// </summary>
/// <param name="key">to add
/// </param>
/// <returns> true if the key is removed, false if it stays in the set
/// </returns>
/// <throws> IllegalStateException is a key is removed that wasn't added to the map </throws>
public virtual bool Remove(TK key)
{
if (ReferenceEquals(key, null)) {
return RemoveNull();
}
int value;
if (!_refSet.TryGetValue(key, out value)) {
return true; // ignore duplcate removals
}
if (value == 1) {
_refSet.Remove(key);
_numValues--;
return true;
}
value--;
_refSet[key] = value;
_numValues--;
return false;
}
/// <summary>
/// Remove a key from the set regardless of the number of references.
/// </summary>
/// <param name="key">to add</param>
/// <returns>
/// true if the key is removed, false if the key was not found
/// </returns>
/// <throws>IllegalStateException if a key is removed that wasn't added to the map</throws>
public bool RemoveAll(TK key)
{
return _refSet.Remove(key);
}
/// <summary> Returns an iterator over the entry set.</summary>
/// <returns> entry set iterator
/// </returns>
public IEnumerator<KeyValuePair<TK, int>> GetEnumerator()
{
if (_hasNullEntry) {
yield return new KeyValuePair<TK, int>(default(TK), _nullEntry);
}
foreach (KeyValuePair<TK, int> value in _refSet) {
yield return value;
}
}
/// <summary>
/// Gets the keys.
/// </summary>
/// <value>The keys.</value>
public ICollection<TK> Keys {
get { return _refSet.Keys; }
}
/// <summary> Returns the number of values in the collection.</summary>
/// <returns> size
/// </returns>
public virtual int Count {
get { return _numValues; }
}
/// <summary>
/// Clear out the collection.
/// </summary>
public virtual void Clear()
{
_refSet.Clear();
_numValues = 0;
}
public IDictionary<TK, int> RefSet {
get { return _refSet; }
}
public int NumValues {
get { return _numValues; }
|
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 RefCountedSet class:
**Context:**
```csharp
public class RefCountedSet<TK>
{
// ...
public virtual bool Remove(TK key)
{
if (ReferenceEquals(key, null)) {
return RemoveNull();
}
int value;
if (!_refSet.TryGetValue(key, out value)) {
return true; // ignore duplicate removals
}
if (value == 1) {
_refSet.Remove(key);
_numValues--;
return true;
}
value--;
_refSet[key] = value;
_numValues--;
return false;
}
// ...
}
```
**Cheat sheet (for next line):**
- We are in the Remove method, which is handling the case where the key is not null and already exists in the set.
- The key is already in the set, and we need to decrement its reference count.
- The current reference count is stored in the `value` variable.
- We need to update the reference count in the `_refSet` dictionary.
- The `_numValues` variable should be updated accordingly.
- The method should return `false` to indicate that the key is still in the set.
**Relevant lines:**
- The `Remove` method header
- The `value` variable declaration
- The `_refSet` dictionary
- The `_numValues` variable
**Next line will likely be:**
```csharp
_refSet[key] = value;
_numValues--;
return false;
```
However, considering the context, the correct next line should be:
```csharp
_refSet[key] = value;
return false;
```
The `_numValues--;` line is already present in the code, so it should not be repeated.
|
|
Please complete the code given below.
namespace Tripodmaps
{
partial class DummySolutionExplorer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Solution \'WinFormsUI\' (2 projects)");
System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("System", 6, 6);
System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("System.Data", 6, 6);
System.Windows.Forms.TreeNode treeNode4 = new System.Windows.Forms.TreeNode("System.Drawing", 6, 6);
System.Windows.Forms.TreeNode treeNode5 = new System.Windows.Forms.TreeNode("System.Windows.Forms", 6, 6);
System.Windows.Forms.TreeNode treeNode6 = new System.Windows.Forms.TreeNode("System.XML", 6, 6);
System.Windows.Forms.TreeNode treeNode7 = new System.Windows.Forms.TreeNode("WeifenLuo.WinFormsUI.Docking", 6, 6);
System.Windows.Forms.TreeNode treeNode8 = new System.Windows.Forms.TreeNode("References", 4, 4, new System.Windows.Forms.TreeNode[] {
treeNode2,
treeNode3,
treeNode4,
treeNode5,
treeNode6,
treeNode7});
System.Windows.Forms.TreeNode treeNode9 = new System.Windows.Forms.TreeNode("BlankIcon.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode10 = new System.Windows.Forms.TreeNode("CSProject.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode11 = new System.Windows.Forms.TreeNode("OutputWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode12 = new System.Windows.Forms.TreeNode("References.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode13 = new System.Windows.Forms.TreeNode("SolutionExplorer.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode14 = new System.Windows.Forms.TreeNode("TaskListWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode15 = new System.Windows.Forms.TreeNode("ToolboxWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode16 = new System.Windows.Forms.TreeNode("Images", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode9,
treeNode10,
treeNode11,
treeNode12,
treeNode13,
treeNode14,
treeNode15});
System.Windows.Forms.TreeNode treeNode17 = new System.Windows.Forms.TreeNode("AboutDialog.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode18 = new System.Windows.Forms.TreeNode("App.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode19 = new System.Windows.Forms.TreeNode("AssemblyInfo.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode20 = new System.Windows.Forms.TreeNode("DummyOutputWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode21 = new System.Windows.Forms.TreeNode("DummyPropertyWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode22 = new System.Windows.Forms.TreeNode("DummySolutionExplorer.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode23 = new System.Windows.Forms.TreeNode("DummyTaskList.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode24 = new System.Windows.Forms.TreeNode("DummyToolbox.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode25 = new System.Windows.Forms.TreeNode("MianForm.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode26 = new System.Windows.Forms.TreeNode("Options.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode27 = new System.Windows.Forms.TreeNode("OptionsDialog.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode28 = new System.Windows.Forms.TreeNode("DockSample", 3, 3, new System.Windows.Forms.TreeNode[] {
treeNode8,
treeNode16,
treeNode17,
treeNode18,
treeNode19,
treeNode20,
treeNode21,
treeNode22,
treeNode23,
treeNode24,
treeNode25,
treeNode26,
treeNode27});
System.Windows.Forms.TreeNode treeNode29 = new System.Windows.Forms.TreeNode("System", 6, 6);
System.Windows.Forms.TreeNode treeNode30 = new System.Windows.Forms.TreeNode("System.Data", 6, 6);
System.Windows.Forms.TreeNode treeNode31 = new System.Windows.Forms.TreeNode("System.Design", 6, 6);
System.Windows.Forms.TreeNode treeNode32 = new System.Windows.Forms.TreeNode("System.Drawing", 6, 6);
System.Windows.Forms.TreeNode treeNode33 = new System.Windows.Forms.TreeNode("System.Windows.Forms", 6, 6);
System.Windows.Forms.TreeNode treeNode34 = new System.Windows.Forms.TreeNode("System.XML", 6, 6);
System.Windows.Forms.TreeNode treeNode35 = new System.Windows.Forms.TreeNode("References", 4, 4, new System.Windows.Forms.TreeNode[] {
treeNode29,
treeNode30,
treeNode31,
treeNode32,
treeNode33,
treeNode34});
System.Windows.Forms.TreeNode treeNode36 = new System.Windows.Forms.TreeNode("DockWindow.AutoHideNo.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode37 = new System.Windows.Forms.TreeNode("DockWindow.AutoHideYes.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode38 = new System.Windows.Forms.TreeNode("DockWindow.Close.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode39 = new System.Windows.Forms.TreeNode("DocumentWindow.Close.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode40 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollLeftDisabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode41 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollLeftEnabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode42 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollRightDisabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode43 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollRightEnabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode44 = new System.Windows.Forms.TreeNode("Resources", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode36,
treeNode37,
treeNode38,
treeNode39,
treeNode40,
treeNode41,
treeNode42,
treeNode43});
System.Windows.Forms.TreeNode treeNode45 = new System.Windows.Forms.TreeNode("Enums.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode46 = new System.Windows.Forms.TreeNode("Gdi32.cs", 7, 3);
System.Windows.Forms.TreeNode treeNode47 = new System.Windows.Forms.TreeNode("Structs.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode48 = new System.Windows.Forms.TreeNode("User32.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode49 = new System.Windows.Forms.TreeNode("Win32", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode45,
treeNode46,
treeNode47,
treeNode48});
System.Windows.Forms.TreeNode treeNode50 = new System.Windows.Forms.TreeNode("AssemblyInfo.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode51 = new System.Windows.Forms.TreeNode("Content.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode52 = new System.Windows.Forms.TreeNode("CotentCollection.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode53 = new System.Windows.Forms.TreeNode("CotentWindowCollection.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode54 = new System.Windows.Forms.TreeNode("DockHelper.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode55 = new System.Windows.Forms.TreeNode("DragHandler.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode56 = new System.Windows.Forms.TreeNode("DragHandlerBase.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode57 = new System.Windows.Forms.TreeNode("FloatWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode58 = new System.Windows.Forms.TreeNode("HiddenMdiChild.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode59 = new System.Windows.Forms.TreeNode("InertButton.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode60 = new System.Windows.Forms.TreeNode("Measures.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode61 = new System.Windows.Forms.TreeNode("NormalTabStripWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode62 = new System.Windows.Forms.TreeNode("ResourceHelper.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode63 = new System.Windows.Forms.TreeNode("WeifenLuo.WinFormsUI.Docking", 3, 3, new System.Windows.Forms.TreeNode[] {
treeNode35,
treeNode44,
treeNode49,
treeNode50,
treeNode51,
treeNode52,
treeNode53,
treeNode54,
treeNode55,
treeNode56,
treeNode57,
treeNode58,
treeNode59,
treeNode60,
treeNode61,
treeNode62});
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DummySolutionExplorer));
this.treeView1 = new System.Windows.Forms.TreeView();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.ImageIndex = 0;
this.treeView1.ImageList = this.imageList1;
this.treeView1.Indent = 19;
this.treeView1.Location = new System.Drawing.Point(0, 24);
this.treeView1.Name = "treeView1";
treeNode1.Name = "";
treeNode1.Text = "Solution \'WinFormsUI\' (2 projects)";
treeNode2.ImageIndex = 6;
treeNode2.Name = "";
treeNode2.SelectedImageIndex = 6;
treeNode2.Text = "System";
treeNode3.ImageIndex = 6;
treeNode3.Name = "";
treeNode3.SelectedImageIndex = 6;
treeNode3.Text = "System.Data";
treeNode4.ImageIndex = 6;
treeNode4.Name = "";
treeNode4.SelectedImageIndex = 6;
treeNode4.Text = "System.Drawing";
treeNode5.ImageIndex = 6;
treeNode5.Name = "";
treeNode5.SelectedImageIndex = 6;
treeNode5.Text = "System.Windows.Forms";
treeNode6.ImageIndex = 6;
treeNode6.Name = "";
treeNode6.SelectedImageIndex = 6;
treeNode6.Text = "System.XML";
treeNode7.ImageIndex = 6;
treeNode7.Name = "";
treeNode7.SelectedImageIndex = 6;
treeNode7.Text = "WeifenLuo.WinFormsUI.Docking";
treeNode8.ImageIndex = 4;
treeNode8.Name = "";
treeNode8.SelectedImageIndex = 4;
treeNode8.Text = "References";
treeNode9.ImageIndex = 5;
treeNode9.Name = "";
treeNode9.SelectedImageIndex = 5;
treeNode9.Text = "BlankIcon.ico";
treeNode10.ImageIndex = 5;
treeNode10.Name = "";
treeNode10.SelectedImageIndex = 5;
treeNode10.Text = "CSProject.ico";
treeNode11.ImageIndex = 5;
treeNode11.Name = "";
treeNode11.SelectedImageIndex = 5;
treeNode11.Text = "OutputWindow.ico";
treeNode12.ImageIndex = 5;
treeNode12.Name = "";
treeNode12.SelectedImageIndex = 5;
treeNode12.Text = "References.ico";
treeNode13.ImageIndex = 5;
treeNode13.Name = "";
treeNode13.SelectedImageIndex = 5;
treeNode13.Text = "SolutionExplorer.ico";
treeNode14.ImageIndex = 5;
treeNode14.Name = "";
treeNode14.SelectedImageIndex = 5;
treeNode14.Text = "TaskListWindow.ico";
treeNode15.ImageIndex = 5;
treeNode15.Name = "";
treeNode15.SelectedImageIndex = 5;
treeNode15.Text = "ToolboxWindow.ico";
treeNode16.ImageIndex = 2;
treeNode16.Name = "";
treeNode16.SelectedImageIndex = 1;
treeNode16.Text = "Images";
treeNode17.ImageIndex = 8;
treeNode17.Name = "";
treeNode17.SelectedImageIndex = 8;
treeNode17.Text = "AboutDialog.cs";
treeNode18.ImageIndex = 5;
treeNode18.Name = "";
treeNode18.SelectedImageIndex = 5;
treeNode18.Text = "App.ico";
treeNode19.ImageIndex = 7;
treeNode19.Name = "";
treeNode19.SelectedImageIndex = 7;
treeNode19.Text = "AssemblyInfo.cs";
treeNode20.ImageIndex = 8;
treeNode20.Name = "";
treeNode20.SelectedImageIndex = 8;
treeNode20.Text = "DummyOutputWindow.cs";
treeNode21.ImageIndex = 8;
treeNode21.Name = "";
treeNode21.SelectedImageIndex = 8;
treeNode21.Text = "DummyPropertyWindow.cs";
treeNode22.ImageIndex = 8;
treeNode22.Name = "";
treeNode22.SelectedImageIndex = 8;
treeNode22.Text = "DummySolutionExplorer.cs";
treeNode23.ImageIndex = 8;
treeNode23.Name = "";
treeNode23.SelectedImageIndex = 8;
treeNode23.Text = "DummyTaskList.cs";
treeNode24.ImageIndex = 8;
treeNode24.Name = "";
treeNode24.SelectedImageIndex = 8;
treeNode24.Text = "DummyToolbox.cs";
treeNode25.ImageIndex = 8;
treeNode25.Name = "";
treeNode25.SelectedImageIndex = 8;
treeNode25.Text = "MianForm.cs";
treeNode26.ImageIndex = 7;
treeNode26.Name = "";
treeNode26.SelectedImageIndex = 7;
treeNode26.Text = "Options.cs";
treeNode27.ImageIndex = 8;
treeNode27.Name = "";
treeNode27.SelectedImageIndex = 8;
treeNode27.Text = "OptionsDialog.cs";
treeNode28.ImageIndex = 3;
treeNode28.Name = "";
treeNode28.SelectedImageIndex = 3;
treeNode28.Text = "DockSample";
treeNode29.ImageIndex = 6;
treeNode29.Name = "";
treeNode29.SelectedImageIndex = 6;
treeNode29.Text = "System";
treeNode30.ImageIndex = 6;
treeNode30.Name = "";
treeNode30.SelectedImageIndex = 6;
treeNode30.Text = "System.Data";
treeNode31.ImageIndex = 6;
treeNode31.Name = "";
treeNode31.SelectedImageIndex = 6;
treeNode31.Text = "System.Design";
treeNode32.ImageIndex = 6;
treeNode32.Name = "";
treeNode32.SelectedImageIndex = 6;
treeNode32.Text = "System.Drawing";
treeNode33.ImageIndex = 6;
treeNode33.Name = "";
treeNode33.SelectedImageIndex = 6;
treeNode33.Text = "System.Windows.Forms";
treeNode34.ImageIndex = 6;
treeNode34.Name = "";
treeNode34.SelectedImageIndex = 6;
treeNode34.Text = "System.XML";
treeNode35.ImageIndex = 4;
treeNode35.Name = "";
treeNode35.SelectedImageIndex = 4;
treeNode35.Text = "References";
treeNode36.ImageIndex = 9;
treeNode36.Name = "";
treeNode36.SelectedImageIndex = 9;
treeNode36.Text = "DockWindow.AutoHideNo.bmp";
treeNode37.ImageIndex = 9;
treeNode37.Name = "";
treeNode37.SelectedImageIndex = 9;
treeNode37.Text = "DockWindow.AutoHideYes.bmp";
treeNode38.ImageIndex = 9;
treeNode38.Name = "";
treeNode38.SelectedImageIndex = 9;
treeNode38.Text = "DockWindow.Close.bmp";
treeNode39.ImageIndex = 9;
treeNode39.Name = "";
treeNode39.SelectedImageIndex = 9;
treeNode39.Text = "DocumentWindow.Close.bmp";
treeNode40.ImageIndex = 9;
treeNode40.Name = "";
treeNode40.SelectedImageIndex = 9;
treeNode40.Text = "DocumentWindow.ScrollLeftDisabled.bmp";
treeNode41.ImageIndex = 9;
treeNode41.Name = "";
treeNode41.SelectedImageIndex = 9;
treeNode41.Text = "DocumentWindow.ScrollLeftEnabled.bmp";
treeNode42.ImageIndex = 9;
treeNode42.Name = "";
treeNode42.SelectedImageIndex = 9;
treeNode42.Text = "DocumentWindow.ScrollRightDisabled.bmp";
treeNode43.ImageIndex = 9;
treeNode43.Name = "";
treeNode43.SelectedImageIndex = 9;
treeNode43.Text = "DocumentWindow.ScrollRightEnabled.bmp";
treeNode44.ImageIndex = 2;
treeNode44.Name = "";
treeNode44.SelectedImageIndex = 1;
treeNode44.Text = "Resources";
treeNode45.ImageIndex = 7;
treeNode45.Name = "";
treeNode45.SelectedImageIndex = 7;
treeNode45.Text = "Enums.cs";
treeNode46.ImageIndex = 7;
treeNode46.Name = "";
treeNode46.SelectedImageIndex = 3;
treeNode46.Text = "Gdi32.cs";
treeNode47.ImageIndex = 7;
treeNode47.Name = "";
treeNode47.SelectedImageIndex = 7;
treeNode47.Text = "Structs.cs";
treeNode48.ImageIndex = 7;
treeNode48.Name = "";
treeNode48.SelectedImageIndex = 7;
treeNode48.Text = "User32.cs";
treeNode49.ImageIndex = 2;
treeNode49.Name = "";
treeNode49.SelectedImageIndex = 1;
treeNode49.Text = "Win32";
treeNode50.ImageIndex = 7;
treeNode50.Name = "";
treeNode50.SelectedImageIndex = 7;
treeNode50.Text = "AssemblyInfo.cs";
treeNode51.ImageIndex = 8;
treeNode51.Name = "";
treeNode51.SelectedImageIndex = 8;
treeNode51.Text = "Content.cs";
treeNode52.ImageIndex = 7;
treeNode52.Name = "";
treeNode52.SelectedImageIndex = 7;
treeNode52.Text = "CotentCollection.cs";
treeNode53.ImageIndex = 7;
treeNode53.Name = "";
treeNode53.SelectedImageIndex = 7;
treeNode53.Text = "CotentWindowCollection.cs";
treeNode54.ImageIndex = 7;
treeNode54.Name = "";
treeNode54.SelectedImageIndex = 7;
treeNode54.Text = "DockHelper.cs";
treeNode55.ImageIndex = 7;
treeNode55.Name = "";
treeNode55.SelectedImageIndex = 7;
treeNode55.Text = "DragHandler.cs";
treeNode56.ImageIndex = 7;
treeNode56.Name = "";
treeNode56.SelectedImageIndex = 7;
treeNode56.Text = "DragHandlerBase.cs";
treeNode57.ImageIndex = 8;
treeNode57.Name = "";
treeNode57.SelectedImageIndex = 8;
treeNode57.Text = "FloatWindow.cs";
treeNode58.ImageIndex = 8;
treeNode58.Name = "";
treeNode58.SelectedImageIndex = 8;
treeNode58.Text = "HiddenMdiChild.cs";
treeNode59.ImageIndex = 7;
treeNode59.Name = "";
treeNode59.SelectedImageIndex = 7;
treeNode59.Text = "InertButton.cs";
treeNode60.ImageIndex = 7;
treeNode60.Name = "";
treeNode60.SelectedImageIndex = 7;
treeNode60.Text = "Measures.cs";
treeNode61.ImageIndex = 8;
treeNode61.Name = "";
treeNode61.SelectedImageIndex = 8;
treeNode61.Text = "NormalTabStripWindow.cs";
treeNode62.ImageIndex = 7;
treeNode62.Name = "";
treeNode62.SelectedImageIndex = 7;
treeNode62.Text = "ResourceHelper.cs";
treeNode63.ImageIndex = 3;
treeNode63.Name = "";
treeNode63.SelectedImageIndex = 3;
treeNode63.Text = "WeifenLuo.WinFormsUI.Docking";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode1,
treeNode28,
treeNode63});
this.treeView1.SelectedImageIndex = 0;
this.treeView1.Size = new System.Drawing.Size(245, 297);
this.treeView1.TabIndex = 0;
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "");
this.imageList1.Images.SetKeyName(1, "");
this.imageList1.Images.SetKeyName(2, "");
this.imageList1.Images.SetKeyName(3, "");
this.imageList1.Images.SetKeyName(4, "");
this.imageList1.Images.SetKeyName(5, "");
this.imageList1.Images.SetKeyName(6, "");
this.imageList1.Images.SetKeyName(7, "");
this.imageList1.Images.SetKeyName(8, "");
this.imageList1.Images.SetKeyName(9, "");
//
// DummySolutionExplorer
//
|
[
" this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);"
] | 1,467
|
lcc
|
csharp
| null |
e51a6d98c9314e0d0e73c15da39e443dc71aa90ae24eefe6
| 74
|
Your task is code completion.
namespace Tripodmaps
{
partial class DummySolutionExplorer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Solution \'WinFormsUI\' (2 projects)");
System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("System", 6, 6);
System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("System.Data", 6, 6);
System.Windows.Forms.TreeNode treeNode4 = new System.Windows.Forms.TreeNode("System.Drawing", 6, 6);
System.Windows.Forms.TreeNode treeNode5 = new System.Windows.Forms.TreeNode("System.Windows.Forms", 6, 6);
System.Windows.Forms.TreeNode treeNode6 = new System.Windows.Forms.TreeNode("System.XML", 6, 6);
System.Windows.Forms.TreeNode treeNode7 = new System.Windows.Forms.TreeNode("WeifenLuo.WinFormsUI.Docking", 6, 6);
System.Windows.Forms.TreeNode treeNode8 = new System.Windows.Forms.TreeNode("References", 4, 4, new System.Windows.Forms.TreeNode[] {
treeNode2,
treeNode3,
treeNode4,
treeNode5,
treeNode6,
treeNode7});
System.Windows.Forms.TreeNode treeNode9 = new System.Windows.Forms.TreeNode("BlankIcon.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode10 = new System.Windows.Forms.TreeNode("CSProject.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode11 = new System.Windows.Forms.TreeNode("OutputWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode12 = new System.Windows.Forms.TreeNode("References.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode13 = new System.Windows.Forms.TreeNode("SolutionExplorer.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode14 = new System.Windows.Forms.TreeNode("TaskListWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode15 = new System.Windows.Forms.TreeNode("ToolboxWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode16 = new System.Windows.Forms.TreeNode("Images", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode9,
treeNode10,
treeNode11,
treeNode12,
treeNode13,
treeNode14,
treeNode15});
System.Windows.Forms.TreeNode treeNode17 = new System.Windows.Forms.TreeNode("AboutDialog.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode18 = new System.Windows.Forms.TreeNode("App.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode19 = new System.Windows.Forms.TreeNode("AssemblyInfo.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode20 = new System.Windows.Forms.TreeNode("DummyOutputWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode21 = new System.Windows.Forms.TreeNode("DummyPropertyWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode22 = new System.Windows.Forms.TreeNode("DummySolutionExplorer.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode23 = new System.Windows.Forms.TreeNode("DummyTaskList.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode24 = new System.Windows.Forms.TreeNode("DummyToolbox.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode25 = new System.Windows.Forms.TreeNode("MianForm.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode26 = new System.Windows.Forms.TreeNode("Options.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode27 = new System.Windows.Forms.TreeNode("OptionsDialog.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode28 = new System.Windows.Forms.TreeNode("DockSample", 3, 3, new System.Windows.Forms.TreeNode[] {
treeNode8,
treeNode16,
treeNode17,
treeNode18,
treeNode19,
treeNode20,
treeNode21,
treeNode22,
treeNode23,
treeNode24,
treeNode25,
treeNode26,
treeNode27});
System.Windows.Forms.TreeNode treeNode29 = new System.Windows.Forms.TreeNode("System", 6, 6);
System.Windows.Forms.TreeNode treeNode30 = new System.Windows.Forms.TreeNode("System.Data", 6, 6);
System.Windows.Forms.TreeNode treeNode31 = new System.Windows.Forms.TreeNode("System.Design", 6, 6);
System.Windows.Forms.TreeNode treeNode32 = new System.Windows.Forms.TreeNode("System.Drawing", 6, 6);
System.Windows.Forms.TreeNode treeNode33 = new System.Windows.Forms.TreeNode("System.Windows.Forms", 6, 6);
System.Windows.Forms.TreeNode treeNode34 = new System.Windows.Forms.TreeNode("System.XML", 6, 6);
System.Windows.Forms.TreeNode treeNode35 = new System.Windows.Forms.TreeNode("References", 4, 4, new System.Windows.Forms.TreeNode[] {
treeNode29,
treeNode30,
treeNode31,
treeNode32,
treeNode33,
treeNode34});
System.Windows.Forms.TreeNode treeNode36 = new System.Windows.Forms.TreeNode("DockWindow.AutoHideNo.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode37 = new System.Windows.Forms.TreeNode("DockWindow.AutoHideYes.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode38 = new System.Windows.Forms.TreeNode("DockWindow.Close.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode39 = new System.Windows.Forms.TreeNode("DocumentWindow.Close.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode40 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollLeftDisabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode41 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollLeftEnabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode42 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollRightDisabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode43 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollRightEnabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode44 = new System.Windows.Forms.TreeNode("Resources", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode36,
treeNode37,
treeNode38,
treeNode39,
treeNode40,
treeNode41,
treeNode42,
treeNode43});
System.Windows.Forms.TreeNode treeNode45 = new System.Windows.Forms.TreeNode("Enums.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode46 = new System.Windows.Forms.TreeNode("Gdi32.cs", 7, 3);
System.Windows.Forms.TreeNode treeNode47 = new System.Windows.Forms.TreeNode("Structs.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode48 = new System.Windows.Forms.TreeNode("User32.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode49 = new System.Windows.Forms.TreeNode("Win32", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode45,
treeNode46,
treeNode47,
treeNode48});
System.Windows.Forms.TreeNode treeNode50 = new System.Windows.Forms.TreeNode("AssemblyInfo.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode51 = new System.Windows.Forms.TreeNode("Content.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode52 = new System.Windows.Forms.TreeNode("CotentCollection.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode53 = new System.Windows.Forms.TreeNode("CotentWindowCollection.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode54 = new System.Windows.Forms.TreeNode("DockHelper.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode55 = new System.Windows.Forms.TreeNode("DragHandler.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode56 = new System.Windows.Forms.TreeNode("DragHandlerBase.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode57 = new System.Windows.Forms.TreeNode("FloatWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode58 = new System.Windows.Forms.TreeNode("HiddenMdiChild.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode59 = new System.Windows.Forms.TreeNode("InertButton.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode60 = new System.Windows.Forms.TreeNode("Measures.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode61 = new System.Windows.Forms.TreeNode("NormalTabStripWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode62 = new System.Windows.Forms.TreeNode("ResourceHelper.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode63 = new System.Windows.Forms.TreeNode("WeifenLuo.WinFormsUI.Docking", 3, 3, new System.Windows.Forms.TreeNode[] {
treeNode35,
treeNode44,
treeNode49,
treeNode50,
treeNode51,
treeNode52,
treeNode53,
treeNode54,
treeNode55,
treeNode56,
treeNode57,
treeNode58,
treeNode59,
treeNode60,
treeNode61,
treeNode62});
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DummySolutionExplorer));
this.treeView1 = new System.Windows.Forms.TreeView();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.ImageIndex = 0;
this.treeView1.ImageList = this.imageList1;
this.treeView1.Indent = 19;
this.treeView1.Location = new System.Drawing.Point(0, 24);
this.treeView1.Name = "treeView1";
treeNode1.Name = "";
treeNode1.Text = "Solution \'WinFormsUI\' (2 projects)";
treeNode2.ImageIndex = 6;
treeNode2.Name = "";
treeNode2.SelectedImageIndex = 6;
treeNode2.Text = "System";
treeNode3.ImageIndex = 6;
treeNode3.Name = "";
treeNode3.SelectedImageIndex = 6;
treeNode3.Text = "System.Data";
treeNode4.ImageIndex = 6;
treeNode4.Name = "";
treeNode4.SelectedImageIndex = 6;
treeNode4.Text = "System.Drawing";
treeNode5.ImageIndex = 6;
treeNode5.Name = "";
treeNode5.SelectedImageIndex = 6;
treeNode5.Text = "System.Windows.Forms";
treeNode6.ImageIndex = 6;
treeNode6.Name = "";
treeNode6.SelectedImageIndex = 6;
treeNode6.Text = "System.XML";
treeNode7.ImageIndex = 6;
treeNode7.Name = "";
treeNode7.SelectedImageIndex = 6;
treeNode7.Text = "WeifenLuo.WinFormsUI.Docking";
treeNode8.ImageIndex = 4;
treeNode8.Name = "";
treeNode8.SelectedImageIndex = 4;
treeNode8.Text = "References";
treeNode9.ImageIndex = 5;
treeNode9.Name = "";
treeNode9.SelectedImageIndex = 5;
treeNode9.Text = "BlankIcon.ico";
treeNode10.ImageIndex = 5;
treeNode10.Name = "";
treeNode10.SelectedImageIndex = 5;
treeNode10.Text = "CSProject.ico";
treeNode11.ImageIndex = 5;
treeNode11.Name = "";
treeNode11.SelectedImageIndex = 5;
treeNode11.Text = "OutputWindow.ico";
treeNode12.ImageIndex = 5;
treeNode12.Name = "";
treeNode12.SelectedImageIndex = 5;
treeNode12.Text = "References.ico";
treeNode13.ImageIndex = 5;
treeNode13.Name = "";
treeNode13.SelectedImageIndex = 5;
treeNode13.Text = "SolutionExplorer.ico";
treeNode14.ImageIndex = 5;
treeNode14.Name = "";
treeNode14.SelectedImageIndex = 5;
treeNode14.Text = "TaskListWindow.ico";
treeNode15.ImageIndex = 5;
treeNode15.Name = "";
treeNode15.SelectedImageIndex = 5;
treeNode15.Text = "ToolboxWindow.ico";
treeNode16.ImageIndex = 2;
treeNode16.Name = "";
treeNode16.SelectedImageIndex = 1;
treeNode16.Text = "Images";
treeNode17.ImageIndex = 8;
treeNode17.Name = "";
treeNode17.SelectedImageIndex = 8;
treeNode17.Text = "AboutDialog.cs";
treeNode18.ImageIndex = 5;
treeNode18.Name = "";
treeNode18.SelectedImageIndex = 5;
treeNode18.Text = "App.ico";
treeNode19.ImageIndex = 7;
treeNode19.Name = "";
treeNode19.SelectedImageIndex = 7;
treeNode19.Text = "AssemblyInfo.cs";
treeNode20.ImageIndex = 8;
treeNode20.Name = "";
treeNode20.SelectedImageIndex = 8;
treeNode20.Text = "DummyOutputWindow.cs";
treeNode21.ImageIndex = 8;
treeNode21.Name = "";
treeNode21.SelectedImageIndex = 8;
treeNode21.Text = "DummyPropertyWindow.cs";
treeNode22.ImageIndex = 8;
treeNode22.Name = "";
treeNode22.SelectedImageIndex = 8;
treeNode22.Text = "DummySolutionExplorer.cs";
treeNode23.ImageIndex = 8;
treeNode23.Name = "";
treeNode23.SelectedImageIndex = 8;
treeNode23.Text = "DummyTaskList.cs";
treeNode24.ImageIndex = 8;
treeNode24.Name = "";
treeNode24.SelectedImageIndex = 8;
treeNode24.Text = "DummyToolbox.cs";
treeNode25.ImageIndex = 8;
treeNode25.Name = "";
treeNode25.SelectedImageIndex = 8;
treeNode25.Text = "MianForm.cs";
treeNode26.ImageIndex = 7;
treeNode26.Name = "";
treeNode26.SelectedImageIndex = 7;
treeNode26.Text = "Options.cs";
treeNode27.ImageIndex = 8;
treeNode27.Name = "";
treeNode27.SelectedImageIndex = 8;
treeNode27.Text = "OptionsDialog.cs";
treeNode28.ImageIndex = 3;
treeNode28.Name = "";
treeNode28.SelectedImageIndex = 3;
treeNode28.Text = "DockSample";
treeNode29.ImageIndex = 6;
treeNode29.Name = "";
treeNode29.SelectedImageIndex = 6;
treeNode29.Text = "System";
treeNode30.ImageIndex = 6;
treeNode30.Name = "";
treeNode30.SelectedImageIndex = 6;
treeNode30.Text = "System.Data";
treeNode31.ImageIndex = 6;
treeNode31.Name = "";
treeNode31.SelectedImageIndex = 6;
treeNode31.Text = "System.Design";
treeNode32.ImageIndex = 6;
treeNode32.Name = "";
treeNode32.SelectedImageIndex = 6;
treeNode32.Text = "System.Drawing";
treeNode33.ImageIndex = 6;
treeNode33.Name = "";
treeNode33.SelectedImageIndex = 6;
treeNode33.Text = "System.Windows.Forms";
treeNode34.ImageIndex = 6;
treeNode34.Name = "";
treeNode34.SelectedImageIndex = 6;
treeNode34.Text = "System.XML";
treeNode35.ImageIndex = 4;
treeNode35.Name = "";
treeNode35.SelectedImageIndex = 4;
treeNode35.Text = "References";
treeNode36.ImageIndex = 9;
treeNode36.Name = "";
treeNode36.SelectedImageIndex = 9;
treeNode36.Text = "DockWindow.AutoHideNo.bmp";
treeNode37.ImageIndex = 9;
treeNode37.Name = "";
treeNode37.SelectedImageIndex = 9;
treeNode37.Text = "DockWindow.AutoHideYes.bmp";
treeNode38.ImageIndex = 9;
treeNode38.Name = "";
treeNode38.SelectedImageIndex = 9;
treeNode38.Text = "DockWindow.Close.bmp";
treeNode39.ImageIndex = 9;
treeNode39.Name = "";
treeNode39.SelectedImageIndex = 9;
treeNode39.Text = "DocumentWindow.Close.bmp";
treeNode40.ImageIndex = 9;
treeNode40.Name = "";
treeNode40.SelectedImageIndex = 9;
treeNode40.Text = "DocumentWindow.ScrollLeftDisabled.bmp";
treeNode41.ImageIndex = 9;
treeNode41.Name = "";
treeNode41.SelectedImageIndex = 9;
treeNode41.Text = "DocumentWindow.ScrollLeftEnabled.bmp";
treeNode42.ImageIndex = 9;
treeNode42.Name = "";
treeNode42.SelectedImageIndex = 9;
treeNode42.Text = "DocumentWindow.ScrollRightDisabled.bmp";
treeNode43.ImageIndex = 9;
treeNode43.Name = "";
treeNode43.SelectedImageIndex = 9;
treeNode43.Text = "DocumentWindow.ScrollRightEnabled.bmp";
treeNode44.ImageIndex = 2;
treeNode44.Name = "";
treeNode44.SelectedImageIndex = 1;
treeNode44.Text = "Resources";
treeNode45.ImageIndex = 7;
treeNode45.Name = "";
treeNode45.SelectedImageIndex = 7;
treeNode45.Text = "Enums.cs";
treeNode46.ImageIndex = 7;
treeNode46.Name = "";
treeNode46.SelectedImageIndex = 3;
treeNode46.Text = "Gdi32.cs";
treeNode47.ImageIndex = 7;
treeNode47.Name = "";
treeNode47.SelectedImageIndex = 7;
treeNode47.Text = "Structs.cs";
treeNode48.ImageIndex = 7;
treeNode48.Name = "";
treeNode48.SelectedImageIndex = 7;
treeNode48.Text = "User32.cs";
treeNode49.ImageIndex = 2;
treeNode49.Name = "";
treeNode49.SelectedImageIndex = 1;
treeNode49.Text = "Win32";
treeNode50.ImageIndex = 7;
treeNode50.Name = "";
treeNode50.SelectedImageIndex = 7;
treeNode50.Text = "AssemblyInfo.cs";
treeNode51.ImageIndex = 8;
treeNode51.Name = "";
treeNode51.SelectedImageIndex = 8;
treeNode51.Text = "Content.cs";
treeNode52.ImageIndex = 7;
treeNode52.Name = "";
treeNode52.SelectedImageIndex = 7;
treeNode52.Text = "CotentCollection.cs";
treeNode53.ImageIndex = 7;
treeNode53.Name = "";
treeNode53.SelectedImageIndex = 7;
treeNode53.Text = "CotentWindowCollection.cs";
treeNode54.ImageIndex = 7;
treeNode54.Name = "";
treeNode54.SelectedImageIndex = 7;
treeNode54.Text = "DockHelper.cs";
treeNode55.ImageIndex = 7;
treeNode55.Name = "";
treeNode55.SelectedImageIndex = 7;
treeNode55.Text = "DragHandler.cs";
treeNode56.ImageIndex = 7;
treeNode56.Name = "";
treeNode56.SelectedImageIndex = 7;
treeNode56.Text = "DragHandlerBase.cs";
treeNode57.ImageIndex = 8;
treeNode57.Name = "";
treeNode57.SelectedImageIndex = 8;
treeNode57.Text = "FloatWindow.cs";
treeNode58.ImageIndex = 8;
treeNode58.Name = "";
treeNode58.SelectedImageIndex = 8;
treeNode58.Text = "HiddenMdiChild.cs";
treeNode59.ImageIndex = 7;
treeNode59.Name = "";
treeNode59.SelectedImageIndex = 7;
treeNode59.Text = "InertButton.cs";
treeNode60.ImageIndex = 7;
treeNode60.Name = "";
treeNode60.SelectedImageIndex = 7;
treeNode60.Text = "Measures.cs";
treeNode61.ImageIndex = 8;
treeNode61.Name = "";
treeNode61.SelectedImageIndex = 8;
treeNode61.Text = "NormalTabStripWindow.cs";
treeNode62.ImageIndex = 7;
treeNode62.Name = "";
treeNode62.SelectedImageIndex = 7;
treeNode62.Text = "ResourceHelper.cs";
treeNode63.ImageIndex = 3;
treeNode63.Name = "";
treeNode63.SelectedImageIndex = 3;
treeNode63.Text = "WeifenLuo.WinFormsUI.Docking";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode1,
treeNode28,
treeNode63});
this.treeView1.SelectedImageIndex = 0;
this.treeView1.Size = new System.Drawing.Size(245, 297);
this.treeView1.TabIndex = 0;
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "");
this.imageList1.Images.SetKeyName(1, "");
this.imageList1.Images.SetKeyName(2, "");
this.imageList1.Images.SetKeyName(3, "");
this.imageList1.Images.SetKeyName(4, "");
this.imageList1.Images.SetKeyName(5, "");
this.imageList1.Images.SetKeyName(6, "");
this.imageList1.Images.SetKeyName(7, "");
this.imageList1.Images.SetKeyName(8, "");
this.imageList1.Images.SetKeyName(9, "");
//
// DummySolutionExplorer
//
|
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 Code Completion Task:
**Context:** The provided code is a Windows Forms application with a TreeView control named `treeView1` and an ImageList control named `imageList1`. The code is generated by the Visual Studio designer.
**Relevant Variables and Methods:**
1. `treeView1`: The TreeView control that displays the solution explorer.
2. `imageList1`: The ImageList control that stores the images for the TreeView.
3. `components`: The ComponentCollection that stores the components of the form.
**Relevant Lines:**
1. `this.treeView1 = new System.Windows.Forms.TreeView();`
2. `this.imageList1 = new System.Windows.Forms.ImageList(this.components);`
3. `treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] { ... });`
**Task:** The task is to complete the code for the `DummySolutionExplorer` class.
**Cheat Sheet:**
- We are in the `DummySolutionExplorer` class, which is a Windows Forms application.
- The class has a TreeView control named `treeView1` and an ImageList control named `imageList1`.
- The `treeView1` control has a `Nodes` collection that stores the nodes of the TreeView.
- The `imageList1` control stores the images for the TreeView.
- The `components` variable is a ComponentCollection that stores the components of the form.
**Next Line:**
Based on the context, the next line of code is likely to be related to the initialization of the `imageList1` control. The `imageList1` control is used to display images in the TreeView, and the images are stored in the `imageList1` control.
**Possible Next Line:**
```csharp
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
```
This line sets the size of the images in the `imageList1` control to 16x16 pixels, which is a common size for icons in Windows Forms applications.
Please let me know if you would like me to proceed with the next step or if you have any further questions.
|
|
Please complete the code given below.
"""Base class for platform implementations
"""
import ctypes
from OpenGL.platform import ctypesloader
import sys
import OpenGL as top_level_module
from OpenGL import logs
class _CheckContext( object ):
def __init__( self, func, ccisvalid ):
self.func = func
self.ccisvalid = ccisvalid
def __setattr__( self, key, value ):
if key not in ('func','ccisvalid'):
return setattr( self.func, key, value )
else:
self.__dict__[key] = value
def __getattr__( self, key ):
if key != 'func':
return getattr(self.func, key )
raise AttributeError( key )
def __call__( self, *args, **named ):
if not self.ccisvalid():
from OpenGL import error
raise error.NoContext( self.func, args, named )
return self.func( *args, **named )
class BasePlatform( object ):
"""Base class for per-platform implementations
Attributes of note:
EXPORTED_NAMES -- set of names exported via the platform
module's namespace...
GL, GLU, GLUT, GLE, OpenGL -- ctypes libraries
DEFAULT_FUNCTION_TYPE -- used as the default function
type for functions unless overridden on a per-DLL
basis with a "FunctionType" member
GLUT_GUARD_CALLBACKS -- if True, the GLUT wrappers
will provide guarding wrappers to prevent GLUT
errors with uninitialised GLUT.
EXTENSIONS_USE_BASE_FUNCTIONS -- if True, uses regular
dll attribute-based lookup to retrieve extension
function pointers.
"""
EXPORTED_NAMES = [
'GetCurrentContext','CurrentContextIsValid','safeGetError',
'createBaseFunction', 'createExtensionFunction', 'copyBaseFunction',
'GL','GLU','GLUT','GLE','OpenGL',
'getGLUTFontPointer',
'GLUT_GUARD_CALLBACKS',
]
DEFAULT_FUNCTION_TYPE = None
GLUT_GUARD_CALLBACKS = False
EXTENSIONS_USE_BASE_FUNCTIONS = False
def install( self, namespace ):
"""Install this platform instance into the platform module"""
for name in self.EXPORTED_NAMES:
namespace[ name ] = getattr(self,name)
namespace['PLATFORM'] = self
return self
def functionTypeFor( self, dll ):
"""Given a DLL, determine appropriate function type..."""
if hasattr( dll, 'FunctionType' ):
return dll.FunctionType
else:
return self.DEFAULT_FUNCTION_TYPE
def errorChecking( self, func, dll ):
"""Add error checking to the function if appropriate"""
from OpenGL import error
if top_level_module.ERROR_CHECKING:
if dll not in (self.GLUT,):
#GLUT spec says error-checking is basically undefined...
# there *may* be GL errors on GLUT calls that e.g. render
# geometry, but that's all basically "maybe" stuff...
func.errcheck = error.glCheckError
return func
def wrapContextCheck( self, func, dll ):
"""Wrap function with context-checking if appropriate"""
if top_level_module.CONTEXT_CHECKING and dll is not self.GLUT:
return _CheckContext( func, self.CurrentContextIsValid )
return func
def wrapLogging( self, func ):
"""Wrap function with logging operations if appropriate"""
return logs.logOnFail( func, logs.getLog( 'OpenGL.errors' ))
def finalArgType( self, typ ):
"""Retrieve a final type for arg-type"""
if typ == ctypes.POINTER( None ) and not getattr( typ, 'final',False):
from OpenGL.arrays import ArrayDatatype
return ArrayDatatype
else:
return typ
def constructFunction(
self,
functionName, dll,
resultType=ctypes.c_int, argTypes=(),
doc = None, argNames = (),
extension = None,
deprecated = False,
):
"""Core operation to create a new base ctypes function
raises AttributeError if can't find the procedure...
"""
if extension and not self.checkExtension( extension ):
raise AttributeError( """Extension not available""" )
argTypes = [ self.finalArgType( t ) for t in argTypes ]
if extension and not self.EXTENSIONS_USE_BASE_FUNCTIONS:
# what about the VERSION values???
if self.checkExtension( extension ):
pointer = self.getExtensionProcedure( functionName )
if pointer:
func = self.functionTypeFor( dll )(
resultType,
*argTypes
)(
pointer
)
else:
raise AttributeError( """Extension %r available, but no pointer for function %r"""%(extension,functionName))
else:
raise AttributeError( """No extension %r"""%(extension,))
else:
func = ctypesloader.buildFunction(
self.functionTypeFor( dll )(
resultType,
*argTypes
),
functionName,
dll,
)
func.__doc__ = doc
func.argNames = list(argNames or ())
func.__name__ = functionName
func.DLL = dll
func.extension = extension
func.deprecated = deprecated
func = self.wrapLogging(
self.wrapContextCheck(
self.errorChecking( func, dll ),
dll,
)
)
return func
def createBaseFunction(
self,
functionName, dll,
resultType=ctypes.c_int, argTypes=(),
doc = None, argNames = (),
extension = None,
deprecated = False,
):
"""Create a base function for given name
Normally you can just use the dll.name hook to get the object,
but we want to be able to create different bindings for the
same function, so we do the work manually here to produce a
base function from a DLL.
"""
from OpenGL import wrapper
try:
if top_level_module.FORWARD_COMPATIBLE_ONLY and dll is self.GL:
if deprecated:
return self.nullFunction(
functionName, dll=dll,
resultType=resultType,
argTypes=argTypes,
doc = doc, argNames = argNames,
extension = extension,
deprecated = deprecated,
)
return self.constructFunction(
functionName, dll,
resultType=resultType, argTypes=argTypes,
doc = doc, argNames = argNames,
extension = extension,
)
except AttributeError, err:
return self.nullFunction(
functionName, dll=dll,
resultType=resultType,
argTypes=argTypes,
doc = doc, argNames = argNames,
extension = extension,
)
def checkExtension( self, name ):
"""Check whether the given extension is supported by current context"""
if not name:
return True
context = self.GetCurrentContext()
if context:
from OpenGL import contextdata
from OpenGL.raw.GL import GL_EXTENSIONS
set = contextdata.getValue( GL_EXTENSIONS, context=context )
if set is None:
set = {}
contextdata.setValue(
GL_EXTENSIONS, set, context=context, weak=False
)
current = set.get( name )
if current is None:
from OpenGL import extensions
result = extensions.hasGLExtension( name )
set[name] = result
return result
return current
else:
return False
createExtensionFunction = createBaseFunction
def copyBaseFunction( self, original ):
"""Create a new base function based on an already-created function
This is normally used to provide type-specific convenience versions of
a definition created by the automated generator.
"""
from OpenGL import wrapper, error
if isinstance( original, _NullFunctionPointer ):
return self.nullFunction(
original.__name__,
original.DLL,
resultType = original.restype,
argTypes= original.argtypes,
doc = original.__doc__,
argNames = original.argNames,
extension = original.extension,
deprecated = original.deprecated,
)
|
[
" elif hasattr( original, 'originalFunction' ):"
] | 831
|
lcc
|
python
| null |
e23602db74e35727f7f766eb0f92a05cdb9599280a144a07
| 75
|
Your task is code completion.
"""Base class for platform implementations
"""
import ctypes
from OpenGL.platform import ctypesloader
import sys
import OpenGL as top_level_module
from OpenGL import logs
class _CheckContext( object ):
def __init__( self, func, ccisvalid ):
self.func = func
self.ccisvalid = ccisvalid
def __setattr__( self, key, value ):
if key not in ('func','ccisvalid'):
return setattr( self.func, key, value )
else:
self.__dict__[key] = value
def __getattr__( self, key ):
if key != 'func':
return getattr(self.func, key )
raise AttributeError( key )
def __call__( self, *args, **named ):
if not self.ccisvalid():
from OpenGL import error
raise error.NoContext( self.func, args, named )
return self.func( *args, **named )
class BasePlatform( object ):
"""Base class for per-platform implementations
Attributes of note:
EXPORTED_NAMES -- set of names exported via the platform
module's namespace...
GL, GLU, GLUT, GLE, OpenGL -- ctypes libraries
DEFAULT_FUNCTION_TYPE -- used as the default function
type for functions unless overridden on a per-DLL
basis with a "FunctionType" member
GLUT_GUARD_CALLBACKS -- if True, the GLUT wrappers
will provide guarding wrappers to prevent GLUT
errors with uninitialised GLUT.
EXTENSIONS_USE_BASE_FUNCTIONS -- if True, uses regular
dll attribute-based lookup to retrieve extension
function pointers.
"""
EXPORTED_NAMES = [
'GetCurrentContext','CurrentContextIsValid','safeGetError',
'createBaseFunction', 'createExtensionFunction', 'copyBaseFunction',
'GL','GLU','GLUT','GLE','OpenGL',
'getGLUTFontPointer',
'GLUT_GUARD_CALLBACKS',
]
DEFAULT_FUNCTION_TYPE = None
GLUT_GUARD_CALLBACKS = False
EXTENSIONS_USE_BASE_FUNCTIONS = False
def install( self, namespace ):
"""Install this platform instance into the platform module"""
for name in self.EXPORTED_NAMES:
namespace[ name ] = getattr(self,name)
namespace['PLATFORM'] = self
return self
def functionTypeFor( self, dll ):
"""Given a DLL, determine appropriate function type..."""
if hasattr( dll, 'FunctionType' ):
return dll.FunctionType
else:
return self.DEFAULT_FUNCTION_TYPE
def errorChecking( self, func, dll ):
"""Add error checking to the function if appropriate"""
from OpenGL import error
if top_level_module.ERROR_CHECKING:
if dll not in (self.GLUT,):
#GLUT spec says error-checking is basically undefined...
# there *may* be GL errors on GLUT calls that e.g. render
# geometry, but that's all basically "maybe" stuff...
func.errcheck = error.glCheckError
return func
def wrapContextCheck( self, func, dll ):
"""Wrap function with context-checking if appropriate"""
if top_level_module.CONTEXT_CHECKING and dll is not self.GLUT:
return _CheckContext( func, self.CurrentContextIsValid )
return func
def wrapLogging( self, func ):
"""Wrap function with logging operations if appropriate"""
return logs.logOnFail( func, logs.getLog( 'OpenGL.errors' ))
def finalArgType( self, typ ):
"""Retrieve a final type for arg-type"""
if typ == ctypes.POINTER( None ) and not getattr( typ, 'final',False):
from OpenGL.arrays import ArrayDatatype
return ArrayDatatype
else:
return typ
def constructFunction(
self,
functionName, dll,
resultType=ctypes.c_int, argTypes=(),
doc = None, argNames = (),
extension = None,
deprecated = False,
):
"""Core operation to create a new base ctypes function
raises AttributeError if can't find the procedure...
"""
if extension and not self.checkExtension( extension ):
raise AttributeError( """Extension not available""" )
argTypes = [ self.finalArgType( t ) for t in argTypes ]
if extension and not self.EXTENSIONS_USE_BASE_FUNCTIONS:
# what about the VERSION values???
if self.checkExtension( extension ):
pointer = self.getExtensionProcedure( functionName )
if pointer:
func = self.functionTypeFor( dll )(
resultType,
*argTypes
)(
pointer
)
else:
raise AttributeError( """Extension %r available, but no pointer for function %r"""%(extension,functionName))
else:
raise AttributeError( """No extension %r"""%(extension,))
else:
func = ctypesloader.buildFunction(
self.functionTypeFor( dll )(
resultType,
*argTypes
),
functionName,
dll,
)
func.__doc__ = doc
func.argNames = list(argNames or ())
func.__name__ = functionName
func.DLL = dll
func.extension = extension
func.deprecated = deprecated
func = self.wrapLogging(
self.wrapContextCheck(
self.errorChecking( func, dll ),
dll,
)
)
return func
def createBaseFunction(
self,
functionName, dll,
resultType=ctypes.c_int, argTypes=(),
doc = None, argNames = (),
extension = None,
deprecated = False,
):
"""Create a base function for given name
Normally you can just use the dll.name hook to get the object,
but we want to be able to create different bindings for the
same function, so we do the work manually here to produce a
base function from a DLL.
"""
from OpenGL import wrapper
try:
if top_level_module.FORWARD_COMPATIBLE_ONLY and dll is self.GL:
if deprecated:
return self.nullFunction(
functionName, dll=dll,
resultType=resultType,
argTypes=argTypes,
doc = doc, argNames = argNames,
extension = extension,
deprecated = deprecated,
)
return self.constructFunction(
functionName, dll,
resultType=resultType, argTypes=argTypes,
doc = doc, argNames = argNames,
extension = extension,
)
except AttributeError, err:
return self.nullFunction(
functionName, dll=dll,
resultType=resultType,
argTypes=argTypes,
doc = doc, argNames = argNames,
extension = extension,
)
def checkExtension( self, name ):
"""Check whether the given extension is supported by current context"""
if not name:
return True
context = self.GetCurrentContext()
if context:
from OpenGL import contextdata
from OpenGL.raw.GL import GL_EXTENSIONS
set = contextdata.getValue( GL_EXTENSIONS, context=context )
if set is None:
set = {}
contextdata.setValue(
GL_EXTENSIONS, set, context=context, weak=False
)
current = set.get( name )
if current is None:
from OpenGL import extensions
result = extensions.hasGLExtension( name )
set[name] = result
return result
return current
else:
return False
createExtensionFunction = createBaseFunction
def copyBaseFunction( self, original ):
"""Create a new base function based on an already-created function
This is normally used to provide type-specific convenience versions of
a definition created by the automated generator.
"""
from OpenGL import wrapper, error
if isinstance( original, _NullFunctionPointer ):
return self.nullFunction(
original.__name__,
original.DLL,
resultType = original.restype,
argTypes= original.argtypes,
doc = original.__doc__,
argNames = original.argNames,
extension = original.extension,
deprecated = original.deprecated,
)
|
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:
**Class and Methods**
- The code is in the `BasePlatform` class.
- The class has several methods, including `install`, `functionTypeFor`, `errorChecking`, `wrapContextCheck`, `wrapLogging`, `finalArgType`, `constructFunction`, `createBaseFunction`, `checkExtension`, and `copyBaseFunction`.
**Relevant Variables and Attributes**
- `self`: the instance of the `BasePlatform` class.
- `dll`: a ctypes library object.
- `functionName`: the name of the function to be created.
- `resultType`: the return type of the function (default: `ctypes.c_int`).
- `argTypes`: a tuple of argument types (default: `()`).
- `doc`: the documentation string for the function (default: `None`).
- `argNames`: a tuple of argument names (default: `()`).
- `extension`: the name of the extension (default: `None`).
- `deprecated`: a boolean indicating whether the function is deprecated (default: `False`).
**Context**
- The code is creating a new function using the `constructFunction` method.
- The function is being created for a specific DLL (`dll`).
- The function has a specific name (`functionName`).
- The function has a specific return type (`resultType`) and argument types (`argTypes`).
- The function may have a documentation string (`doc`) and argument names (`argNames`).
- The function may be part of an extension (`extension`) and may be deprecated (`deprecated`).
**Task**
- Complete the `constructFunction` method to create a new function with the given parameters.
Based on this cheat sheet, I'm ready to solve the code completion task. Please provide the next line of code to complete.
|
|
Please complete the code given below.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.amaze.filemanager.filesystem.compressed.sevenz;
import android.annotation.TargetApi;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.zip.CRC32;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.utils.CountingOutputStream;
/**
* Writes a 7z file.
* @since 1.6
*/
public class SevenZOutputFile implements Closeable {
private final RandomAccessFile channel;
private final List<SevenZArchiveEntry> files = new ArrayList<>();
private int numNonEmptyStreams = 0;
private final CRC32 crc32 = new CRC32();
private final CRC32 compressedCrc32 = new CRC32();
private long fileBytesWritten = 0;
private boolean finished = false;
private CountingOutputStream currentOutputStream;
private CountingOutputStream[] additionalCountingStreams;
private Iterable<? extends SevenZMethodConfiguration> contentMethods =
Collections.singletonList(new SevenZMethodConfiguration(SevenZMethod.LZMA2));
private final Map<SevenZArchiveEntry, long[]> additionalSizes = new HashMap<>();
/**
* Opens file to write a 7z archive to.
*
* @param filename the file to write to
* @throws IOException if opening the file fails
*/
public SevenZOutputFile(final File filename) throws IOException {
this(new RandomAccessFile(filename, ""));
}
/**
* Prepares channel to write a 7z archive to.
*
* <p>{@link
* org.apache.commons.compress.utils.SeekableInMemoryByteChannel}
* allows you to write to an in-memory archive.</p>
*
* @param channel the channel to write to
* @throws IOException if the channel cannot be positioned properly
* @since 1.13
*/
public SevenZOutputFile(final RandomAccessFile channel) throws IOException {
this.channel = channel;
channel.seek(SevenZFile.SIGNATURE_HEADER_SIZE);
}
/**
* Sets the default compression method to use for entry contents - the
* default is LZMA2.
*
* <p>Currently only {@link SevenZMethod#COPY}, {@link
* SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
* SevenZMethod#DEFLATE} are supported.</p>
*
* <p>This is a short form for passing a single-element iterable
* to {@link #setContentMethods}.</p>
* @param method the default compression method
*/
public void setContentCompression(final SevenZMethod method) {
setContentMethods(Collections.singletonList(new SevenZMethodConfiguration(method)));
}
/**
* Sets the default (compression) methods to use for entry contents - the
* default is LZMA2.
*
* <p>Currently only {@link SevenZMethod#COPY}, {@link
* SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
* SevenZMethod#DEFLATE} are supported.</p>
*
* <p>The methods will be consulted in iteration order to create
* the final output.</p>
*
* @since 1.8
* @param methods the default (compression) methods
*/
public void setContentMethods(final Iterable<? extends SevenZMethodConfiguration> methods) {
this.contentMethods = reverse(methods);
}
/**
* Closes the archive, calling {@link #finish} if necessary.
*
* @throws IOException on error
*/
@Override
public void close() throws IOException {
try {
if (!finished) {
finish();
}
} finally {
channel.close();
}
}
/**
* Create an archive entry using the inputFile and entryName provided.
*
* @param inputFile file to create an entry from
* @param entryName the name to use
* @return the ArchiveEntry set up with details from the file
*
* @throws IOException on error
*/
public SevenZArchiveEntry createArchiveEntry(final File inputFile,
final String entryName) throws IOException {
final SevenZArchiveEntry entry = new SevenZArchiveEntry();
entry.setDirectory(inputFile.isDirectory());
entry.setName(entryName);
entry.setLastModifiedDate(new Date(inputFile.lastModified()));
return entry;
}
/**
* Records an archive entry to add.
*
* The caller must then write the content to the archive and call
* {@link #closeArchiveEntry()} to complete the process.
*
* @param archiveEntry describes the entry
* @throws IOException on error
*/
public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException {
final SevenZArchiveEntry entry = (SevenZArchiveEntry) archiveEntry;
files.add(entry);
}
/**
* Closes the archive entry.
* @throws IOException on error
*/
public void closeArchiveEntry() throws IOException {
if (currentOutputStream != null) {
currentOutputStream.flush();
currentOutputStream.close();
}
final SevenZArchiveEntry entry = files.get(files.size() - 1);
if (fileBytesWritten > 0) { // this implies currentOutputStream != null
entry.setHasStream(true);
++numNonEmptyStreams;
entry.setSize(currentOutputStream.getBytesWritten()); //NOSONAR
entry.setCompressedSize(fileBytesWritten);
entry.setCrcValue(crc32.getValue());
entry.setCompressedCrcValue(compressedCrc32.getValue());
entry.setHasCrc(true);
if (additionalCountingStreams != null) {
final long[] sizes = new long[additionalCountingStreams.length];
for (int i = 0; i < additionalCountingStreams.length; i++) {
sizes[i] = additionalCountingStreams[i].getBytesWritten();
}
additionalSizes.put(entry, sizes);
}
} else {
entry.setHasStream(false);
entry.setSize(0);
entry.setCompressedSize(0);
entry.setHasCrc(false);
}
currentOutputStream = null;
additionalCountingStreams = null;
crc32.reset();
compressedCrc32.reset();
fileBytesWritten = 0;
}
/**
* Writes a byte to the current archive entry.
* @param b The byte to be written.
* @throws IOException on error
*/
public void write(final int b) throws IOException {
getCurrentOutputStream().write(b);
}
/**
* Writes a byte array to the current archive entry.
* @param b The byte array to be written.
* @throws IOException on error
*/
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
/**
* Writes part of a byte array to the current archive entry.
* @param b The byte array to be written.
* @param off offset into the array to start writing from
* @param len number of bytes to write
* @throws IOException on error
*/
public void write(final byte[] b, final int off, final int len) throws IOException {
if (len > 0) {
getCurrentOutputStream().write(b, off, len);
}
}
/**
* Finishes the addition of entries to this archive, without closing it.
*
* @throws IOException if archive is already closed.
*/
public void finish() throws IOException {
if (finished) {
throw new IOException("This archive has already been finished");
}
finished = true;
final long headerPosition = channel.getFilePointer();
final ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
final DataOutputStream header = new DataOutputStream(headerBaos);
writeHeader(header);
header.flush();
final byte[] headerBytes = headerBaos.toByteArray();
channel.write(headerBytes);
final CRC32 crc32 = new CRC32();
crc32.update(headerBytes);
ByteBuffer bb = ByteBuffer.allocate(SevenZFile.sevenZSignature.length
+ 2 /* version */
+ 4 /* start header CRC */
+ 8 /* next header position */
+ 8 /* next header length */
+ 4 /* next header CRC */)
.order(ByteOrder.LITTLE_ENDIAN);
// signature header
channel.seek(0);
bb.put(SevenZFile.sevenZSignature);
// version
bb.put((byte) 0).put((byte) 2);
// placeholder for start header CRC
bb.putInt(0);
// start header
bb.putLong(headerPosition - SevenZFile.SIGNATURE_HEADER_SIZE)
.putLong(0xffffFFFFL & headerBytes.length)
.putInt((int) crc32.getValue());
crc32.reset();
crc32.update(bb.array(), SevenZFile.sevenZSignature.length + 6, 20);
bb.putInt(SevenZFile.sevenZSignature.length + 2, (int) crc32.getValue());
bb.flip();
channel.write(bb.array());
}
/*
* Creation of output stream is deferred until data is actually
* written as some codecs might write header information even for
* empty streams and directories otherwise.
*/
private OutputStream getCurrentOutputStream() throws IOException {
if (currentOutputStream == null) {
currentOutputStream = setupFileOutputStream();
}
return currentOutputStream;
}
private CountingOutputStream setupFileOutputStream() throws IOException {
if (files.isEmpty()) {
throw new IllegalStateException("No current 7z entry");
}
OutputStream out = new OutputStreamWrapper();
final ArrayList<CountingOutputStream> moreStreams = new ArrayList<>();
boolean first = true;
for (final SevenZMethodConfiguration m : getContentMethods(files.get(files.size() - 1))) {
if (!first) {
final CountingOutputStream cos = new CountingOutputStream(out);
moreStreams.add(cos);
out = cos;
}
out = Coders.addEncoder(out, m.getMethod(), m.getOptions());
first = false;
}
if (!moreStreams.isEmpty()) {
additionalCountingStreams = moreStreams.toArray(new CountingOutputStream[moreStreams.size()]);
}
return new CountingOutputStream(out) {
@Override
public void write(final int b) throws IOException {
super.write(b);
crc32.update(b);
}
@Override
public void write(final byte[] b) throws IOException {
super.write(b);
crc32.update(b);
}
@Override
public void write(final byte[] b, final int off, final int len)
throws IOException {
super.write(b, off, len);
crc32.update(b, off, len);
}
};
}
private Iterable<? extends SevenZMethodConfiguration> getContentMethods(final SevenZArchiveEntry entry) {
final Iterable<? extends SevenZMethodConfiguration> ms = entry.getContentMethods();
return ms == null ? contentMethods : ms;
}
private void writeHeader(final DataOutput header) throws IOException {
header.write(NID.kHeader);
header.write(NID.kMainStreamsInfo);
writeStreamsInfo(header);
writeFilesInfo(header);
header.write(NID.kEnd);
}
private void writeStreamsInfo(final DataOutput header) throws IOException {
if (numNonEmptyStreams > 0) {
writePackInfo(header);
writeUnpackInfo(header);
}
writeSubStreamsInfo(header);
header.write(NID.kEnd);
}
private void writePackInfo(final DataOutput header) throws IOException {
header.write(NID.kPackInfo);
writeUint64(header, 0);
writeUint64(header, 0xffffFFFFL & numNonEmptyStreams);
header.write(NID.kSize);
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
writeUint64(header, entry.getCompressedSize());
}
}
header.write(NID.kCRC);
header.write(1); // "allAreDefined" == true
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
header.writeInt(Integer.reverseBytes((int) entry.getCompressedCrcValue()));
}
}
header.write(NID.kEnd);
}
private void writeUnpackInfo(final DataOutput header) throws IOException {
header.write(NID.kUnpackInfo);
header.write(NID.kFolder);
writeUint64(header, numNonEmptyStreams);
header.write(0);
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
writeFolder(header, entry);
}
}
header.write(NID.kCodersUnpackSize);
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
final long[] moreSizes = additionalSizes.get(entry);
if (moreSizes != null) {
for (final long s : moreSizes) {
writeUint64(header, s);
}
}
writeUint64(header, entry.getSize());
}
}
header.write(NID.kCRC);
header.write(1); // "allAreDefined" == true
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
header.writeInt(Integer.reverseBytes((int) entry.getCrcValue()));
}
}
header.write(NID.kEnd);
}
private void writeFolder(final DataOutput header, final SevenZArchiveEntry entry) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
int numCoders = 0;
for (final SevenZMethodConfiguration m : getContentMethods(entry)) {
numCoders++;
writeSingleCodec(m, bos);
}
writeUint64(header, numCoders);
header.write(bos.toByteArray());
for (long i = 0; i < numCoders - 1; i++) {
writeUint64(header, i + 1);
writeUint64(header, i);
}
}
private void writeSingleCodec(final SevenZMethodConfiguration m, final OutputStream bos) throws IOException {
final byte[] id = m.getMethod().getId();
final byte[] properties = Coders.findByMethod(m.getMethod())
.getOptionsAsProperties(m.getOptions());
int codecFlags = id.length;
if (properties.length > 0) {
codecFlags |= 0x20;
}
bos.write(codecFlags);
bos.write(id);
if (properties.length > 0) {
bos.write(properties.length);
bos.write(properties);
}
}
private void writeSubStreamsInfo(final DataOutput header) throws IOException {
header.write(NID.kSubStreamsInfo);
//
// header.write(NID.kCRC);
// header.write(1);
// for (final SevenZArchiveEntry entry : files) {
// if (entry.getHasCrc()) {
// header.writeInt(Integer.reverseBytes(entry.getCrc()));
// }
// }
//
header.write(NID.kEnd);
}
private void writeFilesInfo(final DataOutput header) throws IOException {
header.write(NID.kFilesInfo);
writeUint64(header, files.size());
writeFileEmptyStreams(header);
writeFileEmptyFiles(header);
writeFileAntiItems(header);
writeFileNames(header);
writeFileCTimes(header);
writeFileATimes(header);
writeFileMTimes(header);
writeFileWindowsAttributes(header);
header.write(NID.kEnd);
}
private void writeFileEmptyStreams(final DataOutput header) throws IOException {
boolean hasEmptyStreams = false;
for (final SevenZArchiveEntry entry : files) {
if (!entry.hasStream()) {
hasEmptyStreams = true;
break;
}
}
if (hasEmptyStreams) {
header.write(NID.kEmptyStream);
final BitSet emptyStreams = new BitSet(files.size());
for (int i = 0; i < files.size(); i++) {
emptyStreams.set(i, !files.get(i).hasStream());
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
[
" final DataOutputStream out = new DataOutputStream(baos);"
] | 1,652
|
lcc
|
java
| null |
ce9e73e7e622c7688ef392b99d6afaa87bea6b138e34fa82
| 76
|
Your task is code completion.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.amaze.filemanager.filesystem.compressed.sevenz;
import android.annotation.TargetApi;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.zip.CRC32;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.utils.CountingOutputStream;
/**
* Writes a 7z file.
* @since 1.6
*/
public class SevenZOutputFile implements Closeable {
private final RandomAccessFile channel;
private final List<SevenZArchiveEntry> files = new ArrayList<>();
private int numNonEmptyStreams = 0;
private final CRC32 crc32 = new CRC32();
private final CRC32 compressedCrc32 = new CRC32();
private long fileBytesWritten = 0;
private boolean finished = false;
private CountingOutputStream currentOutputStream;
private CountingOutputStream[] additionalCountingStreams;
private Iterable<? extends SevenZMethodConfiguration> contentMethods =
Collections.singletonList(new SevenZMethodConfiguration(SevenZMethod.LZMA2));
private final Map<SevenZArchiveEntry, long[]> additionalSizes = new HashMap<>();
/**
* Opens file to write a 7z archive to.
*
* @param filename the file to write to
* @throws IOException if opening the file fails
*/
public SevenZOutputFile(final File filename) throws IOException {
this(new RandomAccessFile(filename, ""));
}
/**
* Prepares channel to write a 7z archive to.
*
* <p>{@link
* org.apache.commons.compress.utils.SeekableInMemoryByteChannel}
* allows you to write to an in-memory archive.</p>
*
* @param channel the channel to write to
* @throws IOException if the channel cannot be positioned properly
* @since 1.13
*/
public SevenZOutputFile(final RandomAccessFile channel) throws IOException {
this.channel = channel;
channel.seek(SevenZFile.SIGNATURE_HEADER_SIZE);
}
/**
* Sets the default compression method to use for entry contents - the
* default is LZMA2.
*
* <p>Currently only {@link SevenZMethod#COPY}, {@link
* SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
* SevenZMethod#DEFLATE} are supported.</p>
*
* <p>This is a short form for passing a single-element iterable
* to {@link #setContentMethods}.</p>
* @param method the default compression method
*/
public void setContentCompression(final SevenZMethod method) {
setContentMethods(Collections.singletonList(new SevenZMethodConfiguration(method)));
}
/**
* Sets the default (compression) methods to use for entry contents - the
* default is LZMA2.
*
* <p>Currently only {@link SevenZMethod#COPY}, {@link
* SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
* SevenZMethod#DEFLATE} are supported.</p>
*
* <p>The methods will be consulted in iteration order to create
* the final output.</p>
*
* @since 1.8
* @param methods the default (compression) methods
*/
public void setContentMethods(final Iterable<? extends SevenZMethodConfiguration> methods) {
this.contentMethods = reverse(methods);
}
/**
* Closes the archive, calling {@link #finish} if necessary.
*
* @throws IOException on error
*/
@Override
public void close() throws IOException {
try {
if (!finished) {
finish();
}
} finally {
channel.close();
}
}
/**
* Create an archive entry using the inputFile and entryName provided.
*
* @param inputFile file to create an entry from
* @param entryName the name to use
* @return the ArchiveEntry set up with details from the file
*
* @throws IOException on error
*/
public SevenZArchiveEntry createArchiveEntry(final File inputFile,
final String entryName) throws IOException {
final SevenZArchiveEntry entry = new SevenZArchiveEntry();
entry.setDirectory(inputFile.isDirectory());
entry.setName(entryName);
entry.setLastModifiedDate(new Date(inputFile.lastModified()));
return entry;
}
/**
* Records an archive entry to add.
*
* The caller must then write the content to the archive and call
* {@link #closeArchiveEntry()} to complete the process.
*
* @param archiveEntry describes the entry
* @throws IOException on error
*/
public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException {
final SevenZArchiveEntry entry = (SevenZArchiveEntry) archiveEntry;
files.add(entry);
}
/**
* Closes the archive entry.
* @throws IOException on error
*/
public void closeArchiveEntry() throws IOException {
if (currentOutputStream != null) {
currentOutputStream.flush();
currentOutputStream.close();
}
final SevenZArchiveEntry entry = files.get(files.size() - 1);
if (fileBytesWritten > 0) { // this implies currentOutputStream != null
entry.setHasStream(true);
++numNonEmptyStreams;
entry.setSize(currentOutputStream.getBytesWritten()); //NOSONAR
entry.setCompressedSize(fileBytesWritten);
entry.setCrcValue(crc32.getValue());
entry.setCompressedCrcValue(compressedCrc32.getValue());
entry.setHasCrc(true);
if (additionalCountingStreams != null) {
final long[] sizes = new long[additionalCountingStreams.length];
for (int i = 0; i < additionalCountingStreams.length; i++) {
sizes[i] = additionalCountingStreams[i].getBytesWritten();
}
additionalSizes.put(entry, sizes);
}
} else {
entry.setHasStream(false);
entry.setSize(0);
entry.setCompressedSize(0);
entry.setHasCrc(false);
}
currentOutputStream = null;
additionalCountingStreams = null;
crc32.reset();
compressedCrc32.reset();
fileBytesWritten = 0;
}
/**
* Writes a byte to the current archive entry.
* @param b The byte to be written.
* @throws IOException on error
*/
public void write(final int b) throws IOException {
getCurrentOutputStream().write(b);
}
/**
* Writes a byte array to the current archive entry.
* @param b The byte array to be written.
* @throws IOException on error
*/
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
/**
* Writes part of a byte array to the current archive entry.
* @param b The byte array to be written.
* @param off offset into the array to start writing from
* @param len number of bytes to write
* @throws IOException on error
*/
public void write(final byte[] b, final int off, final int len) throws IOException {
if (len > 0) {
getCurrentOutputStream().write(b, off, len);
}
}
/**
* Finishes the addition of entries to this archive, without closing it.
*
* @throws IOException if archive is already closed.
*/
public void finish() throws IOException {
if (finished) {
throw new IOException("This archive has already been finished");
}
finished = true;
final long headerPosition = channel.getFilePointer();
final ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
final DataOutputStream header = new DataOutputStream(headerBaos);
writeHeader(header);
header.flush();
final byte[] headerBytes = headerBaos.toByteArray();
channel.write(headerBytes);
final CRC32 crc32 = new CRC32();
crc32.update(headerBytes);
ByteBuffer bb = ByteBuffer.allocate(SevenZFile.sevenZSignature.length
+ 2 /* version */
+ 4 /* start header CRC */
+ 8 /* next header position */
+ 8 /* next header length */
+ 4 /* next header CRC */)
.order(ByteOrder.LITTLE_ENDIAN);
// signature header
channel.seek(0);
bb.put(SevenZFile.sevenZSignature);
// version
bb.put((byte) 0).put((byte) 2);
// placeholder for start header CRC
bb.putInt(0);
// start header
bb.putLong(headerPosition - SevenZFile.SIGNATURE_HEADER_SIZE)
.putLong(0xffffFFFFL & headerBytes.length)
.putInt((int) crc32.getValue());
crc32.reset();
crc32.update(bb.array(), SevenZFile.sevenZSignature.length + 6, 20);
bb.putInt(SevenZFile.sevenZSignature.length + 2, (int) crc32.getValue());
bb.flip();
channel.write(bb.array());
}
/*
* Creation of output stream is deferred until data is actually
* written as some codecs might write header information even for
* empty streams and directories otherwise.
*/
private OutputStream getCurrentOutputStream() throws IOException {
if (currentOutputStream == null) {
currentOutputStream = setupFileOutputStream();
}
return currentOutputStream;
}
private CountingOutputStream setupFileOutputStream() throws IOException {
if (files.isEmpty()) {
throw new IllegalStateException("No current 7z entry");
}
OutputStream out = new OutputStreamWrapper();
final ArrayList<CountingOutputStream> moreStreams = new ArrayList<>();
boolean first = true;
for (final SevenZMethodConfiguration m : getContentMethods(files.get(files.size() - 1))) {
if (!first) {
final CountingOutputStream cos = new CountingOutputStream(out);
moreStreams.add(cos);
out = cos;
}
out = Coders.addEncoder(out, m.getMethod(), m.getOptions());
first = false;
}
if (!moreStreams.isEmpty()) {
additionalCountingStreams = moreStreams.toArray(new CountingOutputStream[moreStreams.size()]);
}
return new CountingOutputStream(out) {
@Override
public void write(final int b) throws IOException {
super.write(b);
crc32.update(b);
}
@Override
public void write(final byte[] b) throws IOException {
super.write(b);
crc32.update(b);
}
@Override
public void write(final byte[] b, final int off, final int len)
throws IOException {
super.write(b, off, len);
crc32.update(b, off, len);
}
};
}
private Iterable<? extends SevenZMethodConfiguration> getContentMethods(final SevenZArchiveEntry entry) {
final Iterable<? extends SevenZMethodConfiguration> ms = entry.getContentMethods();
return ms == null ? contentMethods : ms;
}
private void writeHeader(final DataOutput header) throws IOException {
header.write(NID.kHeader);
header.write(NID.kMainStreamsInfo);
writeStreamsInfo(header);
writeFilesInfo(header);
header.write(NID.kEnd);
}
private void writeStreamsInfo(final DataOutput header) throws IOException {
if (numNonEmptyStreams > 0) {
writePackInfo(header);
writeUnpackInfo(header);
}
writeSubStreamsInfo(header);
header.write(NID.kEnd);
}
private void writePackInfo(final DataOutput header) throws IOException {
header.write(NID.kPackInfo);
writeUint64(header, 0);
writeUint64(header, 0xffffFFFFL & numNonEmptyStreams);
header.write(NID.kSize);
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
writeUint64(header, entry.getCompressedSize());
}
}
header.write(NID.kCRC);
header.write(1); // "allAreDefined" == true
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
header.writeInt(Integer.reverseBytes((int) entry.getCompressedCrcValue()));
}
}
header.write(NID.kEnd);
}
private void writeUnpackInfo(final DataOutput header) throws IOException {
header.write(NID.kUnpackInfo);
header.write(NID.kFolder);
writeUint64(header, numNonEmptyStreams);
header.write(0);
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
writeFolder(header, entry);
}
}
header.write(NID.kCodersUnpackSize);
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
final long[] moreSizes = additionalSizes.get(entry);
if (moreSizes != null) {
for (final long s : moreSizes) {
writeUint64(header, s);
}
}
writeUint64(header, entry.getSize());
}
}
header.write(NID.kCRC);
header.write(1); // "allAreDefined" == true
for (final SevenZArchiveEntry entry : files) {
if (entry.hasStream()) {
header.writeInt(Integer.reverseBytes((int) entry.getCrcValue()));
}
}
header.write(NID.kEnd);
}
private void writeFolder(final DataOutput header, final SevenZArchiveEntry entry) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
int numCoders = 0;
for (final SevenZMethodConfiguration m : getContentMethods(entry)) {
numCoders++;
writeSingleCodec(m, bos);
}
writeUint64(header, numCoders);
header.write(bos.toByteArray());
for (long i = 0; i < numCoders - 1; i++) {
writeUint64(header, i + 1);
writeUint64(header, i);
}
}
private void writeSingleCodec(final SevenZMethodConfiguration m, final OutputStream bos) throws IOException {
final byte[] id = m.getMethod().getId();
final byte[] properties = Coders.findByMethod(m.getMethod())
.getOptionsAsProperties(m.getOptions());
int codecFlags = id.length;
if (properties.length > 0) {
codecFlags |= 0x20;
}
bos.write(codecFlags);
bos.write(id);
if (properties.length > 0) {
bos.write(properties.length);
bos.write(properties);
}
}
private void writeSubStreamsInfo(final DataOutput header) throws IOException {
header.write(NID.kSubStreamsInfo);
//
// header.write(NID.kCRC);
// header.write(1);
// for (final SevenZArchiveEntry entry : files) {
// if (entry.getHasCrc()) {
// header.writeInt(Integer.reverseBytes(entry.getCrc()));
// }
// }
//
header.write(NID.kEnd);
}
private void writeFilesInfo(final DataOutput header) throws IOException {
header.write(NID.kFilesInfo);
writeUint64(header, files.size());
writeFileEmptyStreams(header);
writeFileEmptyFiles(header);
writeFileAntiItems(header);
writeFileNames(header);
writeFileCTimes(header);
writeFileATimes(header);
writeFileMTimes(header);
writeFileWindowsAttributes(header);
header.write(NID.kEnd);
}
private void writeFileEmptyStreams(final DataOutput header) throws IOException {
boolean hasEmptyStreams = false;
for (final SevenZArchiveEntry entry : files) {
if (!entry.hasStream()) {
hasEmptyStreams = true;
break;
}
}
if (hasEmptyStreams) {
header.write(NID.kEmptyStream);
final BitSet emptyStreams = new BitSet(files.size());
for (int i = 0; i < files.size(); i++) {
emptyStreams.set(i, !files.get(i).hasStream());
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
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]
private void writeFileEmptyFiles(final DataOutput header) throws IOException {
boolean hasEmptyFiles = false;
for (final SevenZArchiveEntry entry : files) {
if (!entry.hasStream() && !entry.isDirectory()) {
hasEmptyFiles = true;
break;
}
}
if (hasEmptyFiles) {
header.write(NID.kEmptyFile);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
// [Current line]
// [Previous code... ~10,000 lines omitted for brevity]
header.write(baos.toByteArray());
header.write(NID.kEnd);
}
}
Cheatsheet (for next line):
- We are in writeFileEmptyFiles(), which is writing the information about empty files in the 7z archive.
- baos is a ByteArrayOutputStream object used to store the information about empty files.
- The information about empty files is written to the header in the format of NID.kEmptyFile, followed by the information in baos, and finally NID.kEnd.
- The information in baos is a bitset representing the empty files.
- [Relevant lines: declaration of baos, previous lines in writeFileEmptyFiles()]
Next line will likely be: header.write(baos.toByteArray());
|
|
Please complete the code given below.
package fr.nantes.univ.alma.tools.ui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
public class InfiniteProgressPanel extends JComponent implements MouseListener
{
private static final long serialVersionUID = 8770653983557145191L;
protected Area[] ticker = null;
protected Thread animation = null;
protected boolean started = false;
protected int alphaLevel = 0;
protected int rampDelay = 300;
protected float shield = 0.70f;
protected String text = "";
protected int barsCount = 14;
protected float fps = 15.0f;
protected RenderingHints hints = null;
public InfiniteProgressPanel()
{
this("");
}
public InfiniteProgressPanel(String text)
{
this(text, 14);
}
public InfiniteProgressPanel(String text, int barsCount)
{
this(text, barsCount, 0.70f);
}
public InfiniteProgressPanel(String text, int barsCount, float shield)
{
this(text, barsCount, shield, 15.0f);
}
public InfiniteProgressPanel(String text, int barsCount, float shield, float fps)
{
this(text, barsCount, shield, fps, 300);
}
public InfiniteProgressPanel(String text, int barsCount, float shield, float fps, int rampDelay)
{
this.text = text;
this.rampDelay = rampDelay >= 0 ? rampDelay : 0;
this.shield = shield >= 0.0f ? shield : 0.0f;
this.fps = fps > 0.0f ? fps : 15.0f;
this.barsCount = barsCount > 0 ? barsCount : 14;
this.hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
this.hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
this.hints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
}
public void setText(String text)
{
repaint();
this.text = text;
}
public String getText()
{
return text;
}
public void start()
{
addMouseListener(this);
setVisible(true);
ticker = buildTicker();
animation = new Thread(new Animator(true));
animation.start();
}
public void stop()
{
if (animation != null) {
animation.interrupt();
animation = null;
animation = new Thread(new Animator(false));
animation.start();
}
}
public void interrupt()
{
if (animation != null) {
animation.interrupt();
animation = null;
removeMouseListener(this);
setVisible(false);
}
}
public void paintComponent(Graphics g)
{
if (started)
{
int width = getWidth();
double maxY = 0.0;
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHints(hints);
g2.setColor(new Color(255, 255, 255, (int) (alphaLevel * shield)));
g2.fillRect(0, 0, getWidth(), getHeight());
for (int i = 0; i < ticker.length; i++)
{
int channel = 224 - 128 / (i + 1);
g2.setColor(new Color(channel, channel, channel, alphaLevel));
g2.fill(ticker[i]);
Rectangle2D bounds = ticker[i].getBounds2D();
if (bounds.getMaxY() > maxY)
maxY = bounds.getMaxY();
}
if (text != null && text.length() > 0)
{
FontRenderContext context = g2.getFontRenderContext();
TextLayout layout = new TextLayout(text, getFont(), context);
Rectangle2D bounds = layout.getBounds();
g2.setColor(getForeground());
layout.draw(g2, (float) (width - bounds.getWidth()) / 2,
(float) (maxY + layout.getLeading() + 2 * layout.getAscent()));
}
}
}
private Area[] buildTicker()
{
Area[] ticker = new Area[barsCount];
Point2D.Double center = new Point2D.Double((double) getWidth() / 2, (double) getHeight() / 2);
double fixedAngle = 2.0 * Math.PI / ((double) barsCount);
for (double i = 0.0; i < (double) barsCount; i++)
{
Area primitive = buildPrimitive();
AffineTransform toCenter = AffineTransform.getTranslateInstance(center.getX(), center.getY());
AffineTransform toBorder = AffineTransform.getTranslateInstance(45.0, -6.0);
AffineTransform toCircle = AffineTransform.getRotateInstance(-i * fixedAngle, center.getX(), center.getY());
AffineTransform toWheel = new AffineTransform();
toWheel.concatenate(toCenter);
toWheel.concatenate(toBorder);
primitive.transform(toWheel);
primitive.transform(toCircle);
ticker[(int) i] = primitive;
}
return ticker;
}
private Area buildPrimitive()
{
Rectangle2D.Double body = new Rectangle2D.Double(6, 0, 30, 12);
Ellipse2D.Double head = new Ellipse2D.Double(0, 0, 12, 12);
Ellipse2D.Double tail = new Ellipse2D.Double(30, 0, 12, 12);
Area tick = new Area(body);
tick.add(new Area(head));
tick.add(new Area(tail));
return tick;
}
protected class Animator implements Runnable
{
private boolean rampUp = true;
protected Animator(boolean rampUp)
{
this.rampUp = rampUp;
}
public void run()
{
Point2D.Double center = new Point2D.Double((double) getWidth() / 2, (double) getHeight() / 2);
double fixedIncrement = 2.0 * Math.PI / ((double) barsCount);
AffineTransform toCircle = AffineTransform.getRotateInstance(fixedIncrement, center.getX(), center.getY());
long start = System.currentTimeMillis();
if (rampDelay == 0)
alphaLevel = rampUp ? 255 : 0;
started = true;
boolean inRamp = rampUp;
while (!Thread.interrupted())
{
if (!inRamp)
{
|
[
" for (int i = 0; i < ticker.length; i++)"
] | 600
|
lcc
|
java
| null |
6a3563763220617ce12df989e13f3ad3d2a6e723fd3d119e
| 77
|
Your task is code completion.
package fr.nantes.univ.alma.tools.ui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
public class InfiniteProgressPanel extends JComponent implements MouseListener
{
private static final long serialVersionUID = 8770653983557145191L;
protected Area[] ticker = null;
protected Thread animation = null;
protected boolean started = false;
protected int alphaLevel = 0;
protected int rampDelay = 300;
protected float shield = 0.70f;
protected String text = "";
protected int barsCount = 14;
protected float fps = 15.0f;
protected RenderingHints hints = null;
public InfiniteProgressPanel()
{
this("");
}
public InfiniteProgressPanel(String text)
{
this(text, 14);
}
public InfiniteProgressPanel(String text, int barsCount)
{
this(text, barsCount, 0.70f);
}
public InfiniteProgressPanel(String text, int barsCount, float shield)
{
this(text, barsCount, shield, 15.0f);
}
public InfiniteProgressPanel(String text, int barsCount, float shield, float fps)
{
this(text, barsCount, shield, fps, 300);
}
public InfiniteProgressPanel(String text, int barsCount, float shield, float fps, int rampDelay)
{
this.text = text;
this.rampDelay = rampDelay >= 0 ? rampDelay : 0;
this.shield = shield >= 0.0f ? shield : 0.0f;
this.fps = fps > 0.0f ? fps : 15.0f;
this.barsCount = barsCount > 0 ? barsCount : 14;
this.hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
this.hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
this.hints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
}
public void setText(String text)
{
repaint();
this.text = text;
}
public String getText()
{
return text;
}
public void start()
{
addMouseListener(this);
setVisible(true);
ticker = buildTicker();
animation = new Thread(new Animator(true));
animation.start();
}
public void stop()
{
if (animation != null) {
animation.interrupt();
animation = null;
animation = new Thread(new Animator(false));
animation.start();
}
}
public void interrupt()
{
if (animation != null) {
animation.interrupt();
animation = null;
removeMouseListener(this);
setVisible(false);
}
}
public void paintComponent(Graphics g)
{
if (started)
{
int width = getWidth();
double maxY = 0.0;
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHints(hints);
g2.setColor(new Color(255, 255, 255, (int) (alphaLevel * shield)));
g2.fillRect(0, 0, getWidth(), getHeight());
for (int i = 0; i < ticker.length; i++)
{
int channel = 224 - 128 / (i + 1);
g2.setColor(new Color(channel, channel, channel, alphaLevel));
g2.fill(ticker[i]);
Rectangle2D bounds = ticker[i].getBounds2D();
if (bounds.getMaxY() > maxY)
maxY = bounds.getMaxY();
}
if (text != null && text.length() > 0)
{
FontRenderContext context = g2.getFontRenderContext();
TextLayout layout = new TextLayout(text, getFont(), context);
Rectangle2D bounds = layout.getBounds();
g2.setColor(getForeground());
layout.draw(g2, (float) (width - bounds.getWidth()) / 2,
(float) (maxY + layout.getLeading() + 2 * layout.getAscent()));
}
}
}
private Area[] buildTicker()
{
Area[] ticker = new Area[barsCount];
Point2D.Double center = new Point2D.Double((double) getWidth() / 2, (double) getHeight() / 2);
double fixedAngle = 2.0 * Math.PI / ((double) barsCount);
for (double i = 0.0; i < (double) barsCount; i++)
{
Area primitive = buildPrimitive();
AffineTransform toCenter = AffineTransform.getTranslateInstance(center.getX(), center.getY());
AffineTransform toBorder = AffineTransform.getTranslateInstance(45.0, -6.0);
AffineTransform toCircle = AffineTransform.getRotateInstance(-i * fixedAngle, center.getX(), center.getY());
AffineTransform toWheel = new AffineTransform();
toWheel.concatenate(toCenter);
toWheel.concatenate(toBorder);
primitive.transform(toWheel);
primitive.transform(toCircle);
ticker[(int) i] = primitive;
}
return ticker;
}
private Area buildPrimitive()
{
Rectangle2D.Double body = new Rectangle2D.Double(6, 0, 30, 12);
Ellipse2D.Double head = new Ellipse2D.Double(0, 0, 12, 12);
Ellipse2D.Double tail = new Ellipse2D.Double(30, 0, 12, 12);
Area tick = new Area(body);
tick.add(new Area(head));
tick.add(new Area(tail));
return tick;
}
protected class Animator implements Runnable
{
private boolean rampUp = true;
protected Animator(boolean rampUp)
{
this.rampUp = rampUp;
}
public void run()
{
Point2D.Double center = new Point2D.Double((double) getWidth() / 2, (double) getHeight() / 2);
double fixedIncrement = 2.0 * Math.PI / ((double) barsCount);
AffineTransform toCircle = AffineTransform.getRotateInstance(fixedIncrement, center.getX(), center.getY());
long start = System.currentTimeMillis();
if (rampDelay == 0)
alphaLevel = rampUp ? 255 : 0;
started = true;
boolean inRamp = rampUp;
while (!Thread.interrupted())
{
if (!inRamp)
{
|
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]
public class InfiniteProgressPanel extends JComponent implements MouseListener
{
...
protected class Animator implements Runnable
{
private boolean rampUp = true;
protected Animator(boolean rampUp)
{
this.rampUp = rampUp;
}
public void run()
{
Point2D.Double center = new Point2D.Double((double) getWidth() / 2, (double) getHeight() / 2);
double fixedIncrement = 2.0 * Math.PI / ((double) barsCount);
AffineTransform toCircle = AffineTransform.getRotateInstance(fixedIncrement, center.getX(), center.getY());
long start = System.currentTimeMillis();
if (rampDelay == 0)
alphaLevel = rampUp ? 255 : 0;
started = true;
boolean inRamp = rampUp;
while (!Thread.interrupted())
{
if (!inRamp)
{
Cheatsheet (for next line):
- We are in the Animator's run() method, which is a loop that continues until the thread is interrupted.
- The loop condition is !Thread.interrupted(), which means the loop will continue as long as the thread is not interrupted.
- The current line is inside the while loop, and the next line should likely be related to updating the animation.
- The animation involves rotating the ticker (a series of shapes) around a center point.
- The rotation is done using an AffineTransform, specifically toCircle.
- The alphaLevel variable is used to control the transparency of the shapes.
- The rampUp variable determines whether the animation is ramping up or down.
- The inRamp variable is a flag that indicates whether the animation is currently ramping up or down.
Relevant lines:
- The while loop condition
- The AffineTransform toCircle
- The alphaLevel variable
- The rampUp variable
- The inRamp variable
Next line will likely be:
- Update the alphaLevel variable based on the rampUp flag and the elapsed time since the start of the animation.
|
|
Please complete the code given below.
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using NzbDrone.Core.Download;
using NzbDrone.Core.Download.Clients.Transmission;
namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests
{
[TestFixture]
public class TransmissionFixture : TransmissionFixtureBase<Transmission>
{
[Test]
public void queued_item_should_have_required_properties()
{
PrepareClientToReturnQueuedItem();
var item = Subject.GetItems().Single();
VerifyQueued(item);
}
[Test]
public void downloading_item_should_have_required_properties()
{
PrepareClientToReturnDownloadingItem();
var item = Subject.GetItems().Single();
VerifyDownloading(item);
}
[Test]
public void failed_item_should_have_required_properties()
{
PrepareClientToReturnFailedItem();
var item = Subject.GetItems().Single();
VerifyWarning(item);
}
[Test]
public void completed_download_should_have_required_properties()
{
PrepareClientToReturnCompletedItem();
var item = Subject.GetItems().Single();
VerifyCompleted(item);
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void magnet_download_should_not_return_the_item()
{
PrepareClientToReturnMagnetItem();
Subject.GetItems().Count().Should().Be(0);
}
[Test]
public void Download_should_return_unique_id()
{
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
}
[Test]
public void Download_with_MovieDirectory_should_force_directory()
{
GivenMovieDirectory();
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
Mocker.GetMock<ITransmissionProxy>()
.Verify(v => v.AddTorrentFromData(It.IsAny<byte[]>(), @"C:/Downloads/Finished/radarr", It.IsAny<TransmissionSettings>()), Times.Once());
}
[Test]
public void Download_with_category_should_force_directory()
{
GivenMovieCategory();
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
Mocker.GetMock<ITransmissionProxy>()
.Verify(v => v.AddTorrentFromData(It.IsAny<byte[]>(), @"C:/Downloads/Finished/transmission/radarr", It.IsAny<TransmissionSettings>()), Times.Once());
}
[Test]
public void Download_with_category_should_not_have_double_slashes()
{
GivenMovieCategory();
GivenSuccessfulDownload();
_transmissionConfigItems["download-dir"] += "/";
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
Mocker.GetMock<ITransmissionProxy>()
.Verify(v => v.AddTorrentFromData(It.IsAny<byte[]>(), @"C:/Downloads/Finished/transmission/radarr", It.IsAny<TransmissionSettings>()), Times.Once());
}
[Test]
public void Download_without_TvDirectory_and_Category_should_use_default()
{
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
Mocker.GetMock<ITransmissionProxy>()
.Verify(v => v.AddTorrentFromData(It.IsAny<byte[]>(), null, It.IsAny<TransmissionSettings>()), Times.Once());
}
[TestCase("magnet:?xt=urn:btih:ZPBPA2P6ROZPKRHK44D5OW6NHXU5Z6KR&tr=udp", "CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951")]
public void Download_should_get_hash_from_magnet_url(string magnetUrl, string expectedHash)
{
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
remoteMovie.Release.DownloadUrl = magnetUrl;
var id = Subject.Download(remoteMovie);
id.Should().Be(expectedHash);
}
[TestCase(TransmissionTorrentStatus.Stopped, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.CheckWait, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.Check, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.Queued, DownloadItemStatus.Queued)]
[TestCase(TransmissionTorrentStatus.Downloading, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.SeedingWait, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.Seeding, DownloadItemStatus.Downloading)]
public void GetItems_should_return_queued_item_as_downloadItemStatus(TransmissionTorrentStatus apiStatus, DownloadItemStatus expectedItemStatus)
{
_queued.Status = apiStatus;
PrepareClientToReturnQueuedItem();
var item = Subject.GetItems().Single();
item.Status.Should().Be(expectedItemStatus);
}
[TestCase(TransmissionTorrentStatus.Queued, DownloadItemStatus.Queued)]
[TestCase(TransmissionTorrentStatus.Downloading, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.Seeding, DownloadItemStatus.Downloading)]
public void GetItems_should_return_downloading_item_as_downloadItemStatus(TransmissionTorrentStatus apiStatus, DownloadItemStatus expectedItemStatus)
{
_downloading.Status = apiStatus;
PrepareClientToReturnDownloadingItem();
var item = Subject.GetItems().Single();
item.Status.Should().Be(expectedItemStatus);
}
[TestCase(TransmissionTorrentStatus.Stopped, DownloadItemStatus.Completed, false)]
[TestCase(TransmissionTorrentStatus.CheckWait, DownloadItemStatus.Downloading, false)]
[TestCase(TransmissionTorrentStatus.Check, DownloadItemStatus.Downloading, false)]
[TestCase(TransmissionTorrentStatus.Queued, DownloadItemStatus.Completed, false)]
[TestCase(TransmissionTorrentStatus.SeedingWait, DownloadItemStatus.Completed, false)]
[TestCase(TransmissionTorrentStatus.Seeding, DownloadItemStatus.Completed, false)]
public void GetItems_should_return_completed_item_as_downloadItemStatus(TransmissionTorrentStatus apiStatus, DownloadItemStatus expectedItemStatus, bool expectedValue)
{
_completed.Status = apiStatus;
PrepareClientToReturnCompletedItem();
var item = Subject.GetItems().Single();
item.Status.Should().Be(expectedItemStatus);
item.CanBeRemoved.Should().Be(expectedValue);
item.CanMoveFiles.Should().Be(expectedValue);
}
[Test]
public void should_return_status_with_outputdirs()
{
var result = Subject.GetStatus();
result.IsLocalhost.Should().BeTrue();
result.OutputRootFolders.Should().NotBeNull();
result.OutputRootFolders.First().Should().Be(@"C:\Downloads\Finished\transmission");
}
[Test]
public void should_exclude_items_not_in_category()
{
GivenMovieCategory();
_downloading.DownloadDir = @"C:/Downloads/Finished/transmission/radarr";
GivenTorrents(new List<TransmissionTorrent>
{
_downloading,
_queued
});
var items = Subject.GetItems().ToList();
items.Count.Should().Be(1);
items.First().Status.Should().Be(DownloadItemStatus.Downloading);
}
[Test]
public void should_exclude_items_not_in_TvDirectory()
{
GivenMovieDirectory();
_downloading.DownloadDir = @"C:/Downloads/Finished/radarr/subdir";
GivenTorrents(new List<TransmissionTorrent>
{
_downloading,
_queued
});
var items = Subject.GetItems().ToList();
items.Count.Should().Be(1);
items.First().Status.Should().Be(DownloadItemStatus.Downloading);
}
[Test]
public void should_fix_forward_slashes()
{
WindowsOnly();
_downloading.DownloadDir = @"C:/Downloads/Finished/transmission";
GivenTorrents(new List<TransmissionTorrent>
{
_downloading
});
var items = Subject.GetItems().ToList();
items.Should().HaveCount(1);
items.First().OutputPath.Should().Be(@"C:\Downloads\Finished\transmission\" + _title);
}
[TestCase("2.84 ()")]
[TestCase("2.84+ ()")]
[TestCase("2.84 (other info)")]
[TestCase("2.84 (2.84)")]
public void should_only_check_version_number(string version)
{
Mocker.GetMock<ITransmissionProxy>()
.Setup(s => s.GetClientVersion(It.IsAny<TransmissionSettings>()))
.Returns(version);
Subject.Test().IsValid.Should().BeTrue();
}
[TestCase(-1)] // Infinite/Unknown
[TestCase(-2)] // Magnet Downloading
public void should_ignore_negative_eta(int eta)
{
_completed.Eta = eta;
PrepareClientToReturnCompletedItem();
var item = Subject.GetItems().Single();
item.RemainingTime.Should().NotHaveValue();
}
[Test]
public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio_reached_and_not_stopped()
{
GivenGlobalSeedLimits(1.0);
PrepareClientToReturnCompletedItem(false, ratio: 1.0);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio_is_not_set()
{
GivenGlobalSeedLimits();
PrepareClientToReturnCompletedItem(true, ratio: 1.0);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_max_ratio_reached_and_paused()
{
GivenGlobalSeedLimits(1.0);
PrepareClientToReturnCompletedItem(true, ratio: 1.0);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeTrue();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_overridden_max_ratio_reached_and_paused()
{
GivenGlobalSeedLimits(2.0);
PrepareClientToReturnCompletedItem(true, ratio: 1.0, ratioLimit: 0.8);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeTrue();
}
[Test]
public void should_not_be_removable_if_overridden_max_ratio_not_reached_and_paused()
{
GivenGlobalSeedLimits(0.2);
PrepareClientToReturnCompletedItem(true, ratio: 0.5, ratioLimit: 0.8);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_not_be_removable_and_should_not_allow_move_files_if_max_idletime_reached_and_not_paused()
{
GivenGlobalSeedLimits(null, 20);
PrepareClientToReturnCompletedItem(false, ratio: 2.0, seedingTime: 30);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_max_idletime_reached_and_paused()
{
GivenGlobalSeedLimits(null, 20);
PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 20);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeTrue();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_overridden_max_idletime_reached_and_paused()
{
GivenGlobalSeedLimits(null, 40);
PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 20, idleLimit: 10);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeTrue();
}
[Test]
public void should_be_removable_and_should_not_allow_move_files_if_overridden_max_idletime_reached_and_not_paused()
{
GivenGlobalSeedLimits(null, 40);
PrepareClientToReturnCompletedItem(false, ratio: 2.0, seedingTime: 20, idleLimit: 10);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_not_be_removable_if_overridden_max_idletime_not_reached_and_paused()
{
GivenGlobalSeedLimits(null, 20);
PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 30, idleLimit: 40);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_not_be_removable_if_max_idletime_reached_but_ratio_not_and_not_paused()
{
GivenGlobalSeedLimits(2.0, 20);
PrepareClientToReturnCompletedItem(false, ratio: 1.0, seedingTime: 30);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_max_idletime_configured_and_paused()
{
GivenGlobalSeedLimits(2.0, 20);
PrepareClientToReturnCompletedItem(true, ratio: 1.0, seedingTime: 30);
|
[
" var item = Subject.GetItems().Single();"
] | 655
|
lcc
|
csharp
| null |
83459d6f1f2adf3b906ee4a28eaf21c3a195f75ae100c64b
| 78
|
Your task is code completion.
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using NzbDrone.Core.Download;
using NzbDrone.Core.Download.Clients.Transmission;
namespace NzbDrone.Core.Test.Download.DownloadClientTests.TransmissionTests
{
[TestFixture]
public class TransmissionFixture : TransmissionFixtureBase<Transmission>
{
[Test]
public void queued_item_should_have_required_properties()
{
PrepareClientToReturnQueuedItem();
var item = Subject.GetItems().Single();
VerifyQueued(item);
}
[Test]
public void downloading_item_should_have_required_properties()
{
PrepareClientToReturnDownloadingItem();
var item = Subject.GetItems().Single();
VerifyDownloading(item);
}
[Test]
public void failed_item_should_have_required_properties()
{
PrepareClientToReturnFailedItem();
var item = Subject.GetItems().Single();
VerifyWarning(item);
}
[Test]
public void completed_download_should_have_required_properties()
{
PrepareClientToReturnCompletedItem();
var item = Subject.GetItems().Single();
VerifyCompleted(item);
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void magnet_download_should_not_return_the_item()
{
PrepareClientToReturnMagnetItem();
Subject.GetItems().Count().Should().Be(0);
}
[Test]
public void Download_should_return_unique_id()
{
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
}
[Test]
public void Download_with_MovieDirectory_should_force_directory()
{
GivenMovieDirectory();
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
Mocker.GetMock<ITransmissionProxy>()
.Verify(v => v.AddTorrentFromData(It.IsAny<byte[]>(), @"C:/Downloads/Finished/radarr", It.IsAny<TransmissionSettings>()), Times.Once());
}
[Test]
public void Download_with_category_should_force_directory()
{
GivenMovieCategory();
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
Mocker.GetMock<ITransmissionProxy>()
.Verify(v => v.AddTorrentFromData(It.IsAny<byte[]>(), @"C:/Downloads/Finished/transmission/radarr", It.IsAny<TransmissionSettings>()), Times.Once());
}
[Test]
public void Download_with_category_should_not_have_double_slashes()
{
GivenMovieCategory();
GivenSuccessfulDownload();
_transmissionConfigItems["download-dir"] += "/";
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
Mocker.GetMock<ITransmissionProxy>()
.Verify(v => v.AddTorrentFromData(It.IsAny<byte[]>(), @"C:/Downloads/Finished/transmission/radarr", It.IsAny<TransmissionSettings>()), Times.Once());
}
[Test]
public void Download_without_TvDirectory_and_Category_should_use_default()
{
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
var id = Subject.Download(remoteMovie);
id.Should().NotBeNullOrEmpty();
Mocker.GetMock<ITransmissionProxy>()
.Verify(v => v.AddTorrentFromData(It.IsAny<byte[]>(), null, It.IsAny<TransmissionSettings>()), Times.Once());
}
[TestCase("magnet:?xt=urn:btih:ZPBPA2P6ROZPKRHK44D5OW6NHXU5Z6KR&tr=udp", "CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951")]
public void Download_should_get_hash_from_magnet_url(string magnetUrl, string expectedHash)
{
GivenSuccessfulDownload();
var remoteMovie = CreateRemoteMovie();
remoteMovie.Release.DownloadUrl = magnetUrl;
var id = Subject.Download(remoteMovie);
id.Should().Be(expectedHash);
}
[TestCase(TransmissionTorrentStatus.Stopped, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.CheckWait, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.Check, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.Queued, DownloadItemStatus.Queued)]
[TestCase(TransmissionTorrentStatus.Downloading, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.SeedingWait, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.Seeding, DownloadItemStatus.Downloading)]
public void GetItems_should_return_queued_item_as_downloadItemStatus(TransmissionTorrentStatus apiStatus, DownloadItemStatus expectedItemStatus)
{
_queued.Status = apiStatus;
PrepareClientToReturnQueuedItem();
var item = Subject.GetItems().Single();
item.Status.Should().Be(expectedItemStatus);
}
[TestCase(TransmissionTorrentStatus.Queued, DownloadItemStatus.Queued)]
[TestCase(TransmissionTorrentStatus.Downloading, DownloadItemStatus.Downloading)]
[TestCase(TransmissionTorrentStatus.Seeding, DownloadItemStatus.Downloading)]
public void GetItems_should_return_downloading_item_as_downloadItemStatus(TransmissionTorrentStatus apiStatus, DownloadItemStatus expectedItemStatus)
{
_downloading.Status = apiStatus;
PrepareClientToReturnDownloadingItem();
var item = Subject.GetItems().Single();
item.Status.Should().Be(expectedItemStatus);
}
[TestCase(TransmissionTorrentStatus.Stopped, DownloadItemStatus.Completed, false)]
[TestCase(TransmissionTorrentStatus.CheckWait, DownloadItemStatus.Downloading, false)]
[TestCase(TransmissionTorrentStatus.Check, DownloadItemStatus.Downloading, false)]
[TestCase(TransmissionTorrentStatus.Queued, DownloadItemStatus.Completed, false)]
[TestCase(TransmissionTorrentStatus.SeedingWait, DownloadItemStatus.Completed, false)]
[TestCase(TransmissionTorrentStatus.Seeding, DownloadItemStatus.Completed, false)]
public void GetItems_should_return_completed_item_as_downloadItemStatus(TransmissionTorrentStatus apiStatus, DownloadItemStatus expectedItemStatus, bool expectedValue)
{
_completed.Status = apiStatus;
PrepareClientToReturnCompletedItem();
var item = Subject.GetItems().Single();
item.Status.Should().Be(expectedItemStatus);
item.CanBeRemoved.Should().Be(expectedValue);
item.CanMoveFiles.Should().Be(expectedValue);
}
[Test]
public void should_return_status_with_outputdirs()
{
var result = Subject.GetStatus();
result.IsLocalhost.Should().BeTrue();
result.OutputRootFolders.Should().NotBeNull();
result.OutputRootFolders.First().Should().Be(@"C:\Downloads\Finished\transmission");
}
[Test]
public void should_exclude_items_not_in_category()
{
GivenMovieCategory();
_downloading.DownloadDir = @"C:/Downloads/Finished/transmission/radarr";
GivenTorrents(new List<TransmissionTorrent>
{
_downloading,
_queued
});
var items = Subject.GetItems().ToList();
items.Count.Should().Be(1);
items.First().Status.Should().Be(DownloadItemStatus.Downloading);
}
[Test]
public void should_exclude_items_not_in_TvDirectory()
{
GivenMovieDirectory();
_downloading.DownloadDir = @"C:/Downloads/Finished/radarr/subdir";
GivenTorrents(new List<TransmissionTorrent>
{
_downloading,
_queued
});
var items = Subject.GetItems().ToList();
items.Count.Should().Be(1);
items.First().Status.Should().Be(DownloadItemStatus.Downloading);
}
[Test]
public void should_fix_forward_slashes()
{
WindowsOnly();
_downloading.DownloadDir = @"C:/Downloads/Finished/transmission";
GivenTorrents(new List<TransmissionTorrent>
{
_downloading
});
var items = Subject.GetItems().ToList();
items.Should().HaveCount(1);
items.First().OutputPath.Should().Be(@"C:\Downloads\Finished\transmission\" + _title);
}
[TestCase("2.84 ()")]
[TestCase("2.84+ ()")]
[TestCase("2.84 (other info)")]
[TestCase("2.84 (2.84)")]
public void should_only_check_version_number(string version)
{
Mocker.GetMock<ITransmissionProxy>()
.Setup(s => s.GetClientVersion(It.IsAny<TransmissionSettings>()))
.Returns(version);
Subject.Test().IsValid.Should().BeTrue();
}
[TestCase(-1)] // Infinite/Unknown
[TestCase(-2)] // Magnet Downloading
public void should_ignore_negative_eta(int eta)
{
_completed.Eta = eta;
PrepareClientToReturnCompletedItem();
var item = Subject.GetItems().Single();
item.RemainingTime.Should().NotHaveValue();
}
[Test]
public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio_reached_and_not_stopped()
{
GivenGlobalSeedLimits(1.0);
PrepareClientToReturnCompletedItem(false, ratio: 1.0);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio_is_not_set()
{
GivenGlobalSeedLimits();
PrepareClientToReturnCompletedItem(true, ratio: 1.0);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_max_ratio_reached_and_paused()
{
GivenGlobalSeedLimits(1.0);
PrepareClientToReturnCompletedItem(true, ratio: 1.0);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeTrue();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_overridden_max_ratio_reached_and_paused()
{
GivenGlobalSeedLimits(2.0);
PrepareClientToReturnCompletedItem(true, ratio: 1.0, ratioLimit: 0.8);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeTrue();
}
[Test]
public void should_not_be_removable_if_overridden_max_ratio_not_reached_and_paused()
{
GivenGlobalSeedLimits(0.2);
PrepareClientToReturnCompletedItem(true, ratio: 0.5, ratioLimit: 0.8);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_not_be_removable_and_should_not_allow_move_files_if_max_idletime_reached_and_not_paused()
{
GivenGlobalSeedLimits(null, 20);
PrepareClientToReturnCompletedItem(false, ratio: 2.0, seedingTime: 30);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_max_idletime_reached_and_paused()
{
GivenGlobalSeedLimits(null, 20);
PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 20);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeTrue();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_overridden_max_idletime_reached_and_paused()
{
GivenGlobalSeedLimits(null, 40);
PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 20, idleLimit: 10);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeTrue();
}
[Test]
public void should_be_removable_and_should_not_allow_move_files_if_overridden_max_idletime_reached_and_not_paused()
{
GivenGlobalSeedLimits(null, 40);
PrepareClientToReturnCompletedItem(false, ratio: 2.0, seedingTime: 20, idleLimit: 10);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeTrue();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_not_be_removable_if_overridden_max_idletime_not_reached_and_paused()
{
GivenGlobalSeedLimits(null, 20);
PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 30, idleLimit: 40);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_not_be_removable_if_max_idletime_reached_but_ratio_not_and_not_paused()
{
GivenGlobalSeedLimits(2.0, 20);
PrepareClientToReturnCompletedItem(false, ratio: 1.0, seedingTime: 30);
var item = Subject.GetItems().Single();
item.CanBeRemoved.Should().BeFalse();
item.CanMoveFiles.Should().BeFalse();
}
[Test]
public void should_be_removable_and_should_allow_move_files_if_max_idletime_configured_and_paused()
{
GivenGlobalSeedLimits(2.0, 20);
PrepareClientToReturnCompletedItem(true, ratio: 1.0, seedingTime: 30);
|
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
|
Based on the provided code, I will create a cheat sheet to help with the code completion task.
**Context:**
The code is a set of unit tests for a Transmission client in the NzbDrone project. The tests cover various scenarios related to downloading, getting items, and checking the status of the Transmission client.
**Relevant Variables and Methods:**
* `_transmissionConfigItems`: a dictionary containing configuration items for the Transmission client
* `Subject`: an instance of the Transmission client
* `ITransmissionProxy`: a mock object for the Transmission client
* `TransmissionTorrentStatus`: an enum representing the status of a torrent in Transmission
* `DownloadItemStatus`: an enum representing the status of a download item
* `GetItems()`: a method that returns a list of download items
* `GetStatus()`: a method that returns the status of the Transmission client
* `Download()`: a method that downloads a movie and returns the ID of the downloaded item
* `VerifyQueued()`, `VerifyDownloading()`, `VerifyWarning()`, `VerifyCompleted()`: methods that verify the properties of a download item
* `PrepareClientToReturnQueuedItem()`, `PrepareClientToReturnDownloadingItem()`, `PrepareClientToReturnFailedItem()`, `PrepareClientToReturnCompletedItem()`: methods that prepare the Transmission client to return a specific type of item
**Relevant Scenarios:**
* Downloading a movie and verifying its properties
* Getting the status of the Transmission client
* Checking the status of a download item
* Verifying the properties of a download item
* Preparing the Transmission client to return a specific type of item
**Cheat Sheet:**
* We are in a test method that is testing the `GetItems()` method.
* The method is expected to return a list of download items.
* The list should contain items with the correct status and properties.
* The `GetItems()` method is likely to be called on the `Subject` instance.
**Next Line:**
```csharp
var items = Subject.GetItems().ToList();
```
This line retrieves the list of download items from the `Subject` instance and stores it in the `items` variable. The `ToList()` method is used to materialize the query and ensure that the list is not lazy-loaded.
|
|
Please complete the code given below.
#region using directives
using System;
using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Common;
using PoGo.NecroBot.Logic.Event;
using PoGo.NecroBot.Logic.Logging;
using PoGo.NecroBot.Logic.State;
using PoGo.NecroBot.Logic.Utils;
using POGOProtos.Inventory.Item;
#endregion
namespace PoGo.NecroBot.Logic.Tasks
{
public class RecycleItemsTask
{
private static int _diff;
private static Random rnd = new Random();
public static async Task Execute(ISession session, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await session.Inventory.RefreshCachedInventory();
var currentTotalItems = await session.Inventory.GetTotalItemCount();
if ((session.Profile.PlayerData.MaxItemStorage * session.LogicSettings.RecycleInventoryAtUsagePercentage / 100.0f) > currentTotalItems)
return;
var currentAmountOfPokeballs = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall);
var currentAmountOfGreatballs = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall);
var currentAmountOfUltraballs = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall);
var currentAmountOfMasterballs = await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall);
if (session.LogicSettings.DetailedCountsBeforeRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentPokeballInv,
currentAmountOfPokeballs, currentAmountOfGreatballs, currentAmountOfUltraballs,
currentAmountOfMasterballs));
var currentPotions = await session.Inventory.GetItemAmountByType(ItemId.ItemPotion);
var currentSuperPotions = await session.Inventory.GetItemAmountByType(ItemId.ItemSuperPotion);
var currentHyperPotions = await session.Inventory.GetItemAmountByType(ItemId.ItemHyperPotion);
var currentMaxPotions = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxPotion);
var currentAmountOfPotions = currentPotions + currentSuperPotions + currentHyperPotions + currentMaxPotions;
if (session.LogicSettings.DetailedCountsBeforeRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentPotionInv,
currentPotions, currentSuperPotions, currentHyperPotions, currentMaxPotions));
var currentRevives = await session.Inventory.GetItemAmountByType(ItemId.ItemRevive);
var currentMaxRevives = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxRevive);
var currentAmountOfRevives = currentRevives + currentMaxRevives;
if (session.LogicSettings.DetailedCountsBeforeRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentReviveInv,
currentRevives, currentMaxRevives));
var currentAmountOfBerries = await session.Inventory.GetItemAmountByType(ItemId.ItemRazzBerry) +
await session.Inventory.GetItemAmountByType(ItemId.ItemBlukBerry) +
await session.Inventory.GetItemAmountByType(ItemId.ItemNanabBerry) +
await session.Inventory.GetItemAmountByType(ItemId.ItemWeparBerry) +
await session.Inventory.GetItemAmountByType(ItemId.ItemPinapBerry);
var currentAmountOfIncense = await session.Inventory.GetItemAmountByType(ItemId.ItemIncenseOrdinary) +
await session.Inventory.GetItemAmountByType(ItemId.ItemIncenseSpicy) +
await session.Inventory.GetItemAmountByType(ItemId.ItemIncenseCool) +
await session.Inventory.GetItemAmountByType(ItemId.ItemIncenseFloral);
var currentAmountOfLuckyEggs = await session.Inventory.GetItemAmountByType(ItemId.ItemLuckyEgg);
var currentAmountOfLures = await session.Inventory.GetItemAmountByType(ItemId.ItemTroyDisk);
if (session.LogicSettings.DetailedCountsBeforeRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentMiscItemInv,
currentAmountOfBerries, currentAmountOfIncense, currentAmountOfLuckyEggs, currentAmountOfLures));
if (session.LogicSettings.TotalAmountOfPokeballsToKeep != 0)
await OptimizedRecycleBalls(session, cancellationToken);
if (!session.LogicSettings.VerboseRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.RecyclingQuietly), LogLevel.Recycling);
if (session.LogicSettings.TotalAmountOfPotionsToKeep>=0)
await OptimizedRecyclePotions(session, cancellationToken);
if (session.LogicSettings.TotalAmountOfRevivesToKeep>=0)
await OptimizedRecycleRevives(session, cancellationToken);
if (session.LogicSettings.TotalAmountOfBerriesToKeep >= 0)
await OptimizedRecycleBerries(session, cancellationToken);
await session.Inventory.RefreshCachedInventory();
currentTotalItems = await session.Inventory.GetTotalItemCount();
if ((session.Profile.PlayerData.MaxItemStorage * session.LogicSettings.RecycleInventoryAtUsagePercentage / 100.0f) > currentTotalItems)
return;
var items = await session.Inventory.GetItemsToRecycle(session);
foreach (var item in items)
{
cancellationToken.ThrowIfCancellationRequested();
await session.Client.Inventory.RecycleItem(item.ItemId, item.Count);
if (session.LogicSettings.VerboseRecycling)
session.EventDispatcher.Send(new ItemRecycledEvent { Id = item.ItemId, Count = item.Count });
DelayingUtils.Delay(session.LogicSettings.RecycleActionDelay, 500);
}
await session.Inventory.RefreshCachedInventory();
}
private static async Task RecycleItems(ISession session, CancellationToken cancellationToken, int itemCount, ItemId item)
{
int itemsToRecycle = 0;
int itemsToKeep = itemCount - _diff;
if (itemsToKeep < 0)
itemsToKeep = 0;
itemsToRecycle = itemCount - itemsToKeep;
if (itemsToRecycle != 0)
{
_diff -= itemsToRecycle;
cancellationToken.ThrowIfCancellationRequested();
await session.Client.Inventory.RecycleItem(item, itemsToRecycle);
if (session.LogicSettings.VerboseRecycling)
session.EventDispatcher.Send(new ItemRecycledEvent { Id = item, Count = itemsToRecycle });
DelayingUtils.Delay(session.LogicSettings.RecycleActionDelay, 500);
}
}
private static async Task OptimizedRecycleBalls(ISession session, CancellationToken cancellationToken)
{
var pokeBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall);
var greatBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall);
var ultraBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall);
var masterBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall);
int totalBallsCount = pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalBallsCount > session.LogicSettings.TotalAmountOfPokeballsToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalBallsCount - session.LogicSettings.TotalAmountOfPokeballsToKeep + random;
} else {
_diff = totalBallsCount - session.LogicSettings.TotalAmountOfPokeballsToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, pokeBallsCount, ItemId.ItemPokeBall);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, greatBallsCount, ItemId.ItemGreatBall);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, ultraBallsCount, ItemId.ItemUltraBall);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, masterBallsCount, ItemId.ItemMasterBall);
}
}
}
private static async Task OptimizedRecyclePotions(ISession session, CancellationToken cancellationToken)
{
var potionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPotion);
var superPotionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemSuperPotion);
var hyperPotionsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemHyperPotion);
var maxPotionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxPotion);
int totalPotionsCount = potionCount + superPotionCount + hyperPotionsCount + maxPotionCount;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalPotionsCount > session.LogicSettings.TotalAmountOfPotionsToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalPotionsCount - session.LogicSettings.TotalAmountOfPotionsToKeep + random;
}
else
{
_diff = totalPotionsCount - session.LogicSettings.TotalAmountOfPotionsToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, potionCount, ItemId.ItemPotion);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, superPotionCount, ItemId.ItemSuperPotion);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, hyperPotionsCount, ItemId.ItemHyperPotion);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, maxPotionCount, ItemId.ItemMaxPotion);
}
}
}
private static async Task OptimizedRecycleRevives(ISession session, CancellationToken cancellationToken)
{
var reviveCount = await session.Inventory.GetItemAmountByType(ItemId.ItemRevive);
var maxReviveCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxRevive);
int totalRevivesCount = reviveCount + maxReviveCount;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalRevivesCount > session.LogicSettings.TotalAmountOfRevivesToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalRevivesCount - session.LogicSettings.TotalAmountOfRevivesToKeep + random;
}
else
{
_diff = totalRevivesCount - session.LogicSettings.TotalAmountOfRevivesToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, reviveCount, ItemId.ItemRevive);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, maxReviveCount, ItemId.ItemMaxRevive);
}
}
}
private static async Task OptimizedRecycleBerries(ISession session, CancellationToken cancellationToken)
{
var razz = await session.Inventory.GetItemAmountByType(ItemId.ItemRazzBerry);
var bluk = await session.Inventory.GetItemAmountByType(ItemId.ItemBlukBerry);
var nanab = await session.Inventory.GetItemAmountByType(ItemId.ItemNanabBerry);
var pinap = await session.Inventory.GetItemAmountByType(ItemId.ItemPinapBerry);
var wepar = await session.Inventory.GetItemAmountByType(ItemId.ItemWeparBerry);
int totalBerryCount = razz + bluk + nanab + pinap + wepar;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalBerryCount > session.LogicSettings.TotalAmountOfBerriesToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalBerryCount - session.LogicSettings.TotalAmountOfBerriesToKeep + random;
}
else
{
_diff = totalBerryCount - session.LogicSettings.TotalAmountOfBerriesToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, razz, ItemId.ItemRazzBerry);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, bluk, ItemId.ItemBlukBerry);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, nanab, ItemId.ItemNanabBerry);
}
|
[
" if (_diff > 0)"
] | 772
|
lcc
|
csharp
| null |
a35dec5733725ddbb50c8215f4db5a1bb8d03ea5bf6f87c7
| 79
|
Your task is code completion.
#region using directives
using System;
using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Common;
using PoGo.NecroBot.Logic.Event;
using PoGo.NecroBot.Logic.Logging;
using PoGo.NecroBot.Logic.State;
using PoGo.NecroBot.Logic.Utils;
using POGOProtos.Inventory.Item;
#endregion
namespace PoGo.NecroBot.Logic.Tasks
{
public class RecycleItemsTask
{
private static int _diff;
private static Random rnd = new Random();
public static async Task Execute(ISession session, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await session.Inventory.RefreshCachedInventory();
var currentTotalItems = await session.Inventory.GetTotalItemCount();
if ((session.Profile.PlayerData.MaxItemStorage * session.LogicSettings.RecycleInventoryAtUsagePercentage / 100.0f) > currentTotalItems)
return;
var currentAmountOfPokeballs = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall);
var currentAmountOfGreatballs = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall);
var currentAmountOfUltraballs = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall);
var currentAmountOfMasterballs = await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall);
if (session.LogicSettings.DetailedCountsBeforeRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentPokeballInv,
currentAmountOfPokeballs, currentAmountOfGreatballs, currentAmountOfUltraballs,
currentAmountOfMasterballs));
var currentPotions = await session.Inventory.GetItemAmountByType(ItemId.ItemPotion);
var currentSuperPotions = await session.Inventory.GetItemAmountByType(ItemId.ItemSuperPotion);
var currentHyperPotions = await session.Inventory.GetItemAmountByType(ItemId.ItemHyperPotion);
var currentMaxPotions = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxPotion);
var currentAmountOfPotions = currentPotions + currentSuperPotions + currentHyperPotions + currentMaxPotions;
if (session.LogicSettings.DetailedCountsBeforeRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentPotionInv,
currentPotions, currentSuperPotions, currentHyperPotions, currentMaxPotions));
var currentRevives = await session.Inventory.GetItemAmountByType(ItemId.ItemRevive);
var currentMaxRevives = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxRevive);
var currentAmountOfRevives = currentRevives + currentMaxRevives;
if (session.LogicSettings.DetailedCountsBeforeRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentReviveInv,
currentRevives, currentMaxRevives));
var currentAmountOfBerries = await session.Inventory.GetItemAmountByType(ItemId.ItemRazzBerry) +
await session.Inventory.GetItemAmountByType(ItemId.ItemBlukBerry) +
await session.Inventory.GetItemAmountByType(ItemId.ItemNanabBerry) +
await session.Inventory.GetItemAmountByType(ItemId.ItemWeparBerry) +
await session.Inventory.GetItemAmountByType(ItemId.ItemPinapBerry);
var currentAmountOfIncense = await session.Inventory.GetItemAmountByType(ItemId.ItemIncenseOrdinary) +
await session.Inventory.GetItemAmountByType(ItemId.ItemIncenseSpicy) +
await session.Inventory.GetItemAmountByType(ItemId.ItemIncenseCool) +
await session.Inventory.GetItemAmountByType(ItemId.ItemIncenseFloral);
var currentAmountOfLuckyEggs = await session.Inventory.GetItemAmountByType(ItemId.ItemLuckyEgg);
var currentAmountOfLures = await session.Inventory.GetItemAmountByType(ItemId.ItemTroyDisk);
if (session.LogicSettings.DetailedCountsBeforeRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.CurrentMiscItemInv,
currentAmountOfBerries, currentAmountOfIncense, currentAmountOfLuckyEggs, currentAmountOfLures));
if (session.LogicSettings.TotalAmountOfPokeballsToKeep != 0)
await OptimizedRecycleBalls(session, cancellationToken);
if (!session.LogicSettings.VerboseRecycling)
Logger.Write(session.Translation.GetTranslation(TranslationString.RecyclingQuietly), LogLevel.Recycling);
if (session.LogicSettings.TotalAmountOfPotionsToKeep>=0)
await OptimizedRecyclePotions(session, cancellationToken);
if (session.LogicSettings.TotalAmountOfRevivesToKeep>=0)
await OptimizedRecycleRevives(session, cancellationToken);
if (session.LogicSettings.TotalAmountOfBerriesToKeep >= 0)
await OptimizedRecycleBerries(session, cancellationToken);
await session.Inventory.RefreshCachedInventory();
currentTotalItems = await session.Inventory.GetTotalItemCount();
if ((session.Profile.PlayerData.MaxItemStorage * session.LogicSettings.RecycleInventoryAtUsagePercentage / 100.0f) > currentTotalItems)
return;
var items = await session.Inventory.GetItemsToRecycle(session);
foreach (var item in items)
{
cancellationToken.ThrowIfCancellationRequested();
await session.Client.Inventory.RecycleItem(item.ItemId, item.Count);
if (session.LogicSettings.VerboseRecycling)
session.EventDispatcher.Send(new ItemRecycledEvent { Id = item.ItemId, Count = item.Count });
DelayingUtils.Delay(session.LogicSettings.RecycleActionDelay, 500);
}
await session.Inventory.RefreshCachedInventory();
}
private static async Task RecycleItems(ISession session, CancellationToken cancellationToken, int itemCount, ItemId item)
{
int itemsToRecycle = 0;
int itemsToKeep = itemCount - _diff;
if (itemsToKeep < 0)
itemsToKeep = 0;
itemsToRecycle = itemCount - itemsToKeep;
if (itemsToRecycle != 0)
{
_diff -= itemsToRecycle;
cancellationToken.ThrowIfCancellationRequested();
await session.Client.Inventory.RecycleItem(item, itemsToRecycle);
if (session.LogicSettings.VerboseRecycling)
session.EventDispatcher.Send(new ItemRecycledEvent { Id = item, Count = itemsToRecycle });
DelayingUtils.Delay(session.LogicSettings.RecycleActionDelay, 500);
}
}
private static async Task OptimizedRecycleBalls(ISession session, CancellationToken cancellationToken)
{
var pokeBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall);
var greatBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall);
var ultraBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall);
var masterBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall);
int totalBallsCount = pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalBallsCount > session.LogicSettings.TotalAmountOfPokeballsToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalBallsCount - session.LogicSettings.TotalAmountOfPokeballsToKeep + random;
} else {
_diff = totalBallsCount - session.LogicSettings.TotalAmountOfPokeballsToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, pokeBallsCount, ItemId.ItemPokeBall);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, greatBallsCount, ItemId.ItemGreatBall);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, ultraBallsCount, ItemId.ItemUltraBall);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, masterBallsCount, ItemId.ItemMasterBall);
}
}
}
private static async Task OptimizedRecyclePotions(ISession session, CancellationToken cancellationToken)
{
var potionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPotion);
var superPotionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemSuperPotion);
var hyperPotionsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemHyperPotion);
var maxPotionCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxPotion);
int totalPotionsCount = potionCount + superPotionCount + hyperPotionsCount + maxPotionCount;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalPotionsCount > session.LogicSettings.TotalAmountOfPotionsToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalPotionsCount - session.LogicSettings.TotalAmountOfPotionsToKeep + random;
}
else
{
_diff = totalPotionsCount - session.LogicSettings.TotalAmountOfPotionsToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, potionCount, ItemId.ItemPotion);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, superPotionCount, ItemId.ItemSuperPotion);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, hyperPotionsCount, ItemId.ItemHyperPotion);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, maxPotionCount, ItemId.ItemMaxPotion);
}
}
}
private static async Task OptimizedRecycleRevives(ISession session, CancellationToken cancellationToken)
{
var reviveCount = await session.Inventory.GetItemAmountByType(ItemId.ItemRevive);
var maxReviveCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMaxRevive);
int totalRevivesCount = reviveCount + maxReviveCount;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalRevivesCount > session.LogicSettings.TotalAmountOfRevivesToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalRevivesCount - session.LogicSettings.TotalAmountOfRevivesToKeep + random;
}
else
{
_diff = totalRevivesCount - session.LogicSettings.TotalAmountOfRevivesToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, reviveCount, ItemId.ItemRevive);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, maxReviveCount, ItemId.ItemMaxRevive);
}
}
}
private static async Task OptimizedRecycleBerries(ISession session, CancellationToken cancellationToken)
{
var razz = await session.Inventory.GetItemAmountByType(ItemId.ItemRazzBerry);
var bluk = await session.Inventory.GetItemAmountByType(ItemId.ItemBlukBerry);
var nanab = await session.Inventory.GetItemAmountByType(ItemId.ItemNanabBerry);
var pinap = await session.Inventory.GetItemAmountByType(ItemId.ItemPinapBerry);
var wepar = await session.Inventory.GetItemAmountByType(ItemId.ItemWeparBerry);
int totalBerryCount = razz + bluk + nanab + pinap + wepar;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalBerryCount > session.LogicSettings.TotalAmountOfBerriesToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalBerryCount - session.LogicSettings.TotalAmountOfBerriesToKeep + random;
}
else
{
_diff = totalBerryCount - session.LogicSettings.TotalAmountOfBerriesToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, razz, ItemId.ItemRazzBerry);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, bluk, ItemId.ItemBlukBerry);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, nanab, ItemId.ItemNanabBerry);
}
|
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:**
```csharp
private static async Task OptimizedRecycleBerries(ISession session, CancellationToken cancellationToken)
{
var razz = await session.Inventory.GetItemAmountByType(ItemId.ItemRazzBerry);
var bluk = await session.Inventory.GetItemAmountByType(ItemId.ItemBlukBerry);
var nanab = await session.Inventory.GetItemAmountByType(ItemId.ItemNanabBerry);
var pinap = await session.Inventory.GetItemAmountByType(ItemId.ItemPinapBerry);
var wepar = await session.Inventory.GetItemAmountByType(ItemId.ItemWeparBerry);
int totalBerryCount = razz + bluk + nanab + pinap + wepar;
int random = rnd.Next(-1 * session.LogicSettings.RandomRecycleValue, session.LogicSettings.RandomRecycleValue + 1);
if (totalBerryCount > session.LogicSettings.TotalAmountOfBerriesToKeep)
{
if (session.LogicSettings.RandomizeRecycle)
{
_diff = totalBerryCount - session.LogicSettings.TotalAmountOfBerriesToKeep + random;
}
else
{
_diff = totalBerryCount - session.LogicSettings.TotalAmountOfBerriesToKeep;
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, razz, ItemId.ItemRazzBerry);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, bluk, ItemId.ItemBlukBerry);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, nanab, ItemId.ItemNanabBerry);
}
```
**Cheat sheet:**
- We are in the OptimizedRecycleBerries method, which is optimizing the recycling of berries.
- The method is checking if the total berry count exceeds the TotalAmountOfBerriesToKeep setting.
- If it does, the method is recycling the berries, but it only recycles the razz, bluk, and nanab berries so far.
- The next line should continue recycling the remaining berries (pinap and wepar).
**Relevant lines:**
- The declaration of the pinap and wepar variables
- The calculation of the total berry count
- The if statement that checks if the total berry count exceeds the TotalAmountOfBerriesToKeep setting
**Expected next line(s):**
```csharp
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, pinap, ItemId.ItemPinapBerry);
}
if (_diff > 0)
{
await RecycleItems(session, cancellationToken, wepar, ItemId.ItemWeparBerry);
}
```
|
|
Please complete the code given below.
import os
import sys
import pyfits
import config as c
from os.path import exists
from numpy import log10
from readlog import ReadLog
from runsexfunc import *
from flagfunc import *
class ConfigIter:
"""The class making configuration file for GALFIT. The configuration file
consists of bulge and disk component of the object and only Sersic
component for the neighbours, if any. The sky is always fixed and has
the value of SExtractor. The disk/boxy parameter is also fixed to zero.
The initial value for Sersic index 'n' is 4.The configuration file has
the name G_string(galid).in. The output image has the name
O_string(galid).fits"""
def __init__(self, cutimage, whtimage, xcntr, ycntr, NXPTS, NYPTS, line_s, psffile):
self.cutimage = cutimage
self.line_s = line_s
self.whtimage = whtimage
self.xcntr = xcntr
self.ycntr = ycntr
self.NXPTS = NXPTS
self.NYPTS = NYPTS
self.psffile = psffile
self.confiter = confiter(cutimage, whtimage, xcntr, ycntr, NXPTS, NYPTS, line_s, psffile)
def confiter(cutimage, whtimage, xcntr, ycntr, NXPTS, NYPTS, line_s, psffile):
RunSex(cutimage, whtimage, 'TEMP.SEX.cat', 9999, 9999, 0)
imagefile = c.imagefile
sex_cata = 'TEMP.SEX.cat'
threshold = c.threshold
thresh_area = c.thresh_area
mask_reg = c.mask_reg
try:
ComP = c.components
except:
ComP = ['bulge', 'disk']
if len(ComP) == 0:
ComP = ['bulge', 'disk']
values = line_s.split()
outfile = 'O_' + c.fstring + '.fits'
mask_file = 'M_' + c.fstring + '.fits'
config_file = 'G_' + c.fstring + '.in' #Name of the GALFIT configuration file
constrain_file = c.fstring + '.con'
try:
c.center_constrain = c.center_constrain
except:
c.center_constrain = 2.0
def SersicMainConstrain(constrain_file, cO):
f_constrain = open(constrain_file, 'ab')
f_constrain.write(str(cO) + ' n ' + str(c.LN) + \
' to ' + str(c.UN) + '\n')
f_constrain.write(str(cO) + ' x ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' y ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' mag ' + str(c.UMag) + \
' to ' + str(c.LMag) + '\n')
f_constrain.write(str(cO) + ' re ' + str(c.LRe) +\
' to ' + str(c.URe) + '\n')
f_constrain.write(str(cO) + ' q 0.0 to 1.0\n')
f_constrain.write(str(cO) + ' pa -360.0 to 360.0\n')
f_constrain.close()
def BarConstrain(constrain_file, cO):
f_constrain = open(constrain_file, 'ab')
f_constrain.write(str(cO) + ' n ' + str('0.1') + \
' to ' + str('2.2') + '\n')
f_constrain.write(str(cO) + ' x ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' y ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' mag ' + str(c.UMag) + \
' to ' + str(c.LMag) + '\n')
f_constrain.write(str(cO) + ' re ' + str(c.LRe) +\
' to ' + str(c.URe) + '\n')
f_constrain.write(str(cO) + ' q 0.0 to 0.5\n')
f_constrain.write(str(cO) + ' pa -360.0 to 360.0\n')
f_constrain.close()
def ExpdiskConstrain(constrain_file, cO):
f_constrain = open(constrain_file, 'ab')
f_constrain.write(str(cO) + ' x ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' y ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' mag ' + str(c.UMag) + \
' to ' + str(c.LMag) + '\n')
f_constrain.write(str(cO) + ' rs ' + str(c.LRd) + \
' to ' + str(c.URd) + '\n')
f_constrain.write(str(cO) + ' q 0.0 to 1.0\n')
f_constrain.write(str(cO) + ' pa -360.0 to 360.0\n')
f_constrain.close()
def SersicConstrain(constrain_file, cO):
f_constrain = open(constrain_file, 'ab')
f_constrain.write(str(cO) + ' n 0.02 to 20.0 \n')
f_constrain.write(str(cO) + ' mag -100.0 to 100.0\n')
f_constrain.write(str(cO) + ' re 0.0 to 500.0\n')
f_constrain.write(str(cO) + ' q 0.0 to 1.0\n')
f_constrain.write(str(cO) + ' pa -360.0 to 360.0\n')
f_constrain.close()
xcntr_o = xcntr #float(values[1]) #x center of the object
ycntr_o = ycntr #float(values[2]) #y center of the object
mag = float(values[7]) #Magnitude
radius = float(values[9]) #Half light radius
mag_zero = c.mag_zero #magnitude zero point
sky = float(values[10]) #sky
pos_ang = float(values[11]) - 90.0 #position angle
axis_rat = 1.0/float(values[12]) #axis ration b/a
area_o = float(values[13]) # object's area
major_axis = float(values[14]) #major axis of the object
ParamDict = {}
#Add components
AdComp = 1
if 'bulge' in ComP:
c.Flag = SetFlag(c.Flag, GetFlag('FIT_BULGE'))
ParamDict[AdComp] = {}
#Bulge Parameters
ParamDict[AdComp][1] = 'sersic'
ParamDict[AdComp][2] = [xcntr_o, ycntr_o]
ParamDict[AdComp][3] = mag
ParamDict[AdComp][4] = radius
ParamDict[AdComp][5] = 4.0
ParamDict[AdComp][6] = axis_rat
ParamDict[AdComp][7] = pos_ang
ParamDict[AdComp][8] = 0
ParamDict[AdComp][9] = 0
ParamDict[AdComp][11] = 'Main'
AdComp += 1
if 'bar' in ComP:
c.Flag = SetFlag(c.Flag, GetFlag('FIT_BAR'))
ParamDict[AdComp] = {}
#Bulge Parameters
ParamDict[AdComp][1] = 'bar'
ParamDict[AdComp][2] = [xcntr_o, ycntr_o]
ParamDict[AdComp][3] = mag + 2.5 * log10(2.0)
ParamDict[AdComp][4] = radius
ParamDict[AdComp][5] = 0.5
ParamDict[AdComp][6] = 0.3
ParamDict[AdComp][7] = pos_ang
ParamDict[AdComp][8] = 0
ParamDict[AdComp][9] = 0
ParamDict[AdComp][11] = 'Main'
AdComp += 1
if 'disk' in ComP:
c.Flag = SetFlag(c.Flag, GetFlag('FIT_DISK'))
#Disk parameters
ParamDict[AdComp] = {}
ParamDict[AdComp][1] = 'expdisk'
ParamDict[AdComp][2] = [xcntr_o, ycntr_o]
ParamDict[AdComp][3] = mag
ParamDict[AdComp][4] = radius
ParamDict[AdComp][5] = axis_rat
ParamDict[AdComp][6] = pos_ang
ParamDict[AdComp][7] = 0
ParamDict[AdComp][8] = 0
ParamDict[AdComp][11] = 'Main'
AdComp += 1
isneighbour = 0
f_constrain = open(constrain_file, 'ab')
for line_j in open(sex_cata,'r'):
try:
values = line_j.split()
xcntr_n = float(values[1]) #x center of the neighbour
ycntr_n = float(values[2]) #y center of the neighbour
mag = float(values[7]) #Magnitude
radius = float(values[9]) #Half light radius
sky = float(values[10]) #sky
pos_ang = float(values[11]) - 90.0 #position angle
axis_rat = 1.0/float(values[12]) #axis ration b/a
area_n = float(values[13]) # neighbour area
maj_axis = float(values[14])#major axis of neighbour
NotFitNeigh = 0
if abs(xcntr_n - xcntr_o) > NXPTS / 2.0 + c.avoidme or \
abs(ycntr_n - ycntr_o) > NYPTS / 2.0 + c.avoidme:
NotFitNeigh = 1
if(abs(xcntr_n - xcntr_o) <= (major_axis + maj_axis) * \
threshold and \
abs(ycntr_n - ycntr_o) <= (major_axis + maj_axis) * \
threshold and area_n >= thresh_area * area_o and \
xcntr_n != xcntr_o and ycntr_n != ycntr_o and NotFitNeigh == 0):
if((xcntr_o - xcntr_n) < 0):
xn = xcntr + abs(xcntr_n - xcntr_o)
if((ycntr_o - ycntr_n) < 0):
yn = ycntr + abs(ycntr_n - ycntr_o)
if((xcntr_o - xcntr_n) > 0):
xn = xcntr - (xcntr_o - xcntr_n)
if((ycntr_o - ycntr_n) > 0):
yn = ycntr - (ycntr_o - ycntr_n)
ParamDict[AdComp] = {}
ParamDict[AdComp][1] = 'sersic'
ParamDict[AdComp][2] = [xn, yn]
ParamDict[AdComp][3] = mag
ParamDict[AdComp][4] = radius
ParamDict[AdComp][5] = 4.0
ParamDict[AdComp][6] = axis_rat
ParamDict[AdComp][7] = pos_ang
ParamDict[AdComp][8] = 0
ParamDict[AdComp][9] = 0
ParamDict[AdComp][11] = 'Other'
isneighbour = 1
AdComp += 1
except:
pass
f_constrain.close()
if isneighbour:
c.Flag = SetFlag(c.Flag, GetFlag('NEIGHBOUR_FIT'))
#Sky component
ParamDict[AdComp] = {}
ParamDict[AdComp][1] = 'sky'
ParamDict[AdComp][2] = sky
ParamDict[AdComp][3] = 0
ParamDict[AdComp][4] = 0
ParamDict[AdComp][5] = 0
ParamDict[AdComp][11] = 'Other'
#Write Sersic function
def SersicFunc(conffile, ParamDict, FitDict, No):
f=open(config_file, 'ab')
f.write('# Sersic function\n\n')
f.writelines([' 0) sersic \n'])
f.writelines([' 1) ', str(ParamDict[No][2][0]), ' ', \
str(ParamDict[No][2][1]), ' ', \
str(FitDict[No][1][0]), ' ', \
str(FitDict[No][1][1]), '\n'])
f.writelines([' 3) ', str(ParamDict[No][3]), ' ', \
str(FitDict[No][2]), '\n'])
f.writelines([' 4) ', str(ParamDict[No][4]), ' ', \
str(FitDict[No][3]), '\n'])
f.writelines([' 5) ', str(ParamDict[No][5]), ' ',\
str(FitDict[No][4]), '\n'])
f.writelines([' 8) ', str(ParamDict[No][6]), ' ', \
str(FitDict[No][5]), '\n'])
f.writelines([' 9) ', str(ParamDict[No][7]), ' ', \
str(FitDict[No][6]), '\n'])
if c.bdbox or c.bbox:
f.writelines(['10) 0.0 1 \n'])
else:
f.writelines(['10) 0.0 0 \n'])
f.writelines([' Z) 0 \n\n\n'])
f.close()
def ExpFunc(conffile, ParamDict, FitDict, No):
f=open(config_file, 'ab')
f.writelines(['# Exponential function\n\n'])
f.writelines([' 0) expdisk \n'])
f.writelines([' 1) ', str(ParamDict[No][2][0]), ' ', \
str(ParamDict[No][2][1]),' ', \
str(FitDict[No][1][0]), ' ', \
str(FitDict[No][1][1]), '\n'])
f.writelines([' 3) ', str(ParamDict[No][3]), ' ', \
str(FitDict[No][2]), '\n'])
f.writelines([' 4) ', str(ParamDict[No][4]), ' ', \
str(FitDict[No][3]), '\n'])
f.writelines([' 8) ', str(ParamDict[No][5]), ' ', \
str(FitDict[No][4]), '\n'])
f.writelines([' 9) ', str(ParamDict[No][6]), ' ', \
str(FitDict[No][5]), '\n'])
if c.bdbox or c.dbox:
f.writelines(['10) 0.0 1 \n'])
else:
f.writelines(['10) 0.0 0 \n'])
f.writelines([' Z) 0 \n\n\n'])
f.close()
def SkyFunc(conffile, ParamDict, FitDict, No):
f=open(config_file, 'ab')
f.writelines([' 0) sky\n'])
f.writelines([' 1) ', str(ParamDict[No][2]), \
' ', str(FitDict[No][1]), '\n'])
f.writelines([' 2) 0.000 0 \n',\
' 3) 0.000 0 \n',\
' Z) 0 \n\n\n'])
f.writelines(['# Neighbour sersic function\n\n'])
f.close()
def DecideFitting(ParamDict, No):
FitDict = {}
# print ParamDict
if No == 1:
for j in range(len(ParamDict)):
i = j + 1
FitDict[i] = {}
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'bar' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'expdisk' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
if ParamDict[i][1] == 'sky':
FitDict[i][1] = 1
FitDict[i][2] = 0
FitDict[i][3] = 0
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Other':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if No == 4:
for j in range(len(ParamDict)):
i = j + 1
FitDict[i] = {}
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 0
FitDict[i][5] = 0
FitDict[i][6] = 0
if ParamDict[i][1] == 'expdisk' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
if ParamDict[i][1] == 'sky':
FitDict[i][1] = 1
FitDict[i][2] = 0
FitDict[i][3] = 0
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Other':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
FitDict[i][6] = 0
if No == 3:
for j in range(len(ParamDict)):
i = j + 1
FitDict[i] = {}
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'bar' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'expdisk' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
if ParamDict[i][1] == 'sky':
FitDict[i][1] = 1
FitDict[i][2] = 0
FitDict[i][3] = 0
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Other':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
FitDict[i][6] = 0
if No == 2:
for j in range(len(ParamDict)):
i = j + 1
FitDict[i] = {}
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'bar' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 0
FitDict[i][6] = 0
if ParamDict[i][1] == 'expdisk' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
if ParamDict[i][1] == 'sky':
FitDict[i][1] = 1
FitDict[i][2] = 0
FitDict[i][3] = 0
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Other':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
FitDict[i][6] = 0
return FitDict
#Write configuration file. RunNo is the number of iteration
for RunNo in range(3):
f_constrain = open(constrain_file, 'w')
f_constrain.close()
f=open(config_file,'w')
f.write('# IMAGE PARAMETERS\n')
f.writelines(['A) ', str(cutimage), ' # Input data image',\
' (FITS file)\n'])
f.writelines(['B) ', str(outfile), ' # Name for',\
' the output image\n'])
f.writelines(['C) ', str(whtimage), ' # Noise image name', \
' (made from data if blank or "none")\n'])
f.writelines(['D) ', str(psffile), ' # Input PSF', \
' image for convolution (FITS file)\n'])
f.writelines(['E) 1 # PSF oversampling factor '\
|
[
" 'relative to data\\n'])"
] | 1,863
|
lcc
|
python
| null |
c19772b78b722854250c2ccf8a287dc2802417dbeafa7d23
| 80
|
Your task is code completion.
import os
import sys
import pyfits
import config as c
from os.path import exists
from numpy import log10
from readlog import ReadLog
from runsexfunc import *
from flagfunc import *
class ConfigIter:
"""The class making configuration file for GALFIT. The configuration file
consists of bulge and disk component of the object and only Sersic
component for the neighbours, if any. The sky is always fixed and has
the value of SExtractor. The disk/boxy parameter is also fixed to zero.
The initial value for Sersic index 'n' is 4.The configuration file has
the name G_string(galid).in. The output image has the name
O_string(galid).fits"""
def __init__(self, cutimage, whtimage, xcntr, ycntr, NXPTS, NYPTS, line_s, psffile):
self.cutimage = cutimage
self.line_s = line_s
self.whtimage = whtimage
self.xcntr = xcntr
self.ycntr = ycntr
self.NXPTS = NXPTS
self.NYPTS = NYPTS
self.psffile = psffile
self.confiter = confiter(cutimage, whtimage, xcntr, ycntr, NXPTS, NYPTS, line_s, psffile)
def confiter(cutimage, whtimage, xcntr, ycntr, NXPTS, NYPTS, line_s, psffile):
RunSex(cutimage, whtimage, 'TEMP.SEX.cat', 9999, 9999, 0)
imagefile = c.imagefile
sex_cata = 'TEMP.SEX.cat'
threshold = c.threshold
thresh_area = c.thresh_area
mask_reg = c.mask_reg
try:
ComP = c.components
except:
ComP = ['bulge', 'disk']
if len(ComP) == 0:
ComP = ['bulge', 'disk']
values = line_s.split()
outfile = 'O_' + c.fstring + '.fits'
mask_file = 'M_' + c.fstring + '.fits'
config_file = 'G_' + c.fstring + '.in' #Name of the GALFIT configuration file
constrain_file = c.fstring + '.con'
try:
c.center_constrain = c.center_constrain
except:
c.center_constrain = 2.0
def SersicMainConstrain(constrain_file, cO):
f_constrain = open(constrain_file, 'ab')
f_constrain.write(str(cO) + ' n ' + str(c.LN) + \
' to ' + str(c.UN) + '\n')
f_constrain.write(str(cO) + ' x ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' y ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' mag ' + str(c.UMag) + \
' to ' + str(c.LMag) + '\n')
f_constrain.write(str(cO) + ' re ' + str(c.LRe) +\
' to ' + str(c.URe) + '\n')
f_constrain.write(str(cO) + ' q 0.0 to 1.0\n')
f_constrain.write(str(cO) + ' pa -360.0 to 360.0\n')
f_constrain.close()
def BarConstrain(constrain_file, cO):
f_constrain = open(constrain_file, 'ab')
f_constrain.write(str(cO) + ' n ' + str('0.1') + \
' to ' + str('2.2') + '\n')
f_constrain.write(str(cO) + ' x ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' y ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' mag ' + str(c.UMag) + \
' to ' + str(c.LMag) + '\n')
f_constrain.write(str(cO) + ' re ' + str(c.LRe) +\
' to ' + str(c.URe) + '\n')
f_constrain.write(str(cO) + ' q 0.0 to 0.5\n')
f_constrain.write(str(cO) + ' pa -360.0 to 360.0\n')
f_constrain.close()
def ExpdiskConstrain(constrain_file, cO):
f_constrain = open(constrain_file, 'ab')
f_constrain.write(str(cO) + ' x ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' y ' + \
str(-c.center_constrain) + ' ' + \
str(c.center_constrain) + '\n')
f_constrain.write(str(cO) + ' mag ' + str(c.UMag) + \
' to ' + str(c.LMag) + '\n')
f_constrain.write(str(cO) + ' rs ' + str(c.LRd) + \
' to ' + str(c.URd) + '\n')
f_constrain.write(str(cO) + ' q 0.0 to 1.0\n')
f_constrain.write(str(cO) + ' pa -360.0 to 360.0\n')
f_constrain.close()
def SersicConstrain(constrain_file, cO):
f_constrain = open(constrain_file, 'ab')
f_constrain.write(str(cO) + ' n 0.02 to 20.0 \n')
f_constrain.write(str(cO) + ' mag -100.0 to 100.0\n')
f_constrain.write(str(cO) + ' re 0.0 to 500.0\n')
f_constrain.write(str(cO) + ' q 0.0 to 1.0\n')
f_constrain.write(str(cO) + ' pa -360.0 to 360.0\n')
f_constrain.close()
xcntr_o = xcntr #float(values[1]) #x center of the object
ycntr_o = ycntr #float(values[2]) #y center of the object
mag = float(values[7]) #Magnitude
radius = float(values[9]) #Half light radius
mag_zero = c.mag_zero #magnitude zero point
sky = float(values[10]) #sky
pos_ang = float(values[11]) - 90.0 #position angle
axis_rat = 1.0/float(values[12]) #axis ration b/a
area_o = float(values[13]) # object's area
major_axis = float(values[14]) #major axis of the object
ParamDict = {}
#Add components
AdComp = 1
if 'bulge' in ComP:
c.Flag = SetFlag(c.Flag, GetFlag('FIT_BULGE'))
ParamDict[AdComp] = {}
#Bulge Parameters
ParamDict[AdComp][1] = 'sersic'
ParamDict[AdComp][2] = [xcntr_o, ycntr_o]
ParamDict[AdComp][3] = mag
ParamDict[AdComp][4] = radius
ParamDict[AdComp][5] = 4.0
ParamDict[AdComp][6] = axis_rat
ParamDict[AdComp][7] = pos_ang
ParamDict[AdComp][8] = 0
ParamDict[AdComp][9] = 0
ParamDict[AdComp][11] = 'Main'
AdComp += 1
if 'bar' in ComP:
c.Flag = SetFlag(c.Flag, GetFlag('FIT_BAR'))
ParamDict[AdComp] = {}
#Bulge Parameters
ParamDict[AdComp][1] = 'bar'
ParamDict[AdComp][2] = [xcntr_o, ycntr_o]
ParamDict[AdComp][3] = mag + 2.5 * log10(2.0)
ParamDict[AdComp][4] = radius
ParamDict[AdComp][5] = 0.5
ParamDict[AdComp][6] = 0.3
ParamDict[AdComp][7] = pos_ang
ParamDict[AdComp][8] = 0
ParamDict[AdComp][9] = 0
ParamDict[AdComp][11] = 'Main'
AdComp += 1
if 'disk' in ComP:
c.Flag = SetFlag(c.Flag, GetFlag('FIT_DISK'))
#Disk parameters
ParamDict[AdComp] = {}
ParamDict[AdComp][1] = 'expdisk'
ParamDict[AdComp][2] = [xcntr_o, ycntr_o]
ParamDict[AdComp][3] = mag
ParamDict[AdComp][4] = radius
ParamDict[AdComp][5] = axis_rat
ParamDict[AdComp][6] = pos_ang
ParamDict[AdComp][7] = 0
ParamDict[AdComp][8] = 0
ParamDict[AdComp][11] = 'Main'
AdComp += 1
isneighbour = 0
f_constrain = open(constrain_file, 'ab')
for line_j in open(sex_cata,'r'):
try:
values = line_j.split()
xcntr_n = float(values[1]) #x center of the neighbour
ycntr_n = float(values[2]) #y center of the neighbour
mag = float(values[7]) #Magnitude
radius = float(values[9]) #Half light radius
sky = float(values[10]) #sky
pos_ang = float(values[11]) - 90.0 #position angle
axis_rat = 1.0/float(values[12]) #axis ration b/a
area_n = float(values[13]) # neighbour area
maj_axis = float(values[14])#major axis of neighbour
NotFitNeigh = 0
if abs(xcntr_n - xcntr_o) > NXPTS / 2.0 + c.avoidme or \
abs(ycntr_n - ycntr_o) > NYPTS / 2.0 + c.avoidme:
NotFitNeigh = 1
if(abs(xcntr_n - xcntr_o) <= (major_axis + maj_axis) * \
threshold and \
abs(ycntr_n - ycntr_o) <= (major_axis + maj_axis) * \
threshold and area_n >= thresh_area * area_o and \
xcntr_n != xcntr_o and ycntr_n != ycntr_o and NotFitNeigh == 0):
if((xcntr_o - xcntr_n) < 0):
xn = xcntr + abs(xcntr_n - xcntr_o)
if((ycntr_o - ycntr_n) < 0):
yn = ycntr + abs(ycntr_n - ycntr_o)
if((xcntr_o - xcntr_n) > 0):
xn = xcntr - (xcntr_o - xcntr_n)
if((ycntr_o - ycntr_n) > 0):
yn = ycntr - (ycntr_o - ycntr_n)
ParamDict[AdComp] = {}
ParamDict[AdComp][1] = 'sersic'
ParamDict[AdComp][2] = [xn, yn]
ParamDict[AdComp][3] = mag
ParamDict[AdComp][4] = radius
ParamDict[AdComp][5] = 4.0
ParamDict[AdComp][6] = axis_rat
ParamDict[AdComp][7] = pos_ang
ParamDict[AdComp][8] = 0
ParamDict[AdComp][9] = 0
ParamDict[AdComp][11] = 'Other'
isneighbour = 1
AdComp += 1
except:
pass
f_constrain.close()
if isneighbour:
c.Flag = SetFlag(c.Flag, GetFlag('NEIGHBOUR_FIT'))
#Sky component
ParamDict[AdComp] = {}
ParamDict[AdComp][1] = 'sky'
ParamDict[AdComp][2] = sky
ParamDict[AdComp][3] = 0
ParamDict[AdComp][4] = 0
ParamDict[AdComp][5] = 0
ParamDict[AdComp][11] = 'Other'
#Write Sersic function
def SersicFunc(conffile, ParamDict, FitDict, No):
f=open(config_file, 'ab')
f.write('# Sersic function\n\n')
f.writelines([' 0) sersic \n'])
f.writelines([' 1) ', str(ParamDict[No][2][0]), ' ', \
str(ParamDict[No][2][1]), ' ', \
str(FitDict[No][1][0]), ' ', \
str(FitDict[No][1][1]), '\n'])
f.writelines([' 3) ', str(ParamDict[No][3]), ' ', \
str(FitDict[No][2]), '\n'])
f.writelines([' 4) ', str(ParamDict[No][4]), ' ', \
str(FitDict[No][3]), '\n'])
f.writelines([' 5) ', str(ParamDict[No][5]), ' ',\
str(FitDict[No][4]), '\n'])
f.writelines([' 8) ', str(ParamDict[No][6]), ' ', \
str(FitDict[No][5]), '\n'])
f.writelines([' 9) ', str(ParamDict[No][7]), ' ', \
str(FitDict[No][6]), '\n'])
if c.bdbox or c.bbox:
f.writelines(['10) 0.0 1 \n'])
else:
f.writelines(['10) 0.0 0 \n'])
f.writelines([' Z) 0 \n\n\n'])
f.close()
def ExpFunc(conffile, ParamDict, FitDict, No):
f=open(config_file, 'ab')
f.writelines(['# Exponential function\n\n'])
f.writelines([' 0) expdisk \n'])
f.writelines([' 1) ', str(ParamDict[No][2][0]), ' ', \
str(ParamDict[No][2][1]),' ', \
str(FitDict[No][1][0]), ' ', \
str(FitDict[No][1][1]), '\n'])
f.writelines([' 3) ', str(ParamDict[No][3]), ' ', \
str(FitDict[No][2]), '\n'])
f.writelines([' 4) ', str(ParamDict[No][4]), ' ', \
str(FitDict[No][3]), '\n'])
f.writelines([' 8) ', str(ParamDict[No][5]), ' ', \
str(FitDict[No][4]), '\n'])
f.writelines([' 9) ', str(ParamDict[No][6]), ' ', \
str(FitDict[No][5]), '\n'])
if c.bdbox or c.dbox:
f.writelines(['10) 0.0 1 \n'])
else:
f.writelines(['10) 0.0 0 \n'])
f.writelines([' Z) 0 \n\n\n'])
f.close()
def SkyFunc(conffile, ParamDict, FitDict, No):
f=open(config_file, 'ab')
f.writelines([' 0) sky\n'])
f.writelines([' 1) ', str(ParamDict[No][2]), \
' ', str(FitDict[No][1]), '\n'])
f.writelines([' 2) 0.000 0 \n',\
' 3) 0.000 0 \n',\
' Z) 0 \n\n\n'])
f.writelines(['# Neighbour sersic function\n\n'])
f.close()
def DecideFitting(ParamDict, No):
FitDict = {}
# print ParamDict
if No == 1:
for j in range(len(ParamDict)):
i = j + 1
FitDict[i] = {}
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'bar' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'expdisk' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
if ParamDict[i][1] == 'sky':
FitDict[i][1] = 1
FitDict[i][2] = 0
FitDict[i][3] = 0
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Other':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if No == 4:
for j in range(len(ParamDict)):
i = j + 1
FitDict[i] = {}
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 0
FitDict[i][5] = 0
FitDict[i][6] = 0
if ParamDict[i][1] == 'expdisk' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
if ParamDict[i][1] == 'sky':
FitDict[i][1] = 1
FitDict[i][2] = 0
FitDict[i][3] = 0
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Other':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
FitDict[i][6] = 0
if No == 3:
for j in range(len(ParamDict)):
i = j + 1
FitDict[i] = {}
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'bar' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'expdisk' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
if ParamDict[i][1] == 'sky':
FitDict[i][1] = 1
FitDict[i][2] = 0
FitDict[i][3] = 0
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Other':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
FitDict[i][6] = 0
if No == 2:
for j in range(len(ParamDict)):
i = j + 1
FitDict[i] = {}
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 1
FitDict[i][6] = 1
if ParamDict[i][1] == 'bar' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [1, 1]
FitDict[i][2] = 1
FitDict[i][3] = 1
FitDict[i][4] = 1
FitDict[i][5] = 0
FitDict[i][6] = 0
if ParamDict[i][1] == 'expdisk' and ParamDict[i][11] == 'Main':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
if ParamDict[i][1] == 'sky':
FitDict[i][1] = 1
FitDict[i][2] = 0
FitDict[i][3] = 0
if ParamDict[i][1] == 'sersic' and ParamDict[i][11] == 'Other':
FitDict[i][1] = [0, 0]
FitDict[i][2] = 0
FitDict[i][3] = 0
FitDict[i][4] = 0
FitDict[i][5] = 0
FitDict[i][6] = 0
return FitDict
#Write configuration file. RunNo is the number of iteration
for RunNo in range(3):
f_constrain = open(constrain_file, 'w')
f_constrain.close()
f=open(config_file,'w')
f.write('# IMAGE PARAMETERS\n')
f.writelines(['A) ', str(cutimage), ' # Input data image',\
' (FITS file)\n'])
f.writelines(['B) ', str(outfile), ' # Name for',\
' the output image\n'])
f.writelines(['C) ', str(whtimage), ' # Noise image name', \
' (made from data if blank or "none")\n'])
f.writelines(['D) ', str(psffile), ' # Input PSF', \
' image for convolution (FITS file)\n'])
f.writelines(['E) 1 # PSF oversampling factor '\
|
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 SersicFunc(conffile, ParamDict, FitDict, No):
f=open(config_file, 'ab')
f.writelines([' 0) sersic \n'])
f.writelines([' 1) ', str(ParamDict[No][2][0]), ' ', \
str(ParamDict[No][2][1]), ' ', \
str(FitDict[No][1][0]), ' ', \
str(FitDict[No][1][1]), '\n'])
f.writelines([' 3) ', str(ParamDict[No][3]), ' ', \
str(FitDict[No][2]), '\n'])
f.writelines([' 4) ', str(ParamDict[No][4]), ' ', \
str(FitDict[No][3]), '\n'])
f.writelines([' 5) ', str(ParamDict[No][5]), ' ',\
str(FitDict[No][4]), '\n'])
f.writelines([' 8) ', str(ParamDict[No][6]), ' ', \
str(FitDict[No][5]), '\n'])
f.writelines([' 9) ', str(ParamDict[No][7]), ' ', \
str(FitDict[No][6]), '\n'])
if c.bdbox or c.bbox:
f.writelines(['10) 0.0 1 \n'])
else:
f.writelines(['10) 0.0 0 \n'])
f.writelines([' Z) 0 \n\n\n'])
f.close()
Cheatsheet (for next line):
- We are in SersicFunc(), which is writing to a configuration file.
- The function is writing parameters for a Sersic function.
- The parameters are stored in ParamDict and FitDict dictionaries.
- The current line is writing the 9th parameter (index 7) of ParamDict and FitDict.
- The 9th parameter is a string (ParamDict[No][7]) and an integer (FitDict[No][6]).
- The next line should continue writing the configuration file.
Relevant lines: previous lines in SersicFunc(), ParamDict and FitDict dictionaries.
Next line will likely be: f.writelines([' Z) 0 \n\n\n'])
|
|
Please complete the code given below.
/*
This file is part of Arcadeflex.
Arcadeflex is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Arcadeflex 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 Arcadeflex. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ported to v0.37b7
* using automatic conversion tool v0.01
*/
package machine;
import static arcadeflex.fucPtr.WriteHandlerPtr;
import static arcadeflex.libc_v2.UBytePtr;
import static old.arcadeflex.osdepend.logerror;
import static old.mame.cpuintrfH.cpu_getpreviouspc;
import static old.vidhrdw.generic.videoram_w;
import static vidhrdw.segar.*;
public class segar {
public static abstract interface sega_decryptPtr {
public abstract void handler(int pc,/*unsinged*/ int[] lo);
}
public static sega_decryptPtr sega_decrypt;
public static UBytePtr segar_mem = new UBytePtr();
public static WriteHandlerPtr segar_w = new WriteHandlerPtr() {
public void handler(int offset, int data) {
int pc, op, page, off;
/*unsigned*/
int[] bad = new int[1];
off = offset;
pc = cpu_getpreviouspc();
if (pc != -1) {
op = segar_mem.read(pc) & 0xFF;
if (op == 0x32) {
bad[0] = offset & 0x00FF;
page = offset & 0xFF00;
(sega_decrypt).handler(pc, bad);
off = page | bad[0];
}
}
/* MWA_ROM */
if ((off >= 0x0000) && (off <= 0xC7FF)) {
;
} /* MWA_RAM */ else if ((off >= 0xC800) && (off <= 0xCFFF)) {
segar_mem.write(off, data);
} else if ((off >= 0xE000) && (off <= 0xE3FF)) {
videoram_w.handler(off - 0xE000, data);
} /* MWA_RAM */ else if ((off >= 0xE400) && (off <= 0xE7FF)) {
segar_mem.write(off, data);
} else if ((off >= 0xE800) && (off <= 0xEFFF)) {
segar_characterram_w.handler(off - 0xE800, data);
} else if ((off >= 0xF000) && (off <= 0xF03F)) {
segar_colortable_w.handler(off - 0xF000, data);
} else if ((off >= 0xF040) && (off <= 0xF07F)) {
segar_bcolortable_w.handler(off - 0xF040, data);
} /* MWA_RAM */ else if ((off >= 0xF080) && (off <= 0xF7FF)) {
segar_mem.write(off, data);
} else if ((off >= 0xF800) && (off <= 0xFFFF)) {
segar_characterram2_w.handler(off - 0xF800, data);
} else {
logerror("unmapped write at %04X:%02X\n", off, data);
}
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0062 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt62 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x03) {
case 0x00:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
case 0x01:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x02:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x03:
/* A */
i = b;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0063 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt63 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x09) {
case 0x00:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
case 0x01:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x08:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x09:
/* A */
i = b;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0064 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt64 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x03) {
case 0x00:
/* A */
i = b;
break;
case 0x01:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x02:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x03:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0070 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt70 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x09) {
case 0x00:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x01:
/* A */
i = b;
break;
case 0x08:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
case 0x09:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0076 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt76 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x09) {
case 0x00:
/* A */
i = b;
break;
case 0x01:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
|
[
" i += ((b & 0x08) << 2);"
] | 1,309
|
lcc
|
java
| null |
ce7af30933d25fa24c3982a8a49548083f6f94e48e102d6a
| 81
|
Your task is code completion.
/*
This file is part of Arcadeflex.
Arcadeflex is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Arcadeflex 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 Arcadeflex. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ported to v0.37b7
* using automatic conversion tool v0.01
*/
package machine;
import static arcadeflex.fucPtr.WriteHandlerPtr;
import static arcadeflex.libc_v2.UBytePtr;
import static old.arcadeflex.osdepend.logerror;
import static old.mame.cpuintrfH.cpu_getpreviouspc;
import static old.vidhrdw.generic.videoram_w;
import static vidhrdw.segar.*;
public class segar {
public static abstract interface sega_decryptPtr {
public abstract void handler(int pc,/*unsinged*/ int[] lo);
}
public static sega_decryptPtr sega_decrypt;
public static UBytePtr segar_mem = new UBytePtr();
public static WriteHandlerPtr segar_w = new WriteHandlerPtr() {
public void handler(int offset, int data) {
int pc, op, page, off;
/*unsigned*/
int[] bad = new int[1];
off = offset;
pc = cpu_getpreviouspc();
if (pc != -1) {
op = segar_mem.read(pc) & 0xFF;
if (op == 0x32) {
bad[0] = offset & 0x00FF;
page = offset & 0xFF00;
(sega_decrypt).handler(pc, bad);
off = page | bad[0];
}
}
/* MWA_ROM */
if ((off >= 0x0000) && (off <= 0xC7FF)) {
;
} /* MWA_RAM */ else if ((off >= 0xC800) && (off <= 0xCFFF)) {
segar_mem.write(off, data);
} else if ((off >= 0xE000) && (off <= 0xE3FF)) {
videoram_w.handler(off - 0xE000, data);
} /* MWA_RAM */ else if ((off >= 0xE400) && (off <= 0xE7FF)) {
segar_mem.write(off, data);
} else if ((off >= 0xE800) && (off <= 0xEFFF)) {
segar_characterram_w.handler(off - 0xE800, data);
} else if ((off >= 0xF000) && (off <= 0xF03F)) {
segar_colortable_w.handler(off - 0xF000, data);
} else if ((off >= 0xF040) && (off <= 0xF07F)) {
segar_bcolortable_w.handler(off - 0xF040, data);
} /* MWA_RAM */ else if ((off >= 0xF080) && (off <= 0xF7FF)) {
segar_mem.write(off, data);
} else if ((off >= 0xF800) && (off <= 0xFFFF)) {
segar_characterram2_w.handler(off - 0xF800, data);
} else {
logerror("unmapped write at %04X:%02X\n", off, data);
}
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0062 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt62 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x03) {
case 0x00:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
case 0x01:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x02:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x03:
/* A */
i = b;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0063 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt63 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x09) {
case 0x00:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
case 0x01:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x08:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x09:
/* A */
i = b;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0064 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt64 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x03) {
case 0x00:
/* A */
i = b;
break;
case 0x01:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x02:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x03:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0070 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt70 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x09) {
case 0x00:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x01:
/* A */
i = b;
break;
case 0x08:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
case 0x09:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0076 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt76 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x09) {
case 0x00:
/* A */
i = b;
break;
case 0x01:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
|
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]
public class segar {
public static abstract interface sega_decryptPtr {
public abstract void handler(int pc,/*unsinged*/ int[] lo);
}
public static sega_decryptPtr sega_decrypt;
public static UBytePtr segar_mem = new UBytePtr();
public static WriteHandlerPtr segar_w = new WriteHandlerPtr() {
public void handler(int offset, int data) {
int pc, op, page, off;
/*unsigned*/
int[] bad = new int[1];
off = offset;
pc = cpu_getpreviouspc();
if (pc != -1) {
op = segar_mem.read(pc) & 0xFF;
if (op == 0x32) {
bad[0] = offset & 0x00FF;
page = offset & 0xFF00;
(sega_decrypt).handler(pc, bad);
off = page | bad[0];
}
}
/* MWA_ROM */
if ((off >= 0x0000) && (off <= 0xC7FF)) {
;
} /* MWA_RAM */ else if ((off >= 0xC800) && (off <= 0xCFFF)) {
segar_mem.write(off, data);
} else if ((off >= 0xE000) && (off <= 0xE3FF)) {
videoram_w.handler(off - 0xE000, data);
} /* MWA_RAM */ else if ((off >= 0xE400) && (off <= 0xE7FF)) {
segar_mem.write(off, data);
} else if ((off >= 0xE800) && (off <= 0xEFFF)) {
segar_characterram_w.handler(off - 0xE800, data);
} else if ((off >= 0xF000) && (off <= 0xF03F)) {
segar_colortable_w.handler(off - 0xF000, data);
} else if ((off >= 0xF040) && (off <= 0xF07F)) {
segar_bcolortable_w.handler(off - 0xF040, data);
} /* MWA_RAM */ else if ((off >= 0xF080) && (off <= 0xF7FF)) {
segar_mem.write(off, data);
} else if ((off >= 0xF800) && (off <= 0xFFFF)) {
segar_characterram2_w.handler(off - 0xF800, data);
} else {
logerror("unmapped write at %04X:%02X\n", off, data);
}
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0062 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt62 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x03) {
case 0x00:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
case 0x01:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x02:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x03:
/* A */
i = b;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0063 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt63 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x09) {
case 0x00:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
case 0x01:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x08:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x09:
/* A */
i = b;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0064 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt64 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
/*unsigned*/
int i = 0;
/*unsigned*/
int b = lo[0];
switch (pc & 0x03) {
case 0x00:
/* A */
i = b;
break;
case 0x01:
/* B */
i = b & 0x03;
i += ((b & 0x80) >> 1);
i += ((b & 0x60) >> 3);
i += ((~b) & 0x10);
i += ((b & 0x08) << 2);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x02:
/* C */
i = b & 0x03;
i += ((b & 0x80) >> 4);
i += (((~b) & 0x40) >> 1);
i += ((b & 0x20) >> 1);
i += ((b & 0x10) >> 2);
i += ((b & 0x08) << 3);
i += ((b & 0x04) << 5);
i &= 0xFF;
break;
case 0x03:
/* D */
i = b & 0x23;
i += ((b & 0xC0) >> 4);
i += ((b & 0x10) << 2);
i += ((b & 0x08) << 1);
i += (((~b) & 0x04) << 5);
i &= 0xFF;
break;
}
lo[0] = i;
}
};
/**
* *************************************************************************
*/
/* MB 971025 - Emulate Sega G80 security chip 315-0070 */
/**
* *************************************************************************
*/
public static sega_decryptPtr sega_decrypt70 = new sega_decryptPtr() {
public void handler(int pc,/*unsinged*/ int[] lo) {
|
|
Please complete the code given below.
"""
Fixture to create a course and course components (XBlocks).
"""
import datetime
import json
import mimetypes
from collections import namedtuple
from textwrap import dedent
import six
from opaque_keys.edx.keys import CourseKey
from path import Path
from common.test.acceptance.fixtures import STUDIO_BASE_URL
from common.test.acceptance.fixtures.base import FixtureError, XBlockContainerFixture
class XBlockFixtureDesc(object):
"""
Description of an XBlock, used to configure a course fixture.
"""
def __init__(self, category, display_name, data=None,
metadata=None, grader_type=None, publish='make_public', **kwargs):
"""
Configure the XBlock to be created by the fixture.
These arguments have the same meaning as in the Studio REST API:
* `category`
* `display_name`
* `data`
* `metadata`
* `grader_type`
* `publish`
"""
self.category = category
self.display_name = display_name
self.data = data
self.metadata = metadata
self.grader_type = grader_type
self.publish = publish
self.children = []
self.locator = None
self.fields = kwargs
def add_children(self, *args):
"""
Add child XBlocks to this XBlock.
Each item in `args` is an `XBlockFixtureDesc` object.
Returns the `xblock_desc` instance to allow chaining.
"""
self.children.extend(args)
return self
def serialize(self):
"""
Return a JSON representation of the XBlock, suitable
for sending as POST data to /xblock
XBlocks are always set to public visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json.dumps(returned_data)
def __str__(self):
"""
Return a string representation of the description.
Useful for error messages.
"""
return dedent(u"""
<XBlockFixtureDescriptor:
category={0},
data={1},
metadata={2},
grader_type={3},
publish={4},
children={5},
locator={6},
>
""").strip().format(
self.category, self.data, self.metadata,
self.grader_type, self.publish, self.children, self.locator
)
# Description of course updates to add to the course
# `date` is a str (e.g. "January 29, 2014)
# `content` is also a str (e.g. "Test course")
CourseUpdateDesc = namedtuple("CourseUpdateDesc", ['date', 'content'])
class CourseFixture(XBlockContainerFixture):
"""
Fixture for ensuring that a course exists.
WARNING: This fixture is NOT idempotent. To avoid conflicts
between tests, you should use unique course identifiers for each fixture.
"""
def __init__(self, org, number, run, display_name, start_date=None, end_date=None, settings=None):
"""
Configure the course fixture to create a course with
`org`, `number`, `run`, and `display_name` (all unicode).
`start_date` and `end_date` are datetime objects indicating the course start and end date.
The default is for the course to have started in the distant past, which is generally what
we want for testing so students can enroll.
`settings` can be any additional course settings needs to be enabled. for example
to enable entrance exam settings would be a dict like this {"entrance_exam_enabled": "true"}
These have the same meaning as in the Studio restful API /course end-point.
"""
super(CourseFixture, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self._course_dict = {
'org': org,
'number': number,
'run': run,
'display_name': display_name
}
# Set a default start date to the past, but use Studio's
# default for the end date (meaning we don't set it here)
if start_date is None:
start_date = datetime.datetime(1970, 1, 1)
self._course_details = {
'start_date': start_date.isoformat(),
}
if end_date is not None:
self._course_details['end_date'] = end_date.isoformat()
if settings is not None:
self._course_details.update(settings)
self._updates = []
self._handouts = []
self._assets = []
self._textbooks = []
self._advanced_settings = {}
self._course_key = None
def __str__(self):
"""
String representation of the course fixture, useful for debugging.
"""
return u"<CourseFixture: org='{org}', number='{number}', run='{run}'>".format(**self._course_dict)
def add_course_details(self, course_details):
"""
Add course details to dict of course details to be updated when configure_course or install is called.
Arguments:
Dictionary containing key value pairs for course updates,
e.g. {'start_date': datetime.now() }
"""
if 'start_date' in course_details:
course_details['start_date'] = course_details['start_date'].isoformat()
if 'end_date' in course_details:
course_details['end_date'] = course_details['end_date'].isoformat()
self._course_details.update(course_details)
def add_update(self, update):
"""
Add an update to the course. `update` should be a `CourseUpdateDesc`.
"""
self._updates.append(update)
def add_handout(self, asset_name):
"""
Add the handout named `asset_name` to the course info page.
Note that this does not actually *create* the static asset; it only links to it.
"""
self._handouts.append(asset_name)
def add_asset(self, asset_name):
"""
Add the asset to the list of assets to be uploaded when the install method is called.
"""
self._assets.extend(asset_name)
def add_textbook(self, book_title, chapters):
"""
Add textbook to the list of textbooks to be added when the install method is called.
"""
self._textbooks.append({"chapters": chapters, "tab_title": book_title})
def add_advanced_settings(self, settings):
"""
Adds advanced settings to be set on the course when the install method is called.
"""
self._advanced_settings.update(settings)
def install(self):
"""
Create the course and XBlocks within the course.
This is NOT an idempotent method; if the course already exists, this will
raise a `FixtureError`. You should use unique course identifiers to avoid
conflicts between tests.
"""
self._create_course()
self._install_course_updates()
self._install_course_handouts()
self._install_course_textbooks()
self._configure_course()
self._upload_assets()
self._add_advanced_settings()
self._create_xblock_children(self._course_location, self.children)
return self
def configure_course(self):
"""
Configure Course Settings, take new course settings from self._course_details dict object
"""
self._configure_course()
@property
def studio_course_outline_as_json(self):
"""
Retrieves Studio course outline in JSON format.
"""
url = STUDIO_BASE_URL + '/course/' + self._course_key + "?format=json"
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course outline json. Status was {0}".format(
response.status_code))
try:
course_outline_json = response.json()
except ValueError:
raise FixtureError( # lint-amnesty, pylint: disable=raise-missing-from
u"Could not decode course outline as JSON: '{0}'".format(response)
)
return course_outline_json
@property
def _course_location(self):
"""
Return the locator string for the course.
"""
|
[
" course_key = CourseKey.from_string(self._course_key)"
] | 824
|
lcc
|
python
| null |
09ae4ef8effb51b554602ffbe68a496389bb548ebc5983ad
| 82
|
Your task is code completion.
"""
Fixture to create a course and course components (XBlocks).
"""
import datetime
import json
import mimetypes
from collections import namedtuple
from textwrap import dedent
import six
from opaque_keys.edx.keys import CourseKey
from path import Path
from common.test.acceptance.fixtures import STUDIO_BASE_URL
from common.test.acceptance.fixtures.base import FixtureError, XBlockContainerFixture
class XBlockFixtureDesc(object):
"""
Description of an XBlock, used to configure a course fixture.
"""
def __init__(self, category, display_name, data=None,
metadata=None, grader_type=None, publish='make_public', **kwargs):
"""
Configure the XBlock to be created by the fixture.
These arguments have the same meaning as in the Studio REST API:
* `category`
* `display_name`
* `data`
* `metadata`
* `grader_type`
* `publish`
"""
self.category = category
self.display_name = display_name
self.data = data
self.metadata = metadata
self.grader_type = grader_type
self.publish = publish
self.children = []
self.locator = None
self.fields = kwargs
def add_children(self, *args):
"""
Add child XBlocks to this XBlock.
Each item in `args` is an `XBlockFixtureDesc` object.
Returns the `xblock_desc` instance to allow chaining.
"""
self.children.extend(args)
return self
def serialize(self):
"""
Return a JSON representation of the XBlock, suitable
for sending as POST data to /xblock
XBlocks are always set to public visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json.dumps(returned_data)
def __str__(self):
"""
Return a string representation of the description.
Useful for error messages.
"""
return dedent(u"""
<XBlockFixtureDescriptor:
category={0},
data={1},
metadata={2},
grader_type={3},
publish={4},
children={5},
locator={6},
>
""").strip().format(
self.category, self.data, self.metadata,
self.grader_type, self.publish, self.children, self.locator
)
# Description of course updates to add to the course
# `date` is a str (e.g. "January 29, 2014)
# `content` is also a str (e.g. "Test course")
CourseUpdateDesc = namedtuple("CourseUpdateDesc", ['date', 'content'])
class CourseFixture(XBlockContainerFixture):
"""
Fixture for ensuring that a course exists.
WARNING: This fixture is NOT idempotent. To avoid conflicts
between tests, you should use unique course identifiers for each fixture.
"""
def __init__(self, org, number, run, display_name, start_date=None, end_date=None, settings=None):
"""
Configure the course fixture to create a course with
`org`, `number`, `run`, and `display_name` (all unicode).
`start_date` and `end_date` are datetime objects indicating the course start and end date.
The default is for the course to have started in the distant past, which is generally what
we want for testing so students can enroll.
`settings` can be any additional course settings needs to be enabled. for example
to enable entrance exam settings would be a dict like this {"entrance_exam_enabled": "true"}
These have the same meaning as in the Studio restful API /course end-point.
"""
super(CourseFixture, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self._course_dict = {
'org': org,
'number': number,
'run': run,
'display_name': display_name
}
# Set a default start date to the past, but use Studio's
# default for the end date (meaning we don't set it here)
if start_date is None:
start_date = datetime.datetime(1970, 1, 1)
self._course_details = {
'start_date': start_date.isoformat(),
}
if end_date is not None:
self._course_details['end_date'] = end_date.isoformat()
if settings is not None:
self._course_details.update(settings)
self._updates = []
self._handouts = []
self._assets = []
self._textbooks = []
self._advanced_settings = {}
self._course_key = None
def __str__(self):
"""
String representation of the course fixture, useful for debugging.
"""
return u"<CourseFixture: org='{org}', number='{number}', run='{run}'>".format(**self._course_dict)
def add_course_details(self, course_details):
"""
Add course details to dict of course details to be updated when configure_course or install is called.
Arguments:
Dictionary containing key value pairs for course updates,
e.g. {'start_date': datetime.now() }
"""
if 'start_date' in course_details:
course_details['start_date'] = course_details['start_date'].isoformat()
if 'end_date' in course_details:
course_details['end_date'] = course_details['end_date'].isoformat()
self._course_details.update(course_details)
def add_update(self, update):
"""
Add an update to the course. `update` should be a `CourseUpdateDesc`.
"""
self._updates.append(update)
def add_handout(self, asset_name):
"""
Add the handout named `asset_name` to the course info page.
Note that this does not actually *create* the static asset; it only links to it.
"""
self._handouts.append(asset_name)
def add_asset(self, asset_name):
"""
Add the asset to the list of assets to be uploaded when the install method is called.
"""
self._assets.extend(asset_name)
def add_textbook(self, book_title, chapters):
"""
Add textbook to the list of textbooks to be added when the install method is called.
"""
self._textbooks.append({"chapters": chapters, "tab_title": book_title})
def add_advanced_settings(self, settings):
"""
Adds advanced settings to be set on the course when the install method is called.
"""
self._advanced_settings.update(settings)
def install(self):
"""
Create the course and XBlocks within the course.
This is NOT an idempotent method; if the course already exists, this will
raise a `FixtureError`. You should use unique course identifiers to avoid
conflicts between tests.
"""
self._create_course()
self._install_course_updates()
self._install_course_handouts()
self._install_course_textbooks()
self._configure_course()
self._upload_assets()
self._add_advanced_settings()
self._create_xblock_children(self._course_location, self.children)
return self
def configure_course(self):
"""
Configure Course Settings, take new course settings from self._course_details dict object
"""
self._configure_course()
@property
def studio_course_outline_as_json(self):
"""
Retrieves Studio course outline in JSON format.
"""
url = STUDIO_BASE_URL + '/course/' + self._course_key + "?format=json"
response = self.session.get(url, headers=self.headers)
if not response.ok:
raise FixtureError(
u"Could not retrieve course outline json. Status was {0}".format(
response.status_code))
try:
course_outline_json = response.json()
except ValueError:
raise FixtureError( # lint-amnesty, pylint: disable=raise-missing-from
u"Could not decode course outline as JSON: '{0}'".format(response)
)
return course_outline_json
@property
def _course_location(self):
"""
Return the locator string for the course.
"""
|
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 task:
Context:
[Previous code... ~10,000 lines omitted for brevity]
def _create_course(self):
# ... (course creation code)
def _install_course_updates(self):
# ... (update installation code)
def _install_course_handouts(self):
# ... (handout installation code)
def _install_course_textbooks(self):
# ... (textbook installation code)
def _configure_course(self):
# ... (course configuration code)
def _upload_assets(self):
# ... (asset upload code)
def _add_advanced_settings(self):
# ... (advanced settings addition code)
def _create_xblock_children(self, location, children):
# ... (XBlock creation code)
def configure_course(self):
# ... (course configuration code)
@property
def studio_course_outline_as_json(self):
# ... (course outline retrieval code)
@property
def _course_location(self):
# ... (course location retrieval code)
Relevant lines/variables:
- `_create_course()`, `_install_course_updates()`, `_install_course_handouts()`, `_install_course_textbooks()`, `_configure_course()`, `_upload_assets()`, `_add_advanced_settings()`, `_create_xblock_children()`, `configure_course()`, `studio_course_outline_as_json`, `_course_location`
- `self._course_key` (property of CourseFixture class)
Task: Complete the implementation of the `_course_location` property.
Cheatsheet:
- The `_course_location` property is used to return the locator string for the course.
- The course key is stored in `self._course_key`.
- The course key is a CourseKey object, which is a type of opaque key.
- The locator string is likely a string representation of the course key.
Next line will likely be:
```python
return str(self._course_key)
```
|
|
Please complete the code given below.
package de.tink.minecraft.plugin.safari;
/*
Copyright (C) 2012 Thomas Starl
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
public class SafariEventListener implements Listener {
SafariPlugin plugin;
private String SAFARI_FINISHED = "Congratulations, you have successfully completed this safari!";
private String SAFARI_KILL_COUNTS = "This kill is counting for your current safari! ?1/?2 mobs killed.";
private String SAFARI_DROPS_MESSAGES = "Your reward for the completed safari:";
private String SAFARI_PLAYER_CREATED_NEW_RECORD_FEEDBACK = "You scored a new record for this safari!";
private String SAFARI_PLAYER_CREATED_NEW_RECORD_WORLDSAY = "Congratulations! ?1 managed to complete the \"?2\" safari within a new record-time of: ?3!";
@EventHandler
public void onMobKill(EntityDeathEvent deathEvent) {
LivingEntity killedMob = deathEvent.getEntity();
EntityType killedMobType = deathEvent.getEntityType();
Player player = killedMob.getKiller();
if ( player == null ) {
return;
}
Configuration playerConfig = plugin.getPlayerConfig();
Configuration safariConfig = plugin.getConfig();
Configuration groupsConfig = plugin.getGroupsConfig();
ConfigurationSection registeredPlayerSection = null;
boolean playerIsInSafari = false;
boolean killedByPlayer = false;
boolean killIsInSafariTimeframe = false;
boolean safariIsFulfilled = false;
boolean newRecordForSafari = false;
Long duration = null;
String basePath = null;
if ( player != null ) {
killedByPlayer = true;
registeredPlayerSection = playerConfig.getConfigurationSection("registered_players."+player.getName());
}
if ( registeredPlayerSection != null ) {
playerIsInSafari = true;
}
String currentSafari = playerConfig.getString("registered_players."+player.getName()+".safari");
// check Safari Config for Night/Day Config
killIsInSafariTimeframe = false;
Long currentHourLong = (player.getWorld().getFullTime())/1000;
Integer currentHour = (Integer) currentHourLong.intValue();
List<String> safariHours = safariConfig.getStringList("safaris."+currentSafari+".valid_hours");
if ( safariHours == null || ( safariHours != null && safariHours.size() == 0 ) ) {
killIsInSafariTimeframe = true;
} else {
for ( String safariHour : safariHours ) {
Integer safariHourInt = Integer.parseInt(safariHour);
if ( safariHourInt == currentHour ) {
killIsInSafariTimeframe = true;
}
}
}
/*
* Skip/ignore the kill if
* a) the killing player is not registered for a safari
* or
* b) the mob was not killed by a player
* or
* c) the Safari is bound to a given Timeframe (e.g.: day, night, dusk, dawn)
*/
if ( !killedByPlayer || !playerIsInSafari || !killIsInSafariTimeframe ) {
return;
}
Integer currentSafariMobsToKill = playerConfig.getInt("registered_players."+player.getName()+".mobs_to_kill");
Integer currentSafariMobsKilled = playerConfig.getInt("registered_players."+player.getName()+".mobs_killed");
if ( currentSafariMobsKilled == null ) {
currentSafariMobsKilled = 0;
}
String mobKey = "safaris."+currentSafari+".types_of_mobs_to_kill";
List<String> relevantMobs = safariConfig.getStringList(mobKey);
boolean isRelevantMob = false;
for (String mobToKill : relevantMobs ) {
if ( "ANY".equals(mobToKill) || killedMobType.getName().toLowerCase().equals(mobToKill.toLowerCase())) {
isRelevantMob = true;
}
}
// add 1 to mobs_killed
if ( isRelevantMob ) {
currentSafariMobsKilled++;
playerConfig.set("registered_players."+player.getName()+".mobs_killed",currentSafariMobsKilled);
player.sendMessage(SAFARI_KILL_COUNTS.replace("?1", currentSafariMobsKilled.toString()).replace("?2",currentSafariMobsToKill.toString()));
plugin.savePlayerConfig();
if ( currentSafariMobsKilled == currentSafariMobsToKill ) {
player.sendMessage(SAFARI_FINISHED);
player.sendMessage(SAFARI_DROPS_MESSAGES);
basePath = "safaris."+currentSafari;
// should we add drops?
ConfigurationSection addDropsSection = safariConfig.getConfigurationSection(basePath + ".addDrops");
if ( addDropsSection != null ){
Set<String> addDrops = addDropsSection.getKeys(false);
List<ItemStack> drops = deathEvent.getDrops();
for(String drop : addDrops) {
String amount = plugin.getConfig().getString(basePath + ".addDrops." + drop);
int itemAmount = parseInt(amount);
if(itemAmount > 0) {
ItemStack newDrop = new ItemStack(Integer.parseInt(drop), itemAmount);
drops.add(newDrop);
}
}
}
// calculate time needed to complete the safari and check for new record
Long safariStartedAt = playerConfig.getLong("registered_players."+player.getName()+".safari_started");
if ( safariStartedAt == null ) {
safariStartedAt = 0L;
}
Long currentSafariRecordTime = safariConfig.getLong("safaris."+ currentSafari + ".current_recordtime");
if ( currentSafariRecordTime == null ) {
currentSafariRecordTime = 0L;
}
Long now = (new Date()).getTime();
duration = now - safariStartedAt;
// Yippie, new record achieved!
if ( duration < currentSafariRecordTime || currentSafariRecordTime == 0 ) {
newRecordForSafari = true;
}
safariIsFulfilled = true;
}
}
if ( newRecordForSafari ) {
safariConfig.set("safaris."+ currentSafari + ".current_recordtime",duration);
safariConfig.set("safaris."+ currentSafari + ".current_recordholder",player.getName());
plugin.saveConfig();
int minutes = (int) ((duration / (1000*60)) % 60);
int hours = (int) ((duration / (1000*60*60)) % 24);
String durationString = hours+":"+minutes;
player.sendMessage(ChatColor.BLUE+SAFARI_PLAYER_CREATED_NEW_RECORD_FEEDBACK);
plugin.getServer().broadcastMessage(ChatColor.BLUE+SAFARI_PLAYER_CREATED_NEW_RECORD_WORLDSAY.replace("?1",player.getName()).replace("?2", currentSafari).replace("?3",durationString));
ConfigurationSection addDropsSection = safariConfig.getConfigurationSection(basePath + ".addRecordDrops");
if ( addDropsSection != null ){
Set<String> addDrops = addDropsSection.getKeys(false);
List<ItemStack> drops = deathEvent.getDrops();
for(String drop : addDrops) {
String amount = plugin.getConfig().getString(basePath + ".addRecordDrops." + drop);
int itemAmount = parseInt(amount);
if(itemAmount > 0) {
ItemStack newDrop = new ItemStack(Integer.parseInt(drop), itemAmount);
drops.add(newDrop);
}
}
}
}
if ( safariIsFulfilled ) {
plugin.fulfillSafari(player);
}
}
/*
* Used to determine/calculate the drop(s) for the accomplished Safari
* thanks to metakiwi: http://dev.bukkit.org/profiles/metakiwi/
* for this nice piece of code which evolved from his
* "LessFood" Plugin: http://dev.bukkit.org/server-mods/lessfood/
*
*/
private int parseInt(String number) {
if(number == null) return 0;
String[] splitNumber = number.split(" ");
float chance=100;
|
[
"\t\tint min = -1;"
] | 803
|
lcc
|
java
| null |
56d619ed99235ddf5394f3518b191a845301a65eebac5d5e
| 83
|
Your task is code completion.
package de.tink.minecraft.plugin.safari;
/*
Copyright (C) 2012 Thomas Starl
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
public class SafariEventListener implements Listener {
SafariPlugin plugin;
private String SAFARI_FINISHED = "Congratulations, you have successfully completed this safari!";
private String SAFARI_KILL_COUNTS = "This kill is counting for your current safari! ?1/?2 mobs killed.";
private String SAFARI_DROPS_MESSAGES = "Your reward for the completed safari:";
private String SAFARI_PLAYER_CREATED_NEW_RECORD_FEEDBACK = "You scored a new record for this safari!";
private String SAFARI_PLAYER_CREATED_NEW_RECORD_WORLDSAY = "Congratulations! ?1 managed to complete the \"?2\" safari within a new record-time of: ?3!";
@EventHandler
public void onMobKill(EntityDeathEvent deathEvent) {
LivingEntity killedMob = deathEvent.getEntity();
EntityType killedMobType = deathEvent.getEntityType();
Player player = killedMob.getKiller();
if ( player == null ) {
return;
}
Configuration playerConfig = plugin.getPlayerConfig();
Configuration safariConfig = plugin.getConfig();
Configuration groupsConfig = plugin.getGroupsConfig();
ConfigurationSection registeredPlayerSection = null;
boolean playerIsInSafari = false;
boolean killedByPlayer = false;
boolean killIsInSafariTimeframe = false;
boolean safariIsFulfilled = false;
boolean newRecordForSafari = false;
Long duration = null;
String basePath = null;
if ( player != null ) {
killedByPlayer = true;
registeredPlayerSection = playerConfig.getConfigurationSection("registered_players."+player.getName());
}
if ( registeredPlayerSection != null ) {
playerIsInSafari = true;
}
String currentSafari = playerConfig.getString("registered_players."+player.getName()+".safari");
// check Safari Config for Night/Day Config
killIsInSafariTimeframe = false;
Long currentHourLong = (player.getWorld().getFullTime())/1000;
Integer currentHour = (Integer) currentHourLong.intValue();
List<String> safariHours = safariConfig.getStringList("safaris."+currentSafari+".valid_hours");
if ( safariHours == null || ( safariHours != null && safariHours.size() == 0 ) ) {
killIsInSafariTimeframe = true;
} else {
for ( String safariHour : safariHours ) {
Integer safariHourInt = Integer.parseInt(safariHour);
if ( safariHourInt == currentHour ) {
killIsInSafariTimeframe = true;
}
}
}
/*
* Skip/ignore the kill if
* a) the killing player is not registered for a safari
* or
* b) the mob was not killed by a player
* or
* c) the Safari is bound to a given Timeframe (e.g.: day, night, dusk, dawn)
*/
if ( !killedByPlayer || !playerIsInSafari || !killIsInSafariTimeframe ) {
return;
}
Integer currentSafariMobsToKill = playerConfig.getInt("registered_players."+player.getName()+".mobs_to_kill");
Integer currentSafariMobsKilled = playerConfig.getInt("registered_players."+player.getName()+".mobs_killed");
if ( currentSafariMobsKilled == null ) {
currentSafariMobsKilled = 0;
}
String mobKey = "safaris."+currentSafari+".types_of_mobs_to_kill";
List<String> relevantMobs = safariConfig.getStringList(mobKey);
boolean isRelevantMob = false;
for (String mobToKill : relevantMobs ) {
if ( "ANY".equals(mobToKill) || killedMobType.getName().toLowerCase().equals(mobToKill.toLowerCase())) {
isRelevantMob = true;
}
}
// add 1 to mobs_killed
if ( isRelevantMob ) {
currentSafariMobsKilled++;
playerConfig.set("registered_players."+player.getName()+".mobs_killed",currentSafariMobsKilled);
player.sendMessage(SAFARI_KILL_COUNTS.replace("?1", currentSafariMobsKilled.toString()).replace("?2",currentSafariMobsToKill.toString()));
plugin.savePlayerConfig();
if ( currentSafariMobsKilled == currentSafariMobsToKill ) {
player.sendMessage(SAFARI_FINISHED);
player.sendMessage(SAFARI_DROPS_MESSAGES);
basePath = "safaris."+currentSafari;
// should we add drops?
ConfigurationSection addDropsSection = safariConfig.getConfigurationSection(basePath + ".addDrops");
if ( addDropsSection != null ){
Set<String> addDrops = addDropsSection.getKeys(false);
List<ItemStack> drops = deathEvent.getDrops();
for(String drop : addDrops) {
String amount = plugin.getConfig().getString(basePath + ".addDrops." + drop);
int itemAmount = parseInt(amount);
if(itemAmount > 0) {
ItemStack newDrop = new ItemStack(Integer.parseInt(drop), itemAmount);
drops.add(newDrop);
}
}
}
// calculate time needed to complete the safari and check for new record
Long safariStartedAt = playerConfig.getLong("registered_players."+player.getName()+".safari_started");
if ( safariStartedAt == null ) {
safariStartedAt = 0L;
}
Long currentSafariRecordTime = safariConfig.getLong("safaris."+ currentSafari + ".current_recordtime");
if ( currentSafariRecordTime == null ) {
currentSafariRecordTime = 0L;
}
Long now = (new Date()).getTime();
duration = now - safariStartedAt;
// Yippie, new record achieved!
if ( duration < currentSafariRecordTime || currentSafariRecordTime == 0 ) {
newRecordForSafari = true;
}
safariIsFulfilled = true;
}
}
if ( newRecordForSafari ) {
safariConfig.set("safaris."+ currentSafari + ".current_recordtime",duration);
safariConfig.set("safaris."+ currentSafari + ".current_recordholder",player.getName());
plugin.saveConfig();
int minutes = (int) ((duration / (1000*60)) % 60);
int hours = (int) ((duration / (1000*60*60)) % 24);
String durationString = hours+":"+minutes;
player.sendMessage(ChatColor.BLUE+SAFARI_PLAYER_CREATED_NEW_RECORD_FEEDBACK);
plugin.getServer().broadcastMessage(ChatColor.BLUE+SAFARI_PLAYER_CREATED_NEW_RECORD_WORLDSAY.replace("?1",player.getName()).replace("?2", currentSafari).replace("?3",durationString));
ConfigurationSection addDropsSection = safariConfig.getConfigurationSection(basePath + ".addRecordDrops");
if ( addDropsSection != null ){
Set<String> addDrops = addDropsSection.getKeys(false);
List<ItemStack> drops = deathEvent.getDrops();
for(String drop : addDrops) {
String amount = plugin.getConfig().getString(basePath + ".addRecordDrops." + drop);
int itemAmount = parseInt(amount);
if(itemAmount > 0) {
ItemStack newDrop = new ItemStack(Integer.parseInt(drop), itemAmount);
drops.add(newDrop);
}
}
}
}
if ( safariIsFulfilled ) {
plugin.fulfillSafari(player);
}
}
/*
* Used to determine/calculate the drop(s) for the accomplished Safari
* thanks to metakiwi: http://dev.bukkit.org/profiles/metakiwi/
* for this nice piece of code which evolved from his
* "LessFood" Plugin: http://dev.bukkit.org/server-mods/lessfood/
*
*/
private int parseInt(String number) {
if(number == null) return 0;
String[] splitNumber = number.split(" ");
float chance=100;
|
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]
public class SafariEventListener implements Listener {
// ...
private int parseInt(String number) {
if(number == null) return 0;
String[] splitNumber = number.split(" ");
float chance=100;
// [Current line]
// [Relevant lines: parseInt method declaration, splitNumber array]
The task is to complete the parseInt method. The method is supposed to parse a string into an integer. The current implementation splits the string by spaces and does not use the splitNumber array. The relevant lines are the method declaration and the splitNumber array.
Cheatsheet:
- The parseInt method is supposed to parse a string into an integer.
- The method takes a string as input and returns an integer.
- The current implementation splits the string by spaces but does not use the splitNumber array.
- The method should handle the case where the input string is null.
- The method should handle the case where the input string is not a valid integer.
Next line will likely be:
- The method should use the splitNumber array to parse the string into an integer.
- The method should handle the case where the input string is not a valid integer.
Here are a few possible completions:
```java
private int parseInt(String number) {
if(number == null) return 0;
String[] splitNumber = number.split(" ");
float chance=100;
if (splitNumber.length > 0) {
try {
return Integer.parseInt(splitNumber[0]);
} catch (NumberFormatException e) {
return 0;
}
} else {
return 0;
}
}
```
Or
```java
private int parseInt(String number) {
if(number == null) return 0;
String[] splitNumber = number.split(" ");
float chance=100;
if (splitNumber.length > 0) {
return Integer.parseInt(splitNumber[0]);
} else {
return 0;
}
}
```
Or
```java
private int parseInt(String number) {
if(number == null) return 0;
String[] splitNumber = number.split(" ");
float chance=100;
try {
return Integer.parseInt(number);
} catch (NumberFormatException e) {
return 0;
}
}
```
Please let me know which one is the correct completion or if I need to make any adjustments.
|
|
Please complete the code given below.
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to add boundary meters.
(c) 2013, curtis <curtis@serverascode.com>
This file is part of Ansible
Ansible is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
"""
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
module: boundary_meter
short_description: Manage boundary meters
description:
- This module manages boundary meters
version_added: "1.3"
author: "curtis (@ccollicutt)"
requirements:
- Boundary API access
- bprobe is required to send data, but not to register a meter
options:
name:
description:
- meter name
required: true
state:
description:
- Whether to create or remove the client from boundary
required: false
default: true
choices: ["present", "absent"]
apiid:
description:
- Organizations boundary API ID
required: true
apikey:
description:
- Organizations boundary API KEY
required: true
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used
on personally controlled sites using self-signed certificates.
required: false
default: 'yes'
choices: ['yes', 'no']
version_added: 1.5.1
notes:
- This module does not yet support boundary tags.
'''
EXAMPLES='''
- name: Create meter
boundary_meter:
apiid: AAAAAA
apikey: BBBBBB
state: present
name: '{{ inventory_hostname }}'
- name: Delete meter
boundary_meter:
apiid: AAAAAA
apikey: BBBBBB
state: absent
name: '{{ inventory_hostname }}'
'''
import base64
import os
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
api_host = "api.boundary.com"
config_directory = "/etc/bprobe"
# "resource" like thing or apikey?
def auth_encode(apikey):
auth = base64.standard_b64encode(apikey)
auth.replace("\n", "")
return auth
def build_url(name, apiid, action, meter_id=None, cert_type=None):
if action == "create":
return 'https://%s/%s/meters' % (api_host, apiid)
elif action == "search":
return "https://%s/%s/meters?name=%s" % (api_host, apiid, name)
elif action == "certificates":
return "https://%s/%s/meters/%s/%s.pem" % (api_host, apiid, meter_id, cert_type)
elif action == "tags":
return "https://%s/%s/meters/%s/tags" % (api_host, apiid, meter_id)
elif action == "delete":
return "https://%s/%s/meters/%s" % (api_host, apiid, meter_id)
def http_request(module, name, apiid, apikey, action, data=None, meter_id=None, cert_type=None):
if meter_id is None:
url = build_url(name, apiid, action)
else:
if cert_type is None:
url = build_url(name, apiid, action, meter_id)
else:
url = build_url(name, apiid, action, meter_id, cert_type)
headers = dict()
headers["Authorization"] = "Basic %s" % auth_encode(apikey)
headers["Content-Type"] = "application/json"
return fetch_url(module, url, data=data, headers=headers)
def create_meter(module, name, apiid, apikey):
meters = search_meter(module, name, apiid, apikey)
if len(meters) > 0:
# If the meter already exists, do nothing
module.exit_json(status="Meter " + name + " already exists",changed=False)
else:
# If it doesn't exist, create it
body = '{"name":"' + name + '"}'
response, info = http_request(module, name, apiid, apikey, data=body, action="create")
if info['status'] != 200:
module.fail_json(msg="Failed to connect to api host to create meter")
# If the config directory doesn't exist, create it
if not os.path.exists(config_directory):
try:
os.makedirs(config_directory)
except:
module.fail_json("Could not create " + config_directory)
# Download both cert files from the api host
types = ['key', 'cert']
for cert_type in types:
try:
# If we can't open the file it's not there, so we should download it
cert_file = open('%s/%s.pem' % (config_directory,cert_type))
except IOError:
# Now download the file...
rc = download_request(module, name, apiid, apikey, cert_type)
if rc == False:
module.fail_json("Download request for " + cert_type + ".pem failed")
return 0, "Meter " + name + " created"
def search_meter(module, name, apiid, apikey):
response, info = http_request(module, name, apiid, apikey, action="search")
if info['status'] != 200:
module.fail_json("Failed to connect to api host to search for meter")
# Return meters
return json.loads(response.read())
def get_meter_id(module, name, apiid, apikey):
# In order to delete the meter we need its id
meters = search_meter(module, name, apiid, apikey)
if len(meters) > 0:
return meters[0]['id']
else:
return None
def delete_meter(module, name, apiid, apikey):
meter_id = get_meter_id(module, name, apiid, apikey)
if meter_id is None:
return 1, "Meter does not exist, so can't delete it"
else:
response, info = http_request(module, name, apiid, apikey, action, meter_id)
if info['status'] != 200:
module.fail_json("Failed to delete meter")
# Each new meter gets a new key.pem and ca.pem file, so they should be deleted
|
[
" types = ['cert', 'key']"
] | 744
|
lcc
|
python
| null |
41849aea5e307f5199745185087b9ae2038c2a8673824a84
| 84
|
Your task is code completion.
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to add boundary meters.
(c) 2013, curtis <curtis@serverascode.com>
This file is part of Ansible
Ansible is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
"""
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
module: boundary_meter
short_description: Manage boundary meters
description:
- This module manages boundary meters
version_added: "1.3"
author: "curtis (@ccollicutt)"
requirements:
- Boundary API access
- bprobe is required to send data, but not to register a meter
options:
name:
description:
- meter name
required: true
state:
description:
- Whether to create or remove the client from boundary
required: false
default: true
choices: ["present", "absent"]
apiid:
description:
- Organizations boundary API ID
required: true
apikey:
description:
- Organizations boundary API KEY
required: true
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used
on personally controlled sites using self-signed certificates.
required: false
default: 'yes'
choices: ['yes', 'no']
version_added: 1.5.1
notes:
- This module does not yet support boundary tags.
'''
EXAMPLES='''
- name: Create meter
boundary_meter:
apiid: AAAAAA
apikey: BBBBBB
state: present
name: '{{ inventory_hostname }}'
- name: Delete meter
boundary_meter:
apiid: AAAAAA
apikey: BBBBBB
state: absent
name: '{{ inventory_hostname }}'
'''
import base64
import os
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
api_host = "api.boundary.com"
config_directory = "/etc/bprobe"
# "resource" like thing or apikey?
def auth_encode(apikey):
auth = base64.standard_b64encode(apikey)
auth.replace("\n", "")
return auth
def build_url(name, apiid, action, meter_id=None, cert_type=None):
if action == "create":
return 'https://%s/%s/meters' % (api_host, apiid)
elif action == "search":
return "https://%s/%s/meters?name=%s" % (api_host, apiid, name)
elif action == "certificates":
return "https://%s/%s/meters/%s/%s.pem" % (api_host, apiid, meter_id, cert_type)
elif action == "tags":
return "https://%s/%s/meters/%s/tags" % (api_host, apiid, meter_id)
elif action == "delete":
return "https://%s/%s/meters/%s" % (api_host, apiid, meter_id)
def http_request(module, name, apiid, apikey, action, data=None, meter_id=None, cert_type=None):
if meter_id is None:
url = build_url(name, apiid, action)
else:
if cert_type is None:
url = build_url(name, apiid, action, meter_id)
else:
url = build_url(name, apiid, action, meter_id, cert_type)
headers = dict()
headers["Authorization"] = "Basic %s" % auth_encode(apikey)
headers["Content-Type"] = "application/json"
return fetch_url(module, url, data=data, headers=headers)
def create_meter(module, name, apiid, apikey):
meters = search_meter(module, name, apiid, apikey)
if len(meters) > 0:
# If the meter already exists, do nothing
module.exit_json(status="Meter " + name + " already exists",changed=False)
else:
# If it doesn't exist, create it
body = '{"name":"' + name + '"}'
response, info = http_request(module, name, apiid, apikey, data=body, action="create")
if info['status'] != 200:
module.fail_json(msg="Failed to connect to api host to create meter")
# If the config directory doesn't exist, create it
if not os.path.exists(config_directory):
try:
os.makedirs(config_directory)
except:
module.fail_json("Could not create " + config_directory)
# Download both cert files from the api host
types = ['key', 'cert']
for cert_type in types:
try:
# If we can't open the file it's not there, so we should download it
cert_file = open('%s/%s.pem' % (config_directory,cert_type))
except IOError:
# Now download the file...
rc = download_request(module, name, apiid, apikey, cert_type)
if rc == False:
module.fail_json("Download request for " + cert_type + ".pem failed")
return 0, "Meter " + name + " created"
def search_meter(module, name, apiid, apikey):
response, info = http_request(module, name, apiid, apikey, action="search")
if info['status'] != 200:
module.fail_json("Failed to connect to api host to search for meter")
# Return meters
return json.loads(response.read())
def get_meter_id(module, name, apiid, apikey):
# In order to delete the meter we need its id
meters = search_meter(module, name, apiid, apikey)
if len(meters) > 0:
return meters[0]['id']
else:
return None
def delete_meter(module, name, apiid, apikey):
meter_id = get_meter_id(module, name, apiid, apikey)
if meter_id is None:
return 1, "Meter does not exist, so can't delete it"
else:
response, info = http_request(module, name, apiid, apikey, action, meter_id)
if info['status'] != 200:
module.fail_json("Failed to delete meter")
# Each new meter gets a new key.pem and ca.pem file, so they should be deleted
|
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]
def download_request(module, name, apiid, apikey, cert_type):
# If we can't open the file it's not there, so we should download it...
# Now download the file...
# ...and save it to the config directory
# The response from the API should contain the file contents
# We need to save the file to the config directory
# The file name is the name of the meter, followed by the cert type
# The file path is the config directory, followed by the file name
# We need to open the file in write mode
# We need to write the response contents to the file
# We need to close the file
# If the file was downloaded successfully, return True
# If the file was not downloaded successfully, return False
Relevant lines:
- The function download_request() is called in create_meter() when a certificate file is not found.
- The function download_request() takes the module, name, apiid, apikey, and cert_type as parameters.
- The function needs to download a file from the API and save it to the config directory.
- The file name is the name of the meter, followed by the cert type.
- The file path is the config directory, followed by the file name.
Next line will likely be:
```python
try:
with open('%s/%s.pem' % (config_directory, name + cert_type), 'w') as f:
f.write(response.read())
except Exception as e:
return False
```
|
|
Please complete the code given below.
//$Header: /cvsroot/autowikibrowser/src/Project\040select.Designer.cs,v 1.15 2006/06/15 10:14:49 wikibluemoose Exp $
namespace AutoWikiBrowser
{
partial class MyPreferences
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
if (TextBoxFont != null) TextBoxFont.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MyPreferences));
this.cmboLang = new System.Windows.Forms.ComboBox();
this.btnOK = new System.Windows.Forms.Button();
this.cmboProject = new System.Windows.Forms.ComboBox();
this.lblLang = new System.Windows.Forms.Label();
this.lblProject = new System.Windows.Forms.Label();
this.lblNonEnNotice = new System.Windows.Forms.Label();
this.btnTextBoxFont = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.lblPostfix = new System.Windows.Forms.Label();
this.cmboCustomProject = new System.Windows.Forms.ComboBox();
this.chkAddUsingAWBToActionSummaries = new System.Windows.Forms.CheckBox();
this.lblTimeoutPost = new System.Windows.Forms.Label();
this.chkAlwaysConfirmExit = new System.Windows.Forms.CheckBox();
this.chkSupressAWB = new System.Windows.Forms.CheckBox();
this.chkSaveArticleList = new System.Windows.Forms.CheckBox();
this.chkMinimize = new System.Windows.Forms.CheckBox();
this.lblTimeoutPre = new System.Windows.Forms.Label();
this.chkLowPriority = new System.Windows.Forms.CheckBox();
this.nudTimeOutLimit = new System.Windows.Forms.NumericUpDown();
this.chkBeep = new System.Windows.Forms.CheckBox();
this.chkFlash = new System.Windows.Forms.CheckBox();
this.lblDoneDo = new System.Windows.Forms.Label();
this.chkAutoSaveEdit = new System.Windows.Forms.CheckBox();
this.fontDialog = new System.Windows.Forms.FontDialog();
this.AutoSaveEditBoxGroup = new System.Windows.Forms.GroupBox();
this.btnSetFile = new System.Windows.Forms.Button();
this.txtAutosave = new System.Windows.Forms.TextBox();
this.lblAutosaveFile = new System.Windows.Forms.Label();
this.AutoSaveEditCont = new System.Windows.Forms.Label();
this.nudEditBoxAutosave = new System.Windows.Forms.NumericUpDown();
this.saveFile = new System.Windows.Forms.SaveFileDialog();
this.chkPrivacy = new System.Windows.Forms.CheckBox();
this.lblPrivacy = new System.Windows.Forms.Label();
this.tbPrefs = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
this.tabSite = new System.Windows.Forms.TabPage();
this.chkPHP5Ext = new System.Windows.Forms.CheckBox();
this.chkIgnoreNoBots = new System.Windows.Forms.CheckBox();
this.tabEditing = new System.Windows.Forms.TabPage();
this.chkShowTimer = new System.Windows.Forms.CheckBox();
this.tabPrivacy = new System.Windows.Forms.TabPage();
this.lblSaveAsDefaultFile = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.nudTimeOutLimit)).BeginInit();
this.AutoSaveEditBoxGroup.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudEditBoxAutosave)).BeginInit();
this.tbPrefs.SuspendLayout();
this.tabGeneral.SuspendLayout();
this.tabSite.SuspendLayout();
this.tabEditing.SuspendLayout();
this.tabPrivacy.SuspendLayout();
this.SuspendLayout();
//
// cmboLang
//
this.cmboLang.DropDownHeight = 212;
this.cmboLang.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmboLang.FormattingEnabled = true;
this.cmboLang.IntegralHeight = false;
this.cmboLang.Location = new System.Drawing.Point(70, 33);
this.cmboLang.Name = "cmboLang";
this.cmboLang.Size = new System.Drawing.Size(121, 21);
this.cmboLang.TabIndex = 3;
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point(246, 228);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 2;
this.btnOK.Text = "OK";
this.btnOK.Click += new System.EventHandler(this.btnApply_Click);
//
// cmboProject
//
this.cmboProject.DropDownHeight = 206;
this.cmboProject.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmboProject.FormattingEnabled = true;
this.cmboProject.IntegralHeight = false;
this.cmboProject.Location = new System.Drawing.Point(70, 6);
this.cmboProject.Name = "cmboProject";
this.cmboProject.Size = new System.Drawing.Size(121, 21);
this.cmboProject.TabIndex = 1;
this.cmboProject.SelectedIndexChanged += new System.EventHandler(this.cmboProject_SelectedIndexChanged);
//
// lblLang
//
this.lblLang.Location = new System.Drawing.Point(6, 36);
this.lblLang.Name = "lblLang";
this.lblLang.Size = new System.Drawing.Size(58, 13);
this.lblLang.TabIndex = 2;
this.lblLang.Text = "&Language:";
this.lblLang.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// lblProject
//
this.lblProject.AutoSize = true;
this.lblProject.Location = new System.Drawing.Point(21, 9);
this.lblProject.Name = "lblProject";
this.lblProject.Size = new System.Drawing.Size(43, 13);
this.lblProject.TabIndex = 0;
this.lblProject.Text = "&Project:";
//
// lblNonEnNotice
//
this.lblNonEnNotice.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblNonEnNotice.Location = new System.Drawing.Point(6, 80);
this.lblNonEnNotice.Name = "lblNonEnNotice";
this.lblNonEnNotice.Size = new System.Drawing.Size(370, 26);
this.lblNonEnNotice.TabIndex = 6;
this.lblNonEnNotice.Text = "Wikis not related to Wikimedia are not guaranteed to function properly.";
//
// btnTextBoxFont
//
this.btnTextBoxFont.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnTextBoxFont.Location = new System.Drawing.Point(267, 152);
this.btnTextBoxFont.Name = "btnTextBoxFont";
this.btnTextBoxFont.Size = new System.Drawing.Size(112, 23);
this.btnTextBoxFont.TabIndex = 5;
this.btnTextBoxFont.Text = "Set edit box &font";
this.btnTextBoxFont.UseVisualStyleBackColor = true;
this.btnTextBoxFont.Click += new System.EventHandler(this.btnTextBoxFont_Click);
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(327, 228);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "Cancel";
//
// lblPostfix
//
this.lblPostfix.AutoSize = true;
this.lblPostfix.Location = new System.Drawing.Point(197, 36);
this.lblPostfix.Name = "lblPostfix";
this.lblPostfix.Size = new System.Drawing.Size(48, 13);
this.lblPostfix.TabIndex = 4;
this.lblPostfix.Text = "lblPostfix";
//
// cmboCustomProject
//
this.cmboCustomProject.FormattingEnabled = true;
this.cmboCustomProject.Location = new System.Drawing.Point(70, 33);
this.cmboCustomProject.Name = "cmboCustomProject";
this.cmboCustomProject.Size = new System.Drawing.Size(121, 21);
this.cmboCustomProject.TabIndex = 5;
this.cmboCustomProject.SelectedIndexChanged += new System.EventHandler(this.cmboCustomProjectChanged);
this.cmboCustomProject.Leave += new System.EventHandler(this.txtCustomProject_Leave);
this.cmboCustomProject.TextChanged += new System.EventHandler(this.cmboCustomProjectChanged);
//
// chkAddUsingAWBToActionSummaries
//
this.chkAddUsingAWBToActionSummaries.AutoSize = true;
this.chkAddUsingAWBToActionSummaries.Location = new System.Drawing.Point(6, 105);
this.chkAddUsingAWBToActionSummaries.Name = "chkAddUsingAWBToActionSummaries";
this.chkAddUsingAWBToActionSummaries.Size = new System.Drawing.Size(286, 17);
this.chkAddUsingAWBToActionSummaries.TabIndex = 1;
this.chkAddUsingAWBToActionSummaries.Text = "Add \"using AWB\" to when deleting or protecting pages";
this.chkAddUsingAWBToActionSummaries.UseVisualStyleBackColor = true;
//
// lblTimeoutPost
//
this.lblTimeoutPost.AutoSize = true;
this.lblTimeoutPost.Location = new System.Drawing.Point(98, 111);
this.lblTimeoutPost.Name = "lblTimeoutPost";
this.lblTimeoutPost.Size = new System.Drawing.Size(183, 13);
this.lblTimeoutPost.TabIndex = 7;
this.lblTimeoutPost.Text = "seconds before web control × out";
//
// chkAlwaysConfirmExit
//
this.chkAlwaysConfirmExit.AutoSize = true;
this.chkAlwaysConfirmExit.Checked = true;
this.chkAlwaysConfirmExit.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkAlwaysConfirmExit.Location = new System.Drawing.Point(6, 29);
this.chkAlwaysConfirmExit.Name = "chkAlwaysConfirmExit";
this.chkAlwaysConfirmExit.Size = new System.Drawing.Size(86, 17);
this.chkAlwaysConfirmExit.TabIndex = 2;
this.chkAlwaysConfirmExit.Text = "&Warn on exit";
this.chkAlwaysConfirmExit.UseVisualStyleBackColor = true;
//
// chkSupressAWB
//
this.chkSupressAWB.AutoSize = true;
this.chkSupressAWB.Enabled = false;
this.chkSupressAWB.Location = new System.Drawing.Point(70, 60);
this.chkSupressAWB.Name = "chkSupressAWB";
this.chkSupressAWB.Size = new System.Drawing.Size(138, 17);
this.chkSupressAWB.TabIndex = 5;
this.chkSupressAWB.Text = "&Suppress \"Using AWB\"";
this.chkSupressAWB.UseVisualStyleBackColor = true;
//
// chkSaveArticleList
//
this.chkSaveArticleList.AutoSize = true;
this.chkSaveArticleList.Checked = true;
this.chkSaveArticleList.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkSaveArticleList.Location = new System.Drawing.Point(6, 52);
this.chkSaveArticleList.Name = "chkSaveArticleList";
this.chkSaveArticleList.Size = new System.Drawing.Size(154, 17);
this.chkSaveArticleList.TabIndex = 3;
this.chkSaveArticleList.Text = "Save page &list with settings";
this.chkSaveArticleList.UseVisualStyleBackColor = true;
//
// chkMinimize
//
this.chkMinimize.AutoSize = true;
this.chkMinimize.Location = new System.Drawing.Point(6, 6);
this.chkMinimize.Name = "chkMinimize";
this.chkMinimize.Size = new System.Drawing.Size(197, 17);
this.chkMinimize.TabIndex = 1;
this.chkMinimize.Text = "&Minimize to notification area (systray)";
this.chkMinimize.UseVisualStyleBackColor = true;
//
// lblTimeoutPre
//
this.lblTimeoutPre.AutoSize = true;
this.lblTimeoutPre.Location = new System.Drawing.Point(5, 111);
this.lblTimeoutPre.Name = "lblTimeoutPre";
this.lblTimeoutPre.Size = new System.Drawing.Size(29, 13);
this.lblTimeoutPre.TabIndex = 9;
this.lblTimeoutPre.Text = "Wait";
//
// chkLowPriority
//
this.chkLowPriority.AutoSize = true;
this.chkLowPriority.Location = new System.Drawing.Point(6, 75);
this.chkLowPriority.Name = "chkLowPriority";
this.chkLowPriority.Size = new System.Drawing.Size(250, 17);
this.chkLowPriority.TabIndex = 4;
this.chkLowPriority.Text = "Low &thread priority (works better in background)";
this.chkLowPriority.UseVisualStyleBackColor = true;
//
// nudTimeOutLimit
//
this.nudTimeOutLimit.Location = new System.Drawing.Point(37, 109);
this.nudTimeOutLimit.Margin = new System.Windows.Forms.Padding(0, 3, 0, 3);
this.nudTimeOutLimit.Maximum = new decimal(new int[] {
120,
0,
0,
0});
this.nudTimeOutLimit.Minimum = new decimal(new int[] {
30,
0,
0,
0});
this.nudTimeOutLimit.Name = "nudTimeOutLimit";
this.nudTimeOutLimit.Size = new System.Drawing.Size(58, 20);
this.nudTimeOutLimit.TabIndex = 8;
this.nudTimeOutLimit.Value = new decimal(new int[] {
30,
0,
0,
0});
//
// chkBeep
//
this.chkBeep.AutoSize = true;
this.chkBeep.Checked = true;
this.chkBeep.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkBeep.Location = new System.Drawing.Point(178, 128);
this.chkBeep.Name = "chkBeep";
this.chkBeep.Size = new System.Drawing.Size(51, 17);
this.chkBeep.TabIndex = 4;
this.chkBeep.Text = "&Beep";
this.chkBeep.UseVisualStyleBackColor = true;
//
// chkFlash
//
this.chkFlash.AutoSize = true;
this.chkFlash.Checked = true;
this.chkFlash.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkFlash.Location = new System.Drawing.Point(121, 128);
this.chkFlash.Name = "chkFlash";
this.chkFlash.Size = new System.Drawing.Size(51, 17);
this.chkFlash.TabIndex = 3;
this.chkFlash.Text = "&Flash";
this.chkFlash.UseVisualStyleBackColor = true;
//
// lblDoneDo
//
this.lblDoneDo.AutoSize = true;
this.lblDoneDo.Location = new System.Drawing.Point(9, 129);
this.lblDoneDo.Name = "lblDoneDo";
this.lblDoneDo.Size = new System.Drawing.Size(106, 13);
this.lblDoneDo.TabIndex = 2;
this.lblDoneDo.Text = "When ready to save:";
//
// chkAutoSaveEdit
//
this.chkAutoSaveEdit.AutoSize = true;
this.chkAutoSaveEdit.Location = new System.Drawing.Point(6, 19);
this.chkAutoSaveEdit.Name = "chkAutoSaveEdit";
this.chkAutoSaveEdit.Size = new System.Drawing.Size(183, 17);
this.chkAutoSaveEdit.TabIndex = 0;
this.chkAutoSaveEdit.Text = "A&utomatically save edit box every";
this.chkAutoSaveEdit.UseVisualStyleBackColor = true;
this.chkAutoSaveEdit.CheckedChanged += new System.EventHandler(this.chkAutoSaveEdit_CheckedChanged);
//
// AutoSaveEditBoxGroup
//
this.AutoSaveEditBoxGroup.Controls.Add(this.btnSetFile);
this.AutoSaveEditBoxGroup.Controls.Add(this.txtAutosave);
this.AutoSaveEditBoxGroup.Controls.Add(this.lblAutosaveFile);
this.AutoSaveEditBoxGroup.Controls.Add(this.AutoSaveEditCont);
this.AutoSaveEditBoxGroup.Controls.Add(this.nudEditBoxAutosave);
this.AutoSaveEditBoxGroup.Controls.Add(this.chkAutoSaveEdit);
this.AutoSaveEditBoxGroup.Location = new System.Drawing.Point(6, 6);
this.AutoSaveEditBoxGroup.Name = "AutoSaveEditBoxGroup";
this.AutoSaveEditBoxGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.AutoSaveEditBoxGroup.Size = new System.Drawing.Size(370, 70);
this.AutoSaveEditBoxGroup.TabIndex = 0;
this.AutoSaveEditBoxGroup.TabStop = false;
this.AutoSaveEditBoxGroup.Text = "Auto save edit box";
//
// btnSetFile
//
this.btnSetFile.Enabled = false;
this.btnSetFile.Location = new System.Drawing.Point(289, 40);
this.btnSetFile.Name = "btnSetFile";
this.btnSetFile.Size = new System.Drawing.Size(75, 23);
this.btnSetFile.TabIndex = 5;
this.btnSetFile.Text = "&Browse";
this.btnSetFile.UseVisualStyleBackColor = true;
this.btnSetFile.Click += new System.EventHandler(this.btnSetFile_Click);
//
// txtAutosave
//
this.txtAutosave.Location = new System.Drawing.Point(38, 42);
this.txtAutosave.Name = "txtAutosave";
this.txtAutosave.ReadOnly = true;
this.txtAutosave.Size = new System.Drawing.Size(245, 20);
this.txtAutosave.TabIndex = 4;
//
// lblAutosaveFile
//
this.lblAutosaveFile.AutoSize = true;
this.lblAutosaveFile.Location = new System.Drawing.Point(6, 45);
this.lblAutosaveFile.Name = "lblAutosaveFile";
this.lblAutosaveFile.Size = new System.Drawing.Size(26, 13);
this.lblAutosaveFile.TabIndex = 3;
this.lblAutosaveFile.Text = "File:";
//
// AutoSaveEditCont
//
this.AutoSaveEditCont.AutoSize = true;
this.AutoSaveEditCont.Location = new System.Drawing.Point(248, 20);
this.AutoSaveEditCont.Name = "AutoSaveEditCont";
this.AutoSaveEditCont.Size = new System.Drawing.Size(47, 13);
this.AutoSaveEditCont.TabIndex = 2;
this.AutoSaveEditCont.Text = "seconds";
//
// nudEditBoxAutosave
//
this.nudEditBoxAutosave.Location = new System.Drawing.Point(189, 18);
this.nudEditBoxAutosave.Maximum = new decimal(new int[] {
300,
0,
0,
0});
this.nudEditBoxAutosave.Minimum = new decimal(new int[] {
30,
0,
0,
0});
this.nudEditBoxAutosave.Name = "nudEditBoxAutosave";
this.nudEditBoxAutosave.Size = new System.Drawing.Size(58, 20);
this.nudEditBoxAutosave.TabIndex = 1;
this.nudEditBoxAutosave.Value = new decimal(new int[] {
30,
0,
0,
0});
//
// saveFile
//
this.saveFile.Filter = ".txt Files|*.txt";
//
// chkPrivacy
//
this.chkPrivacy.AutoSize = true;
this.chkPrivacy.Checked = true;
this.chkPrivacy.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkPrivacy.Location = new System.Drawing.Point(6, 6);
this.chkPrivacy.Name = "chkPrivacy";
this.chkPrivacy.Size = new System.Drawing.Size(209, 17);
this.chkPrivacy.TabIndex = 0;
this.chkPrivacy.Text = "Include username to im&prove accuracy";
//
// lblPrivacy
//
this.lblPrivacy.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
|
[
" this.lblPrivacy.Location = new System.Drawing.Point(6, 26);"
] | 1,336
|
lcc
|
csharp
| null |
87a46bb8e4f77d817428047955d797ac5726abcbd031985c
| 85
|
Your task is code completion.
//$Header: /cvsroot/autowikibrowser/src/Project\040select.Designer.cs,v 1.15 2006/06/15 10:14:49 wikibluemoose Exp $
namespace AutoWikiBrowser
{
partial class MyPreferences
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
if (TextBoxFont != null) TextBoxFont.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MyPreferences));
this.cmboLang = new System.Windows.Forms.ComboBox();
this.btnOK = new System.Windows.Forms.Button();
this.cmboProject = new System.Windows.Forms.ComboBox();
this.lblLang = new System.Windows.Forms.Label();
this.lblProject = new System.Windows.Forms.Label();
this.lblNonEnNotice = new System.Windows.Forms.Label();
this.btnTextBoxFont = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.lblPostfix = new System.Windows.Forms.Label();
this.cmboCustomProject = new System.Windows.Forms.ComboBox();
this.chkAddUsingAWBToActionSummaries = new System.Windows.Forms.CheckBox();
this.lblTimeoutPost = new System.Windows.Forms.Label();
this.chkAlwaysConfirmExit = new System.Windows.Forms.CheckBox();
this.chkSupressAWB = new System.Windows.Forms.CheckBox();
this.chkSaveArticleList = new System.Windows.Forms.CheckBox();
this.chkMinimize = new System.Windows.Forms.CheckBox();
this.lblTimeoutPre = new System.Windows.Forms.Label();
this.chkLowPriority = new System.Windows.Forms.CheckBox();
this.nudTimeOutLimit = new System.Windows.Forms.NumericUpDown();
this.chkBeep = new System.Windows.Forms.CheckBox();
this.chkFlash = new System.Windows.Forms.CheckBox();
this.lblDoneDo = new System.Windows.Forms.Label();
this.chkAutoSaveEdit = new System.Windows.Forms.CheckBox();
this.fontDialog = new System.Windows.Forms.FontDialog();
this.AutoSaveEditBoxGroup = new System.Windows.Forms.GroupBox();
this.btnSetFile = new System.Windows.Forms.Button();
this.txtAutosave = new System.Windows.Forms.TextBox();
this.lblAutosaveFile = new System.Windows.Forms.Label();
this.AutoSaveEditCont = new System.Windows.Forms.Label();
this.nudEditBoxAutosave = new System.Windows.Forms.NumericUpDown();
this.saveFile = new System.Windows.Forms.SaveFileDialog();
this.chkPrivacy = new System.Windows.Forms.CheckBox();
this.lblPrivacy = new System.Windows.Forms.Label();
this.tbPrefs = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
this.tabSite = new System.Windows.Forms.TabPage();
this.chkPHP5Ext = new System.Windows.Forms.CheckBox();
this.chkIgnoreNoBots = new System.Windows.Forms.CheckBox();
this.tabEditing = new System.Windows.Forms.TabPage();
this.chkShowTimer = new System.Windows.Forms.CheckBox();
this.tabPrivacy = new System.Windows.Forms.TabPage();
this.lblSaveAsDefaultFile = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.nudTimeOutLimit)).BeginInit();
this.AutoSaveEditBoxGroup.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudEditBoxAutosave)).BeginInit();
this.tbPrefs.SuspendLayout();
this.tabGeneral.SuspendLayout();
this.tabSite.SuspendLayout();
this.tabEditing.SuspendLayout();
this.tabPrivacy.SuspendLayout();
this.SuspendLayout();
//
// cmboLang
//
this.cmboLang.DropDownHeight = 212;
this.cmboLang.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmboLang.FormattingEnabled = true;
this.cmboLang.IntegralHeight = false;
this.cmboLang.Location = new System.Drawing.Point(70, 33);
this.cmboLang.Name = "cmboLang";
this.cmboLang.Size = new System.Drawing.Size(121, 21);
this.cmboLang.TabIndex = 3;
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point(246, 228);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 2;
this.btnOK.Text = "OK";
this.btnOK.Click += new System.EventHandler(this.btnApply_Click);
//
// cmboProject
//
this.cmboProject.DropDownHeight = 206;
this.cmboProject.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmboProject.FormattingEnabled = true;
this.cmboProject.IntegralHeight = false;
this.cmboProject.Location = new System.Drawing.Point(70, 6);
this.cmboProject.Name = "cmboProject";
this.cmboProject.Size = new System.Drawing.Size(121, 21);
this.cmboProject.TabIndex = 1;
this.cmboProject.SelectedIndexChanged += new System.EventHandler(this.cmboProject_SelectedIndexChanged);
//
// lblLang
//
this.lblLang.Location = new System.Drawing.Point(6, 36);
this.lblLang.Name = "lblLang";
this.lblLang.Size = new System.Drawing.Size(58, 13);
this.lblLang.TabIndex = 2;
this.lblLang.Text = "&Language:";
this.lblLang.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// lblProject
//
this.lblProject.AutoSize = true;
this.lblProject.Location = new System.Drawing.Point(21, 9);
this.lblProject.Name = "lblProject";
this.lblProject.Size = new System.Drawing.Size(43, 13);
this.lblProject.TabIndex = 0;
this.lblProject.Text = "&Project:";
//
// lblNonEnNotice
//
this.lblNonEnNotice.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblNonEnNotice.Location = new System.Drawing.Point(6, 80);
this.lblNonEnNotice.Name = "lblNonEnNotice";
this.lblNonEnNotice.Size = new System.Drawing.Size(370, 26);
this.lblNonEnNotice.TabIndex = 6;
this.lblNonEnNotice.Text = "Wikis not related to Wikimedia are not guaranteed to function properly.";
//
// btnTextBoxFont
//
this.btnTextBoxFont.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnTextBoxFont.Location = new System.Drawing.Point(267, 152);
this.btnTextBoxFont.Name = "btnTextBoxFont";
this.btnTextBoxFont.Size = new System.Drawing.Size(112, 23);
this.btnTextBoxFont.TabIndex = 5;
this.btnTextBoxFont.Text = "Set edit box &font";
this.btnTextBoxFont.UseVisualStyleBackColor = true;
this.btnTextBoxFont.Click += new System.EventHandler(this.btnTextBoxFont_Click);
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(327, 228);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "Cancel";
//
// lblPostfix
//
this.lblPostfix.AutoSize = true;
this.lblPostfix.Location = new System.Drawing.Point(197, 36);
this.lblPostfix.Name = "lblPostfix";
this.lblPostfix.Size = new System.Drawing.Size(48, 13);
this.lblPostfix.TabIndex = 4;
this.lblPostfix.Text = "lblPostfix";
//
// cmboCustomProject
//
this.cmboCustomProject.FormattingEnabled = true;
this.cmboCustomProject.Location = new System.Drawing.Point(70, 33);
this.cmboCustomProject.Name = "cmboCustomProject";
this.cmboCustomProject.Size = new System.Drawing.Size(121, 21);
this.cmboCustomProject.TabIndex = 5;
this.cmboCustomProject.SelectedIndexChanged += new System.EventHandler(this.cmboCustomProjectChanged);
this.cmboCustomProject.Leave += new System.EventHandler(this.txtCustomProject_Leave);
this.cmboCustomProject.TextChanged += new System.EventHandler(this.cmboCustomProjectChanged);
//
// chkAddUsingAWBToActionSummaries
//
this.chkAddUsingAWBToActionSummaries.AutoSize = true;
this.chkAddUsingAWBToActionSummaries.Location = new System.Drawing.Point(6, 105);
this.chkAddUsingAWBToActionSummaries.Name = "chkAddUsingAWBToActionSummaries";
this.chkAddUsingAWBToActionSummaries.Size = new System.Drawing.Size(286, 17);
this.chkAddUsingAWBToActionSummaries.TabIndex = 1;
this.chkAddUsingAWBToActionSummaries.Text = "Add \"using AWB\" to when deleting or protecting pages";
this.chkAddUsingAWBToActionSummaries.UseVisualStyleBackColor = true;
//
// lblTimeoutPost
//
this.lblTimeoutPost.AutoSize = true;
this.lblTimeoutPost.Location = new System.Drawing.Point(98, 111);
this.lblTimeoutPost.Name = "lblTimeoutPost";
this.lblTimeoutPost.Size = new System.Drawing.Size(183, 13);
this.lblTimeoutPost.TabIndex = 7;
this.lblTimeoutPost.Text = "seconds before web control × out";
//
// chkAlwaysConfirmExit
//
this.chkAlwaysConfirmExit.AutoSize = true;
this.chkAlwaysConfirmExit.Checked = true;
this.chkAlwaysConfirmExit.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkAlwaysConfirmExit.Location = new System.Drawing.Point(6, 29);
this.chkAlwaysConfirmExit.Name = "chkAlwaysConfirmExit";
this.chkAlwaysConfirmExit.Size = new System.Drawing.Size(86, 17);
this.chkAlwaysConfirmExit.TabIndex = 2;
this.chkAlwaysConfirmExit.Text = "&Warn on exit";
this.chkAlwaysConfirmExit.UseVisualStyleBackColor = true;
//
// chkSupressAWB
//
this.chkSupressAWB.AutoSize = true;
this.chkSupressAWB.Enabled = false;
this.chkSupressAWB.Location = new System.Drawing.Point(70, 60);
this.chkSupressAWB.Name = "chkSupressAWB";
this.chkSupressAWB.Size = new System.Drawing.Size(138, 17);
this.chkSupressAWB.TabIndex = 5;
this.chkSupressAWB.Text = "&Suppress \"Using AWB\"";
this.chkSupressAWB.UseVisualStyleBackColor = true;
//
// chkSaveArticleList
//
this.chkSaveArticleList.AutoSize = true;
this.chkSaveArticleList.Checked = true;
this.chkSaveArticleList.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkSaveArticleList.Location = new System.Drawing.Point(6, 52);
this.chkSaveArticleList.Name = "chkSaveArticleList";
this.chkSaveArticleList.Size = new System.Drawing.Size(154, 17);
this.chkSaveArticleList.TabIndex = 3;
this.chkSaveArticleList.Text = "Save page &list with settings";
this.chkSaveArticleList.UseVisualStyleBackColor = true;
//
// chkMinimize
//
this.chkMinimize.AutoSize = true;
this.chkMinimize.Location = new System.Drawing.Point(6, 6);
this.chkMinimize.Name = "chkMinimize";
this.chkMinimize.Size = new System.Drawing.Size(197, 17);
this.chkMinimize.TabIndex = 1;
this.chkMinimize.Text = "&Minimize to notification area (systray)";
this.chkMinimize.UseVisualStyleBackColor = true;
//
// lblTimeoutPre
//
this.lblTimeoutPre.AutoSize = true;
this.lblTimeoutPre.Location = new System.Drawing.Point(5, 111);
this.lblTimeoutPre.Name = "lblTimeoutPre";
this.lblTimeoutPre.Size = new System.Drawing.Size(29, 13);
this.lblTimeoutPre.TabIndex = 9;
this.lblTimeoutPre.Text = "Wait";
//
// chkLowPriority
//
this.chkLowPriority.AutoSize = true;
this.chkLowPriority.Location = new System.Drawing.Point(6, 75);
this.chkLowPriority.Name = "chkLowPriority";
this.chkLowPriority.Size = new System.Drawing.Size(250, 17);
this.chkLowPriority.TabIndex = 4;
this.chkLowPriority.Text = "Low &thread priority (works better in background)";
this.chkLowPriority.UseVisualStyleBackColor = true;
//
// nudTimeOutLimit
//
this.nudTimeOutLimit.Location = new System.Drawing.Point(37, 109);
this.nudTimeOutLimit.Margin = new System.Windows.Forms.Padding(0, 3, 0, 3);
this.nudTimeOutLimit.Maximum = new decimal(new int[] {
120,
0,
0,
0});
this.nudTimeOutLimit.Minimum = new decimal(new int[] {
30,
0,
0,
0});
this.nudTimeOutLimit.Name = "nudTimeOutLimit";
this.nudTimeOutLimit.Size = new System.Drawing.Size(58, 20);
this.nudTimeOutLimit.TabIndex = 8;
this.nudTimeOutLimit.Value = new decimal(new int[] {
30,
0,
0,
0});
//
// chkBeep
//
this.chkBeep.AutoSize = true;
this.chkBeep.Checked = true;
this.chkBeep.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkBeep.Location = new System.Drawing.Point(178, 128);
this.chkBeep.Name = "chkBeep";
this.chkBeep.Size = new System.Drawing.Size(51, 17);
this.chkBeep.TabIndex = 4;
this.chkBeep.Text = "&Beep";
this.chkBeep.UseVisualStyleBackColor = true;
//
// chkFlash
//
this.chkFlash.AutoSize = true;
this.chkFlash.Checked = true;
this.chkFlash.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkFlash.Location = new System.Drawing.Point(121, 128);
this.chkFlash.Name = "chkFlash";
this.chkFlash.Size = new System.Drawing.Size(51, 17);
this.chkFlash.TabIndex = 3;
this.chkFlash.Text = "&Flash";
this.chkFlash.UseVisualStyleBackColor = true;
//
// lblDoneDo
//
this.lblDoneDo.AutoSize = true;
this.lblDoneDo.Location = new System.Drawing.Point(9, 129);
this.lblDoneDo.Name = "lblDoneDo";
this.lblDoneDo.Size = new System.Drawing.Size(106, 13);
this.lblDoneDo.TabIndex = 2;
this.lblDoneDo.Text = "When ready to save:";
//
// chkAutoSaveEdit
//
this.chkAutoSaveEdit.AutoSize = true;
this.chkAutoSaveEdit.Location = new System.Drawing.Point(6, 19);
this.chkAutoSaveEdit.Name = "chkAutoSaveEdit";
this.chkAutoSaveEdit.Size = new System.Drawing.Size(183, 17);
this.chkAutoSaveEdit.TabIndex = 0;
this.chkAutoSaveEdit.Text = "A&utomatically save edit box every";
this.chkAutoSaveEdit.UseVisualStyleBackColor = true;
this.chkAutoSaveEdit.CheckedChanged += new System.EventHandler(this.chkAutoSaveEdit_CheckedChanged);
//
// AutoSaveEditBoxGroup
//
this.AutoSaveEditBoxGroup.Controls.Add(this.btnSetFile);
this.AutoSaveEditBoxGroup.Controls.Add(this.txtAutosave);
this.AutoSaveEditBoxGroup.Controls.Add(this.lblAutosaveFile);
this.AutoSaveEditBoxGroup.Controls.Add(this.AutoSaveEditCont);
this.AutoSaveEditBoxGroup.Controls.Add(this.nudEditBoxAutosave);
this.AutoSaveEditBoxGroup.Controls.Add(this.chkAutoSaveEdit);
this.AutoSaveEditBoxGroup.Location = new System.Drawing.Point(6, 6);
this.AutoSaveEditBoxGroup.Name = "AutoSaveEditBoxGroup";
this.AutoSaveEditBoxGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.AutoSaveEditBoxGroup.Size = new System.Drawing.Size(370, 70);
this.AutoSaveEditBoxGroup.TabIndex = 0;
this.AutoSaveEditBoxGroup.TabStop = false;
this.AutoSaveEditBoxGroup.Text = "Auto save edit box";
//
// btnSetFile
//
this.btnSetFile.Enabled = false;
this.btnSetFile.Location = new System.Drawing.Point(289, 40);
this.btnSetFile.Name = "btnSetFile";
this.btnSetFile.Size = new System.Drawing.Size(75, 23);
this.btnSetFile.TabIndex = 5;
this.btnSetFile.Text = "&Browse";
this.btnSetFile.UseVisualStyleBackColor = true;
this.btnSetFile.Click += new System.EventHandler(this.btnSetFile_Click);
//
// txtAutosave
//
this.txtAutosave.Location = new System.Drawing.Point(38, 42);
this.txtAutosave.Name = "txtAutosave";
this.txtAutosave.ReadOnly = true;
this.txtAutosave.Size = new System.Drawing.Size(245, 20);
this.txtAutosave.TabIndex = 4;
//
// lblAutosaveFile
//
this.lblAutosaveFile.AutoSize = true;
this.lblAutosaveFile.Location = new System.Drawing.Point(6, 45);
this.lblAutosaveFile.Name = "lblAutosaveFile";
this.lblAutosaveFile.Size = new System.Drawing.Size(26, 13);
this.lblAutosaveFile.TabIndex = 3;
this.lblAutosaveFile.Text = "File:";
//
// AutoSaveEditCont
//
this.AutoSaveEditCont.AutoSize = true;
this.AutoSaveEditCont.Location = new System.Drawing.Point(248, 20);
this.AutoSaveEditCont.Name = "AutoSaveEditCont";
this.AutoSaveEditCont.Size = new System.Drawing.Size(47, 13);
this.AutoSaveEditCont.TabIndex = 2;
this.AutoSaveEditCont.Text = "seconds";
//
// nudEditBoxAutosave
//
this.nudEditBoxAutosave.Location = new System.Drawing.Point(189, 18);
this.nudEditBoxAutosave.Maximum = new decimal(new int[] {
300,
0,
0,
0});
this.nudEditBoxAutosave.Minimum = new decimal(new int[] {
30,
0,
0,
0});
this.nudEditBoxAutosave.Name = "nudEditBoxAutosave";
this.nudEditBoxAutosave.Size = new System.Drawing.Size(58, 20);
this.nudEditBoxAutosave.TabIndex = 1;
this.nudEditBoxAutosave.Value = new decimal(new int[] {
30,
0,
0,
0});
//
// saveFile
//
this.saveFile.Filter = ".txt Files|*.txt";
//
// chkPrivacy
//
this.chkPrivacy.AutoSize = true;
this.chkPrivacy.Checked = true;
this.chkPrivacy.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkPrivacy.Location = new System.Drawing.Point(6, 6);
this.chkPrivacy.Name = "chkPrivacy";
this.chkPrivacy.Size = new System.Drawing.Size(209, 17);
this.chkPrivacy.TabIndex = 0;
this.chkPrivacy.Text = "Include username to im&prove accuracy";
//
// lblPrivacy
//
this.lblPrivacy.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
|
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]
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
if (TextBoxFont != null) TextBoxFont.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
// ... (many lines omitted for brevity)
this.chkPrivacy = new System.Windows.Forms.CheckBox();
this.lblPrivacy = new System.Windows.Forms.Label();
this.tbPrefs = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
this.tabSite = new System.Windows.Forms.TabPage();
this.chkPHP5Ext = new System.Windows.Forms.CheckBox();
this.chkIgnoreNoBots = new System.Windows.Forms.CheckBox();
this.tabEditing = new System.Windows.Forms.TabPage();
this.chkShowTimer = new System.Windows.Forms.CheckBox();
this.tabPrivacy = new System.Windows.Forms.TabPage();
this.lblSaveAsDefaultFile = new System.Windows.Forms.Label();
// ... (many lines omitted for brevity)
this.lblPrivacy.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right));
// ... (many lines omitted for brevity)
Cheatsheet (for next line):
- We are in the InitializeComponent() method, which is used to initialize the form's components.
- The last line of the InitializeComponent() method is incomplete, and it seems to be setting the Anchor property of the lblPrivacy control.
- The Anchor property is used to specify how a control should be positioned within its parent container.
- The parent container of lblPrivacy is likely the tabPrivacy control, which is a TabPage in the tbPrefs TabControl.
- The Anchor property is typically set to a combination of the following values: Top, Bottom, Left, Right, or None.
Next line will likely be: this.lblPrivacy.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left));
|
|
Please complete the code given below.
"""
Gather information about a system and report it using plugins
supplied for application-specific information
"""
# sosreport.py
# gather information about a system and report it
# Copyright (C) 2006 Steve Conklin <sconklin@redhat.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import sys
import traceback
import os
import errno
import logging
from optparse import OptionParser, Option
from sos.plugins import import_plugin
from sos.utilities import ImporterHelper
from stat import ST_UID, ST_GID, ST_MODE, ST_CTIME, ST_ATIME, ST_MTIME, S_IMODE
from time import strftime, localtime
from collections import deque
import tempfile
from sos import _sos as _
from sos import __version__
import sos.policies
from sos.archive import TarFileArchive, ZipFileArchive
from sos.reporting import (Report, Section, Command, CopiedFile, CreatedFile,
Alert, Note, PlainTextReport)
# PYCOMPAT
import six
from six.moves import zip, input
if six.PY3:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
from six import print_
# file system errors that should terminate a run
fatal_fs_errors = (errno.ENOSPC, errno.EROFS)
def _format_list(first_line, items, indent=False):
lines = []
line = first_line
if indent:
newline = len(first_line) * ' '
else:
newline = ""
for item in items:
if len(line) + len(item) + 2 > 72:
lines.append(line)
line = newline
line = line + item + ', '
if line[-2:] == ', ':
line = line[:-2]
lines.append(line)
return lines
class TempFileUtil(object):
def __init__(self, tmp_dir):
self.tmp_dir = tmp_dir
self.files = []
def new(self):
fd, fname = tempfile.mkstemp(dir=self.tmp_dir)
fobj = open(fname, 'w')
self.files.append((fname, fobj))
return fobj
def clean(self):
for fname, f in self.files:
try:
f.flush()
f.close()
except Exception:
pass
try:
os.unlink(fname)
except Exception:
pass
self.files = []
class OptionParserExtended(OptionParser):
""" Show examples """
def print_help(self, out=sys.stdout):
""" Prints help content including examples """
OptionParser.print_help(self, out)
print_()
print_("Some examples:")
print_()
print_(" enable cluster plugin only and collect dlm lockdumps:")
print_(" # sosreport -o cluster -k cluster.lockdump")
print_()
print_(" disable memory and samba plugins, turn off rpm -Va "
"collection:")
print_(" # sosreport -n memory,samba -k rpm.rpmva=off")
print_()
class SosOption(Option):
"""Allow to specify comma delimited list of plugins"""
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
""" Performs list extension on plugins """
if action == "extend":
try:
lvalue = value.split(",")
except:
pass
else:
values.ensure_value(dest, deque()).extend(lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
class XmlReport(object):
""" Report build class """
def __init__(self):
try:
import libxml2
except ImportError:
self.enabled = False
return
else:
self.enabled = False
return
self.doc = libxml2.newDoc("1.0")
self.root = self.doc.newChild(None, "sos", None)
self.commands = self.root.newChild(None, "commands", None)
self.files = self.root.newChild(None, "files", None)
def add_command(self, cmdline, exitcode, stdout=None, stderr=None,
f_stdout=None, f_stderr=None, runtime=None):
""" Appends command run into report """
if not self.enabled:
return
cmd = self.commands.newChild(None, "cmd", None)
cmd.setNsProp(None, "cmdline", cmdline)
cmdchild = cmd.newChild(None, "exitcode", str(exitcode))
if runtime:
cmd.newChild(None, "runtime", str(runtime))
if stdout or f_stdout:
cmdchild = cmd.newChild(None, "stdout", stdout)
if f_stdout:
cmdchild.setNsProp(None, "file", f_stdout)
if stderr or f_stderr:
cmdchild = cmd.newChild(None, "stderr", stderr)
if f_stderr:
cmdchild.setNsProp(None, "file", f_stderr)
def add_file(self, fname, stats):
""" Appends file(s) added to report """
if not self.enabled:
return
cfile = self.files.newChild(None, "file", None)
cfile.setNsProp(None, "fname", fname)
cchild = cfile.newChild(None, "uid", str(stats[ST_UID]))
cchild = cfile.newChild(None, "gid", str(stats[ST_GID]))
cfile.newChild(None, "mode", str(oct(S_IMODE(stats[ST_MODE]))))
cchild = cfile.newChild(None, "ctime",
strftime('%a %b %d %H:%M:%S %Y',
localtime(stats[ST_CTIME])))
cchild.setNsProp(None, "tstamp", str(stats[ST_CTIME]))
cchild = cfile.newChild(None, "atime",
strftime('%a %b %d %H:%M:%S %Y',
localtime(stats[ST_ATIME])))
cchild.setNsProp(None, "tstamp", str(stats[ST_ATIME]))
cchild = cfile.newChild(None, "mtime",
strftime('%a %b %d %H:%M:%S %Y',
localtime(stats[ST_MTIME])))
cchild.setNsProp(None, "tstamp", str(stats[ST_MTIME]))
def serialize(self):
""" Serializes xml """
if not self.enabled:
return
self.ui_log.info(self.doc.serialize(None, 1))
def serialize_to_file(self, fname):
""" Serializes to file """
if not self.enabled:
return
outf = tempfile.NamedTemporaryFile()
outf.write(self.doc.serialize(None, 1))
outf.flush()
self.archive.add_file(outf.name, dest=fname)
outf.close()
class SoSOptions(object):
_list_plugins = False
_noplugins = []
_enableplugins = []
_onlyplugins = []
_plugopts = []
_usealloptions = False
_all_logs = False
_log_size = 10
_batch = False
_build = False
_verbosity = 0
_verify = False
_quiet = False
_debug = False
_case_id = ""
_customer_name = ""
_profiles = deque()
_list_profiles = False
_config_file = ""
_tmp_dir = ""
_report = True
_compression_type = 'auto'
_options = None
def __init__(self, args=None):
if args:
self._options = self._parse_args(args)
else:
self._options = None
def _check_options_initialized(self):
if self._options is not None:
raise ValueError("SoSOptions object already initialized "
+ "from command line")
@property
def list_plugins(self):
if self._options is not None:
return self._options.list_plugins
return self._list_plugins
@list_plugins.setter
def list_plugins(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.list_plugins expects a boolean")
self._list_plugins = value
@property
def noplugins(self):
if self._options is not None:
return self._options.noplugins
return self._noplugins
@noplugins.setter
def noplugins(self, value):
self._check_options_initialized()
self._noplugins = value
@property
def enableplugins(self):
if self._options is not None:
return self._options.enableplugins
return self._enableplugins
@enableplugins.setter
def enableplugins(self, value):
self._check_options_initialized()
self._enableplugins = value
@property
def onlyplugins(self):
if self._options is not None:
return self._options.onlyplugins
return self._onlyplugins
@onlyplugins.setter
def onlyplugins(self, value):
self._check_options_initialized()
self._onlyplugins = value
@property
def plugopts(self):
if self._options is not None:
return self._options.plugopts
return self._plugopts
@plugopts.setter
def plugopts(self, value):
# If we check for anything it should be itterability.
# if not isinstance(value, list):
# raise TypeError("SoSOptions.plugopts expects a list")
self._plugopts = value
@property
def usealloptions(self):
if self._options is not None:
return self._options.usealloptions
return self._usealloptions
@usealloptions.setter
def usealloptions(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.usealloptions expects a boolean")
self._usealloptions = value
@property
def all_logs(self):
if self._options is not None:
return self._options.all_logs
return self._all_logs
@all_logs.setter
def all_logs(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.all_logs expects a boolean")
self._all_logs = value
@property
def log_size(self):
if self._options is not None:
return self._options.log_size
return self._log_size
@log_size.setter
def log_size(self, value):
self._check_options_initialized()
if value < 0:
raise ValueError("SoSOptions.log_size expects a value greater "
"than zero")
self._log_size = value
@property
def batch(self):
if self._options is not None:
return self._options.batch
return self._batch
@batch.setter
def batch(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.batch expects a boolean")
self._batch = value
@property
def build(self):
if self._options is not None:
return self._options.build
return self._build
@build.setter
def build(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.build expects a boolean")
self._build = value
@property
def verbosity(self):
if self._options is not None:
return self._options.verbosity
return self._verbosity
@verbosity.setter
def verbosity(self, value):
self._check_options_initialized()
if value < 0 or value > 3:
raise ValueError("SoSOptions.verbosity expects a value [0..3]")
self._verbosity = value
@property
def verify(self):
if self._options is not None:
return self._options.verify
return self._verify
@verify.setter
def verify(self, value):
self._check_options_initialized()
if value < 0 or value > 3:
raise ValueError("SoSOptions.verify expects a value [0..3]")
self._verify = value
@property
def quiet(self):
if self._options is not None:
return self._options.quiet
return self._quiet
@quiet.setter
def quiet(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.quiet expects a boolean")
self._quiet = value
@property
def debug(self):
if self._options is not None:
return self._options.debug
return self._debug
@debug.setter
def debug(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.debug expects a boolean")
self._debug = value
@property
def case_id(self):
if self._options is not None:
return self._options.case_id
return self._case_id
@case_id.setter
def case_id(self, value):
self._check_options_initialized()
self._case_id = value
@property
def customer_name(self):
if self._options is not None:
return self._options.customer_name
return self._customer_name
@customer_name.setter
def customer_name(self, value):
self._check_options_initialized()
self._customer_name = value
@property
def profiles(self):
if self._options is not None:
return self._options.profiles
return self._profiles
@profiles.setter
def profiles(self, value):
self._check_options_initialized()
self._profiles = value
@property
def list_profiles(self):
if self._options is not None:
return self._options.list_profiles
return self._list_profiles
@list_profiles.setter
def list_profiles(self, value):
self._check_options_initialized()
self._list_profiles = value
@property
def config_file(self):
if self._options is not None:
return self._options.config_file
return self._config_file
@config_file.setter
def config_file(self, value):
self._check_options_initialized()
self._config_file = value
@property
def tmp_dir(self):
if self._options is not None:
return self._options.tmp_dir
return self._tmp_dir
@tmp_dir.setter
def tmp_dir(self, value):
self._check_options_initialized()
self._tmp_dir = value
@property
def report(self):
if self._options is not None:
return self._options.report
return self._report
@report.setter
def report(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.report expects a boolean")
self._report = value
@property
def compression_type(self):
if self._options is not None:
return self._options.compression_type
return self._compression_type
@compression_type.setter
def compression_type(self, value):
self._check_options_initialized()
self._compression_type = value
def _parse_args(self, args):
""" Parse command line options and arguments"""
self.parser = parser = OptionParserExtended(option_class=SosOption)
parser.add_option("-l", "--list-plugins", action="store_true",
dest="list_plugins", default=False,
help="list plugins and available plugin options")
parser.add_option("-n", "--skip-plugins", action="extend",
dest="noplugins", type="string",
help="disable these plugins", default=deque())
parser.add_option("-e", "--enable-plugins", action="extend",
dest="enableplugins", type="string",
help="enable these plugins", default=deque())
parser.add_option("-o", "--only-plugins", action="extend",
dest="onlyplugins", type="string",
help="enable these plugins only", default=deque())
parser.add_option("-k", "--plugin-option", action="extend",
dest="plugopts", type="string",
help="plugin options in plugname.option=value "
"format (see -l)",
default=deque())
parser.add_option("--log-size", action="store",
dest="log_size", default=10, type="int",
help="set a limit on the size of collected logs")
parser.add_option("-a", "--alloptions", action="store_true",
dest="usealloptions", default=False,
help="enable all options for loaded plugins")
parser.add_option("--all-logs", action="store_true",
dest="all_logs", default=False,
help="collect all available logs regardless of size")
parser.add_option("--batch", action="store_true",
dest="batch", default=False,
help="batch mode - do not prompt interactively")
parser.add_option("--build", action="store_true",
dest="build", default=False,
help="preserve the temporary directory and do not "
"package results")
parser.add_option("-v", "--verbose", action="count",
dest="verbosity",
help="increase verbosity")
parser.add_option("", "--verify", action="store_true",
dest="verify", default=False,
help="perform data verification during collection")
parser.add_option("", "--quiet", action="store_true",
dest="quiet", default=False,
help="only print fatal errors")
parser.add_option("--debug", action="count",
dest="debug",
help="enable interactive debugging using the python "
"debugger")
parser.add_option("--ticket-number", action="store",
dest="case_id",
help="specify ticket number")
parser.add_option("--case-id", action="store",
dest="case_id",
help="specify case identifier")
parser.add_option("-p", "--profile", action="extend",
dest="profiles", type="string", default=deque(),
help="enable plugins selected by the given profiles")
parser.add_option("--list-profiles", action="store_true",
dest="list_profiles", default=False)
parser.add_option("--name", action="store",
dest="customer_name",
help="specify report name")
parser.add_option("--config-file", action="store",
dest="config_file",
help="specify alternate configuration file")
parser.add_option("--tmp-dir", action="store",
dest="tmp_dir",
help="specify alternate temporary directory",
default=None)
parser.add_option("--no-report", action="store_true",
dest="report",
help="Disable HTML/XML reporting", default=False)
parser.add_option("-z", "--compression-type", dest="compression_type",
help="compression technology to use [auto, zip, "
"gzip, bzip2, xz] (default=auto)",
default="auto")
return parser.parse_args(args)[0]
class SoSReport(object):
"""The main sosreport class"""
def __init__(self, args):
self.loaded_plugins = deque()
self.skipped_plugins = deque()
self.all_options = deque()
self.xml_report = XmlReport()
self.global_plugin_options = {}
self.archive = None
self.tempfile_util = None
self._args = args
try:
import signal
signal.signal(signal.SIGTERM, self.get_exit_handler())
except Exception:
pass # not available in java, but we don't care
self.opts = SoSOptions(args)
self._set_debug()
self._read_config()
try:
self.policy = sos.policies.load()
except KeyboardInterrupt:
self._exit(0)
self._is_root = self.policy.is_root()
self.tmpdir = os.path.abspath(
self.policy.get_tmp_dir(self.opts.tmp_dir))
if not os.path.isdir(self.tmpdir) \
or not os.access(self.tmpdir, os.W_OK):
# write directly to stderr as logging is not initialised yet
sys.stderr.write("temporary directory %s " % self.tmpdir
+ "does not exist or is not writable\n")
self._exit(1)
self.tempfile_util = TempFileUtil(self.tmpdir)
self._set_directories()
def print_header(self):
self.ui_log.info("\n%s\n" % _("sosreport (version %s)" %
(__version__,)))
def get_commons(self):
return {
'cmddir': self.cmddir,
'logdir': self.logdir,
'rptdir': self.rptdir,
'tmpdir': self.tmpdir,
'soslog': self.soslog,
'policy': self.policy,
'verbosity': self.opts.verbosity,
'xmlreport': self.xml_report,
'cmdlineopts': self.opts,
'config': self.config,
'global_plugin_options': self.global_plugin_options,
}
def get_temp_file(self):
return self.tempfile_util.new()
def _set_archive(self):
archive_name = os.path.join(self.tmpdir,
self.policy.get_archive_name())
if self.opts.compression_type == 'auto':
auto_archive = self.policy.get_preferred_archive()
self.archive = auto_archive(archive_name, self.tmpdir)
elif self.opts.compression_type == 'zip':
self.archive = ZipFileArchive(archive_name, self.tmpdir)
else:
self.archive = TarFileArchive(archive_name, self.tmpdir)
self.archive.set_debug(True if self.opts.debug else False)
def _make_archive_paths(self):
self.archive.makedirs(self.cmddir, 0o755)
self.archive.makedirs(self.logdir, 0o755)
self.archive.makedirs(self.rptdir, 0o755)
def _set_directories(self):
self.cmddir = 'sos_commands'
self.logdir = 'sos_logs'
self.rptdir = 'sos_reports'
def _set_debug(self):
if self.opts.debug:
sys.excepthook = self._exception
self.raise_plugins = True
else:
self.raise_plugins = False
@staticmethod
def _exception(etype, eval_, etrace):
""" Wrap exception in debugger if not in tty """
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
import pdb
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
print_()
# ...then start the debugger in post-mortem mode.
pdb.pm()
def _exit(self, error=0):
raise SystemExit()
# sys.exit(error)
def get_exit_handler(self):
def exit_handler(signum, frame):
self._exit()
return exit_handler
def _read_config(self):
self.config = ConfigParser()
if self.opts.config_file:
config_file = self.opts.config_file
else:
config_file = '/etc/sos.conf'
try:
self.config.readfp(open(config_file))
except IOError:
pass
def _setup_logging(self):
# main soslog
self.soslog = logging.getLogger('sos')
self.soslog.setLevel(logging.DEBUG)
self.sos_log_file = self.get_temp_file()
self.sos_log_file.close()
flog = logging.FileHandler(self.sos_log_file.name)
flog.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s'))
flog.setLevel(logging.INFO)
self.soslog.addHandler(flog)
if not self.opts.quiet:
console = logging.StreamHandler(sys.stderr)
console.setFormatter(logging.Formatter('%(message)s'))
if self.opts.verbosity and self.opts.verbosity > 1:
console.setLevel(logging.DEBUG)
flog.setLevel(logging.DEBUG)
elif self.opts.verbosity and self.opts.verbosity > 0:
console.setLevel(logging.INFO)
flog.setLevel(logging.DEBUG)
else:
console.setLevel(logging.WARNING)
self.soslog.addHandler(console)
# ui log
self.ui_log = logging.getLogger('sos_ui')
self.ui_log.setLevel(logging.INFO)
self.sos_ui_log_file = self.get_temp_file()
self.sos_ui_log_file.close()
ui_fhandler = logging.FileHandler(self.sos_ui_log_file.name)
ui_fhandler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s'))
self.ui_log.addHandler(ui_fhandler)
if not self.opts.quiet:
ui_console = logging.StreamHandler(sys.stdout)
ui_console.setFormatter(logging.Formatter('%(message)s'))
ui_console.setLevel(logging.INFO)
self.ui_log.addHandler(ui_console)
def _finish_logging(self):
logging.shutdown()
# Make sure the log files are added before we remove the log
# handlers. This prevents "No handlers could be found.." messages
# from leaking to the console when running in --quiet mode when
# Archive classes attempt to acess the log API.
if getattr(self, "sos_log_file", None):
self.archive.add_file(self.sos_log_file.name,
dest=os.path.join('sos_logs', 'sos.log'))
if getattr(self, "sos_ui_log_file", None):
self.archive.add_file(self.sos_ui_log_file.name,
dest=os.path.join('sos_logs', 'ui.log'))
def _get_disabled_plugins(self):
disabled = []
if self.config.has_option("plugins", "disable"):
disabled = [plugin.strip() for plugin in
self.config.get("plugins", "disable").split(',')]
return disabled
def _is_in_profile(self, plugin_class):
onlyplugins = self.opts.onlyplugins
if not len(self.opts.profiles):
return True
if not hasattr(plugin_class, "profiles"):
return False
if onlyplugins and not self._is_not_specified(plugin_class.name()):
return True
return any([p in self.opts.profiles for p in plugin_class.profiles])
def _is_skipped(self, plugin_name):
return (plugin_name in self.opts.noplugins or
plugin_name in self._get_disabled_plugins())
def _is_inactive(self, plugin_name, pluginClass):
return (not pluginClass(self.get_commons()).check_enabled() and
plugin_name not in self.opts.enableplugins and
plugin_name not in self.opts.onlyplugins)
def _is_not_default(self, plugin_name, pluginClass):
return (not pluginClass(self.get_commons()).default_enabled() and
plugin_name not in self.opts.enableplugins and
plugin_name not in self.opts.onlyplugins)
def _is_not_specified(self, plugin_name):
return (self.opts.onlyplugins and
plugin_name not in self.opts.onlyplugins)
def _skip(self, plugin_class, reason="unknown"):
self.skipped_plugins.append((
plugin_class.name(),
plugin_class(self.get_commons()),
reason
))
def _load(self, plugin_class):
self.loaded_plugins.append((
plugin_class.name(),
plugin_class(self.get_commons())
))
def load_plugins(self):
import sos.plugins
helper = ImporterHelper(sos.plugins)
plugins = helper.get_modules()
self.plugin_names = deque()
self.profiles = set()
using_profiles = len(self.opts.profiles)
# validate and load plugins
for plug in plugins:
plugbase, ext = os.path.splitext(plug)
try:
plugin_classes = import_plugin(
plugbase, tuple(self.policy.valid_subclasses))
if not len(plugin_classes):
# no valid plugin classes for this policy
continue
plugin_class = self.policy.match_plugin(plugin_classes)
if not self.policy.validate_plugin(plugin_class):
self.soslog.warning(
_("plugin %s does not validate, skipping") % plug)
if self.opts.verbosity > 0:
self._skip(plugin_class, _("does not validate"))
continue
if plugin_class.requires_root and not self._is_root:
self.soslog.info(_("plugin %s requires root permissions"
"to execute, skipping") % plug)
self._skip(plugin_class, _("requires root"))
continue
# plug-in is valid, let's decide whether run it or not
self.plugin_names.append(plugbase)
if hasattr(plugin_class, "profiles"):
self.profiles.update(plugin_class.profiles)
in_profile = self._is_in_profile(plugin_class)
if not in_profile:
self._skip(plugin_class, _("excluded"))
continue
if self._is_skipped(plugbase):
self._skip(plugin_class, _("skipped"))
continue
if self._is_inactive(plugbase, plugin_class):
self._skip(plugin_class, _("inactive"))
continue
if self._is_not_default(plugbase, plugin_class):
self._skip(plugin_class, _("optional"))
continue
# true when the null (empty) profile is active
default_profile = not using_profiles and in_profile
if self._is_not_specified(plugbase) and default_profile:
self._skip(plugin_class, _("not specified"))
continue
self._load(plugin_class)
except Exception as e:
self.soslog.warning(_("plugin %s does not install, "
"skipping: %s") % (plug, e))
if self.raise_plugins:
raise
def _set_all_options(self):
if self.opts.usealloptions:
for plugname, plug in self.loaded_plugins:
for name, parms in zip(plug.opt_names, plug.opt_parms):
if type(parms["enabled"]) == bool:
parms["enabled"] = True
def _set_tunables(self):
if self.config.has_section("tunables"):
if not self.opts.plugopts:
self.opts.plugopts = deque()
for opt, val in self.config.items("tunables"):
if not opt.split('.')[0] in self._get_disabled_plugins():
self.opts.plugopts.append(opt + "=" + val)
if self.opts.plugopts:
opts = {}
for opt in self.opts.plugopts:
# split up "general.syslogsize=5"
try:
opt, val = opt.split("=")
except:
val = True
else:
if val.lower() in ["off", "disable", "disabled", "false"]:
val = False
else:
# try to convert string "val" to int()
try:
val = int(val)
except:
pass
# split up "general.syslogsize"
try:
plug, opt = opt.split(".")
except:
plug = opt
opt = True
try:
opts[plug]
except KeyError:
opts[plug] = deque()
opts[plug].append((opt, val))
for plugname, plug in self.loaded_plugins:
if plugname in opts:
for opt, val in opts[plugname]:
if not plug.set_option(opt, val):
self.soslog.error('no such option "%s" for plugin '
'(%s)' % (opt, plugname))
self._exit(1)
del opts[plugname]
for plugname in opts.keys():
self.soslog.error('unable to set option for disabled or '
'non-existing plugin (%s)' % (plugname))
def _check_for_unknown_plugins(self):
import itertools
for plugin in itertools.chain(self.opts.onlyplugins,
self.opts.noplugins,
self.opts.enableplugins):
plugin_name = plugin.split(".")[0]
if plugin_name not in self.plugin_names:
self.soslog.fatal('a non-existing plugin (%s) was specified '
'in the command line' % (plugin_name))
self._exit(1)
def _set_plugin_options(self):
for plugin_name, plugin in self.loaded_plugins:
names, parms = plugin.get_all_options()
for optname, optparm in zip(names, parms):
self.all_options.append((plugin, plugin_name, optname,
optparm))
def list_plugins(self):
if not self.loaded_plugins and not self.skipped_plugins:
self.soslog.fatal(_("no valid plugins found"))
return
if self.loaded_plugins:
self.ui_log.info(_("The following plugins are currently enabled:"))
self.ui_log.info("")
for (plugname, plug) in self.loaded_plugins:
self.ui_log.info(" %-20s %s" % (plugname,
plug.get_description()))
else:
self.ui_log.info(_("No plugin enabled."))
self.ui_log.info("")
if self.skipped_plugins:
self.ui_log.info(_("The following plugins are currently "
"disabled:"))
self.ui_log.info("")
for (plugname, plugclass, reason) in self.skipped_plugins:
self.ui_log.info(" %-20s %-14s %s" % (
plugname,
reason,
plugclass.get_description()))
self.ui_log.info("")
if self.all_options:
self.ui_log.info(_("The following plugin options are available:"))
self.ui_log.info("")
for (plug, plugname, optname, optparm) in self.all_options:
# format option value based on its type (int or bool)
if type(optparm["enabled"]) == bool:
if optparm["enabled"] is True:
tmpopt = "on"
else:
tmpopt = "off"
else:
tmpopt = optparm["enabled"]
self.ui_log.info(" %-25s %-15s %s" % (
plugname + "." + optname, tmpopt, optparm["desc"]))
else:
self.ui_log.info(_("No plugin options available."))
self.ui_log.info("")
profiles = list(self.profiles)
profiles.sort()
lines = _format_list("Profiles: ", profiles, indent=True)
for line in lines:
self.ui_log.info(" %s" % line)
self.ui_log.info("")
self.ui_log.info(" %d profiles, %d plugins"
% (len(self.profiles), len(self.loaded_plugins)))
self.ui_log.info("")
def list_profiles(self):
if not self.profiles:
self.soslog.fatal(_("no valid profiles found"))
return
self.ui_log.info(_("The following profiles are available:"))
self.ui_log.info("")
def _has_prof(c):
return hasattr(c, "profiles")
profiles = list(self.profiles)
profiles.sort()
for profile in profiles:
plugins = []
for name, plugin in self.loaded_plugins:
if _has_prof(plugin) and profile in plugin.profiles:
plugins.append(name)
lines = _format_list("%-15s " % profile, plugins, indent=True)
for line in lines:
self.ui_log.info(" %s" % line)
self.ui_log.info("")
self.ui_log.info(" %d profiles, %d plugins"
% (len(profiles), len(self.loaded_plugins)))
self.ui_log.info("")
def batch(self):
if self.opts.batch:
self.ui_log.info(self.policy.get_msg())
else:
msg = self.policy.get_msg()
msg += _("Press ENTER to continue, or CTRL-C to quit.\n")
try:
input(msg)
except:
self.ui_log.info("")
self._exit()
def _log_plugin_exception(self, plugin_name):
self.soslog.error("%s\n%s" % (plugin_name, traceback.format_exc()))
def prework(self):
self.policy.pre_work()
try:
self.ui_log.info(_(" Setting up archive ..."))
compression_methods = ('auto', 'zip', 'bzip2', 'gzip', 'xz')
method = self.opts.compression_type
if method not in compression_methods:
compression_list = ', '.join(compression_methods)
self.ui_log.error("")
self.ui_log.error("Invalid compression specified: " + method)
self.ui_log.error("Valid types are: " + compression_list)
self.ui_log.error("")
self._exit(1)
self._set_archive()
self._make_archive_paths()
return
except (OSError, IOError) as e:
if e.errno in fatal_fs_errors:
self.ui_log.error("")
self.ui_log.error(" %s while setting up archive" % e.strerror)
self.ui_log.error("")
else:
raise e
except Exception as e:
import traceback
self.ui_log.error("")
self.ui_log.error(" Unexpected exception setting up archive:")
traceback.print_exc(e)
self.ui_log.error(e)
self._exit(1)
def setup(self):
msg = "[%s:%s] executing 'sosreport %s'"
self.soslog.info(msg % (__name__, "setup", " ".join(self._args)))
self.ui_log.info(_(" Setting up plugins ..."))
for plugname, plug in self.loaded_plugins:
try:
plug.archive = self.archive
plug.setup()
except KeyboardInterrupt:
raise
except (OSError, IOError) as e:
if e.errno in fatal_fs_errors:
self.ui_log.error("")
self.ui_log.error(" %s while setting up plugins"
% e.strerror)
self.ui_log.error("")
self._exit(1)
except:
if self.raise_plugins:
raise
else:
self._log_plugin_exception(plugname)
def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt')
def collect(self):
self.ui_log.info(_(" Running plugins. Please wait ..."))
self.ui_log.info("")
plugruncount = 0
|
[
" for i in zip(self.loaded_plugins):"
] | 3,043
|
lcc
|
python
| null |
0040aff29f9f6ccd4819e0793a5a66b9d75d882f56fae40c
| 86
|
Your task is code completion.
"""
Gather information about a system and report it using plugins
supplied for application-specific information
"""
# sosreport.py
# gather information about a system and report it
# Copyright (C) 2006 Steve Conklin <sconklin@redhat.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import sys
import traceback
import os
import errno
import logging
from optparse import OptionParser, Option
from sos.plugins import import_plugin
from sos.utilities import ImporterHelper
from stat import ST_UID, ST_GID, ST_MODE, ST_CTIME, ST_ATIME, ST_MTIME, S_IMODE
from time import strftime, localtime
from collections import deque
import tempfile
from sos import _sos as _
from sos import __version__
import sos.policies
from sos.archive import TarFileArchive, ZipFileArchive
from sos.reporting import (Report, Section, Command, CopiedFile, CreatedFile,
Alert, Note, PlainTextReport)
# PYCOMPAT
import six
from six.moves import zip, input
if six.PY3:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
from six import print_
# file system errors that should terminate a run
fatal_fs_errors = (errno.ENOSPC, errno.EROFS)
def _format_list(first_line, items, indent=False):
lines = []
line = first_line
if indent:
newline = len(first_line) * ' '
else:
newline = ""
for item in items:
if len(line) + len(item) + 2 > 72:
lines.append(line)
line = newline
line = line + item + ', '
if line[-2:] == ', ':
line = line[:-2]
lines.append(line)
return lines
class TempFileUtil(object):
def __init__(self, tmp_dir):
self.tmp_dir = tmp_dir
self.files = []
def new(self):
fd, fname = tempfile.mkstemp(dir=self.tmp_dir)
fobj = open(fname, 'w')
self.files.append((fname, fobj))
return fobj
def clean(self):
for fname, f in self.files:
try:
f.flush()
f.close()
except Exception:
pass
try:
os.unlink(fname)
except Exception:
pass
self.files = []
class OptionParserExtended(OptionParser):
""" Show examples """
def print_help(self, out=sys.stdout):
""" Prints help content including examples """
OptionParser.print_help(self, out)
print_()
print_("Some examples:")
print_()
print_(" enable cluster plugin only and collect dlm lockdumps:")
print_(" # sosreport -o cluster -k cluster.lockdump")
print_()
print_(" disable memory and samba plugins, turn off rpm -Va "
"collection:")
print_(" # sosreport -n memory,samba -k rpm.rpmva=off")
print_()
class SosOption(Option):
"""Allow to specify comma delimited list of plugins"""
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
""" Performs list extension on plugins """
if action == "extend":
try:
lvalue = value.split(",")
except:
pass
else:
values.ensure_value(dest, deque()).extend(lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
class XmlReport(object):
""" Report build class """
def __init__(self):
try:
import libxml2
except ImportError:
self.enabled = False
return
else:
self.enabled = False
return
self.doc = libxml2.newDoc("1.0")
self.root = self.doc.newChild(None, "sos", None)
self.commands = self.root.newChild(None, "commands", None)
self.files = self.root.newChild(None, "files", None)
def add_command(self, cmdline, exitcode, stdout=None, stderr=None,
f_stdout=None, f_stderr=None, runtime=None):
""" Appends command run into report """
if not self.enabled:
return
cmd = self.commands.newChild(None, "cmd", None)
cmd.setNsProp(None, "cmdline", cmdline)
cmdchild = cmd.newChild(None, "exitcode", str(exitcode))
if runtime:
cmd.newChild(None, "runtime", str(runtime))
if stdout or f_stdout:
cmdchild = cmd.newChild(None, "stdout", stdout)
if f_stdout:
cmdchild.setNsProp(None, "file", f_stdout)
if stderr or f_stderr:
cmdchild = cmd.newChild(None, "stderr", stderr)
if f_stderr:
cmdchild.setNsProp(None, "file", f_stderr)
def add_file(self, fname, stats):
""" Appends file(s) added to report """
if not self.enabled:
return
cfile = self.files.newChild(None, "file", None)
cfile.setNsProp(None, "fname", fname)
cchild = cfile.newChild(None, "uid", str(stats[ST_UID]))
cchild = cfile.newChild(None, "gid", str(stats[ST_GID]))
cfile.newChild(None, "mode", str(oct(S_IMODE(stats[ST_MODE]))))
cchild = cfile.newChild(None, "ctime",
strftime('%a %b %d %H:%M:%S %Y',
localtime(stats[ST_CTIME])))
cchild.setNsProp(None, "tstamp", str(stats[ST_CTIME]))
cchild = cfile.newChild(None, "atime",
strftime('%a %b %d %H:%M:%S %Y',
localtime(stats[ST_ATIME])))
cchild.setNsProp(None, "tstamp", str(stats[ST_ATIME]))
cchild = cfile.newChild(None, "mtime",
strftime('%a %b %d %H:%M:%S %Y',
localtime(stats[ST_MTIME])))
cchild.setNsProp(None, "tstamp", str(stats[ST_MTIME]))
def serialize(self):
""" Serializes xml """
if not self.enabled:
return
self.ui_log.info(self.doc.serialize(None, 1))
def serialize_to_file(self, fname):
""" Serializes to file """
if not self.enabled:
return
outf = tempfile.NamedTemporaryFile()
outf.write(self.doc.serialize(None, 1))
outf.flush()
self.archive.add_file(outf.name, dest=fname)
outf.close()
class SoSOptions(object):
_list_plugins = False
_noplugins = []
_enableplugins = []
_onlyplugins = []
_plugopts = []
_usealloptions = False
_all_logs = False
_log_size = 10
_batch = False
_build = False
_verbosity = 0
_verify = False
_quiet = False
_debug = False
_case_id = ""
_customer_name = ""
_profiles = deque()
_list_profiles = False
_config_file = ""
_tmp_dir = ""
_report = True
_compression_type = 'auto'
_options = None
def __init__(self, args=None):
if args:
self._options = self._parse_args(args)
else:
self._options = None
def _check_options_initialized(self):
if self._options is not None:
raise ValueError("SoSOptions object already initialized "
+ "from command line")
@property
def list_plugins(self):
if self._options is not None:
return self._options.list_plugins
return self._list_plugins
@list_plugins.setter
def list_plugins(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.list_plugins expects a boolean")
self._list_plugins = value
@property
def noplugins(self):
if self._options is not None:
return self._options.noplugins
return self._noplugins
@noplugins.setter
def noplugins(self, value):
self._check_options_initialized()
self._noplugins = value
@property
def enableplugins(self):
if self._options is not None:
return self._options.enableplugins
return self._enableplugins
@enableplugins.setter
def enableplugins(self, value):
self._check_options_initialized()
self._enableplugins = value
@property
def onlyplugins(self):
if self._options is not None:
return self._options.onlyplugins
return self._onlyplugins
@onlyplugins.setter
def onlyplugins(self, value):
self._check_options_initialized()
self._onlyplugins = value
@property
def plugopts(self):
if self._options is not None:
return self._options.plugopts
return self._plugopts
@plugopts.setter
def plugopts(self, value):
# If we check for anything it should be itterability.
# if not isinstance(value, list):
# raise TypeError("SoSOptions.plugopts expects a list")
self._plugopts = value
@property
def usealloptions(self):
if self._options is not None:
return self._options.usealloptions
return self._usealloptions
@usealloptions.setter
def usealloptions(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.usealloptions expects a boolean")
self._usealloptions = value
@property
def all_logs(self):
if self._options is not None:
return self._options.all_logs
return self._all_logs
@all_logs.setter
def all_logs(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.all_logs expects a boolean")
self._all_logs = value
@property
def log_size(self):
if self._options is not None:
return self._options.log_size
return self._log_size
@log_size.setter
def log_size(self, value):
self._check_options_initialized()
if value < 0:
raise ValueError("SoSOptions.log_size expects a value greater "
"than zero")
self._log_size = value
@property
def batch(self):
if self._options is not None:
return self._options.batch
return self._batch
@batch.setter
def batch(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.batch expects a boolean")
self._batch = value
@property
def build(self):
if self._options is not None:
return self._options.build
return self._build
@build.setter
def build(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.build expects a boolean")
self._build = value
@property
def verbosity(self):
if self._options is not None:
return self._options.verbosity
return self._verbosity
@verbosity.setter
def verbosity(self, value):
self._check_options_initialized()
if value < 0 or value > 3:
raise ValueError("SoSOptions.verbosity expects a value [0..3]")
self._verbosity = value
@property
def verify(self):
if self._options is not None:
return self._options.verify
return self._verify
@verify.setter
def verify(self, value):
self._check_options_initialized()
if value < 0 or value > 3:
raise ValueError("SoSOptions.verify expects a value [0..3]")
self._verify = value
@property
def quiet(self):
if self._options is not None:
return self._options.quiet
return self._quiet
@quiet.setter
def quiet(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.quiet expects a boolean")
self._quiet = value
@property
def debug(self):
if self._options is not None:
return self._options.debug
return self._debug
@debug.setter
def debug(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.debug expects a boolean")
self._debug = value
@property
def case_id(self):
if self._options is not None:
return self._options.case_id
return self._case_id
@case_id.setter
def case_id(self, value):
self._check_options_initialized()
self._case_id = value
@property
def customer_name(self):
if self._options is not None:
return self._options.customer_name
return self._customer_name
@customer_name.setter
def customer_name(self, value):
self._check_options_initialized()
self._customer_name = value
@property
def profiles(self):
if self._options is not None:
return self._options.profiles
return self._profiles
@profiles.setter
def profiles(self, value):
self._check_options_initialized()
self._profiles = value
@property
def list_profiles(self):
if self._options is not None:
return self._options.list_profiles
return self._list_profiles
@list_profiles.setter
def list_profiles(self, value):
self._check_options_initialized()
self._list_profiles = value
@property
def config_file(self):
if self._options is not None:
return self._options.config_file
return self._config_file
@config_file.setter
def config_file(self, value):
self._check_options_initialized()
self._config_file = value
@property
def tmp_dir(self):
if self._options is not None:
return self._options.tmp_dir
return self._tmp_dir
@tmp_dir.setter
def tmp_dir(self, value):
self._check_options_initialized()
self._tmp_dir = value
@property
def report(self):
if self._options is not None:
return self._options.report
return self._report
@report.setter
def report(self, value):
self._check_options_initialized()
if not isinstance(value, bool):
raise TypeError("SoSOptions.report expects a boolean")
self._report = value
@property
def compression_type(self):
if self._options is not None:
return self._options.compression_type
return self._compression_type
@compression_type.setter
def compression_type(self, value):
self._check_options_initialized()
self._compression_type = value
def _parse_args(self, args):
""" Parse command line options and arguments"""
self.parser = parser = OptionParserExtended(option_class=SosOption)
parser.add_option("-l", "--list-plugins", action="store_true",
dest="list_plugins", default=False,
help="list plugins and available plugin options")
parser.add_option("-n", "--skip-plugins", action="extend",
dest="noplugins", type="string",
help="disable these plugins", default=deque())
parser.add_option("-e", "--enable-plugins", action="extend",
dest="enableplugins", type="string",
help="enable these plugins", default=deque())
parser.add_option("-o", "--only-plugins", action="extend",
dest="onlyplugins", type="string",
help="enable these plugins only", default=deque())
parser.add_option("-k", "--plugin-option", action="extend",
dest="plugopts", type="string",
help="plugin options in plugname.option=value "
"format (see -l)",
default=deque())
parser.add_option("--log-size", action="store",
dest="log_size", default=10, type="int",
help="set a limit on the size of collected logs")
parser.add_option("-a", "--alloptions", action="store_true",
dest="usealloptions", default=False,
help="enable all options for loaded plugins")
parser.add_option("--all-logs", action="store_true",
dest="all_logs", default=False,
help="collect all available logs regardless of size")
parser.add_option("--batch", action="store_true",
dest="batch", default=False,
help="batch mode - do not prompt interactively")
parser.add_option("--build", action="store_true",
dest="build", default=False,
help="preserve the temporary directory and do not "
"package results")
parser.add_option("-v", "--verbose", action="count",
dest="verbosity",
help="increase verbosity")
parser.add_option("", "--verify", action="store_true",
dest="verify", default=False,
help="perform data verification during collection")
parser.add_option("", "--quiet", action="store_true",
dest="quiet", default=False,
help="only print fatal errors")
parser.add_option("--debug", action="count",
dest="debug",
help="enable interactive debugging using the python "
"debugger")
parser.add_option("--ticket-number", action="store",
dest="case_id",
help="specify ticket number")
parser.add_option("--case-id", action="store",
dest="case_id",
help="specify case identifier")
parser.add_option("-p", "--profile", action="extend",
dest="profiles", type="string", default=deque(),
help="enable plugins selected by the given profiles")
parser.add_option("--list-profiles", action="store_true",
dest="list_profiles", default=False)
parser.add_option("--name", action="store",
dest="customer_name",
help="specify report name")
parser.add_option("--config-file", action="store",
dest="config_file",
help="specify alternate configuration file")
parser.add_option("--tmp-dir", action="store",
dest="tmp_dir",
help="specify alternate temporary directory",
default=None)
parser.add_option("--no-report", action="store_true",
dest="report",
help="Disable HTML/XML reporting", default=False)
parser.add_option("-z", "--compression-type", dest="compression_type",
help="compression technology to use [auto, zip, "
"gzip, bzip2, xz] (default=auto)",
default="auto")
return parser.parse_args(args)[0]
class SoSReport(object):
"""The main sosreport class"""
def __init__(self, args):
self.loaded_plugins = deque()
self.skipped_plugins = deque()
self.all_options = deque()
self.xml_report = XmlReport()
self.global_plugin_options = {}
self.archive = None
self.tempfile_util = None
self._args = args
try:
import signal
signal.signal(signal.SIGTERM, self.get_exit_handler())
except Exception:
pass # not available in java, but we don't care
self.opts = SoSOptions(args)
self._set_debug()
self._read_config()
try:
self.policy = sos.policies.load()
except KeyboardInterrupt:
self._exit(0)
self._is_root = self.policy.is_root()
self.tmpdir = os.path.abspath(
self.policy.get_tmp_dir(self.opts.tmp_dir))
if not os.path.isdir(self.tmpdir) \
or not os.access(self.tmpdir, os.W_OK):
# write directly to stderr as logging is not initialised yet
sys.stderr.write("temporary directory %s " % self.tmpdir
+ "does not exist or is not writable\n")
self._exit(1)
self.tempfile_util = TempFileUtil(self.tmpdir)
self._set_directories()
def print_header(self):
self.ui_log.info("\n%s\n" % _("sosreport (version %s)" %
(__version__,)))
def get_commons(self):
return {
'cmddir': self.cmddir,
'logdir': self.logdir,
'rptdir': self.rptdir,
'tmpdir': self.tmpdir,
'soslog': self.soslog,
'policy': self.policy,
'verbosity': self.opts.verbosity,
'xmlreport': self.xml_report,
'cmdlineopts': self.opts,
'config': self.config,
'global_plugin_options': self.global_plugin_options,
}
def get_temp_file(self):
return self.tempfile_util.new()
def _set_archive(self):
archive_name = os.path.join(self.tmpdir,
self.policy.get_archive_name())
if self.opts.compression_type == 'auto':
auto_archive = self.policy.get_preferred_archive()
self.archive = auto_archive(archive_name, self.tmpdir)
elif self.opts.compression_type == 'zip':
self.archive = ZipFileArchive(archive_name, self.tmpdir)
else:
self.archive = TarFileArchive(archive_name, self.tmpdir)
self.archive.set_debug(True if self.opts.debug else False)
def _make_archive_paths(self):
self.archive.makedirs(self.cmddir, 0o755)
self.archive.makedirs(self.logdir, 0o755)
self.archive.makedirs(self.rptdir, 0o755)
def _set_directories(self):
self.cmddir = 'sos_commands'
self.logdir = 'sos_logs'
self.rptdir = 'sos_reports'
def _set_debug(self):
if self.opts.debug:
sys.excepthook = self._exception
self.raise_plugins = True
else:
self.raise_plugins = False
@staticmethod
def _exception(etype, eval_, etrace):
""" Wrap exception in debugger if not in tty """
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
import pdb
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
print_()
# ...then start the debugger in post-mortem mode.
pdb.pm()
def _exit(self, error=0):
raise SystemExit()
# sys.exit(error)
def get_exit_handler(self):
def exit_handler(signum, frame):
self._exit()
return exit_handler
def _read_config(self):
self.config = ConfigParser()
if self.opts.config_file:
config_file = self.opts.config_file
else:
config_file = '/etc/sos.conf'
try:
self.config.readfp(open(config_file))
except IOError:
pass
def _setup_logging(self):
# main soslog
self.soslog = logging.getLogger('sos')
self.soslog.setLevel(logging.DEBUG)
self.sos_log_file = self.get_temp_file()
self.sos_log_file.close()
flog = logging.FileHandler(self.sos_log_file.name)
flog.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s'))
flog.setLevel(logging.INFO)
self.soslog.addHandler(flog)
if not self.opts.quiet:
console = logging.StreamHandler(sys.stderr)
console.setFormatter(logging.Formatter('%(message)s'))
if self.opts.verbosity and self.opts.verbosity > 1:
console.setLevel(logging.DEBUG)
flog.setLevel(logging.DEBUG)
elif self.opts.verbosity and self.opts.verbosity > 0:
console.setLevel(logging.INFO)
flog.setLevel(logging.DEBUG)
else:
console.setLevel(logging.WARNING)
self.soslog.addHandler(console)
# ui log
self.ui_log = logging.getLogger('sos_ui')
self.ui_log.setLevel(logging.INFO)
self.sos_ui_log_file = self.get_temp_file()
self.sos_ui_log_file.close()
ui_fhandler = logging.FileHandler(self.sos_ui_log_file.name)
ui_fhandler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s'))
self.ui_log.addHandler(ui_fhandler)
if not self.opts.quiet:
ui_console = logging.StreamHandler(sys.stdout)
ui_console.setFormatter(logging.Formatter('%(message)s'))
ui_console.setLevel(logging.INFO)
self.ui_log.addHandler(ui_console)
def _finish_logging(self):
logging.shutdown()
# Make sure the log files are added before we remove the log
# handlers. This prevents "No handlers could be found.." messages
# from leaking to the console when running in --quiet mode when
# Archive classes attempt to acess the log API.
if getattr(self, "sos_log_file", None):
self.archive.add_file(self.sos_log_file.name,
dest=os.path.join('sos_logs', 'sos.log'))
if getattr(self, "sos_ui_log_file", None):
self.archive.add_file(self.sos_ui_log_file.name,
dest=os.path.join('sos_logs', 'ui.log'))
def _get_disabled_plugins(self):
disabled = []
if self.config.has_option("plugins", "disable"):
disabled = [plugin.strip() for plugin in
self.config.get("plugins", "disable").split(',')]
return disabled
def _is_in_profile(self, plugin_class):
onlyplugins = self.opts.onlyplugins
if not len(self.opts.profiles):
return True
if not hasattr(plugin_class, "profiles"):
return False
if onlyplugins and not self._is_not_specified(plugin_class.name()):
return True
return any([p in self.opts.profiles for p in plugin_class.profiles])
def _is_skipped(self, plugin_name):
return (plugin_name in self.opts.noplugins or
plugin_name in self._get_disabled_plugins())
def _is_inactive(self, plugin_name, pluginClass):
return (not pluginClass(self.get_commons()).check_enabled() and
plugin_name not in self.opts.enableplugins and
plugin_name not in self.opts.onlyplugins)
def _is_not_default(self, plugin_name, pluginClass):
return (not pluginClass(self.get_commons()).default_enabled() and
plugin_name not in self.opts.enableplugins and
plugin_name not in self.opts.onlyplugins)
def _is_not_specified(self, plugin_name):
return (self.opts.onlyplugins and
plugin_name not in self.opts.onlyplugins)
def _skip(self, plugin_class, reason="unknown"):
self.skipped_plugins.append((
plugin_class.name(),
plugin_class(self.get_commons()),
reason
))
def _load(self, plugin_class):
self.loaded_plugins.append((
plugin_class.name(),
plugin_class(self.get_commons())
))
def load_plugins(self):
import sos.plugins
helper = ImporterHelper(sos.plugins)
plugins = helper.get_modules()
self.plugin_names = deque()
self.profiles = set()
using_profiles = len(self.opts.profiles)
# validate and load plugins
for plug in plugins:
plugbase, ext = os.path.splitext(plug)
try:
plugin_classes = import_plugin(
plugbase, tuple(self.policy.valid_subclasses))
if not len(plugin_classes):
# no valid plugin classes for this policy
continue
plugin_class = self.policy.match_plugin(plugin_classes)
if not self.policy.validate_plugin(plugin_class):
self.soslog.warning(
_("plugin %s does not validate, skipping") % plug)
if self.opts.verbosity > 0:
self._skip(plugin_class, _("does not validate"))
continue
if plugin_class.requires_root and not self._is_root:
self.soslog.info(_("plugin %s requires root permissions"
"to execute, skipping") % plug)
self._skip(plugin_class, _("requires root"))
continue
# plug-in is valid, let's decide whether run it or not
self.plugin_names.append(plugbase)
if hasattr(plugin_class, "profiles"):
self.profiles.update(plugin_class.profiles)
in_profile = self._is_in_profile(plugin_class)
if not in_profile:
self._skip(plugin_class, _("excluded"))
continue
if self._is_skipped(plugbase):
self._skip(plugin_class, _("skipped"))
continue
if self._is_inactive(plugbase, plugin_class):
self._skip(plugin_class, _("inactive"))
continue
if self._is_not_default(plugbase, plugin_class):
self._skip(plugin_class, _("optional"))
continue
# true when the null (empty) profile is active
default_profile = not using_profiles and in_profile
if self._is_not_specified(plugbase) and default_profile:
self._skip(plugin_class, _("not specified"))
continue
self._load(plugin_class)
except Exception as e:
self.soslog.warning(_("plugin %s does not install, "
"skipping: %s") % (plug, e))
if self.raise_plugins:
raise
def _set_all_options(self):
if self.opts.usealloptions:
for plugname, plug in self.loaded_plugins:
for name, parms in zip(plug.opt_names, plug.opt_parms):
if type(parms["enabled"]) == bool:
parms["enabled"] = True
def _set_tunables(self):
if self.config.has_section("tunables"):
if not self.opts.plugopts:
self.opts.plugopts = deque()
for opt, val in self.config.items("tunables"):
if not opt.split('.')[0] in self._get_disabled_plugins():
self.opts.plugopts.append(opt + "=" + val)
if self.opts.plugopts:
opts = {}
for opt in self.opts.plugopts:
# split up "general.syslogsize=5"
try:
opt, val = opt.split("=")
except:
val = True
else:
if val.lower() in ["off", "disable", "disabled", "false"]:
val = False
else:
# try to convert string "val" to int()
try:
val = int(val)
except:
pass
# split up "general.syslogsize"
try:
plug, opt = opt.split(".")
except:
plug = opt
opt = True
try:
opts[plug]
except KeyError:
opts[plug] = deque()
opts[plug].append((opt, val))
for plugname, plug in self.loaded_plugins:
if plugname in opts:
for opt, val in opts[plugname]:
if not plug.set_option(opt, val):
self.soslog.error('no such option "%s" for plugin '
'(%s)' % (opt, plugname))
self._exit(1)
del opts[plugname]
for plugname in opts.keys():
self.soslog.error('unable to set option for disabled or '
'non-existing plugin (%s)' % (plugname))
def _check_for_unknown_plugins(self):
import itertools
for plugin in itertools.chain(self.opts.onlyplugins,
self.opts.noplugins,
self.opts.enableplugins):
plugin_name = plugin.split(".")[0]
if plugin_name not in self.plugin_names:
self.soslog.fatal('a non-existing plugin (%s) was specified '
'in the command line' % (plugin_name))
self._exit(1)
def _set_plugin_options(self):
for plugin_name, plugin in self.loaded_plugins:
names, parms = plugin.get_all_options()
for optname, optparm in zip(names, parms):
self.all_options.append((plugin, plugin_name, optname,
optparm))
def list_plugins(self):
if not self.loaded_plugins and not self.skipped_plugins:
self.soslog.fatal(_("no valid plugins found"))
return
if self.loaded_plugins:
self.ui_log.info(_("The following plugins are currently enabled:"))
self.ui_log.info("")
for (plugname, plug) in self.loaded_plugins:
self.ui_log.info(" %-20s %s" % (plugname,
plug.get_description()))
else:
self.ui_log.info(_("No plugin enabled."))
self.ui_log.info("")
if self.skipped_plugins:
self.ui_log.info(_("The following plugins are currently "
"disabled:"))
self.ui_log.info("")
for (plugname, plugclass, reason) in self.skipped_plugins:
self.ui_log.info(" %-20s %-14s %s" % (
plugname,
reason,
plugclass.get_description()))
self.ui_log.info("")
if self.all_options:
self.ui_log.info(_("The following plugin options are available:"))
self.ui_log.info("")
for (plug, plugname, optname, optparm) in self.all_options:
# format option value based on its type (int or bool)
if type(optparm["enabled"]) == bool:
if optparm["enabled"] is True:
tmpopt = "on"
else:
tmpopt = "off"
else:
tmpopt = optparm["enabled"]
self.ui_log.info(" %-25s %-15s %s" % (
plugname + "." + optname, tmpopt, optparm["desc"]))
else:
self.ui_log.info(_("No plugin options available."))
self.ui_log.info("")
profiles = list(self.profiles)
profiles.sort()
lines = _format_list("Profiles: ", profiles, indent=True)
for line in lines:
self.ui_log.info(" %s" % line)
self.ui_log.info("")
self.ui_log.info(" %d profiles, %d plugins"
% (len(self.profiles), len(self.loaded_plugins)))
self.ui_log.info("")
def list_profiles(self):
if not self.profiles:
self.soslog.fatal(_("no valid profiles found"))
return
self.ui_log.info(_("The following profiles are available:"))
self.ui_log.info("")
def _has_prof(c):
return hasattr(c, "profiles")
profiles = list(self.profiles)
profiles.sort()
for profile in profiles:
plugins = []
for name, plugin in self.loaded_plugins:
if _has_prof(plugin) and profile in plugin.profiles:
plugins.append(name)
lines = _format_list("%-15s " % profile, plugins, indent=True)
for line in lines:
self.ui_log.info(" %s" % line)
self.ui_log.info("")
self.ui_log.info(" %d profiles, %d plugins"
% (len(profiles), len(self.loaded_plugins)))
self.ui_log.info("")
def batch(self):
if self.opts.batch:
self.ui_log.info(self.policy.get_msg())
else:
msg = self.policy.get_msg()
msg += _("Press ENTER to continue, or CTRL-C to quit.\n")
try:
input(msg)
except:
self.ui_log.info("")
self._exit()
def _log_plugin_exception(self, plugin_name):
self.soslog.error("%s\n%s" % (plugin_name, traceback.format_exc()))
def prework(self):
self.policy.pre_work()
try:
self.ui_log.info(_(" Setting up archive ..."))
compression_methods = ('auto', 'zip', 'bzip2', 'gzip', 'xz')
method = self.opts.compression_type
if method not in compression_methods:
compression_list = ', '.join(compression_methods)
self.ui_log.error("")
self.ui_log.error("Invalid compression specified: " + method)
self.ui_log.error("Valid types are: " + compression_list)
self.ui_log.error("")
self._exit(1)
self._set_archive()
self._make_archive_paths()
return
except (OSError, IOError) as e:
if e.errno in fatal_fs_errors:
self.ui_log.error("")
self.ui_log.error(" %s while setting up archive" % e.strerror)
self.ui_log.error("")
else:
raise e
except Exception as e:
import traceback
self.ui_log.error("")
self.ui_log.error(" Unexpected exception setting up archive:")
traceback.print_exc(e)
self.ui_log.error(e)
self._exit(1)
def setup(self):
msg = "[%s:%s] executing 'sosreport %s'"
self.soslog.info(msg % (__name__, "setup", " ".join(self._args)))
self.ui_log.info(_(" Setting up plugins ..."))
for plugname, plug in self.loaded_plugins:
try:
plug.archive = self.archive
plug.setup()
except KeyboardInterrupt:
raise
except (OSError, IOError) as e:
if e.errno in fatal_fs_errors:
self.ui_log.error("")
self.ui_log.error(" %s while setting up plugins"
% e.strerror)
self.ui_log.error("")
self._exit(1)
except:
if self.raise_plugins:
raise
else:
self._log_plugin_exception(plugname)
def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt')
def collect(self):
self.ui_log.info(_(" Running plugins. Please wait ..."))
self.ui_log.info("")
plugruncount = 0
|
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 collect(self):
self.ui_log.info(_(" Running plugins. Please wait ..."))
self.ui_log.info("")
plugruncount = 0
Cheatsheet (for next line):
- We are in the collect() method of the SoSReport class.
- The method is responsible for running plugins.
- The variable plugruncount is initialized to 0.
- The method is expected to iterate over the loaded plugins and run them.
- The plugins are stored in the self.loaded_plugins deque.
- Each plugin is an instance of a plugin class, which has a run() method.
- The run() method is expected to collect data and add it to the archive.
Next line will likely be:
for plugname, plug in self.loaded_plugins:
This line will start the iteration over the loaded plugins, allowing the collect() method to run each plugin and collect its data.
|
|
Please complete the code given below.
# -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>.
from MaKaC.common.fossilize import IFossil
from MaKaC.common.Conversion import Conversion
from MaKaC.webinterface import urlHandlers
from indico.core.fossils.event import ISupportInfoFossil
class ICategoryFossil(IFossil):
def getId(self):
""" Category Id """
def getName(self):
""" Category Name """
class IConferenceMinimalFossil(IFossil):
def getId(self):
"""Conference id"""
def getTitle(self):
"""Conference title"""
class IConferenceFossil(IConferenceMinimalFossil):
def getType(self):
""" Event type: 'conference', 'meeting', 'simple_event' """
def getDescription(self):
"""Conference description"""
def getLocation(self):
""" Location (CERN/...) """
getLocation.convert = lambda l: l and l.getName()
def getRoom(self):
""" Room (inside location) """
getRoom.convert = lambda r: r and r.getName()
def getAddress(self):
""" Address of the event """
getAddress.produce = lambda s: s.getLocation().getAddress() if s.getLocation() is not None else None
def getRoomBookingList(self):
""" Reservations """
getRoomBookingList.convert = Conversion.reservationsList
getRoomBookingList.name = "bookedRooms"
def getStartDate(self):
""" Start Date """
getStartDate.convert = Conversion.datetime
def getEndDate(self):
""" End Date """
getEndDate.convert = Conversion.datetime
def getAdjustedStartDate(self):
""" Adjusted Start Date """
getAdjustedStartDate.convert = Conversion.datetime
def getAdjustedEndDate(self):
""" Adjusted End Date """
getAdjustedEndDate.convert = Conversion.datetime
def getTimezone(self):
""" Time zone """
def getSupportInfo(self):
""" Support Info"""
getSupportInfo.result = ISupportInfoFossil
class IConferenceParticipationMinimalFossil(IFossil):
def getFirstName( self ):
""" Conference Participation First Name """
def getFamilyName( self ):
""" Conference Participation Family Name """
def getDirectFullName(self):
""" Conference Participation Full Name """
getDirectFullName.name = "name"
class IConferenceParticipationFossil(IConferenceParticipationMinimalFossil):
def getId( self ):
""" Conference Participation Id """
def getFullName( self ):
""" Conference Participation Full Name """
def getFullNameNoTitle(self):
""" Conference Participation Full Name """
getFullNameNoTitle.name = "name"
def getAffiliation(self):
"""Conference Participation Affiliation """
def getAddress(self):
"""Conference Participation Address """
def getEmail(self):
"""Conference Participation Email """
def getFax(self):
"""Conference Participation Fax """
def getTitle(self):
"""Conference Participation Title """
def getPhone(self):
"""Conference Participation Phone """
class IResourceBasicFossil(IFossil):
def getName(self):
""" Name of the Resource """
def getDescription(self):
""" Resource Description """
class IResourceMinimalFossil(IResourceBasicFossil):
def getProtectionURL(self):
""" Resource protection URL """
getProtectionURL.produce = lambda s: str(urlHandlers.UHMaterialModification.getURL(s.getOwner()))
class ILinkMinimalFossil(IResourceMinimalFossil):
def getURL(self):
""" URL of the file pointed by the link """
getURL.name = "url"
class ILocalFileMinimalFossil(IResourceMinimalFossil):
def getURL(self):
""" URL of the Local File """
getURL.produce = lambda s: str(urlHandlers.UHFileAccess.getURL(s))
getURL.name = "url"
class IResourceFossil(IResourceMinimalFossil):
def getId(self):
""" Resource Id """
def getDescription(self):
""" Resource description """
def getAccessProtectionLevel(self):
""" Resource Access Protection Level """
getAccessProtectionLevel.name = "protection"
def getReviewingState(self):
""" Resource reviewing state """
def getPDFConversionStatus(self):
""" Resource PDF conversion status"""
getPDFConversionStatus.name = "pdfConversionStatus"
class ILinkFossil(IResourceFossil, ILinkMinimalFossil):
def getType(self):
""" Type """
getType.produce = lambda s: 'external'
class ILocalFileFossil(IResourceFossil, ILocalFileMinimalFossil):
def getType(self):
""" Type """
getType.produce = lambda s: 'stored'
class ILocalFileInfoFossil(IFossil):
def getFileName(self):
""" Local File Filename """
getFileName.name = "file.fileName"
def getFileType(self):
""" Local File File Type """
getFileType.name = "file.fileType"
def getCreationDate(self):
""" Local File Creation Date """
getCreationDate.convert = lambda s: s.strftime("%d.%m.%Y %H:%M:%S")
getCreationDate.name = "file.creationDate"
def getSize(self):
""" Local File File Size """
getSize.name = "file.fileSize"
class ILocalFileExtendedFossil(ILocalFileFossil, ILocalFileInfoFossil):
pass
class ILocalFileAbstractMaterialFossil(IResourceBasicFossil, ILocalFileInfoFossil):
def getURL(self):
""" URL of the Local File """
getURL.produce = lambda s: str(urlHandlers.UHAbstractAttachmentFileAccess.getURL(s))
getURL.name = "url"
class IMaterialMinimalFossil(IFossil):
def getId(self):
""" Material Id """
def getTitle( self ):
""" Material Title """
def getDescription( self ):
""" Material Description """
def getResourceList(self):
""" Material Resource List """
getResourceList.result = {"MaKaC.conference.Link": ILinkMinimalFossil, "MaKaC.conference.LocalFile": ILocalFileMinimalFossil}
getResourceList.name = "resources"
def getType(self):
""" The type of material"""
def getProtectionURL(self):
""" Material protection URL """
getProtectionURL.produce = lambda s: str(urlHandlers.UHMaterialModification.getURL(s))
class IMaterialFossil(IMaterialMinimalFossil):
def getReviewingState(self):
""" Material Reviewing State """
def getAccessProtectionLevel(self):
""" Material Access Protection Level """
getAccessProtectionLevel.name = "protection"
def hasProtectedOwner(self):
""" Does it have a protected owner ?"""
def getDescription(self):
""" Material Description """
def isHidden(self):
""" Whether the Material is hidden or not """
isHidden.name = 'hidden'
def getAccessKey(self):
""" Material Access Key """
def getResourceList(self):
""" Material Resource List """
getResourceList.result = {"MaKaC.conference.Link": ILinkFossil, "MaKaC.conference.LocalFile": ILocalFileExtendedFossil}
getResourceList.name = "resources"
def getMainResource(self):
""" The main resource"""
getMainResource.result = {"MaKaC.conference.Link": ILinkFossil, "MaKaC.conference.LocalFile": ILocalFileExtendedFossil}
def isBuiltin(self):
""" The material is a default one (builtin) """
class ISessionBasicFossil(IFossil):
def getId(self):
""" Session Id """
def getTitle(self):
""" Session Title """
def getDescription(self):
""" Session Description """
class ISessionFossil(ISessionBasicFossil):
def getAllMaterialList(self):
""" Session List of all material """
getAllMaterialList.result = IMaterialFossil
getAllMaterialList.name = "material"
def getNumSlots(self):
""" Number of slots present in the session """
getNumSlots.produce = lambda s : len(s.getSlotList())
def getColor(self):
""" Session Color """
def getAdjustedStartDate(self):
""" Session Start Date """
getAdjustedStartDate.convert = Conversion.datetime
getAdjustedStartDate.name = "startDate"
def getAdjustedEndDate(self):
""" Session End Date """
getAdjustedEndDate.convert = Conversion.datetime
getAdjustedEndDate.name = "endDate"
def getLocation(self):
""" Session Location """
getLocation.convert = Conversion.locationName
def getAddress(self):
""" Session Address """
getAddress.produce = lambda s: s.getLocation()
getAddress.convert = Conversion.locationAddress
def getRoom(self):
""" Session Room """
getRoom.convert = Conversion.roomName
def getRoomFullName(self):
""" Session Room """
|
[
" getRoomFullName.produce = lambda s: s.getRoom()"
] | 893
|
lcc
|
python
| null |
8a746e0f9e09ec54d8d1e7bf7ca7b8e16731fe8f4652e145
| 87
|
Your task is code completion.
# -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
##
## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>.
from MaKaC.common.fossilize import IFossil
from MaKaC.common.Conversion import Conversion
from MaKaC.webinterface import urlHandlers
from indico.core.fossils.event import ISupportInfoFossil
class ICategoryFossil(IFossil):
def getId(self):
""" Category Id """
def getName(self):
""" Category Name """
class IConferenceMinimalFossil(IFossil):
def getId(self):
"""Conference id"""
def getTitle(self):
"""Conference title"""
class IConferenceFossil(IConferenceMinimalFossil):
def getType(self):
""" Event type: 'conference', 'meeting', 'simple_event' """
def getDescription(self):
"""Conference description"""
def getLocation(self):
""" Location (CERN/...) """
getLocation.convert = lambda l: l and l.getName()
def getRoom(self):
""" Room (inside location) """
getRoom.convert = lambda r: r and r.getName()
def getAddress(self):
""" Address of the event """
getAddress.produce = lambda s: s.getLocation().getAddress() if s.getLocation() is not None else None
def getRoomBookingList(self):
""" Reservations """
getRoomBookingList.convert = Conversion.reservationsList
getRoomBookingList.name = "bookedRooms"
def getStartDate(self):
""" Start Date """
getStartDate.convert = Conversion.datetime
def getEndDate(self):
""" End Date """
getEndDate.convert = Conversion.datetime
def getAdjustedStartDate(self):
""" Adjusted Start Date """
getAdjustedStartDate.convert = Conversion.datetime
def getAdjustedEndDate(self):
""" Adjusted End Date """
getAdjustedEndDate.convert = Conversion.datetime
def getTimezone(self):
""" Time zone """
def getSupportInfo(self):
""" Support Info"""
getSupportInfo.result = ISupportInfoFossil
class IConferenceParticipationMinimalFossil(IFossil):
def getFirstName( self ):
""" Conference Participation First Name """
def getFamilyName( self ):
""" Conference Participation Family Name """
def getDirectFullName(self):
""" Conference Participation Full Name """
getDirectFullName.name = "name"
class IConferenceParticipationFossil(IConferenceParticipationMinimalFossil):
def getId( self ):
""" Conference Participation Id """
def getFullName( self ):
""" Conference Participation Full Name """
def getFullNameNoTitle(self):
""" Conference Participation Full Name """
getFullNameNoTitle.name = "name"
def getAffiliation(self):
"""Conference Participation Affiliation """
def getAddress(self):
"""Conference Participation Address """
def getEmail(self):
"""Conference Participation Email """
def getFax(self):
"""Conference Participation Fax """
def getTitle(self):
"""Conference Participation Title """
def getPhone(self):
"""Conference Participation Phone """
class IResourceBasicFossil(IFossil):
def getName(self):
""" Name of the Resource """
def getDescription(self):
""" Resource Description """
class IResourceMinimalFossil(IResourceBasicFossil):
def getProtectionURL(self):
""" Resource protection URL """
getProtectionURL.produce = lambda s: str(urlHandlers.UHMaterialModification.getURL(s.getOwner()))
class ILinkMinimalFossil(IResourceMinimalFossil):
def getURL(self):
""" URL of the file pointed by the link """
getURL.name = "url"
class ILocalFileMinimalFossil(IResourceMinimalFossil):
def getURL(self):
""" URL of the Local File """
getURL.produce = lambda s: str(urlHandlers.UHFileAccess.getURL(s))
getURL.name = "url"
class IResourceFossil(IResourceMinimalFossil):
def getId(self):
""" Resource Id """
def getDescription(self):
""" Resource description """
def getAccessProtectionLevel(self):
""" Resource Access Protection Level """
getAccessProtectionLevel.name = "protection"
def getReviewingState(self):
""" Resource reviewing state """
def getPDFConversionStatus(self):
""" Resource PDF conversion status"""
getPDFConversionStatus.name = "pdfConversionStatus"
class ILinkFossil(IResourceFossil, ILinkMinimalFossil):
def getType(self):
""" Type """
getType.produce = lambda s: 'external'
class ILocalFileFossil(IResourceFossil, ILocalFileMinimalFossil):
def getType(self):
""" Type """
getType.produce = lambda s: 'stored'
class ILocalFileInfoFossil(IFossil):
def getFileName(self):
""" Local File Filename """
getFileName.name = "file.fileName"
def getFileType(self):
""" Local File File Type """
getFileType.name = "file.fileType"
def getCreationDate(self):
""" Local File Creation Date """
getCreationDate.convert = lambda s: s.strftime("%d.%m.%Y %H:%M:%S")
getCreationDate.name = "file.creationDate"
def getSize(self):
""" Local File File Size """
getSize.name = "file.fileSize"
class ILocalFileExtendedFossil(ILocalFileFossil, ILocalFileInfoFossil):
pass
class ILocalFileAbstractMaterialFossil(IResourceBasicFossil, ILocalFileInfoFossil):
def getURL(self):
""" URL of the Local File """
getURL.produce = lambda s: str(urlHandlers.UHAbstractAttachmentFileAccess.getURL(s))
getURL.name = "url"
class IMaterialMinimalFossil(IFossil):
def getId(self):
""" Material Id """
def getTitle( self ):
""" Material Title """
def getDescription( self ):
""" Material Description """
def getResourceList(self):
""" Material Resource List """
getResourceList.result = {"MaKaC.conference.Link": ILinkMinimalFossil, "MaKaC.conference.LocalFile": ILocalFileMinimalFossil}
getResourceList.name = "resources"
def getType(self):
""" The type of material"""
def getProtectionURL(self):
""" Material protection URL """
getProtectionURL.produce = lambda s: str(urlHandlers.UHMaterialModification.getURL(s))
class IMaterialFossil(IMaterialMinimalFossil):
def getReviewingState(self):
""" Material Reviewing State """
def getAccessProtectionLevel(self):
""" Material Access Protection Level """
getAccessProtectionLevel.name = "protection"
def hasProtectedOwner(self):
""" Does it have a protected owner ?"""
def getDescription(self):
""" Material Description """
def isHidden(self):
""" Whether the Material is hidden or not """
isHidden.name = 'hidden'
def getAccessKey(self):
""" Material Access Key """
def getResourceList(self):
""" Material Resource List """
getResourceList.result = {"MaKaC.conference.Link": ILinkFossil, "MaKaC.conference.LocalFile": ILocalFileExtendedFossil}
getResourceList.name = "resources"
def getMainResource(self):
""" The main resource"""
getMainResource.result = {"MaKaC.conference.Link": ILinkFossil, "MaKaC.conference.LocalFile": ILocalFileExtendedFossil}
def isBuiltin(self):
""" The material is a default one (builtin) """
class ISessionBasicFossil(IFossil):
def getId(self):
""" Session Id """
def getTitle(self):
""" Session Title """
def getDescription(self):
""" Session Description """
class ISessionFossil(ISessionBasicFossil):
def getAllMaterialList(self):
""" Session List of all material """
getAllMaterialList.result = IMaterialFossil
getAllMaterialList.name = "material"
def getNumSlots(self):
""" Number of slots present in the session """
getNumSlots.produce = lambda s : len(s.getSlotList())
def getColor(self):
""" Session Color """
def getAdjustedStartDate(self):
""" Session Start Date """
getAdjustedStartDate.convert = Conversion.datetime
getAdjustedStartDate.name = "startDate"
def getAdjustedEndDate(self):
""" Session End Date """
getAdjustedEndDate.convert = Conversion.datetime
getAdjustedEndDate.name = "endDate"
def getLocation(self):
""" Session Location """
getLocation.convert = Conversion.locationName
def getAddress(self):
""" Session Address """
getAddress.produce = lambda s: s.getLocation()
getAddress.convert = Conversion.locationAddress
def getRoom(self):
""" Session Room """
getRoom.convert = Conversion.roomName
def getRoomFullName(self):
""" Session Room """
|
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:
**IFossil Interface**
- `IFossil` is the base interface for all fossils.
- It has no methods defined in the given code snippet.
**ICategoryFossil**
- `ICategoryFossil` inherits from `IFossil`.
- It has two methods: `getId()` and `getName()`.
**IConferenceMinimalFossil**
- `IConferenceMinimalFossil` inherits from `IFossil`.
- It has two methods: `getId()` and `getTitle()`.
**IConferenceFossil**
- `IConferenceFossil` inherits from `IConferenceMinimalFossil`.
- It has several methods:
- `getType()`
- `getDescription()`
- `getLocation()`
- `getRoom()`
- `getAddress()`
- `getRoomBookingList()`
- `getStartDate()`
- `getEndDate()`
- `getAdjustedStartDate()`
- `getAdjustedEndDate()`
- `getTimezone()`
- `getSupportInfo()`
**IConferenceParticipationMinimalFossil**
- `IConferenceParticipationMinimalFossil` inherits from `IFossil`.
- It has three methods:
- `getFirstName()`
- `getFamilyName()`
- `getDirectFullName()`
**IConferenceParticipationFossil**
- `IConferenceParticipationFossil` inherits from `IConferenceParticipationMinimalFossil`.
- It has several methods:
- `getId()`
- `getFullName()`
- `getFullNameNoTitle()`
- `getAffiliation()`
- `getAddress()`
- `getEmail()`
- `getFax()`
- `getTitle()`
- `getPhone()`
**IResourceBasicFossil**
- `IResourceBasicFossil` inherits from `IFossil`.
- It has two methods:
- `getName()`
- `getDescription()`
**IResourceMinimalFossil**
- `IResourceMinimalFossil` inherits from `IResourceBasicFossil`.
- It has two methods:
- `getProtectionURL()`
**ILinkMinimalFossil**
- `ILinkMinimalFossil` inherits from `IResourceMinimalFossil`.
- It has one method:
- `getURL()`
**ILocalFileMinimalFossil**
- `ILocalFileMinimalFossil` inherits from `IResourceMinimalFossil`.
- It has one method:
- `getURL()`
**IResourceFossil**
- `IResourceFossil` inherits from `IResourceMinimalFossil`.
- It has four methods:
- `getId()`
- `getDescription()`
- `getAccessProtectionLevel()`
- `getReviewingState()`
- `getPDFConversionStatus()`
**ILinkFossil**
- `ILinkFossil` inherits from `IResourceFossil` and `ILinkMinimalFossil`.
- It has one method:
- `getType()`
**ILocalFileFossil**
- `ILocalFileFossil` inherits from `IResourceFossil` and `ILocalFileMinimalFossil`.
- It has one method:
- `getType()`
**ILocalFileInfoFossil**
- `ILocalFileInfoFossil` inherits from `IFossil`.
- It has four methods:
- `getFileName()`
- `getFileType()`
- `getCreationDate()`
- `getSize()`
**ILocalFileExtendedFossil**
- `ILocalFileExtendedFossil` inherits from `ILocalFileFossil` and `ILocalFileInfoFossil`.
- It has no additional methods.
**ILocalFileAbstractMaterialFossil**
- `ILocalFileAbstractMaterialFossil` inherits from `IResourceBasicFossil` and `ILocalFileInfoFossil`.
- It has one method:
- `getURL()`
**IMaterialMinimalFossil**
- `IMaterialMinimalFossil` inherits from `IFossil`.
- It has five methods:
- `getId()`
- `getTitle()`
- `getDescription()`
- `getResourceList()`
- `getType()`
- `getProtectionURL()`
**IMaterialFossil**
- `IMaterialFossil` inherits from `IMaterialMinimalFossil`.
- It has six methods:
- `getReviewingState()`
- `getAccessProtectionLevel()`
- `hasProtectedOwner()`
- `getDescription()`
- `isHidden()`
- `getAccessKey()`
- `getResourceList()`
- `getMainResource()`
- `isBuiltin()`
**ISessionBasicFossil**
- `ISessionBasicFossil` inherits from `IFossil`.
- It has three methods:
- `getId()`
- `getTitle()`
- `getDescription()`
**ISessionFossil**
- `ISessionFossil` inherits from `ISessionBasicFossil`.
- It has several methods:
- `getAllMaterialList()`
- `getNumSlots()`
- `getColor()`
- `getAdjustedStartDate()`
- `getAdjustedEndDate()`
- `getLocation()`
- `getAddress()`
- `getRoom()`
- `getRoomFullName()`
Given this cheat sheet, I'm ready to solve the code completion task. Please provide the task.
|
|
Please complete the code given below.
/*
* Copyright (c) Mirth Corporation. All rights reserved.
*
* http://www.mirthcorp.com
*
* The software in this package is published under the terms of the MPL license a copy of which has
* been included with this distribution in the LICENSE.txt file.
*/
package com.mirth.connect.client.ui;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.prefs.Preferences;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import com.mirth.connect.client.core.ClientException;
import com.mirth.connect.client.ui.browsers.message.MessageBrowser;
import com.mirth.connect.client.ui.components.MirthButton;
import com.mirth.connect.client.ui.components.MirthCheckBox;
import com.mirth.connect.client.ui.components.MirthRadioButton;
import com.mirth.connect.client.ui.components.MirthTextField;
import com.mirth.connect.client.ui.util.DialogUtils;
import com.mirth.connect.donkey.model.message.Message;
import com.mirth.connect.model.MessageImportResult;
import com.mirth.connect.util.MessageImporter;
import com.mirth.connect.util.MessageImporter.MessageImportInvalidPathException;
import com.mirth.connect.util.messagewriter.MessageWriter;
import com.mirth.connect.util.messagewriter.MessageWriterException;
public class MessageImportDialog extends JDialog {
private String channelId;
private MessageBrowser messageBrowser;
private Frame parent;
private Preferences userPreferences;
private JLabel importFromLabel = new JLabel("Import From:");
private ButtonGroup importFromButtonGroup = new ButtonGroup();
private MirthRadioButton importServerRadio = new MirthRadioButton("Server");
private MirthRadioButton importLocalRadio = new MirthRadioButton("My Computer");
private MirthButton browseButton = new MirthButton("Browse...");
private JLabel fileLabel = new JLabel("File/Folder/Archive:");
private MirthTextField fileTextField = new MirthTextField();
private MirthCheckBox subfoldersCheckbox = new MirthCheckBox("Include Sub-folders");
private JLabel noteLabel = new JLabel("<html><i>Note: RECEIVED, QUEUED, or PENDING messages will be set to ERROR upon import.</i></html>");
private MirthButton importButton = new MirthButton("Import");
private MirthButton cancelButton = new MirthButton("Cancel");
public MessageImportDialog() {
super(PlatformUI.MIRTH_FRAME);
parent = PlatformUI.MIRTH_FRAME;
userPreferences = Frame.userPreferences;
setTitle("Import Messages");
setBackground(new Color(255, 255, 255));
setLocationRelativeTo(null);
setModal(true);
initComponents();
initLayout();
pack();
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public void setMessageBrowser(MessageBrowser messageBrowser) {
this.messageBrowser = messageBrowser;
}
@Override
public void setBackground(Color color) {
super.setBackground(color);
getContentPane().setBackground(color);
importServerRadio.setBackground(color);
importLocalRadio.setBackground(color);
subfoldersCheckbox.setBackground(color);
}
private void initComponents() {
importServerRadio.setToolTipText("<html>Import messages from a file, folder or archive<br />on the Mirth Connect Server.</html>");
importLocalRadio.setToolTipText("<html>Import messages from a file, folder<br />or archive on this computer.</html>");
fileTextField.setToolTipText("<html>A file containing message(s) in XML format, or a folder/archive<br />containing files with message(s) in XML format.</html>");
subfoldersCheckbox.setToolTipText("<html>If checked, sub-folders of the folder/archive shown above<br />will be searched for messages to import.</html>");
importFromButtonGroup.add(importServerRadio);
importFromButtonGroup.add(importLocalRadio);
importServerRadio.setSelected(true);
subfoldersCheckbox.setSelected(true);
browseButton.setEnabled(false);
ActionListener browseSelected = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
browseSelected();
}
};
ActionListener importDestinationChanged = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (importServerRadio.isSelected()) {
fileTextField.setText(null);
browseButton.setEnabled(false);
} else {
fileTextField.setText(null);
browseButton.setEnabled(true);
}
}
};
ActionListener importMessages = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
importMessages();
}
};
ActionListener cancel = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
};
browseButton.addActionListener(browseSelected);
importServerRadio.addActionListener(importDestinationChanged);
importLocalRadio.addActionListener(importDestinationChanged);
importButton.addActionListener(importMessages);
cancelButton.addActionListener(cancel);
DialogUtils.registerEscapeKey(this, cancel);
}
private void browseSelected() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (userPreferences != null) {
File currentDir = new File(userPreferences.get("currentDirectory", ""));
if (currentDir.exists()) {
chooser.setCurrentDirectory(currentDir);
}
}
if (chooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
if (userPreferences != null) {
userPreferences.put("currentDirectory", chooser.getCurrentDirectory().getPath());
}
fileTextField.setText(chooser.getSelectedFile().getAbsolutePath());
}
}
private void initLayout() {
setLayout(new MigLayout("insets 12, wrap", "[right]4[left, grow]", ""));
add(importFromLabel);
add(importServerRadio, "split 3");
add(importLocalRadio);
add(browseButton);
add(fileLabel);
add(fileTextField, "grow");
add(subfoldersCheckbox, "skip");
add(noteLabel, "skip, grow, pushy, wrap push");
add(new JSeparator(), "grow, gaptop 6, span");
add(importButton, "skip, split 2, gaptop 4, alignx right, width 60");
add(cancelButton, "width 60");
}
private void importMessages() {
if (StringUtils.isBlank(fileTextField.getText())) {
fileTextField.setBackground(UIConstants.INVALID_COLOR);
parent.alertError(parent, "Please enter a file/folder to import.");
setVisible(true);
return;
} else {
fileTextField.setBackground(null);
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
MessageImportResult result;
try {
if (importLocalRadio.isSelected()) {
MessageWriter messageWriter = new MessageWriter() {
@Override
public boolean write(Message message) throws MessageWriterException {
try {
parent.mirthClient.importMessage(channelId, message);
} catch (ClientException e) {
|
[
" throw new MessageWriterException(e);"
] | 543
|
lcc
|
java
| null |
bf41ff7b860961e0d3143422090577f24d568a16dd294083
| 88
|
Your task is code completion.
/*
* Copyright (c) Mirth Corporation. All rights reserved.
*
* http://www.mirthcorp.com
*
* The software in this package is published under the terms of the MPL license a copy of which has
* been included with this distribution in the LICENSE.txt file.
*/
package com.mirth.connect.client.ui;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.prefs.Preferences;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import com.mirth.connect.client.core.ClientException;
import com.mirth.connect.client.ui.browsers.message.MessageBrowser;
import com.mirth.connect.client.ui.components.MirthButton;
import com.mirth.connect.client.ui.components.MirthCheckBox;
import com.mirth.connect.client.ui.components.MirthRadioButton;
import com.mirth.connect.client.ui.components.MirthTextField;
import com.mirth.connect.client.ui.util.DialogUtils;
import com.mirth.connect.donkey.model.message.Message;
import com.mirth.connect.model.MessageImportResult;
import com.mirth.connect.util.MessageImporter;
import com.mirth.connect.util.MessageImporter.MessageImportInvalidPathException;
import com.mirth.connect.util.messagewriter.MessageWriter;
import com.mirth.connect.util.messagewriter.MessageWriterException;
public class MessageImportDialog extends JDialog {
private String channelId;
private MessageBrowser messageBrowser;
private Frame parent;
private Preferences userPreferences;
private JLabel importFromLabel = new JLabel("Import From:");
private ButtonGroup importFromButtonGroup = new ButtonGroup();
private MirthRadioButton importServerRadio = new MirthRadioButton("Server");
private MirthRadioButton importLocalRadio = new MirthRadioButton("My Computer");
private MirthButton browseButton = new MirthButton("Browse...");
private JLabel fileLabel = new JLabel("File/Folder/Archive:");
private MirthTextField fileTextField = new MirthTextField();
private MirthCheckBox subfoldersCheckbox = new MirthCheckBox("Include Sub-folders");
private JLabel noteLabel = new JLabel("<html><i>Note: RECEIVED, QUEUED, or PENDING messages will be set to ERROR upon import.</i></html>");
private MirthButton importButton = new MirthButton("Import");
private MirthButton cancelButton = new MirthButton("Cancel");
public MessageImportDialog() {
super(PlatformUI.MIRTH_FRAME);
parent = PlatformUI.MIRTH_FRAME;
userPreferences = Frame.userPreferences;
setTitle("Import Messages");
setBackground(new Color(255, 255, 255));
setLocationRelativeTo(null);
setModal(true);
initComponents();
initLayout();
pack();
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public void setMessageBrowser(MessageBrowser messageBrowser) {
this.messageBrowser = messageBrowser;
}
@Override
public void setBackground(Color color) {
super.setBackground(color);
getContentPane().setBackground(color);
importServerRadio.setBackground(color);
importLocalRadio.setBackground(color);
subfoldersCheckbox.setBackground(color);
}
private void initComponents() {
importServerRadio.setToolTipText("<html>Import messages from a file, folder or archive<br />on the Mirth Connect Server.</html>");
importLocalRadio.setToolTipText("<html>Import messages from a file, folder<br />or archive on this computer.</html>");
fileTextField.setToolTipText("<html>A file containing message(s) in XML format, or a folder/archive<br />containing files with message(s) in XML format.</html>");
subfoldersCheckbox.setToolTipText("<html>If checked, sub-folders of the folder/archive shown above<br />will be searched for messages to import.</html>");
importFromButtonGroup.add(importServerRadio);
importFromButtonGroup.add(importLocalRadio);
importServerRadio.setSelected(true);
subfoldersCheckbox.setSelected(true);
browseButton.setEnabled(false);
ActionListener browseSelected = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
browseSelected();
}
};
ActionListener importDestinationChanged = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (importServerRadio.isSelected()) {
fileTextField.setText(null);
browseButton.setEnabled(false);
} else {
fileTextField.setText(null);
browseButton.setEnabled(true);
}
}
};
ActionListener importMessages = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
importMessages();
}
};
ActionListener cancel = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
};
browseButton.addActionListener(browseSelected);
importServerRadio.addActionListener(importDestinationChanged);
importLocalRadio.addActionListener(importDestinationChanged);
importButton.addActionListener(importMessages);
cancelButton.addActionListener(cancel);
DialogUtils.registerEscapeKey(this, cancel);
}
private void browseSelected() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (userPreferences != null) {
File currentDir = new File(userPreferences.get("currentDirectory", ""));
if (currentDir.exists()) {
chooser.setCurrentDirectory(currentDir);
}
}
if (chooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
if (userPreferences != null) {
userPreferences.put("currentDirectory", chooser.getCurrentDirectory().getPath());
}
fileTextField.setText(chooser.getSelectedFile().getAbsolutePath());
}
}
private void initLayout() {
setLayout(new MigLayout("insets 12, wrap", "[right]4[left, grow]", ""));
add(importFromLabel);
add(importServerRadio, "split 3");
add(importLocalRadio);
add(browseButton);
add(fileLabel);
add(fileTextField, "grow");
add(subfoldersCheckbox, "skip");
add(noteLabel, "skip, grow, pushy, wrap push");
add(new JSeparator(), "grow, gaptop 6, span");
add(importButton, "skip, split 2, gaptop 4, alignx right, width 60");
add(cancelButton, "width 60");
}
private void importMessages() {
if (StringUtils.isBlank(fileTextField.getText())) {
fileTextField.setBackground(UIConstants.INVALID_COLOR);
parent.alertError(parent, "Please enter a file/folder to import.");
setVisible(true);
return;
} else {
fileTextField.setBackground(null);
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
MessageImportResult result;
try {
if (importLocalRadio.isSelected()) {
MessageWriter messageWriter = new MessageWriter() {
@Override
public boolean write(Message message) throws MessageWriterException {
try {
parent.mirthClient.importMessage(channelId, message);
} catch (ClientException e) {
|
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]
private void importMessages() {
if (StringUtils.isBlank(fileTextField.getText())) {
fileTextField.setBackground(UIConstants.INVALID_COLOR);
parent.alertError(parent, "Please enter a file/folder to import.");
setVisible(true);
return;
} else {
fileTextField.setBackground(null);
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
MessageImportResult result;
try {
if (importLocalRadio.isSelected()) {
MessageWriter messageWriter = new MessageWriter() {
@Override
public boolean write(Message message) throws MessageWriterException {
try {
parent.mirthClient.importMessage(channelId, message);
} catch (ClientException e) {
// Handle exception
}
return true;
}
};
// [Current line]
// [Relevant lines: MessageWriter declaration, importLocalRadio condition, try block]
Cheatsheet (for next line):
- We are in the importMessages() method, specifically in the try block where importLocalRadio is selected.
- The MessageWriter object is declared and initialized with a custom write() method.
- The write() method is called with the parent.mirthClient.importMessage() method, which imports a message.
- The importMessage() method throws a ClientException, which is caught and handled within the write() method.
- The write() method returns a boolean value indicating success or failure.
- The MessageImportResult result is declared but not used; it might be used to store the result of the import operation.
- Convention: The next line should continue the import process, likely by calling a method to import the messages.
Next line will likely be: result = MessageImporter.importMessages(channelId, messageWriter);
|
|
Please complete the code given below.
/*
* Axiom Stack Web Application Framework
* Copyright (C) 2008 Axiom Software Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Axiom Software Inc., 11480 Commerce Park Drive, Third Floor, Reston, VA 20191 USA
* email: info@axiomsoftwareinc.com
*/
package axiom.scripting.rhino;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.store.Directory;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Undefined;
import axiom.framework.core.Application;
import axiom.objectmodel.db.DbKey;
import axiom.objectmodel.db.PathIndexer;
import axiom.objectmodel.dom.LuceneManager;
import axiom.scripting.rhino.extensions.filter.IFilter;
import axiom.scripting.rhino.extensions.filter.SortObject;
import axiom.util.EhCacheMap;
public abstract class QueryDispatcher {
public static final String SORT_FIELD = "sort";
public static final String MAXLENGTH_FIELD = "maxlength";
public static final String UNIQUE_FIELD = "unique";
public static final String FIELD = "field";
public static final String LAYER = "layer";
public static final String VIEW = "view";
protected Application app;
protected RhinoCore core;
protected LuceneManager lmgr;
protected Directory directory;
protected PathIndexer pindxr;
protected QueryParser qparser;
protected EhCacheMap cache;
public QueryDispatcher(){
}
public QueryDispatcher(Application app, String name) throws Exception {
this.core = null;
this.app = app;
this.lmgr = LuceneManager.getInstance(app);
this.directory = this.lmgr.getDirectory();
this.pindxr = app.getPathIndexer();
this.qparser = new QueryParser(LuceneManager.ID, this.lmgr.buildAnalyzer());
this.cache = new EhCacheMap();
this.cache.init(app, name);
}
public void finalize() throws Throwable {
super.finalize();
this.cache.shutdown();
}
public void shutdown() {
this.cache.shutdown();
}
public void setRhinoCore(RhinoCore core) {
this.core = core;
}
public RhinoCore getRhinoCore(){
return this.core;
}
public ArrayList jsStringOrArrayToArrayList(Object value) {
ArrayList list = new ArrayList();
if (value == null || value == Undefined.instance) {
return list;
}
if (value instanceof String) {
list.add(value);
} else if (value instanceof NativeArray) {
final NativeArray na = (NativeArray) value;
final int length = (int) na.getLength();
for (int i = 0; i < length; i++) {
Object o = na.get(i, na);
if (o instanceof String) {
list.add(o);
}
}
}
return list;
}
protected int getMaxResults(Object options) throws Exception {
try{
int numResults = -1;
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(MAXLENGTH_FIELD, (Scriptable) options);
} else if (options instanceof java.util.Map) {
value = ((Map) options).get(MAXLENGTH_FIELD);
}
if (value != null) {
if (value instanceof Number) {
numResults = ((Number) value).intValue();
} else if (value instanceof String) {
numResults = Integer.parseInt((String)value);
}
}
}
return numResults;
} catch (Exception e) {
throw e;
}
}
protected boolean getUnique(Object options) throws Exception {
try {
boolean unique = false;
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(UNIQUE_FIELD, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(UNIQUE_FIELD);
}
if (value != null) {
if (value instanceof Boolean) {
unique = ((Boolean) value).booleanValue();
}
}
}
return unique;
} catch (Exception e) {
throw e;
}
}
protected String getField(Object options) throws Exception {
try {
String field = null;
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(FIELD, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(FIELD);
}
if (value != null) {
if (value instanceof String) {
field = (String)value;
}
}
}
return field;
} catch (Exception e) {
throw e;
}
}
protected SortObject getSortObject(Object options) throws Exception {
try {
SortObject theSort = null;
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(SORT_FIELD, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(SORT_FIELD);
}
if (value != null) {
if (value instanceof Scriptable) {
if (value instanceof SortObject) {
theSort = (SortObject)value;
} else {
theSort = new SortObject(value);
}
}
}
}
return theSort;
} catch (Exception e) {
throw e;
}
}
protected int getLayer(Object options) throws Exception {
int layer = -1;
try {
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(LAYER, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(LAYER);
}
if (value != null) {
if (value instanceof Scriptable) {
|
[
"\t\t \t\t\tlayer = ScriptRuntime.toInt32(value);"
] | 762
|
lcc
|
java
| null |
5e5cdb6218b379ec44de7c00d3f6ce7f79c90829d6cf905f
| 89
|
Your task is code completion.
/*
* Axiom Stack Web Application Framework
* Copyright (C) 2008 Axiom Software Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Axiom Software Inc., 11480 Commerce Park Drive, Third Floor, Reston, VA 20191 USA
* email: info@axiomsoftwareinc.com
*/
package axiom.scripting.rhino;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.store.Directory;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Undefined;
import axiom.framework.core.Application;
import axiom.objectmodel.db.DbKey;
import axiom.objectmodel.db.PathIndexer;
import axiom.objectmodel.dom.LuceneManager;
import axiom.scripting.rhino.extensions.filter.IFilter;
import axiom.scripting.rhino.extensions.filter.SortObject;
import axiom.util.EhCacheMap;
public abstract class QueryDispatcher {
public static final String SORT_FIELD = "sort";
public static final String MAXLENGTH_FIELD = "maxlength";
public static final String UNIQUE_FIELD = "unique";
public static final String FIELD = "field";
public static final String LAYER = "layer";
public static final String VIEW = "view";
protected Application app;
protected RhinoCore core;
protected LuceneManager lmgr;
protected Directory directory;
protected PathIndexer pindxr;
protected QueryParser qparser;
protected EhCacheMap cache;
public QueryDispatcher(){
}
public QueryDispatcher(Application app, String name) throws Exception {
this.core = null;
this.app = app;
this.lmgr = LuceneManager.getInstance(app);
this.directory = this.lmgr.getDirectory();
this.pindxr = app.getPathIndexer();
this.qparser = new QueryParser(LuceneManager.ID, this.lmgr.buildAnalyzer());
this.cache = new EhCacheMap();
this.cache.init(app, name);
}
public void finalize() throws Throwable {
super.finalize();
this.cache.shutdown();
}
public void shutdown() {
this.cache.shutdown();
}
public void setRhinoCore(RhinoCore core) {
this.core = core;
}
public RhinoCore getRhinoCore(){
return this.core;
}
public ArrayList jsStringOrArrayToArrayList(Object value) {
ArrayList list = new ArrayList();
if (value == null || value == Undefined.instance) {
return list;
}
if (value instanceof String) {
list.add(value);
} else if (value instanceof NativeArray) {
final NativeArray na = (NativeArray) value;
final int length = (int) na.getLength();
for (int i = 0; i < length; i++) {
Object o = na.get(i, na);
if (o instanceof String) {
list.add(o);
}
}
}
return list;
}
protected int getMaxResults(Object options) throws Exception {
try{
int numResults = -1;
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(MAXLENGTH_FIELD, (Scriptable) options);
} else if (options instanceof java.util.Map) {
value = ((Map) options).get(MAXLENGTH_FIELD);
}
if (value != null) {
if (value instanceof Number) {
numResults = ((Number) value).intValue();
} else if (value instanceof String) {
numResults = Integer.parseInt((String)value);
}
}
}
return numResults;
} catch (Exception e) {
throw e;
}
}
protected boolean getUnique(Object options) throws Exception {
try {
boolean unique = false;
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(UNIQUE_FIELD, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(UNIQUE_FIELD);
}
if (value != null) {
if (value instanceof Boolean) {
unique = ((Boolean) value).booleanValue();
}
}
}
return unique;
} catch (Exception e) {
throw e;
}
}
protected String getField(Object options) throws Exception {
try {
String field = null;
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(FIELD, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(FIELD);
}
if (value != null) {
if (value instanceof String) {
field = (String)value;
}
}
}
return field;
} catch (Exception e) {
throw e;
}
}
protected SortObject getSortObject(Object options) throws Exception {
try {
SortObject theSort = null;
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(SORT_FIELD, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(SORT_FIELD);
}
if (value != null) {
if (value instanceof Scriptable) {
if (value instanceof SortObject) {
theSort = (SortObject)value;
} else {
theSort = new SortObject(value);
}
}
}
}
return theSort;
} catch (Exception e) {
throw e;
}
}
protected int getLayer(Object options) throws Exception {
int layer = -1;
try {
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(LAYER, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(LAYER);
}
if (value != null) {
if (value instanceof Scriptable) {
|
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]
protected int getLayer(Object options) throws Exception {
int layer = -1;
try {
if (options != null) {
Object value = null;
if (options instanceof Scriptable) {
value = ((Scriptable) options).get(LAYER, (Scriptable) options);
} else if (options instanceof Map) {
value = ((Map) options).get(LAYER);
}
if (value != null) {
if (value instanceof Scriptable) {
// [Task: Complete the line]
}
}
}
return layer;
} catch (Exception e) {
throw e;
}
}
Relevant lines/variables:
- We are in the getLayer() method, which is supposed to return an integer value.
- The method is currently returning an integer variable named 'layer', which is initialized to -1.
- The method is trying to get a value from the 'options' object using the key 'LAYER'.
- The 'options' object can be either a Scriptable or a Map.
- The value obtained from 'options' is stored in the 'value' variable.
- The 'value' variable is checked for null before proceeding.
- If 'value' is not null, it is checked if it is an instance of Scriptable.
Based on the context and the relevant lines/variables, the next line of code is likely to be:
- Checking if the 'value' is an instance of Integer, and if so, returning its value.
Next line will likely be: return (value instanceof Integer) ? (Integer) value : -1;
|
|
Please complete the code given below.
/**
* Copyright 2012 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.*;
import com.facebook.android.R;
import com.facebook.model.GraphUser;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* A Fragment that displays a Login/Logout button as well as the user's
* profile picture and name when logged in.
* <p/>
* This Fragment will create and use the active session upon construction
* if it has the available data (if the app ID is specified in the manifest).
* It will also open the active session if it does not require user interaction
* (i.e. if the session is in the {@link com.facebook.SessionState#CREATED_TOKEN_LOADED} state.
* Developers can override the use of the active session by calling
* the {@link #setSession(com.facebook.Session)} method.
*/
public class UserSettingsFragment extends FacebookFragment {
private static final String NAME = "name";
private static final String ID = "id";
private static final String PICTURE = "picture";
private static final String FIELDS = "fields";
private static final String REQUEST_FIELDS = TextUtils.join(",", new String[] {ID, NAME, PICTURE});
private LoginButton loginButton;
private LoginButton.LoginButtonProperties loginButtonProperties = new LoginButton.LoginButtonProperties();
private TextView connectedStateLabel;
private GraphUser user;
private Session userInfoSession; // the Session used to fetch the current user info
private Drawable userProfilePic;
private String userProfilePicID;
private Session.StatusCallback sessionStatusCallback;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.com_facebook_usersettingsfragment, container, false);
loginButton = (LoginButton) view.findViewById(R.id.com_facebook_usersettingsfragment_login_button);
loginButton.setProperties(loginButtonProperties);
loginButton.setFragment(this);
Session session = getSession();
if (session != null && !session.equals(Session.getActiveSession())) {
loginButton.setSession(session);
}
connectedStateLabel = (TextView) view.findViewById(R.id.com_facebook_usersettingsfragment_profile_name);
// if no background is set for some reason, then default to Facebook blue
if (view.getBackground() == null) {
view.setBackgroundColor(getResources().getColor(R.color.com_facebook_blue));
} else {
view.getBackground().setDither(true);
}
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
/**
* @throws com.facebook.FacebookException if errors occur during the loading of user information
*/
@Override
public void onResume() {
super.onResume();
fetchUserInfo();
updateUI();
}
/**
* Set the Session object to use instead of the active Session. Since a Session
* cannot be reused, if the user logs out from this Session, and tries to
* log in again, a new Active Session will be used instead.
* <p/>
* If the passed in session is currently opened, this method will also attempt to
* load some user information for display (if needed).
*
* @param newSession the Session object to use
* @throws com.facebook.FacebookException if errors occur during the loading of user information
*/
@Override
public void setSession(Session newSession) {
super.setSession(newSession);
if (loginButton != null) {
loginButton.setSession(newSession);
}
fetchUserInfo();
updateUI();
}
/**
* Sets the default audience to use when the session is opened.
* This value is only useful when specifying write permissions for the native
* login dialog.
*
* @param defaultAudience the default audience value to use
*/
public void setDefaultAudience(SessionDefaultAudience defaultAudience) {
loginButtonProperties.setDefaultAudience(defaultAudience);
}
/**
* Gets the default audience to use when the session is opened.
* This value is only useful when specifying write permissions for the native
* login dialog.
*
* @return the default audience value to use
*/
public SessionDefaultAudience getDefaultAudience() {
return loginButtonProperties.getDefaultAudience();
}
/**
* Set the permissions to use when the session is opened. The permissions here
* can only be read permissions. If any publish permissions are included, the login
* attempt by the user will fail. The LoginButton can only be associated with either
* read permissions or publish permissions, but not both. Calling both
* setReadPermissions and setPublishPermissions on the same instance of LoginButton
* will result in an exception being thrown unless clearPermissions is called in between.
* <p/>
* This method is only meaningful if called before the session is open. If this is called
* after the session is opened, and the list of permissions passed in is not a subset
* of the permissions granted during the authorization, it will log an error.
* <p/>
* Since the session can be automatically opened when the UserSettingsFragment is constructed,
* it's important to always pass in a consistent set of permissions to this method, or
* manage the setting of permissions outside of the LoginButton class altogether
* (by managing the session explicitly).
*
* @param permissions the read permissions to use
*
* @throws UnsupportedOperationException if setPublishPermissions has been called
*/
public void setReadPermissions(List<String> permissions) {
loginButtonProperties.setReadPermissions(permissions, getSession());
}
/**
* Set the permissions to use when the session is opened. The permissions here
* should only be publish permissions. If any read permissions are included, the login
* attempt by the user may fail. The LoginButton can only be associated with either
* read permissions or publish permissions, but not both. Calling both
* setReadPermissions and setPublishPermissions on the same instance of LoginButton
* will result in an exception being thrown unless clearPermissions is called in between.
* <p/>
* This method is only meaningful if called before the session is open. If this is called
* after the session is opened, and the list of permissions passed in is not a subset
* of the permissions granted during the authorization, it will log an error.
* <p/>
* Since the session can be automatically opened when the LoginButton is constructed,
* it's important to always pass in a consistent set of permissions to this method, or
* manage the setting of permissions outside of the LoginButton class altogether
* (by managing the session explicitly).
*
* @param permissions the read permissions to use
*
* @throws UnsupportedOperationException if setReadPermissions has been called
* @throws IllegalArgumentException if permissions is null or empty
*/
public void setPublishPermissions(List<String> permissions) {
loginButtonProperties.setPublishPermissions(permissions, getSession());
}
/**
* Clears the permissions currently associated with this LoginButton.
*/
public void clearPermissions() {
loginButtonProperties.clearPermissions();
}
/**
* Sets the login behavior for the session that will be opened. If null is specified,
* the default ({@link SessionLoginBehavior SessionLoginBehavior.SSO_WITH_FALLBACK}
* will be used.
*
* @param loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
*/
public void setLoginBehavior(SessionLoginBehavior loginBehavior) {
loginButtonProperties.setLoginBehavior(loginBehavior);
}
/**
* Gets the login behavior for the session that will be opened. If null is returned,
* the default ({@link SessionLoginBehavior SessionLoginBehavior.SSO_WITH_FALLBACK}
* will be used.
*
* @return loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
*/
public SessionLoginBehavior getLoginBehavior() {
return loginButtonProperties.getLoginBehavior();
}
/**
* Sets an OnErrorListener for this instance of UserSettingsFragment to call into when
* certain exceptions occur.
*
* @param onErrorListener The listener object to set
*/
public void setOnErrorListener(LoginButton.OnErrorListener onErrorListener) {
loginButtonProperties.setOnErrorListener(onErrorListener);
}
/**
* Returns the current OnErrorListener for this instance of UserSettingsFragment.
*
* @return The OnErrorListener
*/
public LoginButton.OnErrorListener getOnErrorListener() {
return loginButtonProperties.getOnErrorListener();
}
/**
* Sets the callback interface that will be called whenever the status of the Session
* associated with this LoginButton changes.
*
* @param callback the callback interface
*/
public void setSessionStatusCallback(Session.StatusCallback callback) {
this.sessionStatusCallback = callback;
}
/**
* Sets the callback interface that will be called whenever the status of the Session
* associated with this LoginButton changes.
* @return the callback interface
*/
public Session.StatusCallback getSessionStatusCallback() {
return sessionStatusCallback;
}
@Override
protected void onSessionStateChange(SessionState state, Exception exception) {
fetchUserInfo();
updateUI();
if (sessionStatusCallback != null) {
sessionStatusCallback.call(getSession(), state, exception);
}
}
// For Testing Only
List<String> getPermissions() {
return loginButtonProperties.getPermissions();
}
private void fetchUserInfo() {
final Session currentSession = getSession();
|
[
" if (currentSession != null && currentSession.isOpened()) {"
] | 1,328
|
lcc
|
java
| null |
1d185bc0190b4d50ec508a59208f05925712f6455d6ece65
| 90
|
Your task is code completion.
/**
* Copyright 2012 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.widget;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.*;
import com.facebook.android.R;
import com.facebook.model.GraphUser;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* A Fragment that displays a Login/Logout button as well as the user's
* profile picture and name when logged in.
* <p/>
* This Fragment will create and use the active session upon construction
* if it has the available data (if the app ID is specified in the manifest).
* It will also open the active session if it does not require user interaction
* (i.e. if the session is in the {@link com.facebook.SessionState#CREATED_TOKEN_LOADED} state.
* Developers can override the use of the active session by calling
* the {@link #setSession(com.facebook.Session)} method.
*/
public class UserSettingsFragment extends FacebookFragment {
private static final String NAME = "name";
private static final String ID = "id";
private static final String PICTURE = "picture";
private static final String FIELDS = "fields";
private static final String REQUEST_FIELDS = TextUtils.join(",", new String[] {ID, NAME, PICTURE});
private LoginButton loginButton;
private LoginButton.LoginButtonProperties loginButtonProperties = new LoginButton.LoginButtonProperties();
private TextView connectedStateLabel;
private GraphUser user;
private Session userInfoSession; // the Session used to fetch the current user info
private Drawable userProfilePic;
private String userProfilePicID;
private Session.StatusCallback sessionStatusCallback;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.com_facebook_usersettingsfragment, container, false);
loginButton = (LoginButton) view.findViewById(R.id.com_facebook_usersettingsfragment_login_button);
loginButton.setProperties(loginButtonProperties);
loginButton.setFragment(this);
Session session = getSession();
if (session != null && !session.equals(Session.getActiveSession())) {
loginButton.setSession(session);
}
connectedStateLabel = (TextView) view.findViewById(R.id.com_facebook_usersettingsfragment_profile_name);
// if no background is set for some reason, then default to Facebook blue
if (view.getBackground() == null) {
view.setBackgroundColor(getResources().getColor(R.color.com_facebook_blue));
} else {
view.getBackground().setDither(true);
}
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
/**
* @throws com.facebook.FacebookException if errors occur during the loading of user information
*/
@Override
public void onResume() {
super.onResume();
fetchUserInfo();
updateUI();
}
/**
* Set the Session object to use instead of the active Session. Since a Session
* cannot be reused, if the user logs out from this Session, and tries to
* log in again, a new Active Session will be used instead.
* <p/>
* If the passed in session is currently opened, this method will also attempt to
* load some user information for display (if needed).
*
* @param newSession the Session object to use
* @throws com.facebook.FacebookException if errors occur during the loading of user information
*/
@Override
public void setSession(Session newSession) {
super.setSession(newSession);
if (loginButton != null) {
loginButton.setSession(newSession);
}
fetchUserInfo();
updateUI();
}
/**
* Sets the default audience to use when the session is opened.
* This value is only useful when specifying write permissions for the native
* login dialog.
*
* @param defaultAudience the default audience value to use
*/
public void setDefaultAudience(SessionDefaultAudience defaultAudience) {
loginButtonProperties.setDefaultAudience(defaultAudience);
}
/**
* Gets the default audience to use when the session is opened.
* This value is only useful when specifying write permissions for the native
* login dialog.
*
* @return the default audience value to use
*/
public SessionDefaultAudience getDefaultAudience() {
return loginButtonProperties.getDefaultAudience();
}
/**
* Set the permissions to use when the session is opened. The permissions here
* can only be read permissions. If any publish permissions are included, the login
* attempt by the user will fail. The LoginButton can only be associated with either
* read permissions or publish permissions, but not both. Calling both
* setReadPermissions and setPublishPermissions on the same instance of LoginButton
* will result in an exception being thrown unless clearPermissions is called in between.
* <p/>
* This method is only meaningful if called before the session is open. If this is called
* after the session is opened, and the list of permissions passed in is not a subset
* of the permissions granted during the authorization, it will log an error.
* <p/>
* Since the session can be automatically opened when the UserSettingsFragment is constructed,
* it's important to always pass in a consistent set of permissions to this method, or
* manage the setting of permissions outside of the LoginButton class altogether
* (by managing the session explicitly).
*
* @param permissions the read permissions to use
*
* @throws UnsupportedOperationException if setPublishPermissions has been called
*/
public void setReadPermissions(List<String> permissions) {
loginButtonProperties.setReadPermissions(permissions, getSession());
}
/**
* Set the permissions to use when the session is opened. The permissions here
* should only be publish permissions. If any read permissions are included, the login
* attempt by the user may fail. The LoginButton can only be associated with either
* read permissions or publish permissions, but not both. Calling both
* setReadPermissions and setPublishPermissions on the same instance of LoginButton
* will result in an exception being thrown unless clearPermissions is called in between.
* <p/>
* This method is only meaningful if called before the session is open. If this is called
* after the session is opened, and the list of permissions passed in is not a subset
* of the permissions granted during the authorization, it will log an error.
* <p/>
* Since the session can be automatically opened when the LoginButton is constructed,
* it's important to always pass in a consistent set of permissions to this method, or
* manage the setting of permissions outside of the LoginButton class altogether
* (by managing the session explicitly).
*
* @param permissions the read permissions to use
*
* @throws UnsupportedOperationException if setReadPermissions has been called
* @throws IllegalArgumentException if permissions is null or empty
*/
public void setPublishPermissions(List<String> permissions) {
loginButtonProperties.setPublishPermissions(permissions, getSession());
}
/**
* Clears the permissions currently associated with this LoginButton.
*/
public void clearPermissions() {
loginButtonProperties.clearPermissions();
}
/**
* Sets the login behavior for the session that will be opened. If null is specified,
* the default ({@link SessionLoginBehavior SessionLoginBehavior.SSO_WITH_FALLBACK}
* will be used.
*
* @param loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
*/
public void setLoginBehavior(SessionLoginBehavior loginBehavior) {
loginButtonProperties.setLoginBehavior(loginBehavior);
}
/**
* Gets the login behavior for the session that will be opened. If null is returned,
* the default ({@link SessionLoginBehavior SessionLoginBehavior.SSO_WITH_FALLBACK}
* will be used.
*
* @return loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that
* specifies what behaviors should be attempted during
* authorization.
*/
public SessionLoginBehavior getLoginBehavior() {
return loginButtonProperties.getLoginBehavior();
}
/**
* Sets an OnErrorListener for this instance of UserSettingsFragment to call into when
* certain exceptions occur.
*
* @param onErrorListener The listener object to set
*/
public void setOnErrorListener(LoginButton.OnErrorListener onErrorListener) {
loginButtonProperties.setOnErrorListener(onErrorListener);
}
/**
* Returns the current OnErrorListener for this instance of UserSettingsFragment.
*
* @return The OnErrorListener
*/
public LoginButton.OnErrorListener getOnErrorListener() {
return loginButtonProperties.getOnErrorListener();
}
/**
* Sets the callback interface that will be called whenever the status of the Session
* associated with this LoginButton changes.
*
* @param callback the callback interface
*/
public void setSessionStatusCallback(Session.StatusCallback callback) {
this.sessionStatusCallback = callback;
}
/**
* Sets the callback interface that will be called whenever the status of the Session
* associated with this LoginButton changes.
* @return the callback interface
*/
public Session.StatusCallback getSessionStatusCallback() {
return sessionStatusCallback;
}
@Override
protected void onSessionStateChange(SessionState state, Exception exception) {
fetchUserInfo();
updateUI();
if (sessionStatusCallback != null) {
sessionStatusCallback.call(getSession(), state, exception);
}
}
// For Testing Only
List<String> getPermissions() {
return loginButtonProperties.getPermissions();
}
private void fetchUserInfo() {
final Session currentSession = getSession();
|
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]
private void fetchUserInfo() {
final Session currentSession = getSession();
if (currentSession != null) {
// [Code to fetch user info]
}
}
Cheatsheet (for next line):
- We are in fetchUserInfo(), which fetches user info from the current session.
- currentSession is the active session.
- The task is to fetch user info from the session.
- The session is used to make a Graph API request to fetch the user's info.
- The relevant lines are the declaration of currentSession and the if statement.
Relevant variables and methods:
- currentSession: the active session
- getSession(): a method that returns the active session
- GraphUser: a class representing a Facebook user
- Session: a class representing a Facebook session
- fetchUserInfo(): the current method
- updateUI(): a method that updates the UI with the fetched user info
Possible next lines of code:
- Make a Graph API request to fetch the user's info using the current session.
- Use the GraphUser class to store the fetched user info.
- Update the UI with the fetched user info using the updateUI() method.
However, the exact next line of code depends on the specific requirements of the task.
|
|
Please complete the code given below.
package info.deskchan.talking_system;
import info.deskchan.core_utils.TextOperations;
import org.json.JSONObject;
import java.util.*;
public class StandardEmotionsController implements EmotionsController{
private static class Emotion{
/** Emotion name. **/
public String name;
/** Array of pairs [feature index, force multiplier]. **/
public int[][] influences;
/** Current emotion strength. **/
public int strength = 0;
/** Chance of getting into this emotion state. **/
public float chance = 1;
public Emotion(String name, int[][] influences) {
this.name = name;
this.influences = influences;
}
public Emotion(Emotion copy) {
this.name = copy.name;
this.influences = new int[copy.influences.length][2];
for (int i=0; i<influences.length; i++) {
influences[i][0] = copy.influences[i][0];
influences[i][1] = copy.influences[i][1];
}
}
public String toString(){
String print = name + ", chance = " + chance + ", strength = " + strength + "\n";
for(int i=0; i<influences.length; i++)
print += "[feature: " + CharacterFeatures.getFeatureName(influences[i][0]) + ", force=" + influences[i][1] + "\n";
return print;
}
}
private static final Emotion[] STANDARD_EMOTIONS = {
new Emotion("happiness", new int[][]{{0, 1}, {1, 1}, {4, 2}, {7, 1}}),
new Emotion("sorrow", new int[][]{{2, -1}, {3, -2}, {4, -2}}),
new Emotion("fun", new int[][]{{1, 2}, {3, 2}, {4, 1}}),
new Emotion("anger", new int[][]{{0, -2}, {1, 2}, {2, 1}, {3, 2}, {4, -1}, {7, -2}}),
new Emotion("confusion", new int[][]{{1, -1}, {2, -1}, {5, -1}}),
new Emotion("affection", new int[][]{{1, 2}, {3, 1}, {7, 1}})
};
private Emotion[] emotions = Arrays.copyOf(STANDARD_EMOTIONS, STANDARD_EMOTIONS.length);
private Emotion currentEmotion = null;
StandardEmotionsController() {
normalize();
reset();
}
private UpdateHandler onUpdate = null;
public void setUpdater(UpdateHandler handler){
onUpdate = handler;
}
private void tryInform(){
if (onUpdate != null) onUpdate.onUpdate();
}
public void reset() {
currentEmotion = null;
tryInform();
}
public String getCurrentEmotionName() {
return currentEmotion != null ? currentEmotion.name : null;
}
public void raiseEmotion(String emotionName) {
raiseEmotion(emotionName, 1);
}
public void raiseEmotion(String emotionName, int value) {
if (currentEmotion != null){
currentEmotion.strength -= value;
if (currentEmotion.strength <= 0)
currentEmotion = null;
else return;
}
for (Emotion emotion : emotions){
if (emotion.name.equals(emotionName)){
currentEmotion = emotion;
emotion.strength = value;
tryInform();
return;
}
}
Main.log("No emotion by name: " + emotionName);
}
public void raiseRandomEmotion(){
if (currentEmotion != null){
currentEmotion.strength += new Random().nextInt(2) - 1;
if (currentEmotion.strength <= 0){
currentEmotion = null;
} else {
return;
}
}
float chance = (float) Math.random();
for (Emotion emotion : emotions){
if (emotion.chance > chance){
currentEmotion = emotion;
emotion.strength = 1 + new Random().nextInt(2);
tryInform();
return;
}
chance -= emotion.chance;
}
}
public List<String> getEmotionsList(){
List<String> res = new ArrayList<>();
for (Emotion e : emotions)
res.add(e.name);
return res;
}
public boolean phraseMatches(Phrase phrase){
Set<String> allowedEmotions = phrase.getTag("emotion");
if (allowedEmotions == null || allowedEmotions.size() == 0){
return true;
}
if (currentEmotion != null){
return allowedEmotions.contains(currentEmotion.name);
}
return false;
}
public CharacterController construct(CharacterController target) {
if (currentEmotion == null) return target;
CharacterController New = target.copy();
for (int i = 0; i < currentEmotion.influences.length; i++) {
int index = currentEmotion.influences[i][0], multiplier = currentEmotion.influences[i][1];
New.setValue(currentEmotion.influences[i][0], target.getValue(index) + currentEmotion.strength * multiplier);
}
return New;
}
public void setFromJSON(JSONObject json) {
if (json == null || json.keySet().size() == 0) return;
List<Emotion> newEmotions = new ArrayList<>();
for (String emotionName : json.keySet()) {
if (!(json.get(emotionName) instanceof JSONObject)) continue;
JSONObject obj = json.getJSONObject(emotionName);
List<int[]> influencesList = new ArrayList<>();
for (String feature : obj.keySet()) {
int index = CharacterFeatures.getFeatureIndex(feature);
if (index < 0) continue;
try {
int force = obj.getInt(feature);
influencesList.add(new int[]{index, force});
} catch (Exception e){ }
}
if (influencesList.size() > 0) {
int[][] influences = new int[influencesList.size()][];
for (int i = 0; i < influencesList.size(); i++)
influences[i] = influencesList.get(i);
Emotion emotion = new Emotion(emotionName, influences);
if (obj.has("chance")) emotion.chance = (float) obj.getDouble("chance");
newEmotions.add(emotion);
} else {
for (int i=0; i<emotions.length; i++)
if (emotions[i].name.equals(emotionName)){
Emotion emotion = new Emotion(emotions[i]);
if (obj.has("chance")) emotion.chance = (float) obj.getDouble("chance");
newEmotions.add(emotion);
break;
}
}
}
emotions = newEmotions.toArray(new Emotion[newEmotions.size()]);
normalize();
reset();
}
public JSONObject toJSON() {
return new JSONObject();
}
private void normalize(){
float sum = 0;
|
[
"\t\tfor(Emotion emotion : emotions)"
] | 630
|
lcc
|
java
| null |
2728509e7278c4d21b0ffa379c7ac4c266c2cb3953c53b51
| 91
|
Your task is code completion.
package info.deskchan.talking_system;
import info.deskchan.core_utils.TextOperations;
import org.json.JSONObject;
import java.util.*;
public class StandardEmotionsController implements EmotionsController{
private static class Emotion{
/** Emotion name. **/
public String name;
/** Array of pairs [feature index, force multiplier]. **/
public int[][] influences;
/** Current emotion strength. **/
public int strength = 0;
/** Chance of getting into this emotion state. **/
public float chance = 1;
public Emotion(String name, int[][] influences) {
this.name = name;
this.influences = influences;
}
public Emotion(Emotion copy) {
this.name = copy.name;
this.influences = new int[copy.influences.length][2];
for (int i=0; i<influences.length; i++) {
influences[i][0] = copy.influences[i][0];
influences[i][1] = copy.influences[i][1];
}
}
public String toString(){
String print = name + ", chance = " + chance + ", strength = " + strength + "\n";
for(int i=0; i<influences.length; i++)
print += "[feature: " + CharacterFeatures.getFeatureName(influences[i][0]) + ", force=" + influences[i][1] + "\n";
return print;
}
}
private static final Emotion[] STANDARD_EMOTIONS = {
new Emotion("happiness", new int[][]{{0, 1}, {1, 1}, {4, 2}, {7, 1}}),
new Emotion("sorrow", new int[][]{{2, -1}, {3, -2}, {4, -2}}),
new Emotion("fun", new int[][]{{1, 2}, {3, 2}, {4, 1}}),
new Emotion("anger", new int[][]{{0, -2}, {1, 2}, {2, 1}, {3, 2}, {4, -1}, {7, -2}}),
new Emotion("confusion", new int[][]{{1, -1}, {2, -1}, {5, -1}}),
new Emotion("affection", new int[][]{{1, 2}, {3, 1}, {7, 1}})
};
private Emotion[] emotions = Arrays.copyOf(STANDARD_EMOTIONS, STANDARD_EMOTIONS.length);
private Emotion currentEmotion = null;
StandardEmotionsController() {
normalize();
reset();
}
private UpdateHandler onUpdate = null;
public void setUpdater(UpdateHandler handler){
onUpdate = handler;
}
private void tryInform(){
if (onUpdate != null) onUpdate.onUpdate();
}
public void reset() {
currentEmotion = null;
tryInform();
}
public String getCurrentEmotionName() {
return currentEmotion != null ? currentEmotion.name : null;
}
public void raiseEmotion(String emotionName) {
raiseEmotion(emotionName, 1);
}
public void raiseEmotion(String emotionName, int value) {
if (currentEmotion != null){
currentEmotion.strength -= value;
if (currentEmotion.strength <= 0)
currentEmotion = null;
else return;
}
for (Emotion emotion : emotions){
if (emotion.name.equals(emotionName)){
currentEmotion = emotion;
emotion.strength = value;
tryInform();
return;
}
}
Main.log("No emotion by name: " + emotionName);
}
public void raiseRandomEmotion(){
if (currentEmotion != null){
currentEmotion.strength += new Random().nextInt(2) - 1;
if (currentEmotion.strength <= 0){
currentEmotion = null;
} else {
return;
}
}
float chance = (float) Math.random();
for (Emotion emotion : emotions){
if (emotion.chance > chance){
currentEmotion = emotion;
emotion.strength = 1 + new Random().nextInt(2);
tryInform();
return;
}
chance -= emotion.chance;
}
}
public List<String> getEmotionsList(){
List<String> res = new ArrayList<>();
for (Emotion e : emotions)
res.add(e.name);
return res;
}
public boolean phraseMatches(Phrase phrase){
Set<String> allowedEmotions = phrase.getTag("emotion");
if (allowedEmotions == null || allowedEmotions.size() == 0){
return true;
}
if (currentEmotion != null){
return allowedEmotions.contains(currentEmotion.name);
}
return false;
}
public CharacterController construct(CharacterController target) {
if (currentEmotion == null) return target;
CharacterController New = target.copy();
for (int i = 0; i < currentEmotion.influences.length; i++) {
int index = currentEmotion.influences[i][0], multiplier = currentEmotion.influences[i][1];
New.setValue(currentEmotion.influences[i][0], target.getValue(index) + currentEmotion.strength * multiplier);
}
return New;
}
public void setFromJSON(JSONObject json) {
if (json == null || json.keySet().size() == 0) return;
List<Emotion> newEmotions = new ArrayList<>();
for (String emotionName : json.keySet()) {
if (!(json.get(emotionName) instanceof JSONObject)) continue;
JSONObject obj = json.getJSONObject(emotionName);
List<int[]> influencesList = new ArrayList<>();
for (String feature : obj.keySet()) {
int index = CharacterFeatures.getFeatureIndex(feature);
if (index < 0) continue;
try {
int force = obj.getInt(feature);
influencesList.add(new int[]{index, force});
} catch (Exception e){ }
}
if (influencesList.size() > 0) {
int[][] influences = new int[influencesList.size()][];
for (int i = 0; i < influencesList.size(); i++)
influences[i] = influencesList.get(i);
Emotion emotion = new Emotion(emotionName, influences);
if (obj.has("chance")) emotion.chance = (float) obj.getDouble("chance");
newEmotions.add(emotion);
} else {
for (int i=0; i<emotions.length; i++)
if (emotions[i].name.equals(emotionName)){
Emotion emotion = new Emotion(emotions[i]);
if (obj.has("chance")) emotion.chance = (float) obj.getDouble("chance");
newEmotions.add(emotion);
break;
}
}
}
emotions = newEmotions.toArray(new Emotion[newEmotions.size()]);
normalize();
reset();
}
public JSONObject toJSON() {
return new JSONObject();
}
private void normalize(){
float sum = 0;
|
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]
public void normalize(){
float sum = 0;
for (Emotion emotion : emotions){
sum += emotion.strength;
}
for (Emotion emotion : emotions){
emotion.chance /= sum;
}
tryInform();
}
Cheatsheet (for next line):
- We are in the normalize() method, which is used to normalize the chances of all emotions.
- The goal is to ensure that the sum of all emotion chances equals 1.
- The current implementation calculates the sum of all emotion strengths and then divides each emotion's chance by this sum.
- The last line of the method calls tryInform() to inform the UpdateHandler about the change.
- [Relevant lines: calculation of sum, division of emotion chances, call to tryInform()]
Next line will likely be: return;
|
|
Please complete the code given below.
# vim: set expandtab sw=4 ts=4:
#
# Unit tests for BuildJob class
#
# Copyright (C) 2014-2016 Dieter Adriaenssens <ruleant@users.sourceforge.net>
#
# This file is part of buildtimetrend/python-lib
# <https://github.com/buildtimetrend/python-lib/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import buildtimetrend
from buildtimetrend.settings import Settings
from buildtimetrend.buildjob import BuildJob
from buildtimetrend.stages import Stage
from buildtimetrend.stages import Stages
from formencode.doctest_xml_compare import xml_compare
from buildtimetrend.test import constants
from lxml import etree
import unittest
class TestBuildJob(unittest.TestCase):
"""Unit tests for BuildJob class"""
@classmethod
def setUpClass(cls):
"""Set up test fixture."""
# show full diff in case of assert mismatch
cls.maxDiff = None
def setUp(self):
"""Initialise test environment before each test."""
self.build = BuildJob()
# reinitialise settings
Settings().__init__()
def test_novalue(self):
"""Test freshly initialised Buildjob object."""
# number of stages should be zero
self.assertEqual(0, len(self.build.stages.stages))
self.assertEqual(0, self.build.properties.get_size())
# get properties should return zero duration
self.assertDictEqual({'duration': 0}, self.build.get_properties())
# dict should be empty
self.assertDictEqual(
{'duration': 0, 'stages': []},
self.build.to_dict()
)
# list should be empty
self.assertListEqual([], self.build.stages_to_list())
# xml shouldn't contain items
self.assertEqual(
b'<build><stages/></build>', etree.tostring(self.build.to_xml()))
self.assertEqual(
b'<build>\n'
b' <stages/>\n'
b'</build>\n', self.build.to_xml_string())
def test_nofile(self):
"""Test creating BuildJob instance with invalid filename."""
# number of stages should be zero when file doesn't exist
self.build = BuildJob('nofile.csv')
self.assertEqual(0, len(self.build.stages.stages))
self.build = BuildJob('')
self.assertEqual(0, len(self.build.stages.stages))
def test_end_timestamp(self):
"""Test setting end timestamp"""
self.assertEqual(0, self.build.stages.end_timestamp)
self.build = BuildJob('', 123)
self.assertEqual(123, self.build.stages.end_timestamp)
def test_set_started_at(self):
"""Test setting started_at timestamp"""
self.assertEqual(None, self.build.properties.get_item("started_at"))
self.build.set_started_at(None)
self.assertEqual(None, self.build.properties.get_item("started_at"))
# set as int, isotimestamp string expected
self.build.set_started_at(constants.TIMESTAMP_STARTED)
self.assertEqual(None, self.build.properties.get_item("started_at"))
# set as isotimestamp string
self.build.set_started_at(constants.ISOTIMESTAMP_STARTED)
self.assertDictEqual(
constants.SPLIT_TIMESTAMP_STARTED,
self.build.properties.get_item("started_at")
)
def test_set_finished_at(self):
"""Test setting finished_at timestamp"""
self.assertEqual(None, self.build.properties.get_item("finished_at"))
self.build.set_finished_at(None)
self.assertEqual(None, self.build.properties.get_item("finished_at"))
# set as int, isotimestamp string expected
self.build.set_finished_at(constants.TIMESTAMP_FINISHED)
self.assertEqual(None, self.build.properties.get_item("finished_at"))
# set as isotimestamp string
self.build.set_finished_at(constants.ISOTIMESTAMP_FINISHED)
self.assertDictEqual(
constants.SPLIT_TIMESTAMP_FINISHED,
self.build.properties.get_item("finished_at")
)
def test_add_stages(self):
"""Test adding stages"""
self.build.add_stages(None)
self.assertEqual(0, len(self.build.stages.stages))
self.build.add_stages("string")
self.assertEqual(0, len(self.build.stages.stages))
stages = Stages()
stages.read_csv(constants.TEST_SAMPLE_TIMESTAMP_FILE)
self.build.add_stages(stages)
self.assertEqual(3, len(self.build.stages.stages))
# stages should not change when submitting an invalid object
self.build.add_stages(None)
self.assertEqual(3, len(self.build.stages.stages))
self.build.add_stages("string")
self.assertEqual(3, len(self.build.stages.stages))
self.build.add_stages(Stages())
self.assertEqual(0, len(self.build.stages.stages))
def test_add_stage(self):
"""Test adding a stage"""
# error is thrown when called without parameters
self.assertRaises(TypeError, self.build.add_stage)
# error is thrown when called with an invalid parameter
self.assertRaises(TypeError, self.build.add_stage, None)
self.assertRaises(TypeError, self.build.add_stage, "string")
# add a stage
stage = Stage()
stage.set_name("stage1")
stage.set_started_at(constants.TIMESTAMP_STARTED)
stage.set_finished_at(constants.TIMESTAMP1)
stage.set_duration(235)
self.build.add_stage(stage)
# test number of stages
self.assertEqual(1, len(self.build.stages.stages))
# test started_at
self.assertEqual(
constants.SPLIT_TIMESTAMP_STARTED,
self.build.stages.started_at
)
# test finished_at
self.assertEqual(
constants.SPLIT_TIMESTAMP1,
self.build.stages.finished_at
)
# test stages (names + duration)
self.assertListEqual(
[{
'duration': 235,
'finished_at': constants.SPLIT_TIMESTAMP1,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP_STARTED
}],
self.build.stages.stages)
# add another stage
stage = Stage()
stage.set_name("stage2")
stage.set_started_at(constants.TIMESTAMP1)
stage.set_finished_at(constants.TIMESTAMP_FINISHED)
stage.set_duration(136.234)
self.build.add_stage(stage)
# test number of stages
self.assertEqual(2, len(self.build.stages.stages))
# test started_at
self.assertEqual(
constants.SPLIT_TIMESTAMP_STARTED,
self.build.stages.started_at
)
# test finished_at
self.assertEqual(
constants.SPLIT_TIMESTAMP_FINISHED,
self.build.stages.finished_at
)
# test stages (names + duration)
self.assertListEqual([
{
'duration': 235,
'finished_at': constants.SPLIT_TIMESTAMP1,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP_STARTED
},
{
'duration': 136.234,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP1
}],
self.build.stages.stages)
def test_add_property(self):
"""Test adding a property"""
self.build.add_property('property1', 2)
self.assertEqual(1, self.build.properties.get_size())
self.assertDictEqual(
{'property1': 2},
self.build.properties.get_items()
)
self.build.add_property('property2', 3)
self.assertEqual(2, self.build.properties.get_size())
self.assertDictEqual(
{'property1': 2, 'property2': 3},
self.build.properties.get_items()
)
self.build.add_property('property2', 4)
self.assertEqual(2, self.build.properties.get_size())
self.assertDictEqual(
{'property1': 2, 'property2': 4},
self.build.properties.get_items()
)
def test_get_property(self):
"""Test getting a property"""
self.build.add_property('property1', 2)
self.assertEqual(2, self.build.get_property('property1'))
self.build.add_property('property1', None)
self.assertEqual(None, self.build.get_property('property1'))
self.build.add_property('property2', 3)
self.assertEqual(3, self.build.get_property('property2'))
self.build.add_property('property2', 4)
self.assertEqual(4, self.build.get_property('property2'))
def test_get_property_does_not_exist(self):
"""Test getting a nonexistant property"""
self.assertEqual(None, self.build.get_property('no_property'))
def test_get_properties(self):
"""Test getting properties"""
self.build.add_property('property1', 2)
self.assertDictEqual(
{'duration': 0, 'property1': 2},
self.build.get_properties())
self.build.add_property('property2', 3)
self.assertDictEqual(
{'duration': 0, 'property1': 2, 'property2': 3},
self.build.get_properties())
self.build.add_property('property2', 4)
self.assertDictEqual(
{'duration': 0, 'property1': 2, 'property2': 4},
self.build.get_properties())
def test_load_properties(self):
"""Test loading properties"""
self.build.load_properties_from_settings()
self.assertDictEqual(
{'duration': 0, "repo": buildtimetrend.NAME},
self.build.get_properties())
settings = Settings()
settings.add_setting("ci_platform", "travis")
settings.add_setting("build", "123")
settings.add_setting("job", "123.1")
settings.add_setting("branch", "branch1")
settings.add_setting("result", "passed")
settings.add_setting("build_trigger", "push")
settings.add_setting(
"pull_request",
{
"is_pull_request": False,
"title": None,
"number": None
}
)
settings.set_project_name("test/project")
self.build.load_properties_from_settings()
self.assertDictEqual(
{
'duration': 0,
'ci_platform': "travis",
'build': "123",
'job': "123.1",
'branch': "branch1",
'result': "passed",
'build_trigger': "push",
'pull_request': {
"is_pull_request": False,
"title": None,
"number": None},
'repo': "test/project"
},
self.build.get_properties())
def test_set_duration(self):
"""Test calculating and setting a duration"""
self.build.add_property("duration", 20)
self.assertDictEqual({'duration': 20}, self.build.get_properties())
# read and parse sample file
self.build = BuildJob(constants.TEST_SAMPLE_TIMESTAMP_FILE)
# test dict
self.assertDictEqual({
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4,
'stages': [
{
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1
},
{
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2
},
{
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3
}
]},
self.build.to_dict())
# setting duration, overrides total stage duration
self.build.add_property("duration", 20)
# test dict
self.assertDictEqual({
'duration': 20,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4,
'stages': [
{
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1
},
{
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2
},
{
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3
}
]},
self.build.to_dict())
def test_to_dict(self):
"""Test exporting as a dictonary."""
# read and parse sample file
self.build = BuildJob(constants.TEST_SAMPLE_TIMESTAMP_FILE)
# test dict
self.assertDictEqual({
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4,
'stages': [
{
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1
},
{
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2
},
{
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3
}
]},
self.build.to_dict())
# add properties
self.build.add_property('property1', 2)
self.build.add_property('property2', 3)
# started_at property should override default value
self.build.set_started_at(constants.ISOTIMESTAMP_STARTED)
# finished_at property should override default value
self.build.set_finished_at(constants.ISOTIMESTAMP_FINISHED)
# test dict
self.assertDictEqual({
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3,
'stages': [
{
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1},
{
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2},
{
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3}
]},
self.build.to_dict())
def test_stages_to_list(self):
"""Test exporting stages as a list."""
# read and parse sample file
self.build = BuildJob(constants.TEST_SAMPLE_TIMESTAMP_FILE)
# test list
self.assertListEqual([
{
'stage': {
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
},
{
'stage': {
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
},
{
'stage': {
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
}],
self.build.stages_to_list())
# add properties
self.build.add_property('property1', 2)
self.build.add_property('property2', 3)
# started_at property should override default value
self.build.set_started_at(constants.ISOTIMESTAMP_STARTED)
# finished_at property should override default value
self.build.set_finished_at(constants.ISOTIMESTAMP_FINISHED)
# test dict
self.assertListEqual([
{
'stage': {
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3}
},
{
'stage': {
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3}
},
{
'stage': {
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
|
[
" 'property1': 2, 'property2': 3}"
] | 1,160
|
lcc
|
python
| null |
937eae55baa939e82bad4567e4b302435ea8891cfa090cc2
| 92
|
Your task is code completion.
# vim: set expandtab sw=4 ts=4:
#
# Unit tests for BuildJob class
#
# Copyright (C) 2014-2016 Dieter Adriaenssens <ruleant@users.sourceforge.net>
#
# This file is part of buildtimetrend/python-lib
# <https://github.com/buildtimetrend/python-lib/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import buildtimetrend
from buildtimetrend.settings import Settings
from buildtimetrend.buildjob import BuildJob
from buildtimetrend.stages import Stage
from buildtimetrend.stages import Stages
from formencode.doctest_xml_compare import xml_compare
from buildtimetrend.test import constants
from lxml import etree
import unittest
class TestBuildJob(unittest.TestCase):
"""Unit tests for BuildJob class"""
@classmethod
def setUpClass(cls):
"""Set up test fixture."""
# show full diff in case of assert mismatch
cls.maxDiff = None
def setUp(self):
"""Initialise test environment before each test."""
self.build = BuildJob()
# reinitialise settings
Settings().__init__()
def test_novalue(self):
"""Test freshly initialised Buildjob object."""
# number of stages should be zero
self.assertEqual(0, len(self.build.stages.stages))
self.assertEqual(0, self.build.properties.get_size())
# get properties should return zero duration
self.assertDictEqual({'duration': 0}, self.build.get_properties())
# dict should be empty
self.assertDictEqual(
{'duration': 0, 'stages': []},
self.build.to_dict()
)
# list should be empty
self.assertListEqual([], self.build.stages_to_list())
# xml shouldn't contain items
self.assertEqual(
b'<build><stages/></build>', etree.tostring(self.build.to_xml()))
self.assertEqual(
b'<build>\n'
b' <stages/>\n'
b'</build>\n', self.build.to_xml_string())
def test_nofile(self):
"""Test creating BuildJob instance with invalid filename."""
# number of stages should be zero when file doesn't exist
self.build = BuildJob('nofile.csv')
self.assertEqual(0, len(self.build.stages.stages))
self.build = BuildJob('')
self.assertEqual(0, len(self.build.stages.stages))
def test_end_timestamp(self):
"""Test setting end timestamp"""
self.assertEqual(0, self.build.stages.end_timestamp)
self.build = BuildJob('', 123)
self.assertEqual(123, self.build.stages.end_timestamp)
def test_set_started_at(self):
"""Test setting started_at timestamp"""
self.assertEqual(None, self.build.properties.get_item("started_at"))
self.build.set_started_at(None)
self.assertEqual(None, self.build.properties.get_item("started_at"))
# set as int, isotimestamp string expected
self.build.set_started_at(constants.TIMESTAMP_STARTED)
self.assertEqual(None, self.build.properties.get_item("started_at"))
# set as isotimestamp string
self.build.set_started_at(constants.ISOTIMESTAMP_STARTED)
self.assertDictEqual(
constants.SPLIT_TIMESTAMP_STARTED,
self.build.properties.get_item("started_at")
)
def test_set_finished_at(self):
"""Test setting finished_at timestamp"""
self.assertEqual(None, self.build.properties.get_item("finished_at"))
self.build.set_finished_at(None)
self.assertEqual(None, self.build.properties.get_item("finished_at"))
# set as int, isotimestamp string expected
self.build.set_finished_at(constants.TIMESTAMP_FINISHED)
self.assertEqual(None, self.build.properties.get_item("finished_at"))
# set as isotimestamp string
self.build.set_finished_at(constants.ISOTIMESTAMP_FINISHED)
self.assertDictEqual(
constants.SPLIT_TIMESTAMP_FINISHED,
self.build.properties.get_item("finished_at")
)
def test_add_stages(self):
"""Test adding stages"""
self.build.add_stages(None)
self.assertEqual(0, len(self.build.stages.stages))
self.build.add_stages("string")
self.assertEqual(0, len(self.build.stages.stages))
stages = Stages()
stages.read_csv(constants.TEST_SAMPLE_TIMESTAMP_FILE)
self.build.add_stages(stages)
self.assertEqual(3, len(self.build.stages.stages))
# stages should not change when submitting an invalid object
self.build.add_stages(None)
self.assertEqual(3, len(self.build.stages.stages))
self.build.add_stages("string")
self.assertEqual(3, len(self.build.stages.stages))
self.build.add_stages(Stages())
self.assertEqual(0, len(self.build.stages.stages))
def test_add_stage(self):
"""Test adding a stage"""
# error is thrown when called without parameters
self.assertRaises(TypeError, self.build.add_stage)
# error is thrown when called with an invalid parameter
self.assertRaises(TypeError, self.build.add_stage, None)
self.assertRaises(TypeError, self.build.add_stage, "string")
# add a stage
stage = Stage()
stage.set_name("stage1")
stage.set_started_at(constants.TIMESTAMP_STARTED)
stage.set_finished_at(constants.TIMESTAMP1)
stage.set_duration(235)
self.build.add_stage(stage)
# test number of stages
self.assertEqual(1, len(self.build.stages.stages))
# test started_at
self.assertEqual(
constants.SPLIT_TIMESTAMP_STARTED,
self.build.stages.started_at
)
# test finished_at
self.assertEqual(
constants.SPLIT_TIMESTAMP1,
self.build.stages.finished_at
)
# test stages (names + duration)
self.assertListEqual(
[{
'duration': 235,
'finished_at': constants.SPLIT_TIMESTAMP1,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP_STARTED
}],
self.build.stages.stages)
# add another stage
stage = Stage()
stage.set_name("stage2")
stage.set_started_at(constants.TIMESTAMP1)
stage.set_finished_at(constants.TIMESTAMP_FINISHED)
stage.set_duration(136.234)
self.build.add_stage(stage)
# test number of stages
self.assertEqual(2, len(self.build.stages.stages))
# test started_at
self.assertEqual(
constants.SPLIT_TIMESTAMP_STARTED,
self.build.stages.started_at
)
# test finished_at
self.assertEqual(
constants.SPLIT_TIMESTAMP_FINISHED,
self.build.stages.finished_at
)
# test stages (names + duration)
self.assertListEqual([
{
'duration': 235,
'finished_at': constants.SPLIT_TIMESTAMP1,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP_STARTED
},
{
'duration': 136.234,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP1
}],
self.build.stages.stages)
def test_add_property(self):
"""Test adding a property"""
self.build.add_property('property1', 2)
self.assertEqual(1, self.build.properties.get_size())
self.assertDictEqual(
{'property1': 2},
self.build.properties.get_items()
)
self.build.add_property('property2', 3)
self.assertEqual(2, self.build.properties.get_size())
self.assertDictEqual(
{'property1': 2, 'property2': 3},
self.build.properties.get_items()
)
self.build.add_property('property2', 4)
self.assertEqual(2, self.build.properties.get_size())
self.assertDictEqual(
{'property1': 2, 'property2': 4},
self.build.properties.get_items()
)
def test_get_property(self):
"""Test getting a property"""
self.build.add_property('property1', 2)
self.assertEqual(2, self.build.get_property('property1'))
self.build.add_property('property1', None)
self.assertEqual(None, self.build.get_property('property1'))
self.build.add_property('property2', 3)
self.assertEqual(3, self.build.get_property('property2'))
self.build.add_property('property2', 4)
self.assertEqual(4, self.build.get_property('property2'))
def test_get_property_does_not_exist(self):
"""Test getting a nonexistant property"""
self.assertEqual(None, self.build.get_property('no_property'))
def test_get_properties(self):
"""Test getting properties"""
self.build.add_property('property1', 2)
self.assertDictEqual(
{'duration': 0, 'property1': 2},
self.build.get_properties())
self.build.add_property('property2', 3)
self.assertDictEqual(
{'duration': 0, 'property1': 2, 'property2': 3},
self.build.get_properties())
self.build.add_property('property2', 4)
self.assertDictEqual(
{'duration': 0, 'property1': 2, 'property2': 4},
self.build.get_properties())
def test_load_properties(self):
"""Test loading properties"""
self.build.load_properties_from_settings()
self.assertDictEqual(
{'duration': 0, "repo": buildtimetrend.NAME},
self.build.get_properties())
settings = Settings()
settings.add_setting("ci_platform", "travis")
settings.add_setting("build", "123")
settings.add_setting("job", "123.1")
settings.add_setting("branch", "branch1")
settings.add_setting("result", "passed")
settings.add_setting("build_trigger", "push")
settings.add_setting(
"pull_request",
{
"is_pull_request": False,
"title": None,
"number": None
}
)
settings.set_project_name("test/project")
self.build.load_properties_from_settings()
self.assertDictEqual(
{
'duration': 0,
'ci_platform': "travis",
'build': "123",
'job': "123.1",
'branch': "branch1",
'result': "passed",
'build_trigger': "push",
'pull_request': {
"is_pull_request": False,
"title": None,
"number": None},
'repo': "test/project"
},
self.build.get_properties())
def test_set_duration(self):
"""Test calculating and setting a duration"""
self.build.add_property("duration", 20)
self.assertDictEqual({'duration': 20}, self.build.get_properties())
# read and parse sample file
self.build = BuildJob(constants.TEST_SAMPLE_TIMESTAMP_FILE)
# test dict
self.assertDictEqual({
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4,
'stages': [
{
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1
},
{
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2
},
{
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3
}
]},
self.build.to_dict())
# setting duration, overrides total stage duration
self.build.add_property("duration", 20)
# test dict
self.assertDictEqual({
'duration': 20,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4,
'stages': [
{
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1
},
{
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2
},
{
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3
}
]},
self.build.to_dict())
def test_to_dict(self):
"""Test exporting as a dictonary."""
# read and parse sample file
self.build = BuildJob(constants.TEST_SAMPLE_TIMESTAMP_FILE)
# test dict
self.assertDictEqual({
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4,
'stages': [
{
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1
},
{
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2
},
{
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3
}
]},
self.build.to_dict())
# add properties
self.build.add_property('property1', 2)
self.build.add_property('property2', 3)
# started_at property should override default value
self.build.set_started_at(constants.ISOTIMESTAMP_STARTED)
# finished_at property should override default value
self.build.set_finished_at(constants.ISOTIMESTAMP_FINISHED)
# test dict
self.assertDictEqual({
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3,
'stages': [
{
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1},
{
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2},
{
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3}
]},
self.build.to_dict())
def test_stages_to_list(self):
"""Test exporting stages as a list."""
# read and parse sample file
self.build = BuildJob(constants.TEST_SAMPLE_TIMESTAMP_FILE)
# test list
self.assertListEqual([
{
'stage': {
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
},
{
'stage': {
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
},
{
'stage': {
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
}],
self.build.stages_to_list())
# add properties
self.build.add_property('property1', 2)
self.build.add_property('property2', 3)
# started_at property should override default value
self.build.set_started_at(constants.ISOTIMESTAMP_STARTED)
# finished_at property should override default value
self.build.set_finished_at(constants.ISOTIMESTAMP_FINISHED)
# test dict
self.assertListEqual([
{
'stage': {
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3}
},
{
'stage': {
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3}
},
{
'stage': {
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
|
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 task:
Context:
[Previous code... ~10,000 lines omitted for brevity]
def test_to_xml_string(self):
self.assertEqual(
b'<build>\n'
b' <stages/>\n'
b'</build>\n', self.build.to_xml_string())
def test_to_xml(self):
self.assertEqual(
b'<build><stages/></build>', etree.tostring(self.build.to_xml()))
def test_stages_to_list(self):
# read and parse sample file
self.build = BuildJob(constants.TEST_SAMPLE_TIMESTAMP_FILE)
# test list
self.assertListEqual([
{
'stage': {
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
},
{
'stage': {
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
},
{
'stage': {
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP1,
'finished_at': constants.SPLIT_TIMESTAMP4}
}],
self.build.stages_to_list())
# add properties
self.build.add_property('property1', 2)
self.build.add_property('property2', 3)
# started_at property should override default value
self.build.set_started_at(constants.ISOTIMESTAMP_STARTED)
# finished_at property should override default value
self.build.set_finished_at(constants.ISOTIMESTAMP_FINISHED)
# test dict
self.assertListEqual([
{
'stage': {
'duration': 2,
'finished_at': constants.SPLIT_TIMESTAMP2,
'name': 'stage1',
'started_at': constants.SPLIT_TIMESTAMP1},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3}
},
{
'stage': {
'duration': 5,
'finished_at': constants.SPLIT_TIMESTAMP3,
'name': 'stage2',
'started_at': constants.SPLIT_TIMESTAMP2},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3}
},
{
'stage': {
'duration': 10,
'finished_at': constants.SPLIT_TIMESTAMP4,
'name': 'stage3',
'started_at': constants.SPLIT_TIMESTAMP3},
'job': {
'duration': 17,
'started_at': constants.SPLIT_TIMESTAMP_STARTED,
'finished_at': constants.SPLIT_TIMESTAMP_FINISHED,
'property1': 2, 'property2': 3}
}],
self.build.stages_to_list())
Cheatsheet (for next line):
- We are in test_stages_to_list() method.
- The method is testing the stages_to_list() method of the BuildJob class.
- The stages_to_list() method is expected to return a list of dictionaries, where each dictionary contains a 'stage' and a 'job' key.
- The 'stage' key contains a dictionary with stage information (name, started_at, finished_at, duration).
- The 'job' key contains a dictionary with job information (duration, started_at, finished_at, properties).
- The test case is using the stages_to_list() method with a BuildJob instance that has been initialized with a sample file.
- The test case is also testing the stages_to_list() method with a BuildJob instance that has properties added and started_at and finished_at overridden.
- Relevant lines: test_stages_to_list() method, stages_to_list() method, BuildJob class.
The next line of code should be a test case for the to_xml() method of the BuildJob class.
|
|
Please complete the code given below.
#!/usr/bin/env python
"""
This modules contains functions for the conversion of types.
Examples:
lat/lon <-> UTM
local time <-> UTC
meters <-> furlongs
.
.
.
@UofA, 2013
(LK)
"""
#=================================================================
from math import pi, sin, cos, tan, sqrt
#=================================================================
# Lat Long - UTM, UTM - Lat Long conversions
_deg2rad = pi / 180.0
_rad2deg = 180.0 / pi
_EquatorialRadius = 2
_eccentricitySquared = 3
_ellipsoid = [
# id, Ellipsoid name, Equatorial Radius, square of eccentricity
# first once is a placeholder only, To allow array indices to match id numbers
[ -1, "Placeholder", 0, 0],
[ 1, "Airy", 6377563, 0.00667054],
[ 2, "Australian National", 6378160, 0.006694542],
[ 3, "Bessel 1841", 6377397, 0.006674372],
[ 4, "Bessel 1841 (Nambia] ", 6377484, 0.006674372],
[ 5, "Clarke 1866", 6378206, 0.006768658],
[ 6, "Clarke 1880", 6378249, 0.006803511],
[ 7, "Everest", 6377276, 0.006637847],
[ 8, "Fischer 1960 (Mercury] ", 6378166, 0.006693422],
[ 9, "Fischer 1968", 6378150, 0.006693422],
[ 10, "GRS 1967", 6378160, 0.006694605],
[ 11, "GRS 1980", 6378137, 0.00669438],
[ 12, "Helmert 1906", 6378200, 0.006693422],
[ 13, "Hough", 6378270, 0.00672267],
[ 14, "International", 6378388, 0.00672267],
[ 15, "Krassovsky", 6378245, 0.006693422],
[ 16, "Modified Airy", 6377340, 0.00667054],
[ 17, "Modified Everest", 6377304, 0.006637847],
[ 18, "Modified Fischer 1960", 6378155, 0.006693422],
[ 19, "South American 1969", 6378160, 0.006694542],
[ 20, "WGS 60", 6378165, 0.006693422],
[ 21, "WGS 66", 6378145, 0.006694542],
[ 22, "WGS-72", 6378135, 0.006694318],
[ 23, "WGS-84", 6378137, 0.00669438]
]
#Reference ellipsoids derived from Peter H. Dana's website-
#http://www.utexas.edu/depts/grg/gcraft/notes/datum/elist.html
#Department of Geography, University of Texas at Austin
#Internet: pdana@mail.utexas.edu
#3/22/95
#Source
#Defense Mapping Agency. 1987b. DMA Technical Report: Supplement to Department of Defense World Geodetic System
#1984 Technical Report. Part I and II. Washington, DC: Defense Mapping Agency
#def LLtoUTM(int ReferenceEllipsoid, const double Lat, const double Long,
# double &UTMNorthing, double &UTMEasting, char* UTMZone)
def LLtoUTM(ReferenceEllipsoid, Lat, Long, zonenumber = None):
"""
converts lat/long to UTM coords. Equations from USGS Bulletin 1532
East Longitudes are positive, West longitudes are negative.
North latitudes are positive, South latitudes are negative
Lat and Long are in decimal degrees
Written by Chuck Gantz- chuck.gantz@globalstar.com
Outputs:
UTMzone, easting, northing"""
a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
k0 = 0.9996
#Make sure the longitude is between -180.00 .. 179.9
LongTemp = (Long+180)-int((Long+180)/360)*360-180 # -180.00 .. 179.9
LatRad = Lat*_deg2rad
LongRad = LongTemp*_deg2rad
if zonenumber is not None:
try:
ZoneNumber = int(float(zonenumber))
except:
ZoneNumber = int((LongTemp + 180)/6) + 1
else:
ZoneNumber = int((LongTemp + 180)/6) + 1
if Lat >= 56.0 and Lat < 64.0 and LongTemp >= 3.0 and LongTemp < 12.0:
ZoneNumber = 32
# Special zones for Svalbard
if Lat >= 72.0 and Lat < 84.0:
if LongTemp >= 0.0 and LongTemp < 9.0:ZoneNumber = 31
elif LongTemp >= 9.0 and LongTemp < 21.0: ZoneNumber = 33
elif LongTemp >= 21.0 and LongTemp < 33.0: ZoneNumber = 35
elif LongTemp >= 33.0 and LongTemp < 42.0: ZoneNumber = 37
LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 #+3 puts origin in middle of zone
LongOriginRad = LongOrigin * _deg2rad
#compute the UTM Zone from the latitude and longitude
UTMZone = "%d%c" % (ZoneNumber, _UTMLetterDesignator(Lat))
eccPrimeSquared = (eccSquared)/(1-eccSquared)
N = a/sqrt(1-eccSquared*sin(LatRad)*sin(LatRad))
T = tan(LatRad)*tan(LatRad)
C = eccPrimeSquared*cos(LatRad)*cos(LatRad)
A = cos(LatRad)*(LongRad-LongOriginRad)
M = a*((1
- eccSquared/4
- 3*eccSquared*eccSquared/64
- 5*eccSquared*eccSquared*eccSquared/256)*LatRad
- (3*eccSquared/8
+ 3*eccSquared*eccSquared/32
+ 45*eccSquared*eccSquared*eccSquared/1024)*sin(2*LatRad)
+ (15*eccSquared*eccSquared/256 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(4*LatRad)
- (35*eccSquared*eccSquared*eccSquared/3072)*sin(6*LatRad))
UTMEasting = (k0*N*(A+(1-T+C)*A*A*A/6
+ (5-18*T+T*T+72*C-58*eccPrimeSquared)*A*A*A*A*A/120)
+ 500000.0)
UTMNorthing = (k0*(M+N*tan(LatRad)*(A*A/2+(5-T+9*C+4*C*C)*A*A*A*A/24
+ (61
-58*T
+T*T
+600*C
-330*eccPrimeSquared)*A*A*A*A*A*A/720)))
if Lat < 0:
UTMNorthing = UTMNorthing + 10000000.0; #10000000 meter offset for southern hemisphere
return (UTMZone, UTMEasting, UTMNorthing)
def _UTMLetterDesignator(Lat):
#This routine determines the correct UTM letter designator for the given latitude
#returns 'Z' if latitude is outside the UTM limits of 84N to 80S
#Written by Chuck Gantz- chuck.gantz@globalstar.com
if 84 >= Lat >= 72: return 'X'
elif 72 > Lat >= 64: return 'W'
elif 64 > Lat >= 56: return 'V'
elif 56 > Lat >= 48: return 'U'
elif 48 > Lat >= 40: return 'T'
elif 40 > Lat >= 32: return 'S'
elif 32 > Lat >= 24: return 'R'
elif 24 > Lat >= 16: return 'Q'
elif 16 > Lat >= 8: return 'P'
elif 8 > Lat >= 0: return 'N'
elif 0 > Lat >= -8: return 'M'
elif -8> Lat >= -16: return 'L'
elif -16 > Lat >= -24: return 'K'
elif -24 > Lat >= -32: return 'J'
elif -32 > Lat >= -40: return 'H'
elif -40 > Lat >= -48: return 'G'
elif -48 > Lat >= -56: return 'F'
elif -56 > Lat >= -64: return 'E'
elif -64 > Lat >= -72: return 'D'
elif -72 > Lat >= -80: return 'C'
else: return 'Z' # if the Latitude is outside the UTM limits
#void UTMtoLL(int ReferenceEllipsoid, const double UTMNorthing, const double UTMEasting, const char* UTMZone,
# double& Lat, double& Long )
def UTMtoLL(ReferenceEllipsoid, northing, easting, zone):
"""
converts UTM coords to lat/long. Equations from USGS Bulletin 1532
East Longitudes are positive, West longitudes are negative.
North latitudes are positive, South latitudes are negative
Lat and Long are in decimal degrees.
Written by Chuck Gantz- chuck.gantz@globalstar.com
Converted to Python by Russ Nelson <nelson@crynwr.com>
Outputs:
Lat,Lon
"""
k0 = 0.9996
a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
e1 = (1-sqrt(1-eccSquared))/(1+sqrt(1-eccSquared))
#NorthernHemisphere; //1 for northern hemispher, 0 for southern
x = easting - 500000.0 #remove 500,000 meter offset for longitude
y = northing
ZoneLetter = zone[-1]
ZoneNumber = int(zone[:-1])
if ZoneLetter >= 'N':
NorthernHemisphere = 1 # point is in northern hemisphere
else:
NorthernHemisphere = 0 # point is in southern hemisphere
y -= 10000000.0 # remove 10,000,000 meter offset used for southern hemisphere
LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 # +3 puts origin in middle of zone
eccPrimeSquared = (eccSquared)/(1-eccSquared)
M = y / k0
mu = M/(a*(1-eccSquared/4-3*eccSquared*eccSquared/64-5*eccSquared*eccSquared*eccSquared/256))
phi1Rad = (mu + (3*e1/2-27*e1*e1*e1/32)*sin(2*mu)
+ (21*e1*e1/16-55*e1*e1*e1*e1/32)*sin(4*mu)
+(151*e1*e1*e1/96)*sin(6*mu))
phi1 = phi1Rad*_rad2deg;
|
[
" N1 = a/sqrt(1-eccSquared*sin(phi1Rad)*sin(phi1Rad))"
] | 980
|
lcc
|
python
| null |
b3d7b8ae829a609d04350475dc3cbba8c1903ae29d44f33f
| 93
|
Your task is code completion.
#!/usr/bin/env python
"""
This modules contains functions for the conversion of types.
Examples:
lat/lon <-> UTM
local time <-> UTC
meters <-> furlongs
.
.
.
@UofA, 2013
(LK)
"""
#=================================================================
from math import pi, sin, cos, tan, sqrt
#=================================================================
# Lat Long - UTM, UTM - Lat Long conversions
_deg2rad = pi / 180.0
_rad2deg = 180.0 / pi
_EquatorialRadius = 2
_eccentricitySquared = 3
_ellipsoid = [
# id, Ellipsoid name, Equatorial Radius, square of eccentricity
# first once is a placeholder only, To allow array indices to match id numbers
[ -1, "Placeholder", 0, 0],
[ 1, "Airy", 6377563, 0.00667054],
[ 2, "Australian National", 6378160, 0.006694542],
[ 3, "Bessel 1841", 6377397, 0.006674372],
[ 4, "Bessel 1841 (Nambia] ", 6377484, 0.006674372],
[ 5, "Clarke 1866", 6378206, 0.006768658],
[ 6, "Clarke 1880", 6378249, 0.006803511],
[ 7, "Everest", 6377276, 0.006637847],
[ 8, "Fischer 1960 (Mercury] ", 6378166, 0.006693422],
[ 9, "Fischer 1968", 6378150, 0.006693422],
[ 10, "GRS 1967", 6378160, 0.006694605],
[ 11, "GRS 1980", 6378137, 0.00669438],
[ 12, "Helmert 1906", 6378200, 0.006693422],
[ 13, "Hough", 6378270, 0.00672267],
[ 14, "International", 6378388, 0.00672267],
[ 15, "Krassovsky", 6378245, 0.006693422],
[ 16, "Modified Airy", 6377340, 0.00667054],
[ 17, "Modified Everest", 6377304, 0.006637847],
[ 18, "Modified Fischer 1960", 6378155, 0.006693422],
[ 19, "South American 1969", 6378160, 0.006694542],
[ 20, "WGS 60", 6378165, 0.006693422],
[ 21, "WGS 66", 6378145, 0.006694542],
[ 22, "WGS-72", 6378135, 0.006694318],
[ 23, "WGS-84", 6378137, 0.00669438]
]
#Reference ellipsoids derived from Peter H. Dana's website-
#http://www.utexas.edu/depts/grg/gcraft/notes/datum/elist.html
#Department of Geography, University of Texas at Austin
#Internet: pdana@mail.utexas.edu
#3/22/95
#Source
#Defense Mapping Agency. 1987b. DMA Technical Report: Supplement to Department of Defense World Geodetic System
#1984 Technical Report. Part I and II. Washington, DC: Defense Mapping Agency
#def LLtoUTM(int ReferenceEllipsoid, const double Lat, const double Long,
# double &UTMNorthing, double &UTMEasting, char* UTMZone)
def LLtoUTM(ReferenceEllipsoid, Lat, Long, zonenumber = None):
"""
converts lat/long to UTM coords. Equations from USGS Bulletin 1532
East Longitudes are positive, West longitudes are negative.
North latitudes are positive, South latitudes are negative
Lat and Long are in decimal degrees
Written by Chuck Gantz- chuck.gantz@globalstar.com
Outputs:
UTMzone, easting, northing"""
a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
k0 = 0.9996
#Make sure the longitude is between -180.00 .. 179.9
LongTemp = (Long+180)-int((Long+180)/360)*360-180 # -180.00 .. 179.9
LatRad = Lat*_deg2rad
LongRad = LongTemp*_deg2rad
if zonenumber is not None:
try:
ZoneNumber = int(float(zonenumber))
except:
ZoneNumber = int((LongTemp + 180)/6) + 1
else:
ZoneNumber = int((LongTemp + 180)/6) + 1
if Lat >= 56.0 and Lat < 64.0 and LongTemp >= 3.0 and LongTemp < 12.0:
ZoneNumber = 32
# Special zones for Svalbard
if Lat >= 72.0 and Lat < 84.0:
if LongTemp >= 0.0 and LongTemp < 9.0:ZoneNumber = 31
elif LongTemp >= 9.0 and LongTemp < 21.0: ZoneNumber = 33
elif LongTemp >= 21.0 and LongTemp < 33.0: ZoneNumber = 35
elif LongTemp >= 33.0 and LongTemp < 42.0: ZoneNumber = 37
LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 #+3 puts origin in middle of zone
LongOriginRad = LongOrigin * _deg2rad
#compute the UTM Zone from the latitude and longitude
UTMZone = "%d%c" % (ZoneNumber, _UTMLetterDesignator(Lat))
eccPrimeSquared = (eccSquared)/(1-eccSquared)
N = a/sqrt(1-eccSquared*sin(LatRad)*sin(LatRad))
T = tan(LatRad)*tan(LatRad)
C = eccPrimeSquared*cos(LatRad)*cos(LatRad)
A = cos(LatRad)*(LongRad-LongOriginRad)
M = a*((1
- eccSquared/4
- 3*eccSquared*eccSquared/64
- 5*eccSquared*eccSquared*eccSquared/256)*LatRad
- (3*eccSquared/8
+ 3*eccSquared*eccSquared/32
+ 45*eccSquared*eccSquared*eccSquared/1024)*sin(2*LatRad)
+ (15*eccSquared*eccSquared/256 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(4*LatRad)
- (35*eccSquared*eccSquared*eccSquared/3072)*sin(6*LatRad))
UTMEasting = (k0*N*(A+(1-T+C)*A*A*A/6
+ (5-18*T+T*T+72*C-58*eccPrimeSquared)*A*A*A*A*A/120)
+ 500000.0)
UTMNorthing = (k0*(M+N*tan(LatRad)*(A*A/2+(5-T+9*C+4*C*C)*A*A*A*A/24
+ (61
-58*T
+T*T
+600*C
-330*eccPrimeSquared)*A*A*A*A*A*A/720)))
if Lat < 0:
UTMNorthing = UTMNorthing + 10000000.0; #10000000 meter offset for southern hemisphere
return (UTMZone, UTMEasting, UTMNorthing)
def _UTMLetterDesignator(Lat):
#This routine determines the correct UTM letter designator for the given latitude
#returns 'Z' if latitude is outside the UTM limits of 84N to 80S
#Written by Chuck Gantz- chuck.gantz@globalstar.com
if 84 >= Lat >= 72: return 'X'
elif 72 > Lat >= 64: return 'W'
elif 64 > Lat >= 56: return 'V'
elif 56 > Lat >= 48: return 'U'
elif 48 > Lat >= 40: return 'T'
elif 40 > Lat >= 32: return 'S'
elif 32 > Lat >= 24: return 'R'
elif 24 > Lat >= 16: return 'Q'
elif 16 > Lat >= 8: return 'P'
elif 8 > Lat >= 0: return 'N'
elif 0 > Lat >= -8: return 'M'
elif -8> Lat >= -16: return 'L'
elif -16 > Lat >= -24: return 'K'
elif -24 > Lat >= -32: return 'J'
elif -32 > Lat >= -40: return 'H'
elif -40 > Lat >= -48: return 'G'
elif -48 > Lat >= -56: return 'F'
elif -56 > Lat >= -64: return 'E'
elif -64 > Lat >= -72: return 'D'
elif -72 > Lat >= -80: return 'C'
else: return 'Z' # if the Latitude is outside the UTM limits
#void UTMtoLL(int ReferenceEllipsoid, const double UTMNorthing, const double UTMEasting, const char* UTMZone,
# double& Lat, double& Long )
def UTMtoLL(ReferenceEllipsoid, northing, easting, zone):
"""
converts UTM coords to lat/long. Equations from USGS Bulletin 1532
East Longitudes are positive, West longitudes are negative.
North latitudes are positive, South latitudes are negative
Lat and Long are in decimal degrees.
Written by Chuck Gantz- chuck.gantz@globalstar.com
Converted to Python by Russ Nelson <nelson@crynwr.com>
Outputs:
Lat,Lon
"""
k0 = 0.9996
a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
e1 = (1-sqrt(1-eccSquared))/(1+sqrt(1-eccSquared))
#NorthernHemisphere; //1 for northern hemispher, 0 for southern
x = easting - 500000.0 #remove 500,000 meter offset for longitude
y = northing
ZoneLetter = zone[-1]
ZoneNumber = int(zone[:-1])
if ZoneLetter >= 'N':
NorthernHemisphere = 1 # point is in northern hemisphere
else:
NorthernHemisphere = 0 # point is in southern hemisphere
y -= 10000000.0 # remove 10,000,000 meter offset used for southern hemisphere
LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 # +3 puts origin in middle of zone
eccPrimeSquared = (eccSquared)/(1-eccSquared)
M = y / k0
mu = M/(a*(1-eccSquared/4-3*eccSquared*eccSquared/64-5*eccSquared*eccSquared*eccSquared/256))
phi1Rad = (mu + (3*e1/2-27*e1*e1*e1/32)*sin(2*mu)
+ (21*e1*e1/16-55*e1*e1*e1*e1/32)*sin(4*mu)
+(151*e1*e1*e1/96)*sin(6*mu))
phi1 = phi1Rad*_rad2deg;
|
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]
def UTMtoLL(ReferenceEllipsoid, northing, easting, zone):
"""
converts UTM coords to lat/long. Equations from USGS Bulletin 1532
East Longitudes are positive, West longitudes are negative.
North latitudes are positive, South latitudes are negative
Lat and Long are in decimal degrees.
Written by Chuck Gantz- chuck.gantz@globalstar.com
Converted to Python by Russ Nelson <nelson@crynwr.com>
Outputs:
Lat,Lon
"""
k0 = 0.9996
a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius]
eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared]
e1 = (1-sqrt(1-eccSquared))/(1+sqrt(1-eccSquared))
#NorthernHemisphere; //1 for northern hemispher, 0 for southern
x = easting - 500000.0 #remove 500,000 meter offset for longitude
y = northing
ZoneLetter = zone[-1]
ZoneNumber = int(zone[:-1])
if ZoneLetter >= 'N':
NorthernHemisphere = 1 # point is in northern hemisphere
else:
NorthernHemisphere = 0 # point is in southern hemisphere
y -= 10000000.0 # remove 10,000,000 meter offset used for southern hemisphere
LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 # +3 puts origin in middle of zone
eccPrimeSquared = (eccSquared)/(1-eccSquared)
M = y / k0
mu = M/(a*(1-eccSquared/4-3*eccSquared*eccSquared/64-5*eccSquared*eccSquared*eccSquared/256))
phi1Rad = (mu + (3*e1/2-27*e1*e1*e1/32)*sin(2*mu)
+ (21*e1*e1/16-55*e1*e1*e1*e1/32)*sin(4*mu)
+(151*e1*e1*e1/96)*sin(6*mu))
phi1 = phi1Rad*_rad2deg;
Cheatsheet (for next line):
- We are in UTMtoLL(), which should return the latitude and longitude values.
- phi1 is the latitude in radians.
- Convention: Return values should be in decimal degrees.
- Relevant lines: method header, calculation of phi1Rad, conversion of phi1Rad to decimal degrees.
Next line will likely be:
Lat = phi1;
|
|
Please complete the code given below.
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from accounts.forms import RegisterForm, ChangeEmailForm, ChangeUsernameForm, SendPMForm, SendMassPMForm, ReportUserForm
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.conf import settings
from accounts.models import UserProfile
from messaging.models import UserMessage
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.views.generic import list_detail
from django.contrib.sites.models import Site
from submissions.models.artist import Artist
from submissions.models.album import Album
from submissions.models.link import Link
from django.views.decorators.cache import cache_page
from recaptcha.client import captcha
from django.utils.safestring import mark_safe
from django.contrib.auth import login, authenticate
def register(request):
if request.method == 'POST':
if 'recaptcha_challenge_field' in request.POST:
check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
if not check_captcha.is_valid:
messages.error(request, "Captcha was incorrect!") #% check_captcha.error_code)
return HttpResponseRedirect(reverse('register'))
form = RegisterForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
username,email,password = cd['username'], cd['email'], cd['password']
new_user = User.objects.create_user(username = username, email = email, password = password)
#TODO: fix this, weird postgres issue in django 1.3 see trac issue #15682
user = User.objects.get(username=new_user.username)
profile = UserProfile.objects.create(user=user)
messages.success(request, "Thanks for registering %s! Welcome to tehorng." % new_user)
authed_user = authenticate(username=username, password=password)
login(request, authed_user)
return HttpResponseRedirect(reverse('profile'))
else:
form = RegisterForm(initial=request.POST)
return render_to_response('registration/register.html', {
'form': form,
'captcha': mark_safe(captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)),
}, context_instance=RequestContext(request))
@login_required
def profile(request):
user = request.user
profile = UserProfile.objects.get(user=user)
artists = profile.artists_for_user(10)
albums = profile.albums_for_user(10)
links = profile.links_for_user(10)
reports = user.report_set.all()
return render_to_response('accounts/profile.html', {
'profile': profile,
'artists_for_user': artists,
'albums_for_user': albums,
'links_for_user': links,
'reports': reports,
}, context_instance=RequestContext(request))
@login_required
def profile_user(request, username):
user = get_object_or_404(User, username=username)
if user == request.user:
return HttpResponseRedirect(reverse('profile'))
profile = UserProfile.objects.get(user=user)
artists = profile.artists_for_user(10)
albums = profile.albums_for_user(10)
links = profile.links_for_user(10)
return render_to_response('accounts/profile_user.html', {
'profile': profile,
'artists_for_user': artists,
'albums_for_user': albums,
'links_for_user': links,
}, context_instance=RequestContext(request))
@login_required
def view_links(request, username=None):
if username:
user = get_object_or_404(User, username=username)
links = Link.objects.filter(uploader=user)
else:
user = request.user
links = Link.objects.filter(uploader=user).order_by('-created')
return list_detail.object_list(
request=request,
queryset = links,
paginate_by = 50,
template_object_name = 'links',
template_name = 'accounts/viewlinks.html',
extra_context = {'profile': user.get_profile()}
)
@login_required
def view_albums(request, username=None):
if username:
user = get_object_or_404(User, username=username)
albums = Album.objects.filter(uploader=user)
else:
user = request.user
albums = Album.objects.filter(uploader=user).order_by('-created')
return list_detail.object_list(
request=request,
queryset = albums,
paginate_by = 50,
template_object_name = 'albums',
template_name = 'accounts/viewalbums.html',
extra_context = {'profile': user.get_profile()}
)
@login_required
def view_artists(request, username=None):
if username:
user = get_object_or_404(User, username=username)
artists = Artist.objects.filter(uploader=user, is_valid=True)
else:
user = request.user
artists = Artist.objects.filter(uploader=user, is_valid=True).order_by('-created')
return list_detail.object_list(
request=request,
queryset = artists,
paginate_by = 50,
template_object_name = 'artists',
template_name = 'accounts/viewartists.html',
extra_context = {'profile': user.get_profile()}
)
@login_required
def change_email(request):
user = User.objects.get(username=request.user)
if request.method == 'POST':
form = ChangeEmailForm(request.POST, instance=user)
if form.is_valid():
form.save()
messages.success(request, "Email changed successfully!")
return HttpResponseRedirect(reverse('profile'))
else:
form = ChangeEmailForm(instance=user)
return render_to_response('accounts/changeemail.html', {
'form': form,
}, context_instance=RequestContext(request))
@login_required
def inbox(request):
if request.method == 'POST':
msgids = request.POST.getlist('selected')
for id in msgids:
umsg = UserMessage.objects.get(id=id)
if "delete" in request.POST:
umsg.delete()
if "mark" in request.POST:
umsg.read = True
umsg.save(email=False)
messages.success(request, "Action completed successfully!")
return HttpResponseRedirect(reverse("inbox"))
return render_to_response('accounts/inbox.html', {}, context_instance=RequestContext(request))
@login_required
def change_username(request):
user = User.objects.get(username=request.user)
if request.method == 'POST':
form = ChangeUsernameForm(request.POST, instance=user)
if form.is_valid():
form.save()
messages.success(request, "Username changed successfully!")
return HttpResponseRedirect(reverse('profile'))
else:
form = ChangeUsernameForm(instance=user)
return render_to_response('accounts/changeusername.html', {
'form': form,
'profile': profile,
}, context_instance=RequestContext(request))
@login_required
def sendpm_user(request, username):
user = get_object_or_404(User, username=username)
profile = user.get_profile()
if request.method == 'POST':
form = SendPMForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
msg = UserMessage.objects.create(
to_user = user,
from_user = request.user,
message = message,
)
messages.success(request, "Message delivered!")
return HttpResponseRedirect(reverse('profile-user', args=[user.username]))
else:
form = SendPMForm()
return render_to_response('accounts/sendpm.html', {
'form': form,
'profile': profile,
}, context_instance=RequestContext(request))
@login_required
def sendpm(request):
profile = request.user.get_profile()
if request.method == 'POST':
form = SendMassPMForm(request.POST)
if form.is_valid():
to = form.cleaned_data['to']
message = form.cleaned_data['message']
usernames = [username.strip() for username in to.split(',') if username]
for username in usernames:
msg = UserMessage.objects.create(
to_user = User.objects.get(username=username),
from_user = request.user,
message = message,
)
messages.success(request, "Messages delivered!")
return HttpResponseRedirect(reverse("profile"))
else:
form = SendMassPMForm()
return render_to_response('accounts/sendmasspm.html', {
'form': form,
'profile': profile,
}, context_instance=RequestContext(request))
@login_required
def report_user(request, username):
user = get_object_or_404(User, username=username)
profile = user.get_profile()
if request.method == 'POST':
|
[
" form = ReportUserForm(request.POST)"
] | 651
|
lcc
|
python
| null |
43b09bf2cf11206d57ef722d796e2250d60d38db8c309917
| 94
|
Your task is code completion.
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from accounts.forms import RegisterForm, ChangeEmailForm, ChangeUsernameForm, SendPMForm, SendMassPMForm, ReportUserForm
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.conf import settings
from accounts.models import UserProfile
from messaging.models import UserMessage
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.views.generic import list_detail
from django.contrib.sites.models import Site
from submissions.models.artist import Artist
from submissions.models.album import Album
from submissions.models.link import Link
from django.views.decorators.cache import cache_page
from recaptcha.client import captcha
from django.utils.safestring import mark_safe
from django.contrib.auth import login, authenticate
def register(request):
if request.method == 'POST':
if 'recaptcha_challenge_field' in request.POST:
check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
if not check_captcha.is_valid:
messages.error(request, "Captcha was incorrect!") #% check_captcha.error_code)
return HttpResponseRedirect(reverse('register'))
form = RegisterForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
username,email,password = cd['username'], cd['email'], cd['password']
new_user = User.objects.create_user(username = username, email = email, password = password)
#TODO: fix this, weird postgres issue in django 1.3 see trac issue #15682
user = User.objects.get(username=new_user.username)
profile = UserProfile.objects.create(user=user)
messages.success(request, "Thanks for registering %s! Welcome to tehorng." % new_user)
authed_user = authenticate(username=username, password=password)
login(request, authed_user)
return HttpResponseRedirect(reverse('profile'))
else:
form = RegisterForm(initial=request.POST)
return render_to_response('registration/register.html', {
'form': form,
'captcha': mark_safe(captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)),
}, context_instance=RequestContext(request))
@login_required
def profile(request):
user = request.user
profile = UserProfile.objects.get(user=user)
artists = profile.artists_for_user(10)
albums = profile.albums_for_user(10)
links = profile.links_for_user(10)
reports = user.report_set.all()
return render_to_response('accounts/profile.html', {
'profile': profile,
'artists_for_user': artists,
'albums_for_user': albums,
'links_for_user': links,
'reports': reports,
}, context_instance=RequestContext(request))
@login_required
def profile_user(request, username):
user = get_object_or_404(User, username=username)
if user == request.user:
return HttpResponseRedirect(reverse('profile'))
profile = UserProfile.objects.get(user=user)
artists = profile.artists_for_user(10)
albums = profile.albums_for_user(10)
links = profile.links_for_user(10)
return render_to_response('accounts/profile_user.html', {
'profile': profile,
'artists_for_user': artists,
'albums_for_user': albums,
'links_for_user': links,
}, context_instance=RequestContext(request))
@login_required
def view_links(request, username=None):
if username:
user = get_object_or_404(User, username=username)
links = Link.objects.filter(uploader=user)
else:
user = request.user
links = Link.objects.filter(uploader=user).order_by('-created')
return list_detail.object_list(
request=request,
queryset = links,
paginate_by = 50,
template_object_name = 'links',
template_name = 'accounts/viewlinks.html',
extra_context = {'profile': user.get_profile()}
)
@login_required
def view_albums(request, username=None):
if username:
user = get_object_or_404(User, username=username)
albums = Album.objects.filter(uploader=user)
else:
user = request.user
albums = Album.objects.filter(uploader=user).order_by('-created')
return list_detail.object_list(
request=request,
queryset = albums,
paginate_by = 50,
template_object_name = 'albums',
template_name = 'accounts/viewalbums.html',
extra_context = {'profile': user.get_profile()}
)
@login_required
def view_artists(request, username=None):
if username:
user = get_object_or_404(User, username=username)
artists = Artist.objects.filter(uploader=user, is_valid=True)
else:
user = request.user
artists = Artist.objects.filter(uploader=user, is_valid=True).order_by('-created')
return list_detail.object_list(
request=request,
queryset = artists,
paginate_by = 50,
template_object_name = 'artists',
template_name = 'accounts/viewartists.html',
extra_context = {'profile': user.get_profile()}
)
@login_required
def change_email(request):
user = User.objects.get(username=request.user)
if request.method == 'POST':
form = ChangeEmailForm(request.POST, instance=user)
if form.is_valid():
form.save()
messages.success(request, "Email changed successfully!")
return HttpResponseRedirect(reverse('profile'))
else:
form = ChangeEmailForm(instance=user)
return render_to_response('accounts/changeemail.html', {
'form': form,
}, context_instance=RequestContext(request))
@login_required
def inbox(request):
if request.method == 'POST':
msgids = request.POST.getlist('selected')
for id in msgids:
umsg = UserMessage.objects.get(id=id)
if "delete" in request.POST:
umsg.delete()
if "mark" in request.POST:
umsg.read = True
umsg.save(email=False)
messages.success(request, "Action completed successfully!")
return HttpResponseRedirect(reverse("inbox"))
return render_to_response('accounts/inbox.html', {}, context_instance=RequestContext(request))
@login_required
def change_username(request):
user = User.objects.get(username=request.user)
if request.method == 'POST':
form = ChangeUsernameForm(request.POST, instance=user)
if form.is_valid():
form.save()
messages.success(request, "Username changed successfully!")
return HttpResponseRedirect(reverse('profile'))
else:
form = ChangeUsernameForm(instance=user)
return render_to_response('accounts/changeusername.html', {
'form': form,
'profile': profile,
}, context_instance=RequestContext(request))
@login_required
def sendpm_user(request, username):
user = get_object_or_404(User, username=username)
profile = user.get_profile()
if request.method == 'POST':
form = SendPMForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
msg = UserMessage.objects.create(
to_user = user,
from_user = request.user,
message = message,
)
messages.success(request, "Message delivered!")
return HttpResponseRedirect(reverse('profile-user', args=[user.username]))
else:
form = SendPMForm()
return render_to_response('accounts/sendpm.html', {
'form': form,
'profile': profile,
}, context_instance=RequestContext(request))
@login_required
def sendpm(request):
profile = request.user.get_profile()
if request.method == 'POST':
form = SendMassPMForm(request.POST)
if form.is_valid():
to = form.cleaned_data['to']
message = form.cleaned_data['message']
usernames = [username.strip() for username in to.split(',') if username]
for username in usernames:
msg = UserMessage.objects.create(
to_user = User.objects.get(username=username),
from_user = request.user,
message = message,
)
messages.success(request, "Messages delivered!")
return HttpResponseRedirect(reverse("profile"))
else:
form = SendMassPMForm()
return render_to_response('accounts/sendmasspm.html', {
'form': form,
'profile': profile,
}, context_instance=RequestContext(request))
@login_required
def report_user(request, username):
user = get_object_or_404(User, username=username)
profile = user.get_profile()
if request.method == 'POST':
|
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...]
@login_required
def report_user(request, username):
user = get_object_or_404(User, username=username)
profile = user.get_profile()
if request.method == 'POST':
# [Code to be completed]
Relevant lines/variables:
- `request`: The current HTTP request object.
- `username`: The username of the user being reported.
- `user`: The User object associated with the username.
- `profile`: The UserProfile object associated with the user.
- `request.method`: The HTTP method of the current request (e.g., 'POST', 'GET', etc.).
- `report_user_form`: A form object for reporting a user (not defined in the given code snippet).
Cheatsheet:
- We are in a view function that handles reporting a user.
- The view function is decorated with `@login_required`, indicating that it requires the user to be logged in.
- The `if request.method == 'POST'` block suggests that the view handles form submissions.
- The `report_user` function is likely intended to handle a form submission for reporting a user.
- The form submission should be validated and processed accordingly.
Based on this information, the next line of code is likely to involve form validation and processing.
|
|
Please complete the code given below.
# Copyright 2009-2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Browser views for products."""
__metaclass__ = type
__all__ = [
'ProductAddSeriesView',
'ProductAddView',
'ProductAddViewBase',
'ProductAdminView',
'ProductBrandingView',
'ProductBugsMenu',
'ProductConfigureBase',
'ProductConfigureAnswersView',
'ProductConfigureBlueprintsView',
'ProductDownloadFileMixin',
'ProductDownloadFilesView',
'ProductEditPeopleView',
'ProductEditView',
'ProductFacets',
'ProductInvolvementView',
'ProductNavigation',
'ProductNavigationMenu',
'ProductOverviewMenu',
'ProductPackagesView',
'ProductPackagesPortletView',
'ProductPurchaseSubscriptionView',
'ProductRdfView',
'ProductReviewLicenseView',
'ProductSeriesSetView',
'ProductSetBreadcrumb',
'ProductSetFacets',
'ProductSetNavigation',
'ProductSetReviewLicensesView',
'ProductSetView',
'ProductSpecificationsMenu',
'ProductView',
'SortSeriesMixin',
'ProjectAddStepOne',
'ProjectAddStepTwo',
]
from operator import attrgetter
from lazr.delegates import delegates
from lazr.restful.interface import copy_field
from lazr.restful.interfaces import IJSONRequestCache
from z3c.ptcompat import ViewPageTemplateFile
from zope.component import getUtility
from zope.event import notify
from zope.formlib import form
from zope.formlib.interfaces import WidgetInputError
from zope.formlib.widget import CustomWidgetFactory
from zope.formlib.widgets import (
CheckBoxWidget,
TextAreaWidget,
TextWidget,
)
from zope.interface import (
implements,
Interface,
)
from zope.lifecycleevent import ObjectCreatedEvent
from zope.schema import (
Bool,
Choice,
)
from zope.schema.vocabulary import (
SimpleTerm,
SimpleVocabulary,
)
from lp import _
from lp.answers.browser.faqtarget import FAQTargetNavigationMixin
from lp.answers.browser.questiontarget import (
QuestionTargetFacetMixin,
QuestionTargetTraversalMixin,
)
from lp.app.browser.launchpadform import (
action,
custom_widget,
LaunchpadEditFormView,
LaunchpadFormView,
ReturnToReferrerMixin,
safe_action,
)
from lp.app.browser.lazrjs import (
BooleanChoiceWidget,
InlinePersonEditPickerWidget,
TextLineEditorWidget,
)
from lp.app.browser.multistep import (
MultiStepView,
StepView,
)
from lp.app.browser.stringformatter import FormattersAPI
from lp.app.browser.tales import (
format_link,
MenuAPI,
)
from lp.app.enums import (
InformationType,
PROPRIETARY_INFORMATION_TYPES,
PUBLIC_PROPRIETARY_INFORMATION_TYPES,
ServiceUsage,
)
from lp.app.errors import NotFoundError
from lp.app.interfaces.headings import IEditableContextTitle
from lp.app.interfaces.launchpad import ILaunchpadCelebrities
from lp.app.utilities import json_dump_information_types
from lp.app.vocabularies import InformationTypeVocabulary
from lp.app.widgets.date import DateWidget
from lp.app.widgets.itemswidgets import (
CheckBoxMatrixWidget,
LaunchpadRadioWidget,
LaunchpadRadioWidgetWithDescription,
)
from lp.app.widgets.popup import PersonPickerWidget
from lp.app.widgets.product import (
GhostWidget,
LicenseWidget,
ProductNameWidget,
)
from lp.app.widgets.textwidgets import StrippedTextWidget
from lp.blueprints.browser.specificationtarget import (
HasSpecificationsMenuMixin,
)
from lp.bugs.browser.bugtask import (
BugTargetTraversalMixin,
get_buglisting_search_filter_url,
)
from lp.bugs.browser.structuralsubscription import (
expose_structural_subscription_data_to_js,
StructuralSubscriptionMenuMixin,
StructuralSubscriptionTargetTraversalMixin,
)
from lp.bugs.interfaces.bugtask import RESOLVED_BUGTASK_STATUSES
from lp.code.browser.branchref import BranchRef
from lp.code.browser.sourcepackagerecipelisting import HasRecipesMenuMixin
from lp.registry.browser import (
add_subscribe_link,
BaseRdfView,
)
from lp.registry.browser.announcement import HasAnnouncementsView
from lp.registry.browser.branding import BrandingChangeView
from lp.registry.browser.menu import (
IRegistryCollectionNavigationMenu,
RegistryCollectionActionMenuBase,
)
from lp.registry.browser.pillar import (
PillarBugsMenu,
PillarInvolvementView,
PillarNavigationMixin,
PillarViewMixin,
)
from lp.registry.browser.productseries import get_series_branch_error
from lp.registry.interfaces.pillar import IPillarNameSet
from lp.registry.interfaces.product import (
IProduct,
IProductReviewSearch,
IProductSet,
License,
LicenseStatus,
)
from lp.registry.interfaces.productrelease import (
IProductRelease,
IProductReleaseSet,
)
from lp.registry.interfaces.productseries import IProductSeries
from lp.registry.interfaces.series import SeriesStatus
from lp.registry.interfaces.sourcepackagename import ISourcePackageNameSet
from lp.services.config import config
from lp.services.database.decoratedresultset import DecoratedResultSet
from lp.services.feeds.browser import FeedsMixin
from lp.services.fields import (
PillarAliases,
PublicPersonChoice,
)
from lp.services.librarian.interfaces import ILibraryFileAliasSet
from lp.services.propertycache import cachedproperty
from lp.services.webapp import (
ApplicationMenu,
canonical_url,
enabled_with_permission,
LaunchpadView,
Link,
Navigation,
sorted_version_numbers,
StandardLaunchpadFacets,
stepthrough,
stepto,
structured,
)
from lp.services.webapp.authorization import check_permission
from lp.services.webapp.batching import BatchNavigator
from lp.services.webapp.breadcrumb import Breadcrumb
from lp.services.webapp.interfaces import UnsafeFormGetSubmissionError
from lp.services.webapp.menu import NavigationMenu
from lp.services.worlddata.helpers import browser_languages
from lp.services.worlddata.interfaces.country import ICountry
from lp.translations.browser.customlanguagecode import (
HasCustomLanguageCodesTraversalMixin,
)
OR = ' OR '
SPACE = ' '
class ProductNavigation(
Navigation, BugTargetTraversalMixin,
FAQTargetNavigationMixin, HasCustomLanguageCodesTraversalMixin,
QuestionTargetTraversalMixin, StructuralSubscriptionTargetTraversalMixin,
PillarNavigationMixin):
usedfor = IProduct
@stepto('.bzr')
def dotbzr(self):
if self.context.development_focus.branch:
return BranchRef(self.context.development_focus.branch)
else:
return None
@stepthrough('+spec')
def traverse_spec(self, name):
spec = self.context.getSpecification(name)
if not check_permission('launchpad.LimitedView', spec):
return None
return spec
@stepthrough('+milestone')
def traverse_milestone(self, name):
return self.context.getMilestone(name)
@stepthrough('+release')
def traverse_release(self, name):
return self.context.getRelease(name)
@stepthrough('+announcement')
def traverse_announcement(self, name):
return self.context.getAnnouncement(name)
@stepthrough('+commercialsubscription')
def traverse_commercialsubscription(self, name):
return self.context.commercial_subscription
def traverse(self, name):
return self.context.getSeries(name)
class ProductSetNavigation(Navigation):
usedfor = IProductSet
def traverse(self, name):
product = self.context.getByName(name)
if product is None:
raise NotFoundError(name)
return self.redirectSubTree(canonical_url(product))
class ProductLicenseMixin:
"""Adds licence validation and requests reviews of licences.
Subclasses must inherit from Launchpad[Edit]FormView as well.
Requires the "product" attribute be set in the child
classes' action handler.
"""
def validate(self, data):
"""Validate 'licenses' and 'license_info'.
'licenses' must not be empty unless the product already
exists and never has had a licence set.
'license_info' must not be empty if "Other/Proprietary"
or "Other/Open Source" is checked.
"""
licenses = data.get('licenses', [])
license_widget = self.widgets.get('licenses')
if (len(licenses) == 0 and license_widget is not None):
self.setFieldError(
'licenses',
'You must select at least one licence. If you select '
'Other/Proprietary or Other/OpenSource you must include a '
'description of the licence.')
elif License.OTHER_PROPRIETARY in licenses:
if not data.get('license_info'):
self.setFieldError(
'license_info',
'A description of the "Other/Proprietary" '
'licence you checked is required.')
elif License.OTHER_OPEN_SOURCE in licenses:
if not data.get('license_info'):
self.setFieldError(
'license_info',
'A description of the "Other/Open Source" '
'licence you checked is required.')
else:
# Launchpad is ok with all licenses used in this project.
pass
class ProductFacets(QuestionTargetFacetMixin, StandardLaunchpadFacets):
"""The links that will appear in the facet menu for an IProduct."""
usedfor = IProduct
enable_only = ['overview', 'bugs', 'answers', 'specifications',
'translations', 'branches']
links = StandardLaunchpadFacets.links
def overview(self):
text = 'Overview'
summary = 'General information about %s' % self.context.displayname
return Link('', text, summary)
def bugs(self):
text = 'Bugs'
summary = 'Bugs reported about %s' % self.context.displayname
return Link('', text, summary)
def branches(self):
text = 'Code'
summary = 'Branches for %s' % self.context.displayname
return Link('', text, summary)
def specifications(self):
text = 'Blueprints'
summary = 'Feature specifications for %s' % self.context.displayname
return Link('', text, summary)
def translations(self):
text = 'Translations'
summary = 'Translations of %s in Launchpad' % self.context.displayname
return Link('', text, summary)
class ProductInvolvementView(PillarInvolvementView):
"""Encourage configuration of involvement links for projects."""
has_involvement = True
@property
def visible_disabled_link_names(self):
"""Show all disabled links...except blueprints"""
involved_menu = MenuAPI(self).navigation
all_links = involved_menu.keys()
# The register blueprints link should not be shown since its use is
# not encouraged.
all_links.remove('register_blueprint')
return all_links
@cachedproperty
def configuration_states(self):
"""Create a dictionary indicating the configuration statuses.
Each app area will be represented in the return dictionary, except
blueprints which we are not currently promoting.
"""
states = {}
states['configure_bugtracker'] = (
self.context.bug_tracking_usage != ServiceUsage.UNKNOWN)
states['configure_answers'] = (
self.context.answers_usage != ServiceUsage.UNKNOWN)
states['configure_translations'] = (
self.context.translations_usage != ServiceUsage.UNKNOWN)
states['configure_codehosting'] = (
self.context.codehosting_usage != ServiceUsage.UNKNOWN)
return states
@property
def configuration_links(self):
"""The enabled involvement links.
Returns a list of dicts keyed by:
'link' -- the menu link, and
'configured' -- a boolean representing the configuration status.
"""
overview_menu = MenuAPI(self.context).overview
series_menu = MenuAPI(self.context.development_focus).overview
configuration_names = [
'configure_bugtracker',
'configure_answers',
'configure_translations',
#'configure_blueprints',
]
config_list = []
config_statuses = self.configuration_states
for key in configuration_names:
config_list.append(dict(link=overview_menu[key],
configured=config_statuses[key]))
# Add the branch configuration in separately.
set_branch = series_menu['set_branch']
set_branch.text = 'Configure project branch'
set_branch.summary = "Specify the location of this project's code."
config_list.append(
dict(link=set_branch,
configured=config_statuses['configure_codehosting']))
return config_list
@property
def registration_completeness(self):
"""The percent complete for registration."""
config_statuses = self.configuration_states
configured = sum(1 for val in config_statuses.values() if val)
scale = 100
done = int(float(configured) / len(config_statuses) * scale)
undone = scale - done
return dict(done=done, undone=undone)
@property
def registration_done(self):
"""A boolean indicating that the services are fully configured."""
return (self.registration_completeness['done'] == 100)
class ProductNavigationMenu(NavigationMenu):
usedfor = IProduct
facet = 'overview'
links = [
'details',
'announcements',
'downloads',
]
def details(self):
text = 'Details'
return Link('', text)
def announcements(self):
text = 'Announcements'
return Link('+announcements', text)
def downloads(self):
text = 'Downloads'
return Link('+download', text)
class ProductEditLinksMixin(StructuralSubscriptionMenuMixin):
"""A mixin class for menus that need Product edit links."""
@enabled_with_permission('launchpad.Edit')
def edit(self):
text = 'Change details'
return Link('+edit', text, icon='edit')
@enabled_with_permission('launchpad.BugSupervisor')
def configure_bugtracker(self):
text = 'Configure bug tracker'
summary = 'Specify where bugs are tracked for this project'
return Link('+configure-bugtracker', text, summary, icon='edit')
@enabled_with_permission('launchpad.TranslationsAdmin')
def configure_translations(self):
text = 'Configure translations'
summary = 'Allow users to submit translations for this project'
return Link('+configure-translations', text, summary, icon='edit')
@enabled_with_permission('launchpad.Edit')
def configure_answers(self):
text = 'Configure support tracker'
summary = 'Allow users to ask questions on this project'
return Link('+configure-answers', text, summary, icon='edit')
@enabled_with_permission('launchpad.Edit')
def configure_blueprints(self):
text = 'Configure blueprints'
summary = 'Enable tracking of feature planning.'
return Link('+configure-blueprints', text, summary, icon='edit')
@enabled_with_permission('launchpad.Edit')
def branding(self):
text = 'Change branding'
return Link('+branding', text, icon='edit')
@enabled_with_permission('launchpad.Edit')
def reassign(self):
text = 'Change people'
return Link('+edit-people', text, icon='edit')
@enabled_with_permission('launchpad.Moderate')
def review_license(self):
text = 'Review project'
return Link('+review-license', text, icon='edit')
@enabled_with_permission('launchpad.Moderate')
def administer(self):
text = 'Administer'
return Link('+admin', text, icon='edit')
@enabled_with_permission('launchpad.Driver')
def sharing(self):
return Link('+sharing', 'Sharing', icon='edit')
class IProductEditMenu(Interface):
"""A marker interface for the 'Change details' navigation menu."""
class IProductActionMenu(Interface):
"""A marker interface for the global action navigation menu."""
class ProductActionNavigationMenu(NavigationMenu, ProductEditLinksMixin):
"""A sub-menu for acting upon a Product."""
usedfor = IProductActionMenu
facet = 'overview'
title = 'Actions'
@cachedproperty
def links(self):
links = ['edit', 'review_license', 'administer', 'sharing']
add_subscribe_link(links)
return links
class ProductOverviewMenu(ApplicationMenu, ProductEditLinksMixin,
HasRecipesMenuMixin):
usedfor = IProduct
facet = 'overview'
links = [
'edit',
'configure_answers',
'configure_blueprints',
'configure_bugtracker',
'configure_translations',
'reassign',
'top_contributors',
'distributions',
'packages',
'series',
'series_add',
'milestones',
'downloads',
'announce',
'announcements',
'administer',
'review_license',
'rdf',
'branding',
'view_recipes',
]
def top_contributors(self):
text = 'More contributors'
return Link('+topcontributors', text, icon='info')
def distributions(self):
text = 'Distribution packaging information'
return Link('+distributions', text, icon='info')
def packages(self):
text = 'Show distribution packages'
return Link('+packages', text, icon='info')
def series(self):
text = 'View full history'
return Link('+series', text, icon='info')
@enabled_with_permission('launchpad.Driver')
def series_add(self):
text = 'Register a series'
return Link('+addseries', text, icon='add')
def milestones(self):
text = 'View milestones'
return Link('+milestones', text, icon='info')
@enabled_with_permission('launchpad.Edit')
def announce(self):
text = 'Make announcement'
summary = 'Publish an item of news for this project'
return Link('+announce', text, summary, icon='add')
def announcements(self):
text = 'Read all announcements'
enabled = bool(self.context.getAnnouncements())
return Link('+announcements', text, icon='info', enabled=enabled)
def rdf(self):
text = structured(
'<abbr title="Resource Description Framework">'
'RDF</abbr> metadata')
return Link('+rdf', text, icon='download')
def downloads(self):
text = 'Downloads'
return Link('+download', text, icon='info')
class ProductBugsMenu(PillarBugsMenu, ProductEditLinksMixin):
usedfor = IProduct
facet = 'bugs'
configurable_bugtracker = True
@cachedproperty
def links(self):
links = ['filebug', 'bugsupervisor', 'cve']
add_subscribe_link(links)
links.append('configure_bugtracker')
return links
class ProductSpecificationsMenu(NavigationMenu, ProductEditLinksMixin,
HasSpecificationsMenuMixin):
usedfor = IProduct
facet = 'specifications'
links = ['configure_blueprints', 'listall', 'doc', 'assignments', 'new',
'register_sprint']
def _cmp_distros(a, b):
"""Put Ubuntu first, otherwise in alpha order."""
if a == 'ubuntu':
return -1
elif b == 'ubuntu':
return 1
else:
return cmp(a, b)
class ProductSetBreadcrumb(Breadcrumb):
"""Return a breadcrumb for an `IProductSet`."""
text = "Projects"
class ProductSetFacets(StandardLaunchpadFacets):
"""The links that will appear in the facet menu for the IProductSet."""
usedfor = IProductSet
enable_only = ['overview', 'branches']
class SortSeriesMixin:
"""Provide access to helpers for series."""
def _sorted_filtered_list(self, filter=None):
"""Return a sorted, filtered list of series.
The series list is sorted by version in reverse order. It is also
filtered by calling `filter` on every series. If the `filter`
function returns False, don't include the series. With None (the
default, include everything).
The development focus is always first in the list.
"""
series_list = []
for series in self.product.series:
if filter is None or filter(series):
series_list.append(series)
# In production data, there exist development focus series that are
# obsolete. This may be caused by bad data, or it may be intended
# functionality. In either case, ensure that the development focus
# branch is first in the list.
if self.product.development_focus in series_list:
series_list.remove(self.product.development_focus)
# Now sort the list by name with newer versions before older.
series_list = sorted_version_numbers(series_list,
key=attrgetter('name'))
series_list.insert(0, self.product.development_focus)
return series_list
@property
def sorted_series_list(self):
"""Return a sorted list of series.
The series list is sorted by version in reverse order.
The development focus is always first in the list.
"""
return self._sorted_filtered_list()
@property
def sorted_active_series_list(self):
"""Like `sorted_series_list()` but filters out OBSOLETE series."""
# Callback for the filter which only allows series that have not been
# marked obsolete.
def check_active(series):
return series.status != SeriesStatus.OBSOLETE
return self._sorted_filtered_list(check_active)
class ProductWithSeries:
"""A decorated product that includes series data.
The extra data is included in this class to avoid repeated
database queries. Rather than hitting the database, the data is
cached locally and simply returned.
"""
# `series` and `development_focus` need to be declared as class
# attributes so that this class will not delegate the actual instance
# variables to self.product, which would bypass the caching.
series = None
development_focus = None
delegates(IProduct, 'product')
def __init__(self, product):
self.product = product
self.series = []
for series in self.product.series:
series_with_releases = SeriesWithReleases(series, parent=self)
self.series.append(series_with_releases)
if self.product.development_focus == series:
self.development_focus = series_with_releases
# Get all of the releases for all of the series in a single
# query. The query sorts the releases properly so we know the
# resulting list is sorted correctly.
series_by_id = dict((series.id, series) for series in self.series)
self.release_by_id = {}
milestones_and_releases = list(
self.product.getMilestonesAndReleases())
for milestone, release in milestones_and_releases:
series = series_by_id[milestone.productseries.id]
release_delegate = ReleaseWithFiles(release, parent=series)
series.addRelease(release_delegate)
self.release_by_id[release.id] = release_delegate
class DecoratedSeries:
"""A decorated series that includes helper attributes for templates."""
delegates(IProductSeries, 'series')
def __init__(self, series):
self.series = series
@property
def css_class(self):
"""The highlight, lowlight, or normal CSS class."""
if self.is_development_focus:
return 'highlight'
elif self.status == SeriesStatus.OBSOLETE:
return 'lowlight'
else:
# This is normal presentation.
return ''
@cachedproperty
def packagings(self):
"""Convert packagings to list to prevent multiple evaluations."""
return list(self.series.packagings)
class SeriesWithReleases(DecoratedSeries):
"""A decorated series that includes releases.
The extra data is included in this class to avoid repeated
database queries. Rather than hitting the database, the data is
cached locally and simply returned.
"""
# `parent` and `releases` need to be declared as class attributes so that
# this class will not delegate the actual instance variables to
# self.series, which would bypass the caching for self.releases and would
# raise an AttributeError for self.parent.
parent = None
releases = None
def __init__(self, series, parent):
super(SeriesWithReleases, self).__init__(series)
self.parent = parent
self.releases = []
def addRelease(self, release):
self.releases.append(release)
@cachedproperty
def has_release_files(self):
for release in self.releases:
if len(release.files) > 0:
return True
return False
class ReleaseWithFiles:
"""A decorated release that includes product release files.
The extra data is included in this class to avoid repeated
database queries. Rather than hitting the database, the data is
cached locally and simply returned.
"""
# `parent` needs to be declared as class attributes so that
# this class will not delegate the actual instance variables to
# self.release, which would raise an AttributeError.
parent = None
delegates(IProductRelease, 'release')
def __init__(self, release, parent):
self.release = release
self.parent = parent
self._files = None
@property
def files(self):
"""Cache the release files for all the releases in the product."""
if self._files is None:
# Get all of the files for all of the releases. The query
# returns all releases sorted properly.
product = self.parent.parent
release_delegates = product.release_by_id.values()
files = getUtility(IProductReleaseSet).getFilesForReleases(
release_delegates)
for release_delegate in release_delegates:
release_delegate._files = []
for file in files:
id = file.productrelease.id
release_delegate = product.release_by_id[id]
release_delegate._files.append(file)
# self._files was set above, since self is actually in the
# release_delegates variable.
return self._files
@property
def name_with_codename(self):
milestone = self.release.milestone
if milestone.code_name:
return "%s (%s)" % (milestone.name, milestone.code_name)
else:
return milestone.name
@cachedproperty
def total_downloads(self):
"""Total downloads of files associated with this release."""
return sum(file.libraryfile.hits for file in self.files)
class ProductDownloadFileMixin:
"""Provides methods for managing download files."""
@cachedproperty
def product(self):
"""Product with all series, release and file data cached.
Decorated classes are created, and they contain cached data
obtained with a few queries rather than many iterated queries.
"""
return ProductWithSeries(self.context)
def deleteFiles(self, releases):
"""Delete the selected files from the set of releases.
:param releases: A set of releases in the view.
:return: The number of files deleted.
"""
del_count = 0
for release in releases:
for release_file in release.files:
if release_file.libraryfile.id in self.delete_ids:
release_file.destroySelf()
self.delete_ids.remove(release_file.libraryfile.id)
del_count += 1
return del_count
def getReleases(self):
"""Find the releases with download files for view."""
raise NotImplementedError
def processDeleteFiles(self):
"""If the 'delete_files' button was pressed, process the deletions."""
del_count = None
if 'delete_files' in self.form:
if self.request.method == 'POST':
self.delete_ids = [
int(value) for key, value in self.form.items()
if key.startswith('checkbox')]
del(self.form['delete_files'])
releases = self.getReleases()
del_count = self.deleteFiles(releases)
else:
# If there is a form submission and it is not a POST then
# raise an error. This is to protect against XSS exploits.
raise UnsafeFormGetSubmissionError(self.form['delete_files'])
if del_count is not None:
if del_count <= 0:
self.request.response.addNotification(
"No files were deleted.")
elif del_count == 1:
self.request.response.addNotification(
"1 file has been deleted.")
else:
self.request.response.addNotification(
"%d files have been deleted." %
del_count)
@cachedproperty
def latest_release_with_download_files(self):
"""Return the latest release with download files."""
for series in self.sorted_active_series_list:
for release in series.releases:
if len(list(release.files)) > 0:
return release
return None
@cachedproperty
def has_download_files(self):
for series in self.context.series:
if series.status == SeriesStatus.OBSOLETE:
continue
for release in series.getCachedReleases():
if len(list(release.files)) > 0:
return True
return False
class ProductView(PillarViewMixin, HasAnnouncementsView, SortSeriesMixin,
FeedsMixin, ProductDownloadFileMixin):
implements(IProductActionMenu, IEditableContextTitle)
@property
def maintainer_widget(self):
return InlinePersonEditPickerWidget(
self.context, IProduct['owner'],
format_link(self.context.owner),
header='Change maintainer', edit_view='+edit-people',
step_title='Select a new maintainer', show_create_team=True)
@property
def driver_widget(self):
return InlinePersonEditPickerWidget(
self.context, IProduct['driver'],
format_link(self.context.driver, empty_value="Not yet selected"),
header='Change driver', edit_view='+edit-people',
step_title='Select a new driver', show_create_team=True,
null_display_value="Not yet selected",
help_link="/+help-registry/driver.html")
def __init__(self, context, request):
HasAnnouncementsView.__init__(self, context, request)
self.form = request.form_ng
def initialize(self):
super(ProductView, self).initialize()
self.status_message = None
product = self.context
title_field = IProduct['title']
title = "Edit this title"
self.title_edit_widget = TextLineEditorWidget(
product, title_field, title, 'h1', max_width='95%',
truncate_lines=2)
programming_lang = IProduct['programminglang']
title = 'Edit programming languages'
additional_arguments = {
'width': '9em',
'css_class': 'nowrap'}
if self.context.programminglang is None:
additional_arguments.update(dict(
default_text='Not yet specified',
initial_value_override='',
))
self.languages_edit_widget = TextLineEditorWidget(
product, programming_lang, title, 'span', **additional_arguments)
self.show_programming_languages = bool(
self.context.programminglang or
check_permission('launchpad.Edit', self.context))
expose_structural_subscription_data_to_js(
self.context, self.request, self.user)
@property
def page_title(self):
return '%s in Launchpad' % self.context.displayname
@property
def page_description(self):
return '\n'.filter(
None,
[self.context.summary, self.context.description])
@property
def show_license_status(self):
return self.context.license_status != LicenseStatus.OPEN_SOURCE
@property
def freshmeat_url(self):
if self.context.freshmeatproject:
return ("http://freshmeat.net/projects/%s"
% self.context.freshmeatproject)
return None
@property
def sourceforge_url(self):
if self.context.sourceforgeproject:
return ("http://sourceforge.net/projects/%s"
% self.context.sourceforgeproject)
return None
@property
def has_external_links(self):
return (self.context.homepageurl or
self.context.sourceforgeproject or
self.context.freshmeatproject or
self.context.wikiurl or
self.context.screenshotsurl or
self.context.downloadurl)
@property
def external_links(self):
"""The project's external links.
The home page link is not included because its link must have the
rel=nofollow attribute.
"""
from lp.services.webapp.menu import MenuLink
urls = [
('Sourceforge project', self.sourceforge_url),
('Freshmeat record', self.freshmeat_url),
('Wiki', self.context.wikiurl),
('Screenshots', self.context.screenshotsurl),
('External downloads', self.context.downloadurl),
]
links = []
for (text, url) in urls:
if url is not None:
menu_link = MenuLink(
Link(url, text, icon='external-link', enabled=True))
menu_link.url = url
links.append(menu_link)
return links
@property
def should_display_homepage(self):
return (self.context.homepageurl and
self.context.homepageurl not in
[self.freshmeat_url, self.sourceforge_url])
def requestCountry(self):
return ICountry(self.request, None)
def browserLanguages(self):
return browser_languages(self.request)
def getClosedBugsURL(self, series):
status = [status.title for status in RESOLVED_BUGTASK_STATUSES]
url = canonical_url(series) + '/+bugs'
return get_buglisting_search_filter_url(url, status=status)
@property
def can_purchase_subscription(self):
return (check_permission('launchpad.Edit', self.context)
and not self.context.qualifies_for_free_hosting)
@cachedproperty
def effective_driver(self):
"""Return the product driver or the project driver."""
if self.context.driver is not None:
driver = self.context.driver
elif (self.context.project is not None and
self.context.project.driver is not None):
driver = self.context.project.driver
else:
driver = None
return driver
@cachedproperty
def show_commercial_subscription_info(self):
"""Should subscription information be shown?
Subscription information is only shown to the project maintainers,
Launchpad admins, and members of the Launchpad commercial team. The
first two are allowed via the Launchpad.Edit permission. The latter
is allowed via Launchpad.Commercial.
"""
return (check_permission('launchpad.Edit', self.context) or
check_permission('launchpad.Commercial', self.context))
@cachedproperty
def show_license_info(self):
"""Should the view show the extra licence information."""
return (
License.OTHER_OPEN_SOURCE in self.context.licenses
or License.OTHER_PROPRIETARY in self.context.licenses)
@cachedproperty
def is_proprietary(self):
"""Is the project proprietary."""
return License.OTHER_PROPRIETARY in self.context.licenses
@property
def active_widget(self):
return BooleanChoiceWidget(
self.context, IProduct['active'],
content_box_id='%s-edit-active' % FormattersAPI(
self.context.name).css_id(),
edit_view='+review-license',
tag='span',
false_text='Deactivated',
true_text='Active',
header='Is this project active and usable by the community?')
@property
def project_reviewed_widget(self):
return BooleanChoiceWidget(
self.context, IProduct['project_reviewed'],
content_box_id='%s-edit-project-reviewed' % FormattersAPI(
self.context.name).css_id(),
edit_view='+review-license',
tag='span',
false_text='Unreviewed',
true_text='Reviewed',
header='Have you reviewed the project?')
@property
def license_approved_widget(self):
licenses = list(self.context.licenses)
if License.OTHER_PROPRIETARY in licenses:
return 'Commercial subscription required'
elif [License.DONT_KNOW] == licenses or [] == licenses:
return 'Licence required'
return BooleanChoiceWidget(
self.context, IProduct['license_approved'],
content_box_id='%s-edit-license-approved' % FormattersAPI(
self.context.name).css_id(),
edit_view='+review-license',
tag='span',
false_text='Unapproved',
true_text='Approved',
header='Does the licence qualifiy the project for free hosting?')
class ProductPurchaseSubscriptionView(ProductView):
"""View the instructions to purchase a commercial subscription."""
page_title = 'Purchase subscription'
class ProductPackagesView(LaunchpadView):
"""View for displaying product packaging"""
label = 'Linked packages'
page_title = label
@cachedproperty
def series_batch(self):
"""A batch of series that are active or have packages."""
decorated_series = DecoratedResultSet(
self.context.active_or_packaged_series, DecoratedSeries)
return BatchNavigator(decorated_series, self.request)
@property
def distro_packaging(self):
"""This method returns a representation of the product packagings
for this product, in a special structure used for the
product-distros.pt page template.
Specifically, it is a list of "distro" objects, each of which has a
title, and an attribute "packagings" which is a list of the relevant
packagings for this distro and product.
"""
distros = {}
for packaging in self.context.packagings:
distribution = packaging.distroseries.distribution
if distribution.name in distros:
distro = distros[distribution.name]
else:
# Create a dictionary for the distribution.
distro = dict(
distribution=distribution,
packagings=[])
distros[distribution.name] = distro
distro['packagings'].append(packaging)
# Now we sort the resulting list of "distro" objects, and return that.
distro_names = distros.keys()
distro_names.sort(cmp=_cmp_distros)
results = [distros[name] for name in distro_names]
return results
class ProductPackagesPortletView(LaunchpadView):
"""View class for product packaging portlet."""
schema = Interface
@cachedproperty
def sourcepackages(self):
"""The project's latest source packages."""
current_packages = [
sp for sp in self.context.sourcepackages
if sp.currentrelease is not None]
current_packages.reverse()
return current_packages[0:5]
@cachedproperty
def can_show_portlet(self):
"""Are there packages, or can packages be suggested."""
if len(self.sourcepackages) > 0:
return True
class SeriesReleasePair:
"""Class for holding a series and release.
Replaces the use of a (series, release) tuple so that it can be more
clearly addressed in the view class.
"""
def __init__(self, series, release):
self.series = series
self.release = release
class ProductDownloadFilesView(LaunchpadView,
SortSeriesMixin,
ProductDownloadFileMixin):
"""View class for the product's file downloads page."""
batch_size = config.launchpad.download_batch_size
@property
def page_title(self):
return "%s project files" % self.context.displayname
def initialize(self):
"""See `LaunchpadFormView`."""
self.form = self.request.form
# Manually process action for the 'Delete' button.
self.processDeleteFiles()
def getReleases(self):
"""See `ProductDownloadFileMixin`."""
releases = set()
for series in self.product.series:
releases.update(series.releases)
return releases
@cachedproperty
def series_and_releases_batch(self):
"""Get a batch of series and release
Each entry returned is a tuple of (series, release).
"""
series_and_releases = []
for series in self.sorted_series_list:
for release in series.releases:
if len(release.files) > 0:
pair = SeriesReleasePair(series, release)
if pair not in series_and_releases:
series_and_releases.append(pair)
batch = BatchNavigator(series_and_releases, self.request,
size=self.batch_size)
batch.setHeadings("release", "releases")
return batch
@cachedproperty
def has_download_files(self):
"""Across series and releases do any download files exist?"""
for series in self.product.series:
if series.has_release_files:
return True
return False
@cachedproperty
def any_download_files_with_signatures(self):
"""Do any series or release download files have signatures?"""
for series in self.product.series:
for release in series.releases:
for file in release.files:
if file.signature:
return True
return False
@cachedproperty
def milestones(self):
"""A mapping between series and releases that are milestones."""
result = dict()
for series in self.product.series:
result[series.name] = set()
milestone_list = [m.name for m in series.milestones]
for release in series.releases:
if release.version in milestone_list:
result[series.name].add(release.version)
return result
def is_milestone(self, series, release):
"""Determine whether a release is milestone for the series."""
return (series.name in self.milestones and
release.version in self.milestones[series.name])
class ProductBrandingView(BrandingChangeView):
"""A view to set branding."""
implements(IProductEditMenu)
label = "Change branding"
schema = IProduct
field_names = ['icon', 'logo', 'mugshot']
@property
def page_title(self):
"""The HTML page title."""
return "Change %s's branding" % self.context.title
@property
def cancel_url(self):
"""See `LaunchpadFormView`."""
return canonical_url(self.context)
class ProductConfigureBase(ReturnToReferrerMixin, LaunchpadEditFormView):
implements(IProductEditMenu)
schema = IProduct
usage_fieldname = None
def setUpFields(self):
super(ProductConfigureBase, self).setUpFields()
if self.usage_fieldname is not None:
# The usage fields are shared among pillars. But when referring
# to an individual object in Launchpad it is better to call it by
# its real name, i.e. 'project' instead of 'pillar'.
usage_field = self.form_fields.get(self.usage_fieldname)
if usage_field:
usage_field.custom_widget = CustomWidgetFactory(
LaunchpadRadioWidget, orientation='vertical')
# Copy the field or else the description in the interface will
# be modified in-place.
field = copy_field(usage_field.field)
field.description = (
field.description.replace('pillar', 'project'))
usage_field.field = field
if (self.usage_fieldname in
('answers_usage', 'translations_usage') and
self.context.information_type in
PROPRIETARY_INFORMATION_TYPES):
values = usage_field.field.vocabulary.items
terms = [SimpleTerm(value, value.name, value.title)
for value in values
if value != ServiceUsage.LAUNCHPAD]
usage_field.field.vocabulary = SimpleVocabulary(terms)
@property
def field_names(self):
return [self.usage_fieldname]
@property
def page_title(self):
return self.label
@action("Change", name='change')
def change_action(self, action, data):
self.updateContextFromData(data)
class ProductConfigureBlueprintsView(ProductConfigureBase):
"""View class to configure the Launchpad Blueprints for a project."""
label = "Configure blueprints"
usage_fieldname = 'blueprints_usage'
class ProductConfigureAnswersView(ProductConfigureBase):
"""View class to configure the Launchpad Answers for a project."""
label = "Configure answers"
usage_fieldname = 'answers_usage'
class ProductEditView(ProductLicenseMixin, LaunchpadEditFormView):
"""View class that lets you edit a Product object."""
implements(IProductEditMenu)
label = "Edit details"
schema = IProduct
field_names = [
"displayname",
"title",
"summary",
"description",
"project",
"homepageurl",
"information_type",
"sourceforgeproject",
"freshmeatproject",
"wikiurl",
"screenshotsurl",
"downloadurl",
"programminglang",
"development_focus",
"licenses",
"license_info",
]
custom_widget('licenses', LicenseWidget)
custom_widget('license_info', GhostWidget)
custom_widget(
'information_type', LaunchpadRadioWidgetWithDescription,
vocabulary=InformationTypeVocabulary(
types=PUBLIC_PROPRIETARY_INFORMATION_TYPES))
@property
def next_url(self):
"""See `LaunchpadFormView`."""
if self.context.active:
if len(self.errors) > 0:
return None
return canonical_url(self.context)
else:
return canonical_url(getUtility(IProductSet))
cancel_url = next_url
@property
def page_title(self):
"""The HTML page title."""
return "Change %s's details" % self.context.title
def initialize(self):
# The JSON cache must be populated before the super call, since
# the form is rendered during LaunchpadFormView's initialize()
# when an action is invoked.
cache = IJSONRequestCache(self.request)
json_dump_information_types(
cache, PUBLIC_PROPRIETARY_INFORMATION_TYPES)
super(ProductEditView, self).initialize()
def validate(self, data):
"""Validate 'licenses' and 'license_info'.
'licenses' must not be empty unless the product already
exists and never has had a licence set.
'license_info' must not be empty if "Other/Proprietary"
or "Other/Open Source" is checked.
"""
super(ProductEditView, self).validate(data)
information_type = data.get('information_type')
if information_type:
errors = [
str(e) for e in self.context.checkInformationType(
information_type)]
if len(errors) > 0:
self.setFieldError('information_type', ' '.join(errors))
def showOptionalMarker(self, field_name):
"""See `LaunchpadFormView`."""
# This has the effect of suppressing the ": (Optional)" stuff for the
# license_info widget. It's the last piece of the puzzle for
# manipulating the license_info widget into the table for the
# LicenseWidget instead of the enclosing form.
if field_name == 'license_info':
return False
return super(ProductEditView, self).showOptionalMarker(field_name)
@action("Change", name='change')
def change_action(self, action, data):
self.updateContextFromData(data)
class ProductValidationMixin:
def validate_deactivation(self, data):
"""Verify whether a product can be safely deactivated."""
if data['active'] == False and self.context.active == True:
if len(self.context.sourcepackages) > 0:
self.setFieldError('active',
structured(
'This project cannot be deactivated since it is '
'linked to one or more '
'<a href="%s">source packages</a>.',
canonical_url(self.context, view_name='+packages')))
class ProductAdminView(ProductEditView, ProductValidationMixin):
"""View for $project/+admin"""
label = "Administer project details"
default_field_names = [
"name",
"owner",
"active",
"autoupdate",
]
@property
def page_title(self):
"""The HTML page title."""
return 'Administer %s' % self.context.title
def setUpFields(self):
"""Setup the normal fields from the schema plus adds 'Registrant'.
The registrant is normally a read-only field and thus does not have a
proper widget created by default. Even though it is read-only, admins
need the ability to change it.
"""
self.field_names = self.default_field_names[:]
admin = check_permission('launchpad.Admin', self.context)
if not admin:
self.field_names.remove('owner')
self.field_names.remove('autoupdate')
super(ProductAdminView, self).setUpFields()
self.form_fields = self._createAliasesField() + self.form_fields
if admin:
self.form_fields = (
self.form_fields + self._createRegistrantField())
def _createAliasesField(self):
"""Return a PillarAliases field for IProduct.aliases."""
return form.Fields(
PillarAliases(
__name__='aliases', title=_('Aliases'),
description=_('Other names (separated by space) under which '
'this project is known.'),
required=False, readonly=False),
render_context=self.render_context)
def _createRegistrantField(self):
"""Return a popup widget person selector for the registrant.
This custom field is necessary because *normally* the registrant is
read-only but we want the admins to have the ability to correct legacy
data that was set before the registrant field existed.
"""
return form.Fields(
PublicPersonChoice(
__name__='registrant',
title=_('Project Registrant'),
description=_('The person who originally registered the '
'product. Distinct from the current '
'owner. This is historical data and should '
'not be changed without good cause.'),
vocabulary='ValidPersonOrTeam',
required=True,
readonly=False,
),
render_context=self.render_context
)
def validate(self, data):
"""See `LaunchpadFormView`."""
super(ProductAdminView, self).validate(data)
self.validate_deactivation(data)
@property
def cancel_url(self):
"""See `LaunchpadFormView`."""
return canonical_url(self.context)
class ProductReviewLicenseView(ReturnToReferrerMixin, ProductEditView,
ProductValidationMixin):
"""A view to review a project and change project privileges."""
label = "Review project"
field_names = [
"project_reviewed",
"license_approved",
"active",
"reviewer_whiteboard",
]
@property
def page_title(self):
"""The HTML page title."""
return 'Review %s' % self.context.title
def validate(self, data):
"""See `LaunchpadFormView`."""
super(ProductReviewLicenseView, self).validate(data)
# A project can only be approved if it has OTHER_OPEN_SOURCE as one of
# its licenses and not OTHER_PROPRIETARY.
licenses = self.context.licenses
license_approved = data.get('license_approved', False)
if license_approved:
if License.OTHER_PROPRIETARY in licenses:
self.setFieldError(
'license_approved',
'Proprietary projects may not be manually '
'approved to use Launchpad. Proprietary projects '
'must use the commercial subscription voucher system '
'to be allowed to use Launchpad.')
else:
# An Other/Open Source licence was specified so it may be
# approved.
pass
self.validate_deactivation(data)
class ProductAddSeriesView(LaunchpadFormView):
"""A form to add new product series"""
schema = IProductSeries
|
[
" field_names = ['name', 'summary', 'branch', 'releasefileglob']"
] | 4,413
|
lcc
|
python
| null |
c87c42b130a11ba81e64078e5be1ddb51be6aa08d42fa60d
| 95
|
Your task is code completion.
# Copyright 2009-2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Browser views for products."""
__metaclass__ = type
__all__ = [
'ProductAddSeriesView',
'ProductAddView',
'ProductAddViewBase',
'ProductAdminView',
'ProductBrandingView',
'ProductBugsMenu',
'ProductConfigureBase',
'ProductConfigureAnswersView',
'ProductConfigureBlueprintsView',
'ProductDownloadFileMixin',
'ProductDownloadFilesView',
'ProductEditPeopleView',
'ProductEditView',
'ProductFacets',
'ProductInvolvementView',
'ProductNavigation',
'ProductNavigationMenu',
'ProductOverviewMenu',
'ProductPackagesView',
'ProductPackagesPortletView',
'ProductPurchaseSubscriptionView',
'ProductRdfView',
'ProductReviewLicenseView',
'ProductSeriesSetView',
'ProductSetBreadcrumb',
'ProductSetFacets',
'ProductSetNavigation',
'ProductSetReviewLicensesView',
'ProductSetView',
'ProductSpecificationsMenu',
'ProductView',
'SortSeriesMixin',
'ProjectAddStepOne',
'ProjectAddStepTwo',
]
from operator import attrgetter
from lazr.delegates import delegates
from lazr.restful.interface import copy_field
from lazr.restful.interfaces import IJSONRequestCache
from z3c.ptcompat import ViewPageTemplateFile
from zope.component import getUtility
from zope.event import notify
from zope.formlib import form
from zope.formlib.interfaces import WidgetInputError
from zope.formlib.widget import CustomWidgetFactory
from zope.formlib.widgets import (
CheckBoxWidget,
TextAreaWidget,
TextWidget,
)
from zope.interface import (
implements,
Interface,
)
from zope.lifecycleevent import ObjectCreatedEvent
from zope.schema import (
Bool,
Choice,
)
from zope.schema.vocabulary import (
SimpleTerm,
SimpleVocabulary,
)
from lp import _
from lp.answers.browser.faqtarget import FAQTargetNavigationMixin
from lp.answers.browser.questiontarget import (
QuestionTargetFacetMixin,
QuestionTargetTraversalMixin,
)
from lp.app.browser.launchpadform import (
action,
custom_widget,
LaunchpadEditFormView,
LaunchpadFormView,
ReturnToReferrerMixin,
safe_action,
)
from lp.app.browser.lazrjs import (
BooleanChoiceWidget,
InlinePersonEditPickerWidget,
TextLineEditorWidget,
)
from lp.app.browser.multistep import (
MultiStepView,
StepView,
)
from lp.app.browser.stringformatter import FormattersAPI
from lp.app.browser.tales import (
format_link,
MenuAPI,
)
from lp.app.enums import (
InformationType,
PROPRIETARY_INFORMATION_TYPES,
PUBLIC_PROPRIETARY_INFORMATION_TYPES,
ServiceUsage,
)
from lp.app.errors import NotFoundError
from lp.app.interfaces.headings import IEditableContextTitle
from lp.app.interfaces.launchpad import ILaunchpadCelebrities
from lp.app.utilities import json_dump_information_types
from lp.app.vocabularies import InformationTypeVocabulary
from lp.app.widgets.date import DateWidget
from lp.app.widgets.itemswidgets import (
CheckBoxMatrixWidget,
LaunchpadRadioWidget,
LaunchpadRadioWidgetWithDescription,
)
from lp.app.widgets.popup import PersonPickerWidget
from lp.app.widgets.product import (
GhostWidget,
LicenseWidget,
ProductNameWidget,
)
from lp.app.widgets.textwidgets import StrippedTextWidget
from lp.blueprints.browser.specificationtarget import (
HasSpecificationsMenuMixin,
)
from lp.bugs.browser.bugtask import (
BugTargetTraversalMixin,
get_buglisting_search_filter_url,
)
from lp.bugs.browser.structuralsubscription import (
expose_structural_subscription_data_to_js,
StructuralSubscriptionMenuMixin,
StructuralSubscriptionTargetTraversalMixin,
)
from lp.bugs.interfaces.bugtask import RESOLVED_BUGTASK_STATUSES
from lp.code.browser.branchref import BranchRef
from lp.code.browser.sourcepackagerecipelisting import HasRecipesMenuMixin
from lp.registry.browser import (
add_subscribe_link,
BaseRdfView,
)
from lp.registry.browser.announcement import HasAnnouncementsView
from lp.registry.browser.branding import BrandingChangeView
from lp.registry.browser.menu import (
IRegistryCollectionNavigationMenu,
RegistryCollectionActionMenuBase,
)
from lp.registry.browser.pillar import (
PillarBugsMenu,
PillarInvolvementView,
PillarNavigationMixin,
PillarViewMixin,
)
from lp.registry.browser.productseries import get_series_branch_error
from lp.registry.interfaces.pillar import IPillarNameSet
from lp.registry.interfaces.product import (
IProduct,
IProductReviewSearch,
IProductSet,
License,
LicenseStatus,
)
from lp.registry.interfaces.productrelease import (
IProductRelease,
IProductReleaseSet,
)
from lp.registry.interfaces.productseries import IProductSeries
from lp.registry.interfaces.series import SeriesStatus
from lp.registry.interfaces.sourcepackagename import ISourcePackageNameSet
from lp.services.config import config
from lp.services.database.decoratedresultset import DecoratedResultSet
from lp.services.feeds.browser import FeedsMixin
from lp.services.fields import (
PillarAliases,
PublicPersonChoice,
)
from lp.services.librarian.interfaces import ILibraryFileAliasSet
from lp.services.propertycache import cachedproperty
from lp.services.webapp import (
ApplicationMenu,
canonical_url,
enabled_with_permission,
LaunchpadView,
Link,
Navigation,
sorted_version_numbers,
StandardLaunchpadFacets,
stepthrough,
stepto,
structured,
)
from lp.services.webapp.authorization import check_permission
from lp.services.webapp.batching import BatchNavigator
from lp.services.webapp.breadcrumb import Breadcrumb
from lp.services.webapp.interfaces import UnsafeFormGetSubmissionError
from lp.services.webapp.menu import NavigationMenu
from lp.services.worlddata.helpers import browser_languages
from lp.services.worlddata.interfaces.country import ICountry
from lp.translations.browser.customlanguagecode import (
HasCustomLanguageCodesTraversalMixin,
)
OR = ' OR '
SPACE = ' '
class ProductNavigation(
Navigation, BugTargetTraversalMixin,
FAQTargetNavigationMixin, HasCustomLanguageCodesTraversalMixin,
QuestionTargetTraversalMixin, StructuralSubscriptionTargetTraversalMixin,
PillarNavigationMixin):
usedfor = IProduct
@stepto('.bzr')
def dotbzr(self):
if self.context.development_focus.branch:
return BranchRef(self.context.development_focus.branch)
else:
return None
@stepthrough('+spec')
def traverse_spec(self, name):
spec = self.context.getSpecification(name)
if not check_permission('launchpad.LimitedView', spec):
return None
return spec
@stepthrough('+milestone')
def traverse_milestone(self, name):
return self.context.getMilestone(name)
@stepthrough('+release')
def traverse_release(self, name):
return self.context.getRelease(name)
@stepthrough('+announcement')
def traverse_announcement(self, name):
return self.context.getAnnouncement(name)
@stepthrough('+commercialsubscription')
def traverse_commercialsubscription(self, name):
return self.context.commercial_subscription
def traverse(self, name):
return self.context.getSeries(name)
class ProductSetNavigation(Navigation):
usedfor = IProductSet
def traverse(self, name):
product = self.context.getByName(name)
if product is None:
raise NotFoundError(name)
return self.redirectSubTree(canonical_url(product))
class ProductLicenseMixin:
"""Adds licence validation and requests reviews of licences.
Subclasses must inherit from Launchpad[Edit]FormView as well.
Requires the "product" attribute be set in the child
classes' action handler.
"""
def validate(self, data):
"""Validate 'licenses' and 'license_info'.
'licenses' must not be empty unless the product already
exists and never has had a licence set.
'license_info' must not be empty if "Other/Proprietary"
or "Other/Open Source" is checked.
"""
licenses = data.get('licenses', [])
license_widget = self.widgets.get('licenses')
if (len(licenses) == 0 and license_widget is not None):
self.setFieldError(
'licenses',
'You must select at least one licence. If you select '
'Other/Proprietary or Other/OpenSource you must include a '
'description of the licence.')
elif License.OTHER_PROPRIETARY in licenses:
if not data.get('license_info'):
self.setFieldError(
'license_info',
'A description of the "Other/Proprietary" '
'licence you checked is required.')
elif License.OTHER_OPEN_SOURCE in licenses:
if not data.get('license_info'):
self.setFieldError(
'license_info',
'A description of the "Other/Open Source" '
'licence you checked is required.')
else:
# Launchpad is ok with all licenses used in this project.
pass
class ProductFacets(QuestionTargetFacetMixin, StandardLaunchpadFacets):
"""The links that will appear in the facet menu for an IProduct."""
usedfor = IProduct
enable_only = ['overview', 'bugs', 'answers', 'specifications',
'translations', 'branches']
links = StandardLaunchpadFacets.links
def overview(self):
text = 'Overview'
summary = 'General information about %s' % self.context.displayname
return Link('', text, summary)
def bugs(self):
text = 'Bugs'
summary = 'Bugs reported about %s' % self.context.displayname
return Link('', text, summary)
def branches(self):
text = 'Code'
summary = 'Branches for %s' % self.context.displayname
return Link('', text, summary)
def specifications(self):
text = 'Blueprints'
summary = 'Feature specifications for %s' % self.context.displayname
return Link('', text, summary)
def translations(self):
text = 'Translations'
summary = 'Translations of %s in Launchpad' % self.context.displayname
return Link('', text, summary)
class ProductInvolvementView(PillarInvolvementView):
"""Encourage configuration of involvement links for projects."""
has_involvement = True
@property
def visible_disabled_link_names(self):
"""Show all disabled links...except blueprints"""
involved_menu = MenuAPI(self).navigation
all_links = involved_menu.keys()
# The register blueprints link should not be shown since its use is
# not encouraged.
all_links.remove('register_blueprint')
return all_links
@cachedproperty
def configuration_states(self):
"""Create a dictionary indicating the configuration statuses.
Each app area will be represented in the return dictionary, except
blueprints which we are not currently promoting.
"""
states = {}
states['configure_bugtracker'] = (
self.context.bug_tracking_usage != ServiceUsage.UNKNOWN)
states['configure_answers'] = (
self.context.answers_usage != ServiceUsage.UNKNOWN)
states['configure_translations'] = (
self.context.translations_usage != ServiceUsage.UNKNOWN)
states['configure_codehosting'] = (
self.context.codehosting_usage != ServiceUsage.UNKNOWN)
return states
@property
def configuration_links(self):
"""The enabled involvement links.
Returns a list of dicts keyed by:
'link' -- the menu link, and
'configured' -- a boolean representing the configuration status.
"""
overview_menu = MenuAPI(self.context).overview
series_menu = MenuAPI(self.context.development_focus).overview
configuration_names = [
'configure_bugtracker',
'configure_answers',
'configure_translations',
#'configure_blueprints',
]
config_list = []
config_statuses = self.configuration_states
for key in configuration_names:
config_list.append(dict(link=overview_menu[key],
configured=config_statuses[key]))
# Add the branch configuration in separately.
set_branch = series_menu['set_branch']
set_branch.text = 'Configure project branch'
set_branch.summary = "Specify the location of this project's code."
config_list.append(
dict(link=set_branch,
configured=config_statuses['configure_codehosting']))
return config_list
@property
def registration_completeness(self):
"""The percent complete for registration."""
config_statuses = self.configuration_states
configured = sum(1 for val in config_statuses.values() if val)
scale = 100
done = int(float(configured) / len(config_statuses) * scale)
undone = scale - done
return dict(done=done, undone=undone)
@property
def registration_done(self):
"""A boolean indicating that the services are fully configured."""
return (self.registration_completeness['done'] == 100)
class ProductNavigationMenu(NavigationMenu):
usedfor = IProduct
facet = 'overview'
links = [
'details',
'announcements',
'downloads',
]
def details(self):
text = 'Details'
return Link('', text)
def announcements(self):
text = 'Announcements'
return Link('+announcements', text)
def downloads(self):
text = 'Downloads'
return Link('+download', text)
class ProductEditLinksMixin(StructuralSubscriptionMenuMixin):
"""A mixin class for menus that need Product edit links."""
@enabled_with_permission('launchpad.Edit')
def edit(self):
text = 'Change details'
return Link('+edit', text, icon='edit')
@enabled_with_permission('launchpad.BugSupervisor')
def configure_bugtracker(self):
text = 'Configure bug tracker'
summary = 'Specify where bugs are tracked for this project'
return Link('+configure-bugtracker', text, summary, icon='edit')
@enabled_with_permission('launchpad.TranslationsAdmin')
def configure_translations(self):
text = 'Configure translations'
summary = 'Allow users to submit translations for this project'
return Link('+configure-translations', text, summary, icon='edit')
@enabled_with_permission('launchpad.Edit')
def configure_answers(self):
text = 'Configure support tracker'
summary = 'Allow users to ask questions on this project'
return Link('+configure-answers', text, summary, icon='edit')
@enabled_with_permission('launchpad.Edit')
def configure_blueprints(self):
text = 'Configure blueprints'
summary = 'Enable tracking of feature planning.'
return Link('+configure-blueprints', text, summary, icon='edit')
@enabled_with_permission('launchpad.Edit')
def branding(self):
text = 'Change branding'
return Link('+branding', text, icon='edit')
@enabled_with_permission('launchpad.Edit')
def reassign(self):
text = 'Change people'
return Link('+edit-people', text, icon='edit')
@enabled_with_permission('launchpad.Moderate')
def review_license(self):
text = 'Review project'
return Link('+review-license', text, icon='edit')
@enabled_with_permission('launchpad.Moderate')
def administer(self):
text = 'Administer'
return Link('+admin', text, icon='edit')
@enabled_with_permission('launchpad.Driver')
def sharing(self):
return Link('+sharing', 'Sharing', icon='edit')
class IProductEditMenu(Interface):
"""A marker interface for the 'Change details' navigation menu."""
class IProductActionMenu(Interface):
"""A marker interface for the global action navigation menu."""
class ProductActionNavigationMenu(NavigationMenu, ProductEditLinksMixin):
"""A sub-menu for acting upon a Product."""
usedfor = IProductActionMenu
facet = 'overview'
title = 'Actions'
@cachedproperty
def links(self):
links = ['edit', 'review_license', 'administer', 'sharing']
add_subscribe_link(links)
return links
class ProductOverviewMenu(ApplicationMenu, ProductEditLinksMixin,
HasRecipesMenuMixin):
usedfor = IProduct
facet = 'overview'
links = [
'edit',
'configure_answers',
'configure_blueprints',
'configure_bugtracker',
'configure_translations',
'reassign',
'top_contributors',
'distributions',
'packages',
'series',
'series_add',
'milestones',
'downloads',
'announce',
'announcements',
'administer',
'review_license',
'rdf',
'branding',
'view_recipes',
]
def top_contributors(self):
text = 'More contributors'
return Link('+topcontributors', text, icon='info')
def distributions(self):
text = 'Distribution packaging information'
return Link('+distributions', text, icon='info')
def packages(self):
text = 'Show distribution packages'
return Link('+packages', text, icon='info')
def series(self):
text = 'View full history'
return Link('+series', text, icon='info')
@enabled_with_permission('launchpad.Driver')
def series_add(self):
text = 'Register a series'
return Link('+addseries', text, icon='add')
def milestones(self):
text = 'View milestones'
return Link('+milestones', text, icon='info')
@enabled_with_permission('launchpad.Edit')
def announce(self):
text = 'Make announcement'
summary = 'Publish an item of news for this project'
return Link('+announce', text, summary, icon='add')
def announcements(self):
text = 'Read all announcements'
enabled = bool(self.context.getAnnouncements())
return Link('+announcements', text, icon='info', enabled=enabled)
def rdf(self):
text = structured(
'<abbr title="Resource Description Framework">'
'RDF</abbr> metadata')
return Link('+rdf', text, icon='download')
def downloads(self):
text = 'Downloads'
return Link('+download', text, icon='info')
class ProductBugsMenu(PillarBugsMenu, ProductEditLinksMixin):
usedfor = IProduct
facet = 'bugs'
configurable_bugtracker = True
@cachedproperty
def links(self):
links = ['filebug', 'bugsupervisor', 'cve']
add_subscribe_link(links)
links.append('configure_bugtracker')
return links
class ProductSpecificationsMenu(NavigationMenu, ProductEditLinksMixin,
HasSpecificationsMenuMixin):
usedfor = IProduct
facet = 'specifications'
links = ['configure_blueprints', 'listall', 'doc', 'assignments', 'new',
'register_sprint']
def _cmp_distros(a, b):
"""Put Ubuntu first, otherwise in alpha order."""
if a == 'ubuntu':
return -1
elif b == 'ubuntu':
return 1
else:
return cmp(a, b)
class ProductSetBreadcrumb(Breadcrumb):
"""Return a breadcrumb for an `IProductSet`."""
text = "Projects"
class ProductSetFacets(StandardLaunchpadFacets):
"""The links that will appear in the facet menu for the IProductSet."""
usedfor = IProductSet
enable_only = ['overview', 'branches']
class SortSeriesMixin:
"""Provide access to helpers for series."""
def _sorted_filtered_list(self, filter=None):
"""Return a sorted, filtered list of series.
The series list is sorted by version in reverse order. It is also
filtered by calling `filter` on every series. If the `filter`
function returns False, don't include the series. With None (the
default, include everything).
The development focus is always first in the list.
"""
series_list = []
for series in self.product.series:
if filter is None or filter(series):
series_list.append(series)
# In production data, there exist development focus series that are
# obsolete. This may be caused by bad data, or it may be intended
# functionality. In either case, ensure that the development focus
# branch is first in the list.
if self.product.development_focus in series_list:
series_list.remove(self.product.development_focus)
# Now sort the list by name with newer versions before older.
series_list = sorted_version_numbers(series_list,
key=attrgetter('name'))
series_list.insert(0, self.product.development_focus)
return series_list
@property
def sorted_series_list(self):
"""Return a sorted list of series.
The series list is sorted by version in reverse order.
The development focus is always first in the list.
"""
return self._sorted_filtered_list()
@property
def sorted_active_series_list(self):
"""Like `sorted_series_list()` but filters out OBSOLETE series."""
# Callback for the filter which only allows series that have not been
# marked obsolete.
def check_active(series):
return series.status != SeriesStatus.OBSOLETE
return self._sorted_filtered_list(check_active)
class ProductWithSeries:
"""A decorated product that includes series data.
The extra data is included in this class to avoid repeated
database queries. Rather than hitting the database, the data is
cached locally and simply returned.
"""
# `series` and `development_focus` need to be declared as class
# attributes so that this class will not delegate the actual instance
# variables to self.product, which would bypass the caching.
series = None
development_focus = None
delegates(IProduct, 'product')
def __init__(self, product):
self.product = product
self.series = []
for series in self.product.series:
series_with_releases = SeriesWithReleases(series, parent=self)
self.series.append(series_with_releases)
if self.product.development_focus == series:
self.development_focus = series_with_releases
# Get all of the releases for all of the series in a single
# query. The query sorts the releases properly so we know the
# resulting list is sorted correctly.
series_by_id = dict((series.id, series) for series in self.series)
self.release_by_id = {}
milestones_and_releases = list(
self.product.getMilestonesAndReleases())
for milestone, release in milestones_and_releases:
series = series_by_id[milestone.productseries.id]
release_delegate = ReleaseWithFiles(release, parent=series)
series.addRelease(release_delegate)
self.release_by_id[release.id] = release_delegate
class DecoratedSeries:
"""A decorated series that includes helper attributes for templates."""
delegates(IProductSeries, 'series')
def __init__(self, series):
self.series = series
@property
def css_class(self):
"""The highlight, lowlight, or normal CSS class."""
if self.is_development_focus:
return 'highlight'
elif self.status == SeriesStatus.OBSOLETE:
return 'lowlight'
else:
# This is normal presentation.
return ''
@cachedproperty
def packagings(self):
"""Convert packagings to list to prevent multiple evaluations."""
return list(self.series.packagings)
class SeriesWithReleases(DecoratedSeries):
"""A decorated series that includes releases.
The extra data is included in this class to avoid repeated
database queries. Rather than hitting the database, the data is
cached locally and simply returned.
"""
# `parent` and `releases` need to be declared as class attributes so that
# this class will not delegate the actual instance variables to
# self.series, which would bypass the caching for self.releases and would
# raise an AttributeError for self.parent.
parent = None
releases = None
def __init__(self, series, parent):
super(SeriesWithReleases, self).__init__(series)
self.parent = parent
self.releases = []
def addRelease(self, release):
self.releases.append(release)
@cachedproperty
def has_release_files(self):
for release in self.releases:
if len(release.files) > 0:
return True
return False
class ReleaseWithFiles:
"""A decorated release that includes product release files.
The extra data is included in this class to avoid repeated
database queries. Rather than hitting the database, the data is
cached locally and simply returned.
"""
# `parent` needs to be declared as class attributes so that
# this class will not delegate the actual instance variables to
# self.release, which would raise an AttributeError.
parent = None
delegates(IProductRelease, 'release')
def __init__(self, release, parent):
self.release = release
self.parent = parent
self._files = None
@property
def files(self):
"""Cache the release files for all the releases in the product."""
if self._files is None:
# Get all of the files for all of the releases. The query
# returns all releases sorted properly.
product = self.parent.parent
release_delegates = product.release_by_id.values()
files = getUtility(IProductReleaseSet).getFilesForReleases(
release_delegates)
for release_delegate in release_delegates:
release_delegate._files = []
for file in files:
id = file.productrelease.id
release_delegate = product.release_by_id[id]
release_delegate._files.append(file)
# self._files was set above, since self is actually in the
# release_delegates variable.
return self._files
@property
def name_with_codename(self):
milestone = self.release.milestone
if milestone.code_name:
return "%s (%s)" % (milestone.name, milestone.code_name)
else:
return milestone.name
@cachedproperty
def total_downloads(self):
"""Total downloads of files associated with this release."""
return sum(file.libraryfile.hits for file in self.files)
class ProductDownloadFileMixin:
"""Provides methods for managing download files."""
@cachedproperty
def product(self):
"""Product with all series, release and file data cached.
Decorated classes are created, and they contain cached data
obtained with a few queries rather than many iterated queries.
"""
return ProductWithSeries(self.context)
def deleteFiles(self, releases):
"""Delete the selected files from the set of releases.
:param releases: A set of releases in the view.
:return: The number of files deleted.
"""
del_count = 0
for release in releases:
for release_file in release.files:
if release_file.libraryfile.id in self.delete_ids:
release_file.destroySelf()
self.delete_ids.remove(release_file.libraryfile.id)
del_count += 1
return del_count
def getReleases(self):
"""Find the releases with download files for view."""
raise NotImplementedError
def processDeleteFiles(self):
"""If the 'delete_files' button was pressed, process the deletions."""
del_count = None
if 'delete_files' in self.form:
if self.request.method == 'POST':
self.delete_ids = [
int(value) for key, value in self.form.items()
if key.startswith('checkbox')]
del(self.form['delete_files'])
releases = self.getReleases()
del_count = self.deleteFiles(releases)
else:
# If there is a form submission and it is not a POST then
# raise an error. This is to protect against XSS exploits.
raise UnsafeFormGetSubmissionError(self.form['delete_files'])
if del_count is not None:
if del_count <= 0:
self.request.response.addNotification(
"No files were deleted.")
elif del_count == 1:
self.request.response.addNotification(
"1 file has been deleted.")
else:
self.request.response.addNotification(
"%d files have been deleted." %
del_count)
@cachedproperty
def latest_release_with_download_files(self):
"""Return the latest release with download files."""
for series in self.sorted_active_series_list:
for release in series.releases:
if len(list(release.files)) > 0:
return release
return None
@cachedproperty
def has_download_files(self):
for series in self.context.series:
if series.status == SeriesStatus.OBSOLETE:
continue
for release in series.getCachedReleases():
if len(list(release.files)) > 0:
return True
return False
class ProductView(PillarViewMixin, HasAnnouncementsView, SortSeriesMixin,
FeedsMixin, ProductDownloadFileMixin):
implements(IProductActionMenu, IEditableContextTitle)
@property
def maintainer_widget(self):
return InlinePersonEditPickerWidget(
self.context, IProduct['owner'],
format_link(self.context.owner),
header='Change maintainer', edit_view='+edit-people',
step_title='Select a new maintainer', show_create_team=True)
@property
def driver_widget(self):
return InlinePersonEditPickerWidget(
self.context, IProduct['driver'],
format_link(self.context.driver, empty_value="Not yet selected"),
header='Change driver', edit_view='+edit-people',
step_title='Select a new driver', show_create_team=True,
null_display_value="Not yet selected",
help_link="/+help-registry/driver.html")
def __init__(self, context, request):
HasAnnouncementsView.__init__(self, context, request)
self.form = request.form_ng
def initialize(self):
super(ProductView, self).initialize()
self.status_message = None
product = self.context
title_field = IProduct['title']
title = "Edit this title"
self.title_edit_widget = TextLineEditorWidget(
product, title_field, title, 'h1', max_width='95%',
truncate_lines=2)
programming_lang = IProduct['programminglang']
title = 'Edit programming languages'
additional_arguments = {
'width': '9em',
'css_class': 'nowrap'}
if self.context.programminglang is None:
additional_arguments.update(dict(
default_text='Not yet specified',
initial_value_override='',
))
self.languages_edit_widget = TextLineEditorWidget(
product, programming_lang, title, 'span', **additional_arguments)
self.show_programming_languages = bool(
self.context.programminglang or
check_permission('launchpad.Edit', self.context))
expose_structural_subscription_data_to_js(
self.context, self.request, self.user)
@property
def page_title(self):
return '%s in Launchpad' % self.context.displayname
@property
def page_description(self):
return '\n'.filter(
None,
[self.context.summary, self.context.description])
@property
def show_license_status(self):
return self.context.license_status != LicenseStatus.OPEN_SOURCE
@property
def freshmeat_url(self):
if self.context.freshmeatproject:
return ("http://freshmeat.net/projects/%s"
% self.context.freshmeatproject)
return None
@property
def sourceforge_url(self):
if self.context.sourceforgeproject:
return ("http://sourceforge.net/projects/%s"
% self.context.sourceforgeproject)
return None
@property
def has_external_links(self):
return (self.context.homepageurl or
self.context.sourceforgeproject or
self.context.freshmeatproject or
self.context.wikiurl or
self.context.screenshotsurl or
self.context.downloadurl)
@property
def external_links(self):
"""The project's external links.
The home page link is not included because its link must have the
rel=nofollow attribute.
"""
from lp.services.webapp.menu import MenuLink
urls = [
('Sourceforge project', self.sourceforge_url),
('Freshmeat record', self.freshmeat_url),
('Wiki', self.context.wikiurl),
('Screenshots', self.context.screenshotsurl),
('External downloads', self.context.downloadurl),
]
links = []
for (text, url) in urls:
if url is not None:
menu_link = MenuLink(
Link(url, text, icon='external-link', enabled=True))
menu_link.url = url
links.append(menu_link)
return links
@property
def should_display_homepage(self):
return (self.context.homepageurl and
self.context.homepageurl not in
[self.freshmeat_url, self.sourceforge_url])
def requestCountry(self):
return ICountry(self.request, None)
def browserLanguages(self):
return browser_languages(self.request)
def getClosedBugsURL(self, series):
status = [status.title for status in RESOLVED_BUGTASK_STATUSES]
url = canonical_url(series) + '/+bugs'
return get_buglisting_search_filter_url(url, status=status)
@property
def can_purchase_subscription(self):
return (check_permission('launchpad.Edit', self.context)
and not self.context.qualifies_for_free_hosting)
@cachedproperty
def effective_driver(self):
"""Return the product driver or the project driver."""
if self.context.driver is not None:
driver = self.context.driver
elif (self.context.project is not None and
self.context.project.driver is not None):
driver = self.context.project.driver
else:
driver = None
return driver
@cachedproperty
def show_commercial_subscription_info(self):
"""Should subscription information be shown?
Subscription information is only shown to the project maintainers,
Launchpad admins, and members of the Launchpad commercial team. The
first two are allowed via the Launchpad.Edit permission. The latter
is allowed via Launchpad.Commercial.
"""
return (check_permission('launchpad.Edit', self.context) or
check_permission('launchpad.Commercial', self.context))
@cachedproperty
def show_license_info(self):
"""Should the view show the extra licence information."""
return (
License.OTHER_OPEN_SOURCE in self.context.licenses
or License.OTHER_PROPRIETARY in self.context.licenses)
@cachedproperty
def is_proprietary(self):
"""Is the project proprietary."""
return License.OTHER_PROPRIETARY in self.context.licenses
@property
def active_widget(self):
return BooleanChoiceWidget(
self.context, IProduct['active'],
content_box_id='%s-edit-active' % FormattersAPI(
self.context.name).css_id(),
edit_view='+review-license',
tag='span',
false_text='Deactivated',
true_text='Active',
header='Is this project active and usable by the community?')
@property
def project_reviewed_widget(self):
return BooleanChoiceWidget(
self.context, IProduct['project_reviewed'],
content_box_id='%s-edit-project-reviewed' % FormattersAPI(
self.context.name).css_id(),
edit_view='+review-license',
tag='span',
false_text='Unreviewed',
true_text='Reviewed',
header='Have you reviewed the project?')
@property
def license_approved_widget(self):
licenses = list(self.context.licenses)
if License.OTHER_PROPRIETARY in licenses:
return 'Commercial subscription required'
elif [License.DONT_KNOW] == licenses or [] == licenses:
return 'Licence required'
return BooleanChoiceWidget(
self.context, IProduct['license_approved'],
content_box_id='%s-edit-license-approved' % FormattersAPI(
self.context.name).css_id(),
edit_view='+review-license',
tag='span',
false_text='Unapproved',
true_text='Approved',
header='Does the licence qualifiy the project for free hosting?')
class ProductPurchaseSubscriptionView(ProductView):
"""View the instructions to purchase a commercial subscription."""
page_title = 'Purchase subscription'
class ProductPackagesView(LaunchpadView):
"""View for displaying product packaging"""
label = 'Linked packages'
page_title = label
@cachedproperty
def series_batch(self):
"""A batch of series that are active or have packages."""
decorated_series = DecoratedResultSet(
self.context.active_or_packaged_series, DecoratedSeries)
return BatchNavigator(decorated_series, self.request)
@property
def distro_packaging(self):
"""This method returns a representation of the product packagings
for this product, in a special structure used for the
product-distros.pt page template.
Specifically, it is a list of "distro" objects, each of which has a
title, and an attribute "packagings" which is a list of the relevant
packagings for this distro and product.
"""
distros = {}
for packaging in self.context.packagings:
distribution = packaging.distroseries.distribution
if distribution.name in distros:
distro = distros[distribution.name]
else:
# Create a dictionary for the distribution.
distro = dict(
distribution=distribution,
packagings=[])
distros[distribution.name] = distro
distro['packagings'].append(packaging)
# Now we sort the resulting list of "distro" objects, and return that.
distro_names = distros.keys()
distro_names.sort(cmp=_cmp_distros)
results = [distros[name] for name in distro_names]
return results
class ProductPackagesPortletView(LaunchpadView):
"""View class for product packaging portlet."""
schema = Interface
@cachedproperty
def sourcepackages(self):
"""The project's latest source packages."""
current_packages = [
sp for sp in self.context.sourcepackages
if sp.currentrelease is not None]
current_packages.reverse()
return current_packages[0:5]
@cachedproperty
def can_show_portlet(self):
"""Are there packages, or can packages be suggested."""
if len(self.sourcepackages) > 0:
return True
class SeriesReleasePair:
"""Class for holding a series and release.
Replaces the use of a (series, release) tuple so that it can be more
clearly addressed in the view class.
"""
def __init__(self, series, release):
self.series = series
self.release = release
class ProductDownloadFilesView(LaunchpadView,
SortSeriesMixin,
ProductDownloadFileMixin):
"""View class for the product's file downloads page."""
batch_size = config.launchpad.download_batch_size
@property
def page_title(self):
return "%s project files" % self.context.displayname
def initialize(self):
"""See `LaunchpadFormView`."""
self.form = self.request.form
# Manually process action for the 'Delete' button.
self.processDeleteFiles()
def getReleases(self):
"""See `ProductDownloadFileMixin`."""
releases = set()
for series in self.product.series:
releases.update(series.releases)
return releases
@cachedproperty
def series_and_releases_batch(self):
"""Get a batch of series and release
Each entry returned is a tuple of (series, release).
"""
series_and_releases = []
for series in self.sorted_series_list:
for release in series.releases:
if len(release.files) > 0:
pair = SeriesReleasePair(series, release)
if pair not in series_and_releases:
series_and_releases.append(pair)
batch = BatchNavigator(series_and_releases, self.request,
size=self.batch_size)
batch.setHeadings("release", "releases")
return batch
@cachedproperty
def has_download_files(self):
"""Across series and releases do any download files exist?"""
for series in self.product.series:
if series.has_release_files:
return True
return False
@cachedproperty
def any_download_files_with_signatures(self):
"""Do any series or release download files have signatures?"""
for series in self.product.series:
for release in series.releases:
for file in release.files:
if file.signature:
return True
return False
@cachedproperty
def milestones(self):
"""A mapping between series and releases that are milestones."""
result = dict()
for series in self.product.series:
result[series.name] = set()
milestone_list = [m.name for m in series.milestones]
for release in series.releases:
if release.version in milestone_list:
result[series.name].add(release.version)
return result
def is_milestone(self, series, release):
"""Determine whether a release is milestone for the series."""
return (series.name in self.milestones and
release.version in self.milestones[series.name])
class ProductBrandingView(BrandingChangeView):
"""A view to set branding."""
implements(IProductEditMenu)
label = "Change branding"
schema = IProduct
field_names = ['icon', 'logo', 'mugshot']
@property
def page_title(self):
"""The HTML page title."""
return "Change %s's branding" % self.context.title
@property
def cancel_url(self):
"""See `LaunchpadFormView`."""
return canonical_url(self.context)
class ProductConfigureBase(ReturnToReferrerMixin, LaunchpadEditFormView):
implements(IProductEditMenu)
schema = IProduct
usage_fieldname = None
def setUpFields(self):
super(ProductConfigureBase, self).setUpFields()
if self.usage_fieldname is not None:
# The usage fields are shared among pillars. But when referring
# to an individual object in Launchpad it is better to call it by
# its real name, i.e. 'project' instead of 'pillar'.
usage_field = self.form_fields.get(self.usage_fieldname)
if usage_field:
usage_field.custom_widget = CustomWidgetFactory(
LaunchpadRadioWidget, orientation='vertical')
# Copy the field or else the description in the interface will
# be modified in-place.
field = copy_field(usage_field.field)
field.description = (
field.description.replace('pillar', 'project'))
usage_field.field = field
if (self.usage_fieldname in
('answers_usage', 'translations_usage') and
self.context.information_type in
PROPRIETARY_INFORMATION_TYPES):
values = usage_field.field.vocabulary.items
terms = [SimpleTerm(value, value.name, value.title)
for value in values
if value != ServiceUsage.LAUNCHPAD]
usage_field.field.vocabulary = SimpleVocabulary(terms)
@property
def field_names(self):
return [self.usage_fieldname]
@property
def page_title(self):
return self.label
@action("Change", name='change')
def change_action(self, action, data):
self.updateContextFromData(data)
class ProductConfigureBlueprintsView(ProductConfigureBase):
"""View class to configure the Launchpad Blueprints for a project."""
label = "Configure blueprints"
usage_fieldname = 'blueprints_usage'
class ProductConfigureAnswersView(ProductConfigureBase):
"""View class to configure the Launchpad Answers for a project."""
label = "Configure answers"
usage_fieldname = 'answers_usage'
class ProductEditView(ProductLicenseMixin, LaunchpadEditFormView):
"""View class that lets you edit a Product object."""
implements(IProductEditMenu)
label = "Edit details"
schema = IProduct
field_names = [
"displayname",
"title",
"summary",
"description",
"project",
"homepageurl",
"information_type",
"sourceforgeproject",
"freshmeatproject",
"wikiurl",
"screenshotsurl",
"downloadurl",
"programminglang",
"development_focus",
"licenses",
"license_info",
]
custom_widget('licenses', LicenseWidget)
custom_widget('license_info', GhostWidget)
custom_widget(
'information_type', LaunchpadRadioWidgetWithDescription,
vocabulary=InformationTypeVocabulary(
types=PUBLIC_PROPRIETARY_INFORMATION_TYPES))
@property
def next_url(self):
"""See `LaunchpadFormView`."""
if self.context.active:
if len(self.errors) > 0:
return None
return canonical_url(self.context)
else:
return canonical_url(getUtility(IProductSet))
cancel_url = next_url
@property
def page_title(self):
"""The HTML page title."""
return "Change %s's details" % self.context.title
def initialize(self):
# The JSON cache must be populated before the super call, since
# the form is rendered during LaunchpadFormView's initialize()
# when an action is invoked.
cache = IJSONRequestCache(self.request)
json_dump_information_types(
cache, PUBLIC_PROPRIETARY_INFORMATION_TYPES)
super(ProductEditView, self).initialize()
def validate(self, data):
"""Validate 'licenses' and 'license_info'.
'licenses' must not be empty unless the product already
exists and never has had a licence set.
'license_info' must not be empty if "Other/Proprietary"
or "Other/Open Source" is checked.
"""
super(ProductEditView, self).validate(data)
information_type = data.get('information_type')
if information_type:
errors = [
str(e) for e in self.context.checkInformationType(
information_type)]
if len(errors) > 0:
self.setFieldError('information_type', ' '.join(errors))
def showOptionalMarker(self, field_name):
"""See `LaunchpadFormView`."""
# This has the effect of suppressing the ": (Optional)" stuff for the
# license_info widget. It's the last piece of the puzzle for
# manipulating the license_info widget into the table for the
# LicenseWidget instead of the enclosing form.
if field_name == 'license_info':
return False
return super(ProductEditView, self).showOptionalMarker(field_name)
@action("Change", name='change')
def change_action(self, action, data):
self.updateContextFromData(data)
class ProductValidationMixin:
def validate_deactivation(self, data):
"""Verify whether a product can be safely deactivated."""
if data['active'] == False and self.context.active == True:
if len(self.context.sourcepackages) > 0:
self.setFieldError('active',
structured(
'This project cannot be deactivated since it is '
'linked to one or more '
'<a href="%s">source packages</a>.',
canonical_url(self.context, view_name='+packages')))
class ProductAdminView(ProductEditView, ProductValidationMixin):
"""View for $project/+admin"""
label = "Administer project details"
default_field_names = [
"name",
"owner",
"active",
"autoupdate",
]
@property
def page_title(self):
"""The HTML page title."""
return 'Administer %s' % self.context.title
def setUpFields(self):
"""Setup the normal fields from the schema plus adds 'Registrant'.
The registrant is normally a read-only field and thus does not have a
proper widget created by default. Even though it is read-only, admins
need the ability to change it.
"""
self.field_names = self.default_field_names[:]
admin = check_permission('launchpad.Admin', self.context)
if not admin:
self.field_names.remove('owner')
self.field_names.remove('autoupdate')
super(ProductAdminView, self).setUpFields()
self.form_fields = self._createAliasesField() + self.form_fields
if admin:
self.form_fields = (
self.form_fields + self._createRegistrantField())
def _createAliasesField(self):
"""Return a PillarAliases field for IProduct.aliases."""
return form.Fields(
PillarAliases(
__name__='aliases', title=_('Aliases'),
description=_('Other names (separated by space) under which '
'this project is known.'),
required=False, readonly=False),
render_context=self.render_context)
def _createRegistrantField(self):
"""Return a popup widget person selector for the registrant.
This custom field is necessary because *normally* the registrant is
read-only but we want the admins to have the ability to correct legacy
data that was set before the registrant field existed.
"""
return form.Fields(
PublicPersonChoice(
__name__='registrant',
title=_('Project Registrant'),
description=_('The person who originally registered the '
'product. Distinct from the current '
'owner. This is historical data and should '
'not be changed without good cause.'),
vocabulary='ValidPersonOrTeam',
required=True,
readonly=False,
),
render_context=self.render_context
)
def validate(self, data):
"""See `LaunchpadFormView`."""
super(ProductAdminView, self).validate(data)
self.validate_deactivation(data)
@property
def cancel_url(self):
"""See `LaunchpadFormView`."""
return canonical_url(self.context)
class ProductReviewLicenseView(ReturnToReferrerMixin, ProductEditView,
ProductValidationMixin):
"""A view to review a project and change project privileges."""
label = "Review project"
field_names = [
"project_reviewed",
"license_approved",
"active",
"reviewer_whiteboard",
]
@property
def page_title(self):
"""The HTML page title."""
return 'Review %s' % self.context.title
def validate(self, data):
"""See `LaunchpadFormView`."""
super(ProductReviewLicenseView, self).validate(data)
# A project can only be approved if it has OTHER_OPEN_SOURCE as one of
# its licenses and not OTHER_PROPRIETARY.
licenses = self.context.licenses
license_approved = data.get('license_approved', False)
if license_approved:
if License.OTHER_PROPRIETARY in licenses:
self.setFieldError(
'license_approved',
'Proprietary projects may not be manually '
'approved to use Launchpad. Proprietary projects '
'must use the commercial subscription voucher system '
'to be allowed to use Launchpad.')
else:
# An Other/Open Source licence was specified so it may be
# approved.
pass
self.validate_deactivation(data)
class ProductAddSeriesView(LaunchpadFormView):
"""A form to add new product series"""
schema = IProductSeries
|
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
|
Context:
[Previous code... ~10,000 lines omitted for brevity]
class ProductDownloadFilesView(LaunchpadView,
SortSeriesMixin,
ProductDownloadFileMixin):
"""View class for the product's file downloads page."""
batch_size = config.launchpad.download_batch_size
@property
def page_title(self):
return "%s project files" % self.context.displayname
def initialize(self):
"""See `LaunchpadFormView`."""
self.form = self.request.form
# Manually process action for the 'Delete' button.
self.processDeleteFiles()
def getReleases(self):
"""See `ProductDownloadFileMixin`."""
releases = set()
for series in self.product.series:
releases.update(series.releases)
return releases
@cachedproperty
def series_and_releases_batch(self):
"""Get a batch of series and release
Each entry returned is a tuple of (series, release).
"""
series_and_releases = []
for series in self.sorted_series_list:
for release in series.releases:
if len(release.files) > 0:
pair = SeriesReleasePair(series, release)
if pair not in series_and_releases:
series_and_releases.append(pair)
batch = BatchNavigator(series_and_releases, self.request,
size=self.batch_size)
batch.setHeadings("release", "releases")
return batch
@cachedproperty
def has_download_files(self):
"""Across series and releases do any download files exist?"""
for series in self.product.series:
if series.has_release_files:
return True
return False
@cachedproperty
def any_download_files_with_signatures(self):
"""Do any series or release download files have signatures?"""
for series in self.product.series:
for release in series.releases:
for file in release.files:
if file.signature:
return True
return False
@cachedproperty
def milestones(self):
"""A mapping between series and releases that are milestones."""
result = dict()
for series in self.product.series:
result[series.name] = set()
milestone_list = [m.name for m in series.milestones]
for release in series.releases:
if release.version in milestone_list:
result[series.name].add(release.version)
return result
def is_milestone(self, series, release):
"""Determine whether a release is milestone for the series."""
return (series.name in self.milestones and
release.version in self.milestones[series.name])
Cheatsheet (for next line):
- We are in ProductDownloadFilesView class.
- The class has a method called getReleases() which returns a set of releases.
- The method processDeleteFiles() is called in the initialize() method.
- The method processDeleteFiles() calls deleteFiles() which takes a set of releases.
- The method deleteFiles() is defined in ProductDownloadFileMixin.
- The method deleteFiles() returns the number of files deleted.
- The method getReleases() is called in the initialize() method.
- The method initialize() is called in the __init__ method.
- The method __init__ is the constructor of the class.
Next line will likely be: return self.deleteFiles(releases);
|
|
Please complete the code given below.
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
#if !KeePassUAP
using System.Drawing;
using System.Windows.Forms;
#endif
#if KeePassLibSD
using ICSharpCode.SharpZipLib.GZip;
#else
using System.IO.Compression;
#endif
using KeePassLib.Interfaces;
using KeePassLib.Utility;
namespace KeePassLib.Translation
{
[XmlRoot("Translation")]
public sealed class KPTranslation
{
public static readonly string FileExtension = "lngx";
private KPTranslationProperties m_props = new KPTranslationProperties();
public KPTranslationProperties Properties
{
get { return m_props; }
set
{
if(value == null) throw new ArgumentNullException("value");
m_props = value;
}
}
private List<KPStringTable> m_vStringTables = new List<KPStringTable>();
[XmlArrayItem("StringTable")]
public List<KPStringTable> StringTables
{
get { return m_vStringTables; }
set
{
if(value == null) throw new ArgumentNullException("value");
m_vStringTables = value;
}
}
private List<KPFormCustomization> m_vForms = new List<KPFormCustomization>();
[XmlArrayItem("Form")]
public List<KPFormCustomization> Forms
{
get { return m_vForms; }
set
{
if(value == null) throw new ArgumentNullException("value");
m_vForms = value;
}
}
private string m_strUnusedText = string.Empty;
[DefaultValue("")]
public string UnusedText
{
get { return m_strUnusedText; }
set
{
if(value == null) throw new ArgumentNullException("value");
m_strUnusedText = value;
}
}
public static void Save(KPTranslation kpTrl, string strFileName,
IXmlSerializerEx xs)
{
using(FileStream fs = new FileStream(strFileName, FileMode.Create,
FileAccess.Write, FileShare.None))
{
Save(kpTrl, fs, xs);
}
}
public static void Save(KPTranslation kpTrl, Stream sOut,
IXmlSerializerEx xs)
{
if(xs == null) throw new ArgumentNullException("xs");
#if !KeePassLibSD
using(GZipStream gz = new GZipStream(sOut, CompressionMode.Compress))
#else
using(GZipOutputStream gz = new GZipOutputStream(sOut))
#endif
{
using(XmlWriter xw = XmlUtilEx.CreateXmlWriter(gz))
{
xs.Serialize(xw, kpTrl);
}
}
sOut.Close();
}
public static KPTranslation Load(string strFile, IXmlSerializerEx xs)
{
KPTranslation kpTrl = null;
using(FileStream fs = new FileStream(strFile, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
kpTrl = Load(fs, xs);
}
return kpTrl;
}
public static KPTranslation Load(Stream s, IXmlSerializerEx xs)
{
if(xs == null) throw new ArgumentNullException("xs");
KPTranslation kpTrl = null;
#if !KeePassLibSD
using(GZipStream gz = new GZipStream(s, CompressionMode.Decompress))
#else
using(GZipInputStream gz = new GZipInputStream(s))
#endif
{
kpTrl = (xs.Deserialize(gz) as KPTranslation);
}
s.Close();
return kpTrl;
}
public Dictionary<string, string> SafeGetStringTableDictionary(
string strTableName)
{
foreach(KPStringTable kpst in m_vStringTables)
{
if(kpst.Name == strTableName) return kpst.ToDictionary();
}
return new Dictionary<string, string>();
}
#if (!KeePassLibSD && !KeePassUAP)
public void ApplyTo(Form form)
{
if(form == null) throw new ArgumentNullException("form");
if(m_props.RightToLeft)
{
try
{
form.RightToLeft = RightToLeft.Yes;
form.RightToLeftLayout = true;
}
catch(Exception) { Debug.Assert(false); }
}
string strTypeName = form.GetType().FullName;
foreach(KPFormCustomization kpfc in m_vForms)
{
if(kpfc.FullName == strTypeName)
{
kpfc.ApplyTo(form);
break;
}
}
if(m_props.RightToLeft)
{
|
[
"\t\t\t\ttry { RtlApplyToControls(form.Controls); }"
] | 511
|
lcc
|
csharp
| null |
6d015d2fedcdf18b400b44406bfa6c05a907c32559c2fac3
| 96
|
Your task is code completion.
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
#if !KeePassUAP
using System.Drawing;
using System.Windows.Forms;
#endif
#if KeePassLibSD
using ICSharpCode.SharpZipLib.GZip;
#else
using System.IO.Compression;
#endif
using KeePassLib.Interfaces;
using KeePassLib.Utility;
namespace KeePassLib.Translation
{
[XmlRoot("Translation")]
public sealed class KPTranslation
{
public static readonly string FileExtension = "lngx";
private KPTranslationProperties m_props = new KPTranslationProperties();
public KPTranslationProperties Properties
{
get { return m_props; }
set
{
if(value == null) throw new ArgumentNullException("value");
m_props = value;
}
}
private List<KPStringTable> m_vStringTables = new List<KPStringTable>();
[XmlArrayItem("StringTable")]
public List<KPStringTable> StringTables
{
get { return m_vStringTables; }
set
{
if(value == null) throw new ArgumentNullException("value");
m_vStringTables = value;
}
}
private List<KPFormCustomization> m_vForms = new List<KPFormCustomization>();
[XmlArrayItem("Form")]
public List<KPFormCustomization> Forms
{
get { return m_vForms; }
set
{
if(value == null) throw new ArgumentNullException("value");
m_vForms = value;
}
}
private string m_strUnusedText = string.Empty;
[DefaultValue("")]
public string UnusedText
{
get { return m_strUnusedText; }
set
{
if(value == null) throw new ArgumentNullException("value");
m_strUnusedText = value;
}
}
public static void Save(KPTranslation kpTrl, string strFileName,
IXmlSerializerEx xs)
{
using(FileStream fs = new FileStream(strFileName, FileMode.Create,
FileAccess.Write, FileShare.None))
{
Save(kpTrl, fs, xs);
}
}
public static void Save(KPTranslation kpTrl, Stream sOut,
IXmlSerializerEx xs)
{
if(xs == null) throw new ArgumentNullException("xs");
#if !KeePassLibSD
using(GZipStream gz = new GZipStream(sOut, CompressionMode.Compress))
#else
using(GZipOutputStream gz = new GZipOutputStream(sOut))
#endif
{
using(XmlWriter xw = XmlUtilEx.CreateXmlWriter(gz))
{
xs.Serialize(xw, kpTrl);
}
}
sOut.Close();
}
public static KPTranslation Load(string strFile, IXmlSerializerEx xs)
{
KPTranslation kpTrl = null;
using(FileStream fs = new FileStream(strFile, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
kpTrl = Load(fs, xs);
}
return kpTrl;
}
public static KPTranslation Load(Stream s, IXmlSerializerEx xs)
{
if(xs == null) throw new ArgumentNullException("xs");
KPTranslation kpTrl = null;
#if !KeePassLibSD
using(GZipStream gz = new GZipStream(s, CompressionMode.Decompress))
#else
using(GZipInputStream gz = new GZipInputStream(s))
#endif
{
kpTrl = (xs.Deserialize(gz) as KPTranslation);
}
s.Close();
return kpTrl;
}
public Dictionary<string, string> SafeGetStringTableDictionary(
string strTableName)
{
foreach(KPStringTable kpst in m_vStringTables)
{
if(kpst.Name == strTableName) return kpst.ToDictionary();
}
return new Dictionary<string, string>();
}
#if (!KeePassLibSD && !KeePassUAP)
public void ApplyTo(Form form)
{
if(form == null) throw new ArgumentNullException("form");
if(m_props.RightToLeft)
{
try
{
form.RightToLeft = RightToLeft.Yes;
form.RightToLeftLayout = true;
}
catch(Exception) { Debug.Assert(false); }
}
string strTypeName = form.GetType().FullName;
foreach(KPFormCustomization kpfc in m_vForms)
{
if(kpfc.FullName == strTypeName)
{
kpfc.ApplyTo(form);
break;
}
}
if(m_props.RightToLeft)
{
|
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 the brevity]
public static void Save(KPTranslation kpTrl, Stream sOut,
IXmlSerializerEx xs)
{
if(xs == null) throw new ArgumentNullException("xs");
#if !KeePassLibSD
using(GZipStream gz = new GZipStream(sOut, CompressionMode.Compress))
#else
using(GZipOutputStream gz = new GZipOutputStream(sOut))
#endif
{
using(XmlWriter xw = XmlUtilEx.CreateXmlWriter(gz))
{
xs.Serialize(xw, kpTrl);
}
}
sOut.Close();
}
Cheatsheet (for next line):
- We are in the Save() method, which is closing the stream sOut.
- The method is already closing the GZipStream (gz) using a using statement.
- Convention: Streams should be closed after use.
- [Relevant lines: sOut.Close(), using statement for gz]
Next line will likely be: sOut.Dispose();
|
|
Please complete the code given below.
/**
* @author : Paul Taylor
* @author : Eric Farng
*
* Version @version:$Id$
*
* MusicTag Copyright (C)2003,2004
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation; either version 2.1 of the License,
* or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not,
* you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Description:
*
*/
package org.jaudiotagger.tag.datatype;
import org.jaudiotagger.tag.InvalidDataTypeException;
import org.jaudiotagger.tag.id3.AbstractTagFrameBody;
import org.jaudiotagger.tag.id3.ID3Tags;
/**
* Represents a number which may span a number of bytes when written to file depending what size is to be represented.
*
* The bitorder in ID3v2 is most significant bit first (MSB). The byteorder in multibyte numbers is most significant
* byte first (e.g. $12345678 would be encoded $12 34 56 78), also known as big endian and network byte order.
*
* In ID3Specification would be denoted as $xx xx xx xx (xx ...) , this denotes at least four bytes but may be more.
* Sometimes may be completely optional (zero bytes)
*/
public class NumberVariableLength extends AbstractDataType
{
private static final int MINIMUM_NO_OF_DIGITS = 1;
private static final int MAXIMUM_NO_OF_DIGITS = 8;
int minLength = MINIMUM_NO_OF_DIGITS;
/**
* Creates a new ObjectNumberVariableLength datatype, set minimum length to zero
* if this datatype is optional.
*
* @param identifier
* @param frameBody
* @param minimumSize
*/
public NumberVariableLength(String identifier, AbstractTagFrameBody frameBody, int minimumSize)
{
super(identifier, frameBody);
//Set minimum length, which can be zero if optional
this.minLength = minimumSize;
}
public NumberVariableLength(NumberVariableLength copy)
{
super(copy);
this.minLength = copy.minLength;
}
/**
* Return the maximum number of digits that can be used to express the number
*
* @return the maximum number of digits that can be used to express the number
*/
public int getMaximumLenth()
{
return MAXIMUM_NO_OF_DIGITS;
}
/**
* Return the minimum number of digits that can be used to express the number
*
* @return the minimum number of digits that can be used to express the number
*/
public int getMinimumLength()
{
return minLength;
}
/**
* @param minimumSize
*/
public void setMinimumSize(int minimumSize)
{
if (minimumSize > 0)
{
this.minLength = minimumSize;
}
}
/**
* @return the number of bytes required to write this to a file
*/
public int getSize()
{
if (value == null)
{
return 0;
}
else
{
int current;
long temp = ID3Tags.getWholeNumber(value);
int size = 0;
for (int i = MINIMUM_NO_OF_DIGITS; i <= MAXIMUM_NO_OF_DIGITS; i++)
{
current = (byte) temp & 0xFF;
if (current != 0)
{
size = i;
}
temp >>= MAXIMUM_NO_OF_DIGITS;
}
return (minLength > size) ? minLength : size;
}
}
/**
* @param obj
* @return
*/
public boolean equals(Object obj)
{
if (!(obj instanceof NumberVariableLength))
{
return false;
}
NumberVariableLength object = (NumberVariableLength) obj;
return this.minLength == object.minLength && super.equals(obj);
}
/**
* Read from Byte Array
*
* @param arr
* @param offset
* @throws NullPointerException
* @throws IndexOutOfBoundsException
*/
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException
{
//Coding error, should never happen
if (arr == null)
{
throw new NullPointerException("Byte array is null");
}
//Coding error, should never happen as far as I can see
if (offset < 0)
{
throw new IllegalArgumentException("negativer offset into an array offset:" + offset);
}
//If optional then set value to zero, this will mean that if this frame is written back to file it will be created
//with this additional datatype wheras it didnt exist but I think this is probably an advantage the frame is
//more likely to be parsed by other applications if it contains optional fields.
//if not optional problem with this frame
if (offset >= arr.length)
{
if (minLength == 0)
{
value = (long) 0;
return;
}
else
{
throw new InvalidDataTypeException("Offset to byte array is out of bounds: offset = " + offset + ", array.length = " + arr.length);
}
}
long lvalue = 0;
//Read the bytes (starting from offset), the most significant byte of the number being constructed is read first,
//we then shift the resulting long one byte over to make room for the next byte
for (int i = offset; i < arr.length; i++)
{
lvalue <<= 8;
lvalue += (arr[i] & 0xff);
}
value = lvalue;
}
/**
* @return String representation of the number
*/
public String toString()
{
if (value == null)
{
return "";
}
else
{
return value.toString();
}
}
/**
* Write to Byte Array
*
* @return the datatype converted to a byte array
*/
public byte[] writeByteArray()
{
int size = getSize();
byte[] arr;
if (size == 0)
{
arr = new byte[0];
}
else
{
long temp = ID3Tags.getWholeNumber(value);
arr = new byte[size];
//keeps shifting the number downwards and masking the last 8 bist to get the value for the next byte
//to be written
for (int i = size - 1; i >= 0; i--)
{
arr[i] = (byte) (temp & 0xFF);
|
[
" temp >>= 8;"
] | 917
|
lcc
|
java
| null |
de844ece27c689ffd57823fb8131dd2a4050b2ce6d5802d8
| 97
|
Your task is code completion.
/**
* @author : Paul Taylor
* @author : Eric Farng
*
* Version @version:$Id$
*
* MusicTag Copyright (C)2003,2004
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation; either version 2.1 of the License,
* or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not,
* you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Description:
*
*/
package org.jaudiotagger.tag.datatype;
import org.jaudiotagger.tag.InvalidDataTypeException;
import org.jaudiotagger.tag.id3.AbstractTagFrameBody;
import org.jaudiotagger.tag.id3.ID3Tags;
/**
* Represents a number which may span a number of bytes when written to file depending what size is to be represented.
*
* The bitorder in ID3v2 is most significant bit first (MSB). The byteorder in multibyte numbers is most significant
* byte first (e.g. $12345678 would be encoded $12 34 56 78), also known as big endian and network byte order.
*
* In ID3Specification would be denoted as $xx xx xx xx (xx ...) , this denotes at least four bytes but may be more.
* Sometimes may be completely optional (zero bytes)
*/
public class NumberVariableLength extends AbstractDataType
{
private static final int MINIMUM_NO_OF_DIGITS = 1;
private static final int MAXIMUM_NO_OF_DIGITS = 8;
int minLength = MINIMUM_NO_OF_DIGITS;
/**
* Creates a new ObjectNumberVariableLength datatype, set minimum length to zero
* if this datatype is optional.
*
* @param identifier
* @param frameBody
* @param minimumSize
*/
public NumberVariableLength(String identifier, AbstractTagFrameBody frameBody, int minimumSize)
{
super(identifier, frameBody);
//Set minimum length, which can be zero if optional
this.minLength = minimumSize;
}
public NumberVariableLength(NumberVariableLength copy)
{
super(copy);
this.minLength = copy.minLength;
}
/**
* Return the maximum number of digits that can be used to express the number
*
* @return the maximum number of digits that can be used to express the number
*/
public int getMaximumLenth()
{
return MAXIMUM_NO_OF_DIGITS;
}
/**
* Return the minimum number of digits that can be used to express the number
*
* @return the minimum number of digits that can be used to express the number
*/
public int getMinimumLength()
{
return minLength;
}
/**
* @param minimumSize
*/
public void setMinimumSize(int minimumSize)
{
if (minimumSize > 0)
{
this.minLength = minimumSize;
}
}
/**
* @return the number of bytes required to write this to a file
*/
public int getSize()
{
if (value == null)
{
return 0;
}
else
{
int current;
long temp = ID3Tags.getWholeNumber(value);
int size = 0;
for (int i = MINIMUM_NO_OF_DIGITS; i <= MAXIMUM_NO_OF_DIGITS; i++)
{
current = (byte) temp & 0xFF;
if (current != 0)
{
size = i;
}
temp >>= MAXIMUM_NO_OF_DIGITS;
}
return (minLength > size) ? minLength : size;
}
}
/**
* @param obj
* @return
*/
public boolean equals(Object obj)
{
if (!(obj instanceof NumberVariableLength))
{
return false;
}
NumberVariableLength object = (NumberVariableLength) obj;
return this.minLength == object.minLength && super.equals(obj);
}
/**
* Read from Byte Array
*
* @param arr
* @param offset
* @throws NullPointerException
* @throws IndexOutOfBoundsException
*/
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException
{
//Coding error, should never happen
if (arr == null)
{
throw new NullPointerException("Byte array is null");
}
//Coding error, should never happen as far as I can see
if (offset < 0)
{
throw new IllegalArgumentException("negativer offset into an array offset:" + offset);
}
//If optional then set value to zero, this will mean that if this frame is written back to file it will be created
//with this additional datatype wheras it didnt exist but I think this is probably an advantage the frame is
//more likely to be parsed by other applications if it contains optional fields.
//if not optional problem with this frame
if (offset >= arr.length)
{
if (minLength == 0)
{
value = (long) 0;
return;
}
else
{
throw new InvalidDataTypeException("Offset to byte array is out of bounds: offset = " + offset + ", array.length = " + arr.length);
}
}
long lvalue = 0;
//Read the bytes (starting from offset), the most significant byte of the number being constructed is read first,
//we then shift the resulting long one byte over to make room for the next byte
for (int i = offset; i < arr.length; i++)
{
lvalue <<= 8;
lvalue += (arr[i] & 0xff);
}
value = lvalue;
}
/**
* @return String representation of the number
*/
public String toString()
{
if (value == null)
{
return "";
}
else
{
return value.toString();
}
}
/**
* Write to Byte Array
*
* @return the datatype converted to a byte array
*/
public byte[] writeByteArray()
{
int size = getSize();
byte[] arr;
if (size == 0)
{
arr = new byte[0];
}
else
{
long temp = ID3Tags.getWholeNumber(value);
arr = new byte[size];
//keeps shifting the number downwards and masking the last 8 bist to get the value for the next byte
//to be written
for (int i = size - 1; i >= 0; i--)
{
arr[i] = (byte) (temp & 0xFF);
|
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 NumberVariableLength extends AbstractDataType
{
private static final int MINIMUM_NO_OF_DIGITS = 1;
private static final int MAXIMUM_NO_OF_DIGITS = 8;
int minLength = MINIMUM_NO_OF_DIGITS;
// ... (rest of the class)
Cheatsheet (for next line):
- We are in the writeByteArray() method, which should return the byte array representation of the number.
- The method has already determined the size of the byte array (size variable).
- The method is using a for loop to construct the byte array.
- The loop is iterating from size - 1 to 0 (inclusive).
- The current byte to be written is stored in the variable arr[i].
- The value to be written is stored in the variable temp.
- The value of temp is being shifted down by 8 bits (temp <<= 8) and then the current byte is added to it (temp += (arr[i] & 0xff)).
- The loop is iterating over the byte array from the end to the beginning.
Next line will likely be:
```java
temp >>= 8;
```
This line is necessary to shift the value of temp down by 8 bits to make room for the next byte in the next iteration of the loop.
|
|
Please complete the code given below.
# Copyright (c) 2017 Mark D. Hill and David A. Wood
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Sean Wilson
'''
Global configuration module which exposes two types of configuration
variables:
1. config
2. constants (Also attached to the config variable as an attribute)
The main motivation for this module is to have a centralized location for
defaults and configuration by command line and files for the test framework.
A secondary goal is to reduce programming errors by providing common constant
strings and values as python attributes to simplify detection of typos.
A simple typo in a string can take a lot of debugging to uncover the issue,
attribute errors are easier to notice and most autocompletion systems detect
them.
The config variable is initialzed by calling :func:`initialize_config`.
Before this point only ``constants`` will be availaible. This is to ensure
that library function writers never accidentally get stale config attributes.
Program arguments/flag arguments are available from the config as attributes.
If an attribute was not set by the command line or the optional config file,
then it will fallback to the `_defaults` value, if still the value is not
found an AttributeError will be raised.
:func define_defaults:
Provided by the config if the attribute is not found in the config or
commandline. For instance, if we are using the list command fixtures might
not be able to count on the build_dir being provided since we aren't going
to build anything.
:var constants:
Values not directly exposed by the config, but are attached to the object
for centralized access. I.E. you can reach them with
:code:`config.constants.attribute`. These should be used for setting
common string names used across the test framework.
:code:`_defaults.build_dir = None` Once this module has been imported
constants should not be modified and their base attributes are frozen.
'''
import abc
import argparse
import copy
import os
import re
from ConfigParser import ConfigParser
from pickle import HIGHEST_PROTOCOL as highest_pickle_protocol
from helper import absdirpath, AttrDict, FrozenAttrDict
class UninitialzedAttributeException(Exception):
'''
Signals that an attribute in the config file was not initialized.
'''
pass
class UninitializedConfigException(Exception):
'''
Signals that the config was not initialized before trying to access an
attribute.
'''
pass
class TagRegex(object):
def __init__(self, include, regex):
self.include = include
self.regex = re.compile(regex)
def __str__(self):
type_ = 'Include' if self.include else 'Remove'
return '%10s: %s' % (type_, self.regex.pattern)
class _Config(object):
_initialized = False
__shared_dict = {}
constants = AttrDict()
_defaults = AttrDict()
_config = {}
_cli_args = {}
_post_processors = {}
def __init__(self):
# This object will act as if it were a singleton.
self.__dict__ = self.__shared_dict
def _init(self, parser):
self._parse_commandline_args(parser)
self._run_post_processors()
self._initialized = True
def _init_with_dicts(self, config, defaults):
self._config = config
self._defaults = defaults
self._initialized = True
def _add_post_processor(self, attr, post_processor):
'''
:param attr: Attribute to pass to and recieve from the
:func:`post_processor`.
:param post_processor: A callback functions called in a chain to
perform additional setup for a config argument. Should return a
tuple containing the new value for the config attr.
'''
if attr not in self._post_processors:
self._post_processors[attr] = []
self._post_processors[attr].append(post_processor)
def _set(self, name, value):
self._config[name] = value
def _parse_commandline_args(self, parser):
args = parser.parse_args()
self._config_file_args = {}
for attr in dir(args):
# Ignore non-argument attributes.
if not attr.startswith('_'):
self._config_file_args[attr] = getattr(args, attr)
self._config.update(self._config_file_args)
def _run_post_processors(self):
for attr, callbacks in self._post_processors.items():
newval = self._lookup_val(attr)
for callback in callbacks:
newval = callback(newval)
if newval is not None:
newval = newval[0]
self._set(attr, newval)
def _lookup_val(self, attr):
'''
Get the attribute from the config or fallback to defaults.
:returns: If the value is not stored return None. Otherwise a tuple
containing the value.
'''
if attr in self._config:
return (self._config[attr],)
elif hasattr(self._defaults, attr):
return (getattr(self._defaults, attr),)
def __getattr__(self, attr):
if attr in dir(super(_Config, self)):
return getattr(super(_Config, self), attr)
elif not self._initialized:
raise UninitializedConfigException(
'Cannot directly access elements from the config before it is'
' initialized')
else:
val = self._lookup_val(attr)
if val is not None:
return val[0]
else:
raise UninitialzedAttributeException(
'%s was not initialzed in the config.' % attr)
def get_tags(self):
d = {typ: set(self.__getattr__(typ))
for typ in self.constants.supported_tags}
if any(map(lambda vals: bool(vals), d.values())):
return d
else:
return {}
def define_defaults(defaults):
'''
Defaults are provided by the config if the attribute is not found in the
config or commandline. For instance, if we are using the list command
fixtures might not be able to count on the build_dir being provided since
we aren't going to build anything.
'''
defaults.base_dir = os.path.abspath(os.path.join(absdirpath(__file__),
os.pardir,
os.pardir))
defaults.result_path = os.path.join(os.getcwd(), '.testing-results')
defaults.list_only_failed = False
def define_constants(constants):
'''
'constants' are values not directly exposed by the config, but are attached
to the object for centralized access. These should be used for setting
common string names used across the test framework. A simple typo in
a string can take a lot of debugging to uncover the issue, attribute errors
are easier to notice and most autocompletion systems detect them.
'''
constants.system_out_name = 'system-out'
constants.system_err_name = 'system-err'
constants.isa_tag_type = 'isa'
constants.x86_tag = 'X86'
constants.sparc_tag = 'SPARC'
constants.alpha_tag = 'ALPHA'
constants.riscv_tag = 'RISCV'
constants.arm_tag = 'ARM'
constants.mips_tag = 'MIPS'
constants.power_tag = 'POWER'
constants.null_tag = 'NULL'
constants.variant_tag_type = 'variant'
constants.opt_tag = 'opt'
constants.debug_tag = 'debug'
constants.fast_tag = 'fast'
constants.length_tag_type = 'length'
constants.quick_tag = 'quick'
constants.long_tag = 'long'
constants.supported_tags = {
constants.isa_tag_type : (
constants.x86_tag,
constants.sparc_tag,
constants.alpha_tag,
constants.riscv_tag,
constants.arm_tag,
constants.mips_tag,
constants.power_tag,
constants.null_tag,
),
constants.variant_tag_type: (
constants.opt_tag,
constants.debug_tag,
constants.fast_tag,
),
constants.length_tag_type: (
constants.quick_tag,
constants.long_tag,
),
}
constants.supported_isas = constants.supported_tags['isa']
constants.supported_variants = constants.supported_tags['variant']
constants.supported_lengths = constants.supported_tags['length']
constants.tempdir_fixture_name = 'tempdir'
constants.gem5_simulation_stderr = 'simerr'
constants.gem5_simulation_stdout = 'simout'
constants.gem5_simulation_stats = 'stats.txt'
constants.gem5_simulation_config_ini = 'config.ini'
constants.gem5_simulation_config_json = 'config.json'
constants.gem5_returncode_fixture_name = 'gem5-returncode'
constants.gem5_binary_fixture_name = 'gem5'
constants.xml_filename = 'results.xml'
constants.pickle_filename = 'results.pickle'
constants.pickle_protocol = highest_pickle_protocol
# The root directory which all test names will be based off of.
constants.testing_base = absdirpath(os.path.join(absdirpath(__file__),
os.pardir))
def define_post_processors(config):
'''
post_processors are used to do final configuration of variables. This is
useful if there is a dynamically set default, or some function that needs
to be applied after parsing in order to set a configration value.
Post processors must accept a single argument that will either be a tuple
containing the already set config value or ``None`` if the config value
has not been set to anything. They must return the modified value in the
same format.
'''
def set_default_build_dir(build_dir):
'''
Post-processor to set the default build_dir based on the base_dir.
.. seealso :func:`~_Config._add_post_processor`
'''
if not build_dir or build_dir[0] is None:
base_dir = config._lookup_val('base_dir')[0]
build_dir = (os.path.join(base_dir, 'build'),)
return build_dir
def fix_verbosity_hack(verbose):
return (verbose[0].val,)
def threads_as_int(threads):
if threads is not None:
return (int(threads[0]),)
def test_threads_as_int(test_threads):
if test_threads is not None:
return (int(test_threads[0]),)
def default_isa(isa):
if not isa[0]:
return [constants.supported_tags[constants.isa_tag_type]]
else:
return isa
def default_variant(variant):
if not variant[0]:
# Default variant is only opt. No need to run tests with multiple
# different compilation targets
return [[constants.opt_tag]]
else:
return variant
def default_length(length):
if not length[0]:
return [[constants.quick_tag]]
else:
return length
def compile_tag_regex(positional_tags):
if not positional_tags:
return positional_tags
else:
new_positional_tags_list = []
positional_tags = positional_tags[0]
for flag, regex in positional_tags:
|
[
" if flag == 'exclude_tags':"
] | 1,382
|
lcc
|
python
| null |
0eae36deb9dbeb31e09db8bd01a91ef5b679925d700f9563
| 98
|
Your task is code completion.
# Copyright (c) 2017 Mark D. Hill and David A. Wood
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Sean Wilson
'''
Global configuration module which exposes two types of configuration
variables:
1. config
2. constants (Also attached to the config variable as an attribute)
The main motivation for this module is to have a centralized location for
defaults and configuration by command line and files for the test framework.
A secondary goal is to reduce programming errors by providing common constant
strings and values as python attributes to simplify detection of typos.
A simple typo in a string can take a lot of debugging to uncover the issue,
attribute errors are easier to notice and most autocompletion systems detect
them.
The config variable is initialzed by calling :func:`initialize_config`.
Before this point only ``constants`` will be availaible. This is to ensure
that library function writers never accidentally get stale config attributes.
Program arguments/flag arguments are available from the config as attributes.
If an attribute was not set by the command line or the optional config file,
then it will fallback to the `_defaults` value, if still the value is not
found an AttributeError will be raised.
:func define_defaults:
Provided by the config if the attribute is not found in the config or
commandline. For instance, if we are using the list command fixtures might
not be able to count on the build_dir being provided since we aren't going
to build anything.
:var constants:
Values not directly exposed by the config, but are attached to the object
for centralized access. I.E. you can reach them with
:code:`config.constants.attribute`. These should be used for setting
common string names used across the test framework.
:code:`_defaults.build_dir = None` Once this module has been imported
constants should not be modified and their base attributes are frozen.
'''
import abc
import argparse
import copy
import os
import re
from ConfigParser import ConfigParser
from pickle import HIGHEST_PROTOCOL as highest_pickle_protocol
from helper import absdirpath, AttrDict, FrozenAttrDict
class UninitialzedAttributeException(Exception):
'''
Signals that an attribute in the config file was not initialized.
'''
pass
class UninitializedConfigException(Exception):
'''
Signals that the config was not initialized before trying to access an
attribute.
'''
pass
class TagRegex(object):
def __init__(self, include, regex):
self.include = include
self.regex = re.compile(regex)
def __str__(self):
type_ = 'Include' if self.include else 'Remove'
return '%10s: %s' % (type_, self.regex.pattern)
class _Config(object):
_initialized = False
__shared_dict = {}
constants = AttrDict()
_defaults = AttrDict()
_config = {}
_cli_args = {}
_post_processors = {}
def __init__(self):
# This object will act as if it were a singleton.
self.__dict__ = self.__shared_dict
def _init(self, parser):
self._parse_commandline_args(parser)
self._run_post_processors()
self._initialized = True
def _init_with_dicts(self, config, defaults):
self._config = config
self._defaults = defaults
self._initialized = True
def _add_post_processor(self, attr, post_processor):
'''
:param attr: Attribute to pass to and recieve from the
:func:`post_processor`.
:param post_processor: A callback functions called in a chain to
perform additional setup for a config argument. Should return a
tuple containing the new value for the config attr.
'''
if attr not in self._post_processors:
self._post_processors[attr] = []
self._post_processors[attr].append(post_processor)
def _set(self, name, value):
self._config[name] = value
def _parse_commandline_args(self, parser):
args = parser.parse_args()
self._config_file_args = {}
for attr in dir(args):
# Ignore non-argument attributes.
if not attr.startswith('_'):
self._config_file_args[attr] = getattr(args, attr)
self._config.update(self._config_file_args)
def _run_post_processors(self):
for attr, callbacks in self._post_processors.items():
newval = self._lookup_val(attr)
for callback in callbacks:
newval = callback(newval)
if newval is not None:
newval = newval[0]
self._set(attr, newval)
def _lookup_val(self, attr):
'''
Get the attribute from the config or fallback to defaults.
:returns: If the value is not stored return None. Otherwise a tuple
containing the value.
'''
if attr in self._config:
return (self._config[attr],)
elif hasattr(self._defaults, attr):
return (getattr(self._defaults, attr),)
def __getattr__(self, attr):
if attr in dir(super(_Config, self)):
return getattr(super(_Config, self), attr)
elif not self._initialized:
raise UninitializedConfigException(
'Cannot directly access elements from the config before it is'
' initialized')
else:
val = self._lookup_val(attr)
if val is not None:
return val[0]
else:
raise UninitialzedAttributeException(
'%s was not initialzed in the config.' % attr)
def get_tags(self):
d = {typ: set(self.__getattr__(typ))
for typ in self.constants.supported_tags}
if any(map(lambda vals: bool(vals), d.values())):
return d
else:
return {}
def define_defaults(defaults):
'''
Defaults are provided by the config if the attribute is not found in the
config or commandline. For instance, if we are using the list command
fixtures might not be able to count on the build_dir being provided since
we aren't going to build anything.
'''
defaults.base_dir = os.path.abspath(os.path.join(absdirpath(__file__),
os.pardir,
os.pardir))
defaults.result_path = os.path.join(os.getcwd(), '.testing-results')
defaults.list_only_failed = False
def define_constants(constants):
'''
'constants' are values not directly exposed by the config, but are attached
to the object for centralized access. These should be used for setting
common string names used across the test framework. A simple typo in
a string can take a lot of debugging to uncover the issue, attribute errors
are easier to notice and most autocompletion systems detect them.
'''
constants.system_out_name = 'system-out'
constants.system_err_name = 'system-err'
constants.isa_tag_type = 'isa'
constants.x86_tag = 'X86'
constants.sparc_tag = 'SPARC'
constants.alpha_tag = 'ALPHA'
constants.riscv_tag = 'RISCV'
constants.arm_tag = 'ARM'
constants.mips_tag = 'MIPS'
constants.power_tag = 'POWER'
constants.null_tag = 'NULL'
constants.variant_tag_type = 'variant'
constants.opt_tag = 'opt'
constants.debug_tag = 'debug'
constants.fast_tag = 'fast'
constants.length_tag_type = 'length'
constants.quick_tag = 'quick'
constants.long_tag = 'long'
constants.supported_tags = {
constants.isa_tag_type : (
constants.x86_tag,
constants.sparc_tag,
constants.alpha_tag,
constants.riscv_tag,
constants.arm_tag,
constants.mips_tag,
constants.power_tag,
constants.null_tag,
),
constants.variant_tag_type: (
constants.opt_tag,
constants.debug_tag,
constants.fast_tag,
),
constants.length_tag_type: (
constants.quick_tag,
constants.long_tag,
),
}
constants.supported_isas = constants.supported_tags['isa']
constants.supported_variants = constants.supported_tags['variant']
constants.supported_lengths = constants.supported_tags['length']
constants.tempdir_fixture_name = 'tempdir'
constants.gem5_simulation_stderr = 'simerr'
constants.gem5_simulation_stdout = 'simout'
constants.gem5_simulation_stats = 'stats.txt'
constants.gem5_simulation_config_ini = 'config.ini'
constants.gem5_simulation_config_json = 'config.json'
constants.gem5_returncode_fixture_name = 'gem5-returncode'
constants.gem5_binary_fixture_name = 'gem5'
constants.xml_filename = 'results.xml'
constants.pickle_filename = 'results.pickle'
constants.pickle_protocol = highest_pickle_protocol
# The root directory which all test names will be based off of.
constants.testing_base = absdirpath(os.path.join(absdirpath(__file__),
os.pardir))
def define_post_processors(config):
'''
post_processors are used to do final configuration of variables. This is
useful if there is a dynamically set default, or some function that needs
to be applied after parsing in order to set a configration value.
Post processors must accept a single argument that will either be a tuple
containing the already set config value or ``None`` if the config value
has not been set to anything. They must return the modified value in the
same format.
'''
def set_default_build_dir(build_dir):
'''
Post-processor to set the default build_dir based on the base_dir.
.. seealso :func:`~_Config._add_post_processor`
'''
if not build_dir or build_dir[0] is None:
base_dir = config._lookup_val('base_dir')[0]
build_dir = (os.path.join(base_dir, 'build'),)
return build_dir
def fix_verbosity_hack(verbose):
return (verbose[0].val,)
def threads_as_int(threads):
if threads is not None:
return (int(threads[0]),)
def test_threads_as_int(test_threads):
if test_threads is not None:
return (int(test_threads[0]),)
def default_isa(isa):
if not isa[0]:
return [constants.supported_tags[constants.isa_tag_type]]
else:
return isa
def default_variant(variant):
if not variant[0]:
# Default variant is only opt. No need to run tests with multiple
# different compilation targets
return [[constants.opt_tag]]
else:
return variant
def default_length(length):
if not length[0]:
return [[constants.quick_tag]]
else:
return length
def compile_tag_regex(positional_tags):
if not positional_tags:
return positional_tags
else:
new_positional_tags_list = []
positional_tags = positional_tags[0]
for flag, regex in positional_tags:
|
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]
def compile_tag_regex(positional_tags):
if not positional_tags:
return positional_tags
else:
new_positional_tags_list = []
positional_tags = positional_tags[0]
for flag, regex in positional_tags:
Relevant lines/variables:
- `positional_tags`: a list of tuples containing flags and regex patterns
- `flag` and `regex` are variables in the for loop
- `new_positional_tags_list`: an empty list to store the compiled regex patterns
- `constants.supported_tags[constants.isa_tag_type]`: a list of supported ISA tags
Task: Complete the `compile_tag_regex` function to compile the regex patterns in `positional_tags` and store them in `new_positional_tags_list`.
Possible next lines:
- `new_positional_tags_list.append(TagRegex(flag, regex))`
- `new_positional_tags_list.append(TagRegex(flag, re.compile(regex)))`
- `new_positional_tags_list.append(TagRegex(flag, re.compile(flag)))` (assuming `flag` is a string)
However, considering the context, it seems that `flag` is not a string, but rather a boolean indicating whether to include or remove the tag. Therefore, the correct completion is:
- `new_positional_tags_list.append(TagRegex(flag, re.compile(regex)))`
This line compiles the regex pattern and creates a `TagRegex` object, which is then appended to the `new_positional_tags_list`.
|
|
Please complete the code given below.
using System;
using System.Globalization;
using System.Reflection;
namespace CorApi2.Metadata
{
namespace Microsoft.Samples.Debugging.CorMetadata
{
public class MethodGenericParameter : GenericParameter
{
public MethodGenericParameter (int index) : base (index)
{
}
}
public class TypeGenericParameter : GenericParameter
{
public TypeGenericParameter (int index) : base (index)
{
}
}
public abstract class GenericParameter : Type
{
public int Index { get; private set; }
public GenericParameter (int index)
{
Index = index;
}
public override Type MakeByRefType ()
{
return this;
}
public override Type MakePointerType ()
{
return this;
}
public override Type MakeArrayType ()
{
return this;
}
public override Type MakeArrayType (int rank)
{
return this;
}
public override Type MakeGenericType (params Type[] typeArguments)
{
return this;
}
public override object[] GetCustomAttributes (bool inherit)
{
return new object[0];
}
public override bool IsDefined (Type attributeType, bool inherit)
{
return false;
}
public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
{
throw new NotImplementedException ();
}
public override Type GetInterface (string name, bool ignoreCase)
{
return null;
}
public override Type[] GetInterfaces ()
{
return EmptyTypes;
}
public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
{
return null;
}
public override EventInfo[] GetEvents (BindingFlags bindingAttr)
{
return new EventInfo[0];
}
public override Type[] GetNestedTypes (BindingFlags bindingAttr)
{
return EmptyTypes;
}
public override Type GetNestedType (string name, BindingFlags bindingAttr)
{
return null;
}
public override Type GetElementType ()
{
return null;
}
protected override bool HasElementTypeImpl ()
{
return false;
}
protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
return null;
}
public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
{
return new PropertyInfo[0];
}
protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
return null;
}
public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
{
return new MethodInfo[0];
}
public override FieldInfo GetField (string name, BindingFlags bindingAttr)
{
return null;
}
public override FieldInfo[] GetFields (BindingFlags bindingAttr)
{
return new FieldInfo[0];
}
public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
{
return new MemberInfo[0];
}
protected override TypeAttributes GetAttributeFlagsImpl ()
{
throw new NotImplementedException ();
}
protected override bool IsArrayImpl ()
{
return false;
}
protected override bool IsByRefImpl ()
{
return false;
}
protected override bool IsPointerImpl ()
{
return false;
}
protected override bool IsPrimitiveImpl ()
{
return false;
}
protected override bool IsCOMObjectImpl ()
{
return false;
}
public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target,
object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
{
throw new NotImplementedException ();
}
public override Type UnderlyingSystemType { get { throw new NotImplementedException (); } }
protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
throw new NotImplementedException ();
}
public override string Name { get { return string.Format("`{0}", Index); }}
public override Guid GUID { get {return Guid.Empty;}}
public override Module Module { get {throw new NotImplementedException ();} }
public override Assembly Assembly { get { throw new NotImplementedException (); } }
public override string FullName { get { return Name; }}
public override string Namespace { get {throw new NotImplementedException ();} }
public override string AssemblyQualifiedName { get { throw new NotImplementedException (); }}
public override Type BaseType { get {throw new NotImplementedException ();} }
public override object[] GetCustomAttributes (Type attributeType, bool inherit)
{
|
[
" return new object[0];"
] | 545
|
lcc
|
csharp
| null |
d9e11801221dccea3ae87a56625d947443bb2bb387b8a83d
| 99
|
Your task is code completion.
using System;
using System.Globalization;
using System.Reflection;
namespace CorApi2.Metadata
{
namespace Microsoft.Samples.Debugging.CorMetadata
{
public class MethodGenericParameter : GenericParameter
{
public MethodGenericParameter (int index) : base (index)
{
}
}
public class TypeGenericParameter : GenericParameter
{
public TypeGenericParameter (int index) : base (index)
{
}
}
public abstract class GenericParameter : Type
{
public int Index { get; private set; }
public GenericParameter (int index)
{
Index = index;
}
public override Type MakeByRefType ()
{
return this;
}
public override Type MakePointerType ()
{
return this;
}
public override Type MakeArrayType ()
{
return this;
}
public override Type MakeArrayType (int rank)
{
return this;
}
public override Type MakeGenericType (params Type[] typeArguments)
{
return this;
}
public override object[] GetCustomAttributes (bool inherit)
{
return new object[0];
}
public override bool IsDefined (Type attributeType, bool inherit)
{
return false;
}
public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
{
throw new NotImplementedException ();
}
public override Type GetInterface (string name, bool ignoreCase)
{
return null;
}
public override Type[] GetInterfaces ()
{
return EmptyTypes;
}
public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
{
return null;
}
public override EventInfo[] GetEvents (BindingFlags bindingAttr)
{
return new EventInfo[0];
}
public override Type[] GetNestedTypes (BindingFlags bindingAttr)
{
return EmptyTypes;
}
public override Type GetNestedType (string name, BindingFlags bindingAttr)
{
return null;
}
public override Type GetElementType ()
{
return null;
}
protected override bool HasElementTypeImpl ()
{
return false;
}
protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
return null;
}
public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
{
return new PropertyInfo[0];
}
protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
return null;
}
public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
{
return new MethodInfo[0];
}
public override FieldInfo GetField (string name, BindingFlags bindingAttr)
{
return null;
}
public override FieldInfo[] GetFields (BindingFlags bindingAttr)
{
return new FieldInfo[0];
}
public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
{
return new MemberInfo[0];
}
protected override TypeAttributes GetAttributeFlagsImpl ()
{
throw new NotImplementedException ();
}
protected override bool IsArrayImpl ()
{
return false;
}
protected override bool IsByRefImpl ()
{
return false;
}
protected override bool IsPointerImpl ()
{
return false;
}
protected override bool IsPrimitiveImpl ()
{
return false;
}
protected override bool IsCOMObjectImpl ()
{
return false;
}
public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target,
object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
{
throw new NotImplementedException ();
}
public override Type UnderlyingSystemType { get { throw new NotImplementedException (); } }
protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
throw new NotImplementedException ();
}
public override string Name { get { return string.Format("`{0}", Index); }}
public override Guid GUID { get {return Guid.Empty;}}
public override Module Module { get {throw new NotImplementedException ();} }
public override Assembly Assembly { get { throw new NotImplementedException (); } }
public override string FullName { get { return Name; }}
public override string Namespace { get {throw new NotImplementedException ();} }
public override string AssemblyQualifiedName { get { throw new NotImplementedException (); }}
public override Type BaseType { get {throw new NotImplementedException ();} }
public override object[] GetCustomAttributes (Type attributeType, bool inherit)
{
|
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 Code Completion Task:
**Context:** `public override object[] GetCustomAttributes (Type attributeType, bool inherit)`
**Relevant Information:**
- We are in the `GetCustomAttributes` method, which is part of the `Type` class.
- This method is used to get the custom attributes of a type.
- The method takes two parameters: `attributeType` (the type of attribute to get) and `inherit` (a boolean indicating whether to search in the current type and its base classes).
- The method is expected to return an array of custom attributes.
**Relevant Lines/Variables:**
- `attributeType`: the type of attribute to get
- `inherit`: a boolean indicating whether to search in the current type and its base classes
- `this`: the current type (the type for which we are getting custom attributes)
**Expected Behavior:**
- The method should return an array of custom attributes of the specified type.
- If the type has no custom attributes of the specified type, an empty array should be returned.
**Possible Next Lines:**
- `return this.GetCustomAttributes(attributeType, inherit);` (assuming the base class `Type` has a method with the same name)
- `return new object[0];` (returning an empty array if no custom attributes are found)
- `return Array.Empty<object>();` (using the `Array.Empty` method to return an empty array)
**Additional Information:**
- The `GetCustomAttributes` method is used to get custom attributes of a type, which are attributes that are not part of the .NET Framework.
- Custom attributes are used to provide additional information about a type, such as metadata or configuration data.
- The `inherit` parameter determines whether to search in the current type and its base classes.
Please let me know when you are ready for me to provide the solution to the code completion task.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.