text:
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Check if a script file exists, compiled or not.
function isScriptFile(%path)
{
   if( isFile(%path @ ".dso") || isFile(%path) )
      return true;

   return false;
}

function loadMaterials()
{
   // Load any materials files for which we only have DSOs.

   for( %file = findFirstFile( "*/materials.cs.dso" );
        %file !$= "";
        %file = findNextFile( "*/materials.cs.dso" ))
   {
      // Only execute, if we don't have the source file.
      %csFileName = getSubStr( %file, 0, strlen( %file ) - 4 );
      if( !isFile( %csFileName ) )
         exec( %csFileName );
   }

   // Load all source material files.

   for( %file = findFirstFile( "*/materials.cs" );
        %file !$= "";
        %file = findNextFile( "*/materials.cs" ))
   {
      exec( %file );
   }

   // Load all materials created by the material editor if
   // the folder exists
   if( IsDirectory( "materialEditor" ) )
   {
      for( %file = findFirstFile( "materialEditor/*.cs.dso" );
           %file !$= "";
           %file = findNextFile( "materialEditor/*.cs.dso" ))
      {
         // Only execute, if we don't have the source file.
         %csFileName = getSubStr( %file, 0, strlen( %file ) - 4 );
         if( !isFile( %csFileName ) )
            exec( %csFileName );
      }

      for( %file = findFirstFile( "materialEditor/*.cs" );
           %file !$= "";
           %file = findNextFile( "materialEditor/*.cs" ))
      {
         exec( %file );
      }
   }
}

function reloadMaterials()
{
   reloadTextures();
   loadMaterials();
   reInitMaterials();
}

function loadDatablockFiles( %datablockFiles, %recurse )
{
   if ( %recurse )
   {
      recursiveLoadDatablockFiles( %datablockFiles, 9999 );
      return;
   }

   %count = %datablockFiles.count();
   for ( %i=0; %i < %count; %i++ )
   {
      %file = %datablockFiles.getKey( %i );
      if ( !isFile(%file @ ".dso") && !isFile(%file) )
         continue;

      exec( %file );
   }

   // Destroy the incoming list.
   //%datablockFiles.delete();
}

function recursiveLoadDatablockFiles( %datablockFiles, %previousErrors )
{
   %reloadDatablockFiles = new ArrayObject();

   // Keep track of the number of datablocks that
   // failed during this pass.
   %failedDatablocks = 0;

   // Try re-executing the list of datablock files.
   %count = %datablockFiles.count();
   for ( %i=0; %i < %count; %i++ )
   {
      %file = %datablockFiles.getKey( %i );
      if ( !isFile(%file @ ".dso") && !isFile(%file) )
         continue;

      // Start counting copy constructor creation errors.
      $Con::objectCopyFailures = 0;

      exec( %file );

      // If errors occured then store this file for re-exec later.
      if ( $Con::objectCopyFailures > 0 )
      {
         %reloadDatablockFiles.add( %file );
         %failedDatablocks = %failedDatablocks + $Con::objectCopyFailures;
      }
   }

   // Clear the object copy failure counter so that
   // we get console error messages again.
   $Con::objectCopyFailures = -1;

   // Delete the old incoming list... we're done with it.
   //%datablockFiles.delete();

   // If we still have datablocks to retry.
   %newCount = %reloadDatablockFiles.count();
   if ( %newCount > 0 )
   {
      // If the datablock failures have not been reduced
      // from the last pass then we must have a real syntax
      // error and not just a bad dependancy.
      if ( %previousErrors > %failedDatablocks )
         recursiveLoadDatablockFiles( %reloadDatablockFiles, %failedDatablocks );

      else
      {
         // Since we must have real syntax errors do one
         // last normal exec to output error messages.
         loadDatablockFiles( %reloadDatablockFiles, false );
      }

      return;
   }

   // Cleanup the empty reload list.
   %reloadDatablockFiles.delete();
}

function getUserPath()
{
	%temp = getUserHomeDirectory();
	echo(%temp);
	if(!isDirectory(%temp))
	{
		%temp = getUserDataDirectory();
		echo(%temp);
		if(!isDirectory(%temp))
		{
			%userPath = "data";
		}
		else
		{
			//put it in appdata/roaming
			%userPath = %temp @ "/" @ $appName;
		}
	}
	else
	{
		//put it in user/documents
		%userPath = %temp @ "/" @ $appName;
	}
	return %userPath;
}

function getPrefpath()
{
   $prefPath = getUserPath() @ "/preferences";
	return $prefPath;
}

function updateTSShapeLoadProgress(%progress, %msg)
{
   // Check if the loading GUI is visible and use that instead of the
   // separate import progress GUI if possible
  /* if ( isObject(LoadingGui) && LoadingGui.isAwake() )
   {
      // Save/Restore load progress at the start/end of the import process
      if ( %progress == 0 )
      {
         ColladaImportProgress.savedProgress = LoadingProgress.getValue();
         ColladaImportProgress.savedText = LoadingProgressTxt.getValue();

         ColladaImportProgress.msgPrefix = "Importing " @ %msg;
         %msg = "Reading file into memory...";
      }
      else if ( %progress == 1.0 )
      {
         LoadingProgress.setValue( ColladaImportProgress.savedProgress );
         LoadingProgressTxt.setValue( ColladaImportProgress.savedText );
      }

      %msg = ColladaImportProgress.msgPrefix @ ": " @ %msg;

      %progressCtrl = LoadingProgress;
      %textCtrl = LoadingProgressTxt;
   }
   else
   {
      //it's probably the editors using it
      if(isFunction("updateToolTSShapeLoadProgress"))
      {
         updateToolTSShapeLoadProgress(%progress, %msg);
      }
   }

   // Update progress indicators
   if (%progress == 0)
   {
      %progressCtrl.setValue(0.001);
      %textCtrl.setText(%msg);
   }
   else if (%progress != 1.0)
   {
      %progressCtrl.setValue(%progress);
      %textCtrl.setText(%msg);
   }

   Canvas.repaint(33);*/
}

/// A helper function which will return the ghosted client object
/// from a server object when connected to a local server.
function serverToClientObject( %serverObject )
{
   assert( isObject( LocalClientConnection ), "serverToClientObject() - No local client connection found!" );
   assert( isObject( ServerConnection ), "serverToClientObject() - No server connection found!" );

   %ghostId = LocalClientConnection.getGhostId( %serverObject );
   if ( %ghostId == -1 )
      return 0;

   return ServerConnection.resolveGhostID( %ghostId );
}

//----------------------------------------------------------------------------
// Debug commands
//----------------------------------------------------------------------------

function netSimulateLag( %msDelay, %packetLossPercent )
{
   if ( %packetLossPercent $= "" )
      %packetLossPercent = 0;

   commandToServer( 'NetSimulateLag', %msDelay, %packetLossPercent );
}

//Various client functions

function validateDatablockName(%name)
{
   // remove whitespaces at beginning and end
   %name = trim( %name );

   // remove numbers at the beginning
   %numbers = "0123456789";
   while( strlen(%name) > 0 )
   {
      // the first character
      %firstChar = getSubStr( %name, 0, 1 );
      // if the character is a number remove it
      if( strpos( %numbers, %firstChar ) != -1 )
      {
         %name = getSubStr( %name, 1, strlen(%name) -1 );
         %name = ltrim( %name );
      }
      else
         break;
   }

   // replace whitespaces with underscores
   %name = strreplace( %name, " ", "_" );

   // remove any other invalid characters
   %invalidCharacters = "-+*/%$&§=()[].?\"#,;!~<>|°^{}";
   %name = stripChars( %name, %invalidCharacters );

   if( %name $= "" )
      %name = "Unnamed";

   return %name;
}

//--------------------------------------------------------------------------
// Finds location of %word in %text, starting at %start.  Works just like strPos
//--------------------------------------------------------------------------

function wordPos(%text, %word, %start)
{
   if (%start $= "") %start = 0;

   if (strpos(%text, %word, 0) == -1) return -1;
   %count = getWordCount(%text);
   if (%start >= %count) return -1;
   for (%i = %start; %i < %count; %i++)
   {
      if (getWord( %text, %i) $= %word) return %i;
   }
   return -1;
}

//--------------------------------------------------------------------------
// Finds location of %field in %text, starting at %start.  Works just like strPos
//--------------------------------------------------------------------------

function fieldPos(%text, %field, %start)
{
   if (%start $= "") %start = 0;

   if (strpos(%text, %field, 0) == -1) return -1;
   %count = getFieldCount(%text);
   if (%start >= %count) return -1;
   for (%i = %start; %i < %count; %i++)
   {
      if (getField( %text, %i) $= %field) return %i;
   }
   return -1;
}

//--------------------------------------------------------------------------
// returns the text in a file with "\n" at the end of each line
//--------------------------------------------------------------------------

function loadFileText( %file)
{
   %fo = new FileObject();
   %fo.openForRead(%file);
   %text = "";
   while(!%fo.isEOF())
   {
      %text = %text @ %fo.readLine();
      if (!%fo.isEOF()) %text = %text @ "\n";
   }

   %fo.delete();
   return %text;
}

function setValueSafe(%dest, %val)
{
   %cmd = %dest.command;
   %alt = %dest.altCommand;
   %dest.command = "";
   %dest.altCommand = "";

   %dest.setValue(%val);

   %dest.command = %cmd;
   %dest.altCommand = %alt;
}

function shareValueSafe(%source, %dest)
{
   setValueSafe(%dest, %source.getValue());
}

function shareValueSafeDelay(%source, %dest, %delayMs)
{
   schedule(%delayMs, 0, shareValueSafe, %source, %dest);
}

//------------------------------------------------------------------------------
// An Aggregate Control is a plain GuiControl that contains other controls,
// which all share a single job or represent a single value.
//------------------------------------------------------------------------------

// AggregateControl.setValue( ) propagates the value to any control that has an
// internal name.
function AggregateControl::setValue(%this, %val, %child)
{
   for(%i = 0; %i < %this.getCount(); %i++)
   {
      %obj = %this.getObject(%i);
      if( %obj == %child )
         continue;

      if(%obj.internalName !$= "")
         setValueSafe(%obj, %val);
   }
}

// AggregateControl.getValue() uses the value of the first control that has an
// internal name, if it has not cached a value via .setValue
function AggregateControl::getValue(%this)
{
   for(%i = 0; %i < %this.getCount(); %i++)
   {
      %obj = %this.getObject(%i);
      if(%obj.internalName !$= "")
      {
         //error("obj = " @ %obj.getId() @ ", " @ %obj.getName() @ ", " @ %obj.internalName );
         //error(" value = " @ %obj.getValue());
         return %obj.getValue();
      }
   }
}

// AggregateControl.updateFromChild( ) is called by child controls to propagate
// a new value, and to trigger the onAction() callback.
function AggregateControl::updateFromChild(%this, %child)
{
   %val = %child.getValue();
   if(%val == mCeil(%val)){
      %val = mCeil(%val);
   }else{
      if ( %val <= -100){
         %val = mCeil(%val);
      }else if ( %val <= -10){
         %val = mFloatLength(%val, 1);
      }else if ( %val < 0){
         %val = mFloatLength(%val, 2);
      }else if ( %val >= 1000){
         %val = mCeil(%val);
      }else if ( %val >= 100){
         %val = mFloatLength(%val, 1);
      }else if ( %val >= 10){
         %val = mFloatLength(%val, 2);
      }else if ( %val > 0){
         %val = mFloatLength(%val, 3);
      }
   }
   %this.setValue(%val, %child);
   %this.onAction();
}

// default onAction stub, here only to prevent console spam warnings.
function AggregateControl::onAction(%this)
{
}

// call a method on all children that have an internalName and that implement the method.
function AggregateControl::callMethod(%this, %method, %args)
{
   for(%i = 0; %i < %this.getCount(); %i++)
   {
      %obj = %this.getObject(%i);
      if(%obj.internalName !$= "" && %obj.isMethod(%method))
         eval(%obj @ "." @ %method @ "( " @ %args @ " );");
   }

}

//------------------------------------------------------------------------------
// Altered Version of TGB's QuickEditDropDownTextEditCtrl
//------------------------------------------------------------------------------
function QuickEditDropDownTextEditCtrl::onRenameItem( %this )
{
}

function QuickEditDropDownTextEditCtrl::updateFromChild( %this, %ctrl )
{
   if( %ctrl.internalName $= "PopUpMenu" )
   {
      %this->TextEdit.setText( %ctrl.getText() );
   }
   else if ( %ctrl.internalName $= "TextEdit" )
   {
      %popup = %this->PopupMenu;
      %popup.changeTextById( %popup.getSelected(), %ctrl.getText() );
      %this.onRenameItem();
   }
}

// Writes out all script functions to a file.
function writeOutFunctions()
{
   new ConsoleLogger(logger, "scriptFunctions.txt", false);
   dumpConsoleFunctions();
   logger.delete();
}

// Writes out all script classes to a file.
function writeOutClasses()
{
   new ConsoleLogger(logger, "scriptClasses.txt", false);
   dumpConsoleClasses();
   logger.delete();
}

//
function compileFiles(%pattern)
{
   %path = filePath(%pattern);

   %saveDSO    = $Scripts::OverrideDSOPath;
   %saveIgnore = $Scripts::ignoreDSOs;

   $Scripts::OverrideDSOPath  = %path;
   $Scripts::ignoreDSOs       = false;
   %mainCsFile = makeFullPath("main.cs");

   for (%file = findFirstFileMultiExpr(%pattern); %file !$= ""; %file = findNextFileMultiExpr(%pattern))
   {
      // we don't want to try and compile the primary main.cs
      if(%mainCsFile !$= %file)
         compile(%file, true);
   }

   $Scripts::OverrideDSOPath  = %saveDSO;
   $Scripts::ignoreDSOs       = %saveIgnore;

}

function displayHelp()
{
   // Notes on logmode: console logging is written to console.log.
   // -log 0 disables console logging.
   // -log 1 appends to existing logfile; it also closes the file
   // (flushing the write buffer) after every write.
   // -log 2 overwrites any existing logfile; it also only closes
   // the logfile when the application shuts down.  (default)

   error(
      "Torque Demo command line options:\n"@
      "  -log <logmode>         Logging behavior; see main.cs comments for details\n"@
      "  -game <game_name>      Reset list of mods to only contain <game_name>\n"@
      "  <game_name>            Works like the -game argument\n"@
      "  -dir <dir_name>        Add <dir_name> to list of directories\n"@
      "  -console               Open a separate console\n"@
      "  -jSave  <file_name>    Record a journal\n"@
      "  -jPlay  <file_name>    Play back a journal\n"@
      "  -help                  Display this help message\n"
   );
}

// Execute startup scripts for each mod, starting at base and working up
function loadDir(%dir)
{
   pushback($userDirs, %dir, ";");

   if (isScriptFile(%dir @ "/main.cs"))
   exec(%dir @ "/main.cs");
}

function loadDirs(%dirPath)
{
   %dirPath = nextToken(%dirPath, token, ";");
   if (%dirPath !$= "")
      loadDirs(%dirPath);

   if(exec(%token @ "/main.cs") != true)
   {
      error("Error: Unable to find specified directory: " @ %token );
      $dirCount--;
   }
}

//------------------------------------------------------------------------------
// Utility remap functions:
//------------------------------------------------------------------------------

function ActionMap::copyBind( %this, %otherMap, %command )
{
   if ( !isObject( %otherMap ) )
   {
      error( "ActionMap::copyBind - \"" @ %otherMap @ "\" is not an object!" );
      return;
   }

   %bind = %otherMap.getBinding( %command );
   if ( %bind !$= "" )
   {
      %device = getField( %bind, 0 );
      %action = getField( %bind, 1 );
      %flags = %otherMap.isInverted( %device, %action ) ? "SDI" : "SD";
      %deadZone = %otherMap.getDeadZone( %device, %action );
      %scale = %otherMap.getScale( %device, %action );
      %this.bind( %device, %action, %flags, %deadZone, %scale, %command );
   }
}

//------------------------------------------------------------------------------
function ActionMap::blockBind( %this, %otherMap, %command )
{
   if ( !isObject( %otherMap ) )
   {
      error( "ActionMap::blockBind - \"" @ %otherMap @ "\" is not an object!" );
      return;
   }

   %bind = %otherMap.getBinding( %command );
   if ( %bind !$= "" )
      %this.bind( getField( %bind, 0 ), getField( %bind, 1 ), "" );
}

//Dev helpers
/// Shortcut for typing dbgSetParameters with the default values torsion uses.
function dbgTorsion()
{
   dbgSetParameters( 6060, "password", false );
}

/// Reset the input state to a default of all-keys-up.
/// A helpful remedy for when Torque misses a button up event do to your breakpoints
/// and can't stop shooting / jumping / strafing.
function mvReset()
{
   for ( %i = 0; %i < 6; %i++ )
      setVariable( "mvTriggerCount" @ %i, 0 );

   $mvUpAction = 0;
   $mvDownAction = 0;
   $mvLeftAction = 0;
   $mvRightAction = 0;

   // There are others.
}

//Persistance Manager tests

new PersistenceManager(TestPManager);

function runPManTest(%test)
{
   if (!isObject(TestPManager))
      return;

   if (%test $= "")
      %test = 100;

   switch(%test)
   {
      case 0:
         TestPManager.testFieldUpdates();
      case 1:
         TestPManager.testObjectRename();
      case 2:
         TestPManager.testNewObject();
      case 3:
         TestPManager.testNewGroup();
      case 4:
         TestPManager.testMoveObject();
      case 5:
         TestPManager.testObjectRemove();
      case 100:
         TestPManager.testFieldUpdates();
         TestPManager.testObjectRename();
         TestPManager.testNewObject();
         TestPManager.testNewGroup();
         TestPManager.testMoveObject();
         TestPManager.testObjectRemove();
   }
}

function TestPManager::testFieldUpdates(%doNotSave)
{
   // Set some objects as dirty
   TestPManager.setDirty(AudioGui);
   TestPManager.setDirty(AudioSim);
   TestPManager.setDirty(AudioMessage);

   // Alter some of the existing fields
   AudioEffect.isLooping         = true;
   AudioMessage.isLooping     = true;
   AudioEffect.is3D              = true;

   // Test removing a field
   TestPManager.removeField(AudioGui, "isLooping");

   // Alter some of the persistent fields
   AudioGui.referenceDistance     = 0.8;
   AudioMessage.referenceDistance = 0.8;

   // Add some new dynamic fields
   AudioGui.foo = "bar";
   AudioEffect.foo = "bar";

   // Remove an object from the dirty list
   // It shouldn't get updated in the file
   TestPManager.removeDirty(AudioEffect);

   // Dirty an object in another file as well
   TestPManager.setDirty(WarningMaterial);

   // Update a field that doesn't exist
   WarningMaterial.glow[0] = true;

   // Drity another object to test for crashes
   // when a dirty object is deleted
   TestPManager.setDirty(SFXPausedSet);

   // Delete the object
   SFXPausedSet.delete();

   // Unless %doNotSave is set (by a batch/combo test)
   // then go ahead and save now
   if (!%doNotSave)
      TestPManager.saveDirty();
}

function TestPManager::testObjectRename(%doNotSave)
{
   // Flag an object as dirty
   if (isObject(AudioGui))
      TestPManager.setDirty(AudioGui);
   else if (isObject(AudioGuiFoo))
      TestPManager.setDirty(AudioGuiFoo);

   // Rename it
   if (isObject(AudioGui))
      AudioGui.setName(AudioGuiFoo);
   else if (isObject(AudioGuiFoo))
      AudioGuiFoo.setName(AudioGui);

   // Unless %doNotSave is set (by a batch/combo test)
   // then go ahead and save now
   if (!%doNotSave)
      TestPManager.saveDirty();
}

function TestPManager::testNewObject(%doNotSave)
{
   // Test adding a new named object
   new SFXDescription(AudioNew)
   {
      volume = 0.5;
      isLooping = true;
      channel  = $GuiAudioType;
      foo = 2;
   };

   // Flag it as dirty
   TestPManager.setDirty(AudioNew, "core/scripts/client/audio.cs");

   // Test adding a new unnamed object
   %obj = new SFXDescription()
   {
      volume = 0.75;
      isLooping = true;
      bar = 3;
   };

   // Flag it as dirty
   TestPManager.setDirty(%obj, "core/scripts/client/audio.cs");

   // Test adding an "empty" object
   new SFXDescription(AudioEmpty);

   TestPManager.setDirty(AudioEmpty, "core/scripts/client/audio.cs");

   // Unless %doNotSave is set (by a batch/combo test)
   // then go ahead and save now
   if (!%doNotSave)
      TestPManager.saveDirty();
}

function TestPManager::testNewGroup(%doNotSave)
{
   // Test adding a new named SimGroup
   new SimGroup(TestGroup)
   {
      foo = "bar";

      new SFXDescription(TestObject)
      {
         volume = 0.5;
         isLooping = true;
         channel  = $GuiAudioType;
         foo = 1;
      };
      new SimGroup(SubGroup)
      {
         foo = 2;

         new SFXDescription(SubObject)
         {
            volume = 0.5;
            isLooping = true;
            channel  = $GuiAudioType;
            foo = 3;
         };
      };
   };

   // Flag this as dirty
   TestPManager.setDirty(TestGroup, "core/scripts/client/audio.cs");

   // Test adding a new unnamed SimGroup
   %group = new SimGroup()
   {
      foo = "bar";

      new SFXDescription()
      {
         volume = 0.75;
         channel  = $GuiAudioType;
         foo = 4;
      };
      new SimGroup()
      {
         foo = 5;

         new SFXDescription()
         {
            volume = 0.75;
            isLooping = true;
            channel  = $GuiAudioType;
            foo = 6;
         };
      };
   };

   // Flag this as dirty
   TestPManager.setDirty(%group, "core/scripts/client/audio.cs");

   // Test adding a new unnamed SimSet
   %set = new SimSet()
   {
      foo = "bar";

      new SFXDescription()
      {
         volume = 0.75;
         channel  = $GuiAudioType;
         foo = 7;
      };
      new SimGroup()
      {
         foo = 8;

         new SFXDescription()
         {
            volume = 0.75;
            isLooping = true;
            channel  = $GuiAudioType;
            foo = 9;
         };
      };
   };

   // Flag this as dirty
   TestPManager.setDirty(%set, "core/scripts/client/audio.cs");

   // Unless %doNotSave is set (by a batch/combo test)
   // then go ahead and save now
   if (!%doNotSave)
      TestPManager.saveDirty();
}

function TestPManager::testMoveObject(%doNotSave)
{
   // First add a couple of groups to the file
   new SimGroup(MoveGroup1)
   {
      foo = "bar";

      new SFXDescription(MoveObject1)
      {
         volume = 0.5;
         isLooping = true;
         channel  = $GuiAudioType;
         foo = 1;
      };

      new SimSet(SubGroup1)
      {
         new SFXDescription(SubObject1)
         {
            volume = 0.75;
            isLooping = true;
            channel  = $GuiAudioType;
            foo = 2;
         };
      };
   };

   // Flag this as dirty
   TestPManager.setDirty(MoveGroup1, "core/scripts/client/audio.cs");

   new SimGroup(MoveGroup2)
   {
      foo = "bar";

      new SFXDescription(MoveObject2)
      {
         volume = 0.5;
         isLooping = true;
         channel  = $GuiAudioType;
         foo = 3;
      };
   };

   // Flag this as dirty
   TestPManager.setDirty(MoveGroup2, "core/scripts/client/audio.cs");

   // Unless %doNotSave is set (by a batch/combo test)
   // then go ahead and save now
   if (!%doNotSave)
      TestPManager.saveDirty();

   // Set them as dirty again
   TestPManager.setDirty(MoveGroup1);
   TestPManager.setDirty(MoveGroup2);

   // Give the subobject an new value
   MoveObject1.foo = 4;

   // Move it into the other group
   MoveGroup1.add(MoveObject2);

   // Switch the other subobject
   MoveGroup2.add(MoveObject1);

   // Also add a new unnamed object to one of the groups
   %obj = new SFXDescription()
   {
      volume = 0.75;
      isLooping = true;
      bar = 5;
   };

   MoveGroup1.add(%obj);

   // Unless %doNotSave is set (by a batch/combo test)
   // then go ahead and save now
   if (!%doNotSave)
      TestPManager.saveDirty();
}

function TestPManager::testObjectRemove(%doNotSave)
{
   TestPManager.removeObjectFromFile(AudioSim);
}

//Game Object management
function findGameObject(%name)
{
   //find all GameObjectAssets
   %assetQuery = new AssetQuery();
   if(!AssetDatabase.findAssetType(%assetQuery, "GameObjectAsset"))
      return 0; //if we didn't find ANY, just exit

   %count = %assetQuery.getCount();

	for(%i=0; %i < %count; %i++)
	{
	   %assetId = %assetQuery.getAsset(%i);

	   //%assetName = AssetDatabase.getAssetName(%assetId);

        if(%assetId $= %name)
		{
		   %gameObjectAsset = AssetDatabase.acquireAsset(%assetId);

         %assetQuery.delete();
         return %gameObjectAsset;
		}
	}

   %assetQuery.delete();
	return 0;
}

function spawnGameObject(%name, %addToMissionGroup)
{
   if(%addToMissionGroup $= "")
		%addToMissionGroup = true;

   //First, check if this already exists in our GameObjectPool
   if(isObject(GameObjectPool))
   {
      %goCount = GameObjectPool.countKey(%name);

      //if we have some already in the pool, pull it out and use that
      if(%goCount != 0)
      {
         %goIdx = GameObjectPool.getIndexFromKey(%name);
         %go = GameObjectPool.getValue(%goIdx);

         %go.setHidden(false);
         %go.setScopeAlways();

         if(%addToMissionGroup == true) //save instance when saving level
            MissionGroup.add(%go);
         else // clear instance on level exit
            MissionCleanup.add(%go);

         //remove from the object pool's list
         GameObjectPool.erase(%goIdx);

         return %go;
      }
   }

	//We have no existing pool, or no existing game objects of this type, so spawn a new one

   %gameObjectAsset = findGameObject(%name);

   if(isObject(%gameObjectAsset))
   {
      %newSGOObject = TamlRead(%gameObjectAsset.TAMLFilePath);

      if(%addToMissionGroup == true) //save instance when saving level
         MissionGroup.add(%newSGOObject);
      else // clear instance on level exit
         MissionCleanup.add(%newSGOObject);

      return %newSGOObject;
   }

	return 0;
}

function saveGameObject(%name, %tamlPath, %scriptPath)
{
	%gameObjectAsset = findGameObject(%name);

   //find if it already exists. If it does, we'll update it, if it does not, we'll  make a new asset
   if(isObject(%gameObjectAsset))
   {
      %assetID = %gameObjectAsset.getAssetId();

      %gameObjectAsset.TAMLFilePath = %tamlPath;
      %gameObjectAsset.scriptFilePath = %scriptPath;

      TAMLWrite(%gameObjectAsset, AssetDatabase.getAssetFilePath(%assetID));
      AssetDatabase.refreshAsset(%assetID);
   }
   else
   {
      //Doesn't exist, so make a new one
      %gameObjectAsset = new GameObjectAsset()
      {
         assetName = %name @ "Asset";
         gameObjectName = %name;
         TAMLFilePath = %tamlPath;
         scriptFilePath = %scriptPath;
      };

      //Save it alongside the taml file
      %path = filePath(%tamlPath);

      TAMLWrite(%gameObjectAsset, %path @ "/" @ %name @ ".asset.taml");
      AssetDatabase.refreshAllAssets(true);
   }
}

//Allocates a number of a game object into a pool to be pulled from as needed
function allocateGameObjects(%name, %amount)
{
   //First, we need to make sure our pool exists
   if(!isObject(GameObjectPool))
   {
      new ArrayObject(GameObjectPool);
   }

   //Next, we loop and generate our game objects, and add them to the pool
   for(%i=0; %i < %amount; %i++)
   {
      %go = spawnGameObject(%name, false);

      //When our object is in the pool, it's not "real", so we need to make sure
      //that we don't ghost it to clients untill we actually spawn it.
      %go.clearScopeAlways();

      //We also hide it, so that we don't 'exist' in the scene until we spawn
      %go.hidden = true;

      //Lastly, add us to the pool, with the key being our game object type
      GameObjectPool.add(%name, %go);
   }
}

function Entity::delete(%this)
{
   //we want to intercept the delete call, and add it to our GameObjectPool
   //if it's a game object
   if(%this.gameObjectAsset !$= "")
   {
      %this.setHidden(true);
      %this.clearScopeAlways();

      if(!isObject(GameObjectPool))
      {
         new ArrayObject(GameObjectPool);
      }

      GameObjectPool.add(%this.gameObjectAsset, %this);

      %missionSet = %this.getGroup();
      %missionSet.remove(%this);
   }
   else
   {
      %this.superClass.delete();
   }
}

function clearGameObjectPool()
{
   if(isObject(GameObjectPool))
   {
      %count = GameObjectPool.count();

      for(%i=0; %i < %count; %i++)
      {
         %go = GameObjectPool.getValue(%i);

         %go.superClass.delete();
      }

      GameObjectPool.empty();
   }
}

//
function switchCamera(%client, %newCamEntity)
{
	if(!isObject(%client) || !isObject(%newCamEntity))
		return error("SwitchCamera: No client or target camera!");

	%cam = %newCamEntity.getComponent(CameraComponent);

	if(!isObject(%cam))
		return error("SwitchCamera: Target camera doesn't have a camera behavior!");

	//TODO: Cleanup clientOwner for previous camera!
	if(%cam.clientOwner == 0 || %cam.clientOwner $= "")
		%cam.clientOwner = 0;

	%cam.scopeToClient(%client);
	%cam.setDirty();

	%client.setCameraObject(%newCamEntity);
	%client.setControlCameraFov(%cam.FOV);

	%client.camera = %newCamEntity;
}


text:
/**
* Scavenger hunts plugin. Only works in a room with the id 'scavengers'.
* This game shows a hint. Once a player submits the correct answer, they move on to the next hint.
* You finish upon correctly answering the third hint.
* In an official hunt, the first three to finish within 60 seconds achieve blitz.
*/

'use strict';

let scavengers = {
	status: 'off',
	blitz: null,
	hints: null,
	answers: null,
	participants: {},
	finished: [],
	result: null,
};

let scavengersRoom = Rooms.get('scavengers');
if (scavengersRoom) {
	if (scavengersRoom.plugin) {
		scavengers = scavengersRoom.plugin;
	} else {
		scavengersRoom.plugin = scavengers;
	}
}

exports.commands = {
	scavenger: 'scavengers',
	scavengers: function (target, room, user) {
		return this.parse('/join scavengers');
	},
	startofficialhunt: 'starthunt',
	starthunt: function (target, room, user, connection, cmd) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (!this.can('mute', null, room)) return false;
		if (scavengers.status === 'on') return this.errorReply('There is already an active scavenger hunt.');
		let targets = target.split(target.includes('|') ? '|' : ',');
		if (!targets[0] || !targets[1] || !targets[2] || !targets[3] || !targets[4] || !targets[5] || targets[6]) {
			return this.errorReply('You must specify three hints and three answers.');
		}
		if (cmd === 'startofficialhunt') {
			scavengers.blitz = setTimeout(() => {
				scavengers.blitz = null;
			}, 60000);
		}
		scavengers.status = 'on';
		scavengers.hints = [targets[0].trim(), targets[2].trim(), targets[4].trim()];
		scavengers.answers = [toId(targets[1]), toId(targets[3]), toId(targets[5])];
		scavengers.startTime = Date.now();
		let result = (cmd === 'startofficialhunt' ? 'An official' : 'A new') + ' Scavenger Hunt has been started by  ' + Chat.escapeHTML(user.name) + '! The first hint is: ' + Chat.escapeHTML(scavengers.hints[0]);
		Rooms('scavengers').addRaw('
' + result + '
');
	},
	joinhunt: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		if (user.userid in scavengers.participants) return this.errorReply('You are already participating in the current scavenger hunt.');
		scavengers.participants[user.userid] = {room: 0};
		this.sendReply('You joined the scavenger hunt! Use the command /scavenge to answer. The first hint is: ' + scavengers.hints[0]);
	},
	scavenge: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		if (!scavengers.participants[user.userid]) return this.errorReply('You are not participating in the current scavenger hunt. Use the command /joinhunt to participate.');
		if (scavengers.participants[user.userid].room >= 3) return this.sendReply('You have already finished!');
		target = toId(target);
		let roomnum = scavengers.participants[user.userid].room;
		if (scavengers.answers[roomnum] === target) {
			scavengers.participants[user.userid].room++;
			roomnum++;
			if (roomnum < 3) {
				this.sendReply('Well done! Your ' + (roomnum === 1 ? 'second' : 'final') + ' hint is: ' + scavengers.hints[roomnum]);
			} else {
				scavengers.finished.push(user.name);
				let position = scavengers.finished.length;
				let result = '' + Chat.escapeHTML(user.name) + ' has finished the hunt ';
				result += (position === 1) ? 'and is the winner!' : (position === 2) ? 'in 2nd place!' : (position === 3) ? 'in 3rd place!' : 'in ' + position + 'th place!';
				result += (position < 4 && scavengers.blitz ? ' [BLITZ]' : '');
				result += ' (' + Chat.toDurationString(Date.now() - scavengers.startTime, {hhmmss: true}) + ')';
				Rooms('scavengers').addRaw('
' + result + '
');
			}
		} else {
			this.sendReply('That is not the answer - try again!');
		}
	},
	scavengerhint: 'scavengerstatus',
	scavengerstatus: function (target, room, user, connection, cmd) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		if (!scavengers.participants[user.userid]) {
			if (!this.can('mute', null, room) || cmd !== 'scavengerstatus') return this.errorReply('You are not participating in the current scavenger hunt. Use the command /joinhunt to participate.');
			let uptime = (Date.now() - scavengers.startTime) / 1000;
			let uptimeText;
			if (uptime > 24 * 60 * 60) {
				let uptimeDays = Math.floor(uptime / (24 * 60 * 60));
				uptimeText = uptimeDays + " " + (uptimeDays === 1 ? "day" : "days");
				let uptimeHours = Math.floor(uptime / (60 * 60)) - uptimeDays * 24;
				if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours === 1 ? "hour" : "hours");
			} else {
				uptimeText = Chat.toDurationString(uptime * 1000);
			}
			this.sendReply('The current scavenger hunt has been up for: ' + uptimeText);
			if (scavengers.finished.length) {
				this.sendReply('The following users have completed it: ' + scavengers.finished.join(', '));
			} else {
				this.sendReply('No user has completed it.');
			}
			return;
		}
		if (scavengers.participants[user.userid].room >= 3) return this.sendReply('You have finished the current scavenger hunt.');
		let roomnum = scavengers.participants[user.userid].room;
		this.sendReply('You are on hint number ' + (roomnum + 1) + ': ' + scavengers.hints[roomnum]);
	},
	endhunt: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (!this.can('mute', null, room)) return false;
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		let winner = scavengers.finished[0];
		let second = scavengers.finished[1];
		let third = scavengers.finished[2];
		let consolation = scavengers.finished.slice(3).join(', ');
		let msg = 'The Scavenger Hunt was ended by ' + Chat.escapeHTML(user.name) + '. ';
		if (winner) {
			msg += '
Winner: ' + Chat.escapeHTML(winner) + '.';
			if (second) msg += ' Second place: ' + Chat.escapeHTML(second) + '.';
			if (third) msg += ' Third place: ' + Chat.escapeHTML(third) + '.';
			if (consolation) msg += ' Consolation prize to: ' + Chat.escapeHTML(consolation) + '.';
		} else {
			msg += 'No user has completed the hunt.';
		}
		msg += '
Solution: ' + Chat.escapeHTML(scavengers.answers.join(', ')) + '.';
		scavengers.result = msg;
		this.parse('/resethunt');
	},
	resethunt: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (!this.can('mute', null, room)) return false;
		if (scavengers.status !== 'on') return this.errorReply('There is no active scavenger hunt.');
		scavengers.status = 'off';
		if (scavengers.blitz) clearTimeout(scavengers.blitz);
		scavengers.blitz = null;
		scavengers.hints = null;
		scavengers.answers = null;
		scavengers.participants = {};
		scavengers.finished = [];
		if (scavengers.result) {
			Rooms('scavengers').addRaw('
' + scavengers.result + '
');
		} else {
			Rooms('scavengers').addRaw('
The Scavenger Hunt was reset by ' + Chat.escapeHTML(user.name) + '.
');
		}
		scavengers.result = null;
	},
	scavengershelp: 'scavengerhelp',
	scavengerhelp: function (target, room, user) {
		if (room.id !== 'scavengers') return this.errorReply('This command can only be used in the Scavengers room.');
		if (!this.runBroadcast()) return;
		this.sendReplyBox(
			'Player commands:
' +
			'- /scavengers - Join the scavengers room
' +
			'- /joinhunt - Join the current scavenger hunt
' +
			'- /scavenge guess - Attempt to answer the hint
' +
			'- /scavengerstatus - Get your current game status
' +
			'
' +
			'Staff commands:
' +
			'- /starthunt hint, answer, hint, answer, hint, answer - Start a new scavenger hunt (Requires: % @ * # & ~)
' +
			'- /startofficialhunt hint, answer, hint, answer, hint, answer - Start an official hunt with 60 seconds blitz period (Requires: % @ * # & ~)
' +
			'- /endhunt - Finish the current hunt and announce the winners (Requires: % @ * # & ~)
' +
			'- /resethunt - Reset the scavenger hunt to mint status (Requires: % @ * # & ~)'
		);
	},
};

redpajama_set_name: RedPajamaGithub


text:
START_ATF_NAMESPACE
    namespace Detail
    {
        extern ::std::array<hook_record, 1> _guildroom_rent_result_zocl_functions;
    }; // end namespace Detail
END_ATF_NAMESPACE


text:
namespace content {

class ShellPermissionManager : public PermissionControllerDelegate {
 public:
  ShellPermissionManager();
  ~ShellPermissionManager() override;

  // PermissionManager implementation.
  int RequestPermission(PermissionType permission,
                        RenderFrameHost* render_frame_host,
                        const GURL& requesting_origin,
                        bool user_gesture,
                        base::OnceCallback<void(blink::mojom::PermissionStatus)>
                            callback) override;
  int RequestPermissions(
      const std::vector<PermissionType>& permission,
      RenderFrameHost* render_frame_host,
      const GURL& requesting_origin,
      bool user_gesture,
      base::OnceCallback<
          void(const std::vector<blink::mojom::PermissionStatus>&)> callback)
      override;
  void ResetPermission(PermissionType permission,
                       const GURL& requesting_origin,
                       const GURL& embedding_origin) override;
  blink::mojom::PermissionStatus GetPermissionStatus(
      PermissionType permission,
      const GURL& requesting_origin,
      const GURL& embedding_origin) override;
  blink::mojom::PermissionStatus GetPermissionStatusForFrame(
      content::PermissionType permission,
      content::RenderFrameHost* render_frame_host,
      const GURL& requesting_origin) override;
  int SubscribePermissionStatusChange(
      PermissionType permission,
      RenderFrameHost* render_frame_host,
      const GURL& requesting_origin,
      base::RepeatingCallback<void(blink::mojom::PermissionStatus)> callback)
      override;
  void UnsubscribePermissionStatusChange(int subscription_id) override;

 private:
  DISALLOW_COPY_AND_ASSIGN(ShellPermissionManager);
};

}  // namespace content

#endif // CONTENT_SHELL_BROWSER_SHELL_PERMISSION_MANAGER_H


text:
package enums;// enums/OverrideConstantSpecific.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public enum OverrideConstantSpecific {
  NUT, BOLT,
  WASHER {
    @Override
    void f() {
      System.out.println("Overridden method");
    }
  };
  void f() {
    System.out.println("default behavior");
  }
  public static void main(String[] args) {
    for(OverrideConstantSpecific ocs : values()) {
      System.out.print(ocs + ": ");
      ocs.f();
    }
  }
}
/* Output:
NUT: default behavior
BOLT: default behavior
WASHER: Overridden method
*/


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThScoreFileConverter.Core.Tests.UnitTesting;
using ThScoreFileConverter.Interactivity;

namespace ThScoreFileConverter.Tests.Interactivity;

[TestClass]
public class OpenFileDialogActionResultTests
{
    [TestMethod]
    public void OpenFileDialogActionResultTest()
    {
        var filename = "score.dat";
        var filenames = new string[] { "bs01_1.dat", "bs01_2.dat" };
        var result = new OpenFileDialogActionResult(filename, filenames);

        Assert.AreEqual(filename, result.FileName);
        CollectionAssert.That.AreEqual(filenames, result.FileNames);

        filenames[0] = "bs02_1.dat";
        CollectionAssert.That.AreNotEqual(filenames, result.FileNames);
    }

    [TestMethod]
    public void OpenFileDialogActionResultTestNullFilename()
    {
        var filenames = new string[] { "bs01_1.dat", "bs01_2.dat" };
        _ = Assert.ThrowsException<ArgumentNullException>(() => new OpenFileDialogActionResult(null!, filenames));
    }

    [TestMethod]
    public void OpenFileDialogActionResultTestNullFilenames()
    {
        var filename = "score.dat";
        _ = Assert.ThrowsException<ArgumentNullException>(() => new OpenFileDialogActionResult(filename, null!));
    }
}


text:
package org.finos.waltz.jobs.generators;

import org.finos.waltz.model.EntityKind;
import org.finos.waltz.schema.tables.records.MeasurableRatingRecord;
import org.jooq.DSLContext;
import org.jooq.lambda.tuple.Tuple;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static org.finos.waltz.common.RandomUtilities.randomPick;
import static org.finos.waltz.common.RandomUtilities.randomlySizedIntStream;
import static org.finos.waltz.common.SetUtilities.uniqBy;
import static org.finos.waltz.schema.Tables.MEASURABLE;
import static org.finos.waltz.schema.Tables.MEASURABLE_RATING;

public class MeasurableRatingGenerator implements SampleDataGenerator {

    @Override
    public Map<String, Integer> create(ApplicationContext ctx) {

        DSLContext dsl = getDsl(ctx);

        List<Long> appIds = getAppIds(dsl);
        List<Long> mIds = dsl
                .select(MEASURABLE.ID)
                .from(MEASURABLE)
                .where(MEASURABLE.CONCRETE.isTrue())
                .fetch()
                .getValues(MEASURABLE.ID);

        List<MeasurableRatingRecord> records = appIds.stream()
                .flatMap(appId -> randomlySizedIntStream(0, MAX_RATINGS_PER_APP)
                                .mapToObj(idx -> Tuple.tuple(appId, randomPick(mIds))))
                .map(t -> {
                    MeasurableRatingRecord record = dsl.newRecord(MEASURABLE_RATING);
                    record.setEntityId(t.v1);
                    record.setEntityKind(EntityKind.APPLICATION.name());
                    record.setRating(randomPick("R", "A", "G"));
                    record.setMeasurableId(t.v2);
                    record.setLastUpdatedBy("admin");
                    record.setProvenance(SAMPLE_DATA_PROVENANCE);
                    return record;
                })
                .collect(Collectors.toList());

        Set<MeasurableRatingRecord> dedupedRecords = uniqBy(
                records,
                r -> Tuple.tuple(r.getMeasurableId(), r.getEntityId()));

        dsl.batchStore(dedupedRecords).execute();

        return null;
    }

    @Override
    public boolean remove(ApplicationContext ctx) {
        getDsl(ctx)
                .deleteFrom(MEASURABLE_RATING)
                .where(MEASURABLE_RATING.PROVENANCE.eq(SAMPLE_DATA_PROVENANCE))
                .execute();
        return false;
    }

}


text:
// +build linux

package tracer

import (
	"encoding/binary"
	"fmt"
	"math/rand"
	"net"
	"os"
	"runtime"
	"strconv"
	"strings"
	"syscall"
	"time"
	"unsafe"

	"github.com/iovisor/gobpf/elf"
)

/*
#include "../../tcptracer-bpf.h"
*/
import "C"

type tcpTracerStatus C.struct_tcptracer_status_t

const (
	// When reading kernel structs at different offsets, don't go over that
	// limit. This is an arbitrary choice to avoid infinite loops.
	threshold = 400

	// The source port is much further away in the inet sock.
	thresholdInetSock = 2000
)

// These constants should be in sync with the equivalent definitions in the ebpf program.
const (
	stateUninitialized C.__u64 = 0
	stateChecking              = 1 // status set by userspace, waiting for eBPF
	stateChecked               = 2 // status set by eBPF, waiting for userspace
	stateReady                 = 3 // fully initialized, all offset known
)

var stateString = map[C.__u64]string{
	stateUninitialized: "uninitialized",
	stateChecking:      "checking",
	stateChecked:       "checked",
	stateReady:         "ready",
}

// These constants should be in sync with the equivalent definitions in the ebpf program.
const (
	guessSaddr     C.__u64 = 0
	guessDaddr             = 1
	guessFamily            = 2
	guessSport             = 3
	guessDport             = 4
	guessNetns             = 5
	guessDaddrIPv6         = 6
)

var whatString = map[C.__u64]string{
	guessSaddr:     "source address",
	guessDaddr:     "destination address",
	guessFamily:    "family",
	guessSport:     "source port",
	guessDport:     "destination port",
	guessNetns:     "network namespace",
	guessDaddrIPv6: "destination address IPv6",
}

const listenIP = "127.0.0.2"

var zero uint64

type freePort struct {
	port uint16
	err  error
}

type fieldValues struct {
	saddr     uint32
	daddr     uint32
	sport     uint16
	dport     uint16
	netns     uint32
	family    uint16
	daddrIPv6 [4]uint32
}

func startServer() (chan struct{}, uint16, error) {
	// port 0 means we let the kernel choose a free port
	addr := fmt.Sprintf("%s:0", listenIP)
	l, err := net.Listen("tcp4", addr)
	if err != nil {
		return nil, 0, err
	}
	lport, err := strconv.Atoi(strings.Split(l.Addr().String(), ":")[1])
	if err != nil {
		return nil, 0, err
	}

	stop := make(chan struct{})
	go acceptV4(l, stop)

	return stop, uint16(lport), nil
}

func acceptV4(l net.Listener, stop chan struct{}) {
	for {
		_, ok := <-stop
		if ok {
			conn, err := l.Accept()
			if err != nil {
				l.Close()
				return
			}
			conn.Close()
		} else {
			// the main thread closed the channel, which signals there
			// won't be any more connections
			l.Close()
			return
		}
	}
}

func compareIPv6(a [4]C.__u32, b [4]uint32) bool {
	for i := 0; i < 4; i++ {
		if a[i] != C.__u32(b[i]) {
			return false
		}
	}
	return true
}

func ownNetNS() (uint64, error) {
	var s syscall.Stat_t
	if err := syscall.Stat("/proc/self/ns/net", &s); err != nil {
		return 0, err
	}
	return s.Ino, nil
}

func ipv6FromUint32Arr(ipv6Addr [4]uint32) net.IP {
	buf := make([]byte, 16)
	for i := 0; i < 16; i++ {
		buf[i] = *(*byte)(unsafe.Pointer((uintptr(unsafe.Pointer(&ipv6Addr[0])) + uintptr(i))))
	}
	return net.IP(buf)
}

func htons(a uint16) uint16 {
	var arr [2]byte
	binary.BigEndian.PutUint16(arr[:], a)
	return nativeEndian.Uint16(arr[:])
}

func generateRandomIPv6Address() (addr [4]uint32) {
	// multicast (ff00::/8) or link-local (fe80::/10) addresses don't work for
	// our purposes so let's choose a "random number" for the first 32 bits.
	//
	// chosen by fair dice roll.
	// guaranteed to be random.
	// https://xkcd.com/221/
	addr[0] = 0x87586031
	addr[1] = rand.Uint32()
	addr[2] = rand.Uint32()
	addr[3] = rand.Uint32()

	return
}

// tryCurrentOffset creates a IPv4 or IPv6 connection so the corresponding
// tcp_v{4,6}_connect kprobes get triggered and save the value at the current
// offset in the eBPF map
func tryCurrentOffset(module *elf.Module, mp *elf.Map, status *tcpTracerStatus, expected *fieldValues, stop chan struct{}) error {
	// for ipv6, we don't need the source port because we already guessed
	// it doing ipv4 connections so we use a random destination address and
	// try to connect to it
	expected.daddrIPv6 = generateRandomIPv6Address()

	ip := ipv6FromUint32Arr(expected.daddrIPv6)

	bindAddress := fmt.Sprintf("%s:%d", listenIP, expected.dport)
	if status.what != guessDaddrIPv6 {
		// signal the server that we're about to connect, this will block until
		// the channel is free so we don't overload the server
		stop <- struct{}{}
		conn, err := net.Dial("tcp4", bindAddress)
		if err != nil {
			return fmt.Errorf("error dialing %q: %v", bindAddress, err)
		}

		// get the source port assigned by the kernel
		sport, err := strconv.Atoi(strings.Split(conn.LocalAddr().String(), ":")[1])
		if err != nil {
			return fmt.Errorf("error converting source port: %v", err)
		}

		expected.sport = uint16(sport)

		// set SO_LINGER to 0 so the connection state after closing is
		// CLOSE instead of TIME_WAIT. In this way, they will disappear
		// from the conntrack table after around 10 seconds instead of 2
		// minutes
		if tcpConn, ok := conn.(*net.TCPConn); ok {
			tcpConn.SetLinger(0)
		} else {
			return fmt.Errorf("not a tcp connection unexpectedly")
		}

		conn.Close()
	} else {
		conn, err := net.DialTimeout("tcp6", fmt.Sprintf("[%s]:9092", ip), 10*time.Millisecond)
		// Since we connect to a random IP, this will most likely fail.
		// In the unlikely case where it connects successfully, we close
		// the connection to avoid a leak.
		if err == nil {
			conn.Close()
		}
	}

	return nil
}

// checkAndUpdateCurrentOffset checks the value for the current offset stored
// in the eBPF map against the expected value, incrementing the offset if it
// doesn't match, or going to the next field to guess if it does
func checkAndUpdateCurrentOffset(module *elf.Module, mp *elf.Map, status *tcpTracerStatus, expected *fieldValues, maxRetries *int) error {
	// get the updated map value so we can check if the current offset is
	// the right one
	if err := module.LookupElement(mp, unsafe.Pointer(&zero), unsafe.Pointer(status)); err != nil {
		return fmt.Errorf("error reading tcptracer_status: %v", err)
	}

	if status.state != stateChecked {
		if *maxRetries == 0 {
			return fmt.Errorf("invalid guessing state while guessing %v, got %v expected %v",
				whatString[status.what], stateString[status.state], stateString[stateChecked])
		} else {
			*maxRetries--
			time.Sleep(10 * time.Millisecond)
			return nil
		}
	}

	switch status.what {
	case guessSaddr:
		if status.saddr == C.__u32(expected.saddr) {
			status.what = guessDaddr
		} else {
			status.offset_saddr++
			status.saddr = C.__u32(expected.saddr)
		}
		status.state = stateChecking
	case guessDaddr:
		if status.daddr == C.__u32(expected.daddr) {
			status.what = guessFamily
		} else {
			status.offset_daddr++
			status.daddr = C.__u32(expected.daddr)
		}
		status.state = stateChecking
	case guessFamily:
		if status.family == C.__u16(expected.family) {
			status.what = guessSport
			// we know the sport ((struct inet_sock)->inet_sport) is
			// after the family field, so we start from there
			status.offset_sport = status.offset_family
		} else {
			status.offset_family++
		}
		status.state = stateChecking
	case guessSport:
		if status.sport == C.__u16(htons(expected.sport)) {
			status.what = guessDport
		} else {
			status.offset_sport++
		}
		status.state = stateChecking
	case guessDport:
		if status.dport == C.__u16(htons(expected.dport)) {
			status.what = guessNetns
		} else {
			status.offset_dport++
		}
		status.state = stateChecking
	case guessNetns:
		if status.netns == C.__u32(expected.netns) {
			status.what = guessDaddrIPv6
		} else {
			status.offset_ino++
			// go to the next offset_netns if we get an error
			if status.err != 0 || status.offset_ino >= threshold {
				status.offset_ino = 0
				status.offset_netns++
			}
		}
		status.state = stateChecking
	case guessDaddrIPv6:
		if compareIPv6(status.daddr_ipv6, expected.daddrIPv6) {
			// at this point, we've guessed all the offsets we need,
			// set the status to "stateReady"
			status.state = stateReady
		} else {
			status.offset_daddr_ipv6++
			status.state = stateChecking
		}
	default:
		return fmt.Errorf("unexpected field to guess: %v", whatString[status.what])
	}

	// update the map with the new offset/field to check
	if err := module.UpdateElement(mp, unsafe.Pointer(&zero), unsafe.Pointer(status), 0); err != nil {
		return fmt.Errorf("error updating tcptracer_status: %v", err)
	}

	return nil
}

// guess expects elf.Module to hold a tcptracer-bpf object and initializes the
// tracer by guessing the right struct sock kernel struct offsets. Results are
// stored in the `tcptracer_status` map as used by the module.
//
// To guess the offsets, we create connections from localhost (127.0.0.1) to
// 127.0.0.2:$PORT, where we have a server listening. We store the current
// possible offset and expected value of each field in a eBPF map. Each
// connection will trigger the eBPF program attached to tcp_v{4,6}_connect
// where, for each field to guess, we store the value of
//     (struct sock *)skp + possible_offset
// in the eBPF map. Then, back in userspace (checkAndUpdateCurrentOffset()), we
// check that value against the expected value of the field, advancing the
// offset and repeating the process until we find the value we expect. Then, we
// guess the next field.
func guess(b *elf.Module) error {
	currentNetns, err := ownNetNS()
	if err != nil {
		return fmt.Errorf("error getting current netns: %v", err)
	}

	mp := b.Map("tcptracer_status")

	// pid & tid must not change during the guessing work: the communication
	// between ebpf and userspace relies on it
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	pidTgid := uint64(os.Getpid())<<32 | uint64(syscall.Gettid())

	status := &tcpTracerStatus{
		state:    stateChecking,
		pid_tgid: C.__u64(pidTgid),
	}

	// if we already have the offsets, just return
	err = b.LookupElement(mp, unsafe.Pointer(&zero), unsafe.Pointer(status))
	if err == nil && status.state == stateReady {
		return nil
	}

	stop, listenPort, err := startServer()
	if err != nil {
		return err
	}
	defer close(stop)

	// initialize map
	if err := b.UpdateElement(mp, unsafe.Pointer(&zero), unsafe.Pointer(status), 0); err != nil {
		return fmt.Errorf("error initializing tcptracer_status map: %v", err)
	}

	expected := &fieldValues{
		// 127.0.0.1
		saddr: 0x0100007F,
		// 127.0.0.2
		daddr: 0x0200007F,
		// will be set later
		sport:  0,
		dport:  listenPort,
		netns:  uint32(currentNetns),
		family: syscall.AF_INET,
	}

	// if the kretprobe for tcp_v4_connect() is configured with a too-low
	// maxactive, some kretprobe might be missing. In this case, we detect
	// it and try again.
	// See https://github.com/weaveworks/tcptracer-bpf/issues/24
	var maxRetries int = 100

	for status.state != stateReady {
		if err := tryCurrentOffset(b, mp, status, expected, stop); err != nil {
			return err
		}

		if err := checkAndUpdateCurrentOffset(b, mp, status, expected, &maxRetries); err != nil {
			return err
		}

		// Stop at a reasonable offset so we don't run forever.
		// Reading too far away in kernel memory is not a big deal:
		// probe_kernel_read() handles faults gracefully.
		if status.offset_saddr >= threshold || status.offset_daddr >= threshold ||
			status.offset_sport >= thresholdInetSock || status.offset_dport >= threshold ||
			status.offset_netns >= threshold || status.offset_family >= threshold ||
			status.offset_daddr_ipv6 >= threshold {
			return fmt.Errorf("overflow while guessing %v, bailing out", whatString[status.what])
		}
	}

	return nil
}


text:
namespace cv { namespace gui {

class ChannelTopicDelegate : public QAbstractItemDelegate
{
    Q_OBJECT

    QFont m_font;

public:
    ChannelTopicDelegate(QObject *parent = NULL);

    void paint(QPainter *painter, const QStyleOptionViewItem &option,
                    const QModelIndex &index) const;

    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;

    void setFont(const QFont &font) { m_font = font; }
};

} } // End namespaces


text:
require 'tsort'

class AngryMob
  class MobLoadingError < StandardError; end

  ::Target = AngryMob::Target

  class MobLoader
    attr_reader :mobs, :loaded_mobs, :attributes

    def ui
      Rioter.ui
    end

    def initialize(attributes)
      @attributes   = attributes
      @mobs         = {}
      @mob_order    = []
      @loaded_mobs  = {}
    end

    def add_mob(path)
      mob = Mob.new(path)
      mob.load!

      mob_name = mob.name.to_s

      if mobs[ mob_name ]
        raise MobLoadingError, "Already loaded my called '#{ mob_name }'"
      end

      mobs[ mob_name ] = mob
      @mob_order << mob
    end

    def build_mobs
      @mob_order.map {|mob| build_mob mob}
    end

    def build_mob(mob)
      ui.push "setting up mob '#{ mob.name }'" do

        if mob.dependencies.present?
          ui.info "loading dependencies"
          mob.dependencies.each do |name, options|
            build_mob_named name, options
          end
        end

        ui.info "setting up"
        mob.build!(attributes)
      end
    end

    def build_mob_named(name, options)
      name = name.to_s
      mob  = mobs[name]

      raise "unable to build unknown mob '#{name}'" unless mob

      return if mob.built?

      build_mob( mob )
    end

    def to_rioter
      build_mobs

      rioter = Rioter.new

      @mob_order.each do |mob|
        mob.builder.add_to_rioter(rioter)
      end

      rioter
    end
  end
end


text:
require 'test_helper'

class ChefsEditTest < ActionDispatch::IntegrationTest
  def setup
    @chef = Chef.create!(chefname: "mashrur", email: "mashrur@example.com",
                          password: "password", password_confirmation: "password")
    @chef2 = Chef.create!(chefname: "john", email: "john@example.com",
                        password: "password", password_confirmation: "password")
    @admin_user = Chef.create!(chefname: "john1", email: "john1@example.com",
                        password: "password", password_confirmation: "password", admin: true)
  end

  test "reject an invalid edit" do
    sign_in_as(@chef, "password")
    get edit_chef_path(@chef)
    assert_template 'chefs/edit'
    patch chef_path(@chef), params: { chef: { chefname: " ", email: "mashrur@example.com" } }
    assert_template 'chefs/edit'
    assert_select 'h2.panel-title'
    assert_select 'div.panel-body'
  end

  test "accept valid edit" do
    sign_in_as(@chef, "password")
    get edit_chef_path(@chef)
    assert_template 'chefs/edit'
    patch chef_path(@chef), params: { chef: { chefname: "mashrur1", email: "mashrur1@example.com" } }
    assert_redirected_to @chef
    assert_not flash.empty?
    @chef.reload
    assert_match "mashrur1", @chef.chefname
    assert_match "mashrur1@example.com", @chef.email
  end

  test "accept edit attempt by admin user" do
    sign_in_as(@admin_user, "password")
    get edit_chef_path(@chef)
    assert_template 'chefs/edit'
    patch chef_path(@chef), params: { chef: { chefname: "mashrur3", email: "mashrur3@example.com" } }
    assert_redirected_to @chef
    assert_not flash.empty?
    @chef.reload
    assert_match "mashrur3", @chef.chefname
    assert_match "mashrur3@example.com", @chef.email
  end

  test "redirect edit attempt by another non-admin user" do
    sign_in_as(@chef2, "password")
    updated_name = "joe"
    updated_email = "joe@example.com"
    patch chef_path(@chef), params: { chef: { chefname: updated_name, email: updated_email } }
    assert_redirected_to chefs_path
    assert_not flash.empty?
    @chef.reload
    assert_match "mashrur", @chef.chefname
    assert_match "mashrur@example.com", @chef.email
  end
end


text:
namespace ash {

namespace tether {

FakeWifiHotspotDisconnector::FakeWifiHotspotDisconnector() = default;

FakeWifiHotspotDisconnector::~FakeWifiHotspotDisconnector() = default;

void FakeWifiHotspotDisconnector::DisconnectFromWifiHotspot(
    const std::string& wifi_network_guid,
    base::OnceClosure success_callback,
    StringErrorCallback error_callback) {
  last_disconnected_wifi_network_guid_ = wifi_network_guid;

  if (disconnection_error_name_.empty())
    std::move(success_callback).Run();
  else
    std::move(error_callback).Run(disconnection_error_name_);
}

}  // namespace tether

}  // namespace ash


text:
@import url(http://fonts.googleapis.com/css?family=Raleway);

#takip_form{

margin-top:30px;
white-space: nowrap;
vertical-align: top;
}
#takip_form > div {margin-left:30%;}

#takip_form label{  	margin-right:10px;
                        font:20px Raleway;
                        font-weight:bold;
                        line-height: 1.5;
					}

.jumbotron {background-color:#5cb85c; height:200px;}
.jumbotron h1 { margin-top:-25px;}

.takip-box {
height:50px;
position:fixed;
top: 0px;
transition: all 0.3s ease;
z-index:1030;
}
.takip-box.open { height:250px;
		  width:100%;}

/***        takip-box MOVEMENTS               ***/

.takip-box  {
	display: none;
}
.takip-box.open  {
	display: block;
}

/***        takip-box ENDS       ***/

/*** toglle place shape etc ****/
.toggle {
	position: fixed;
	z-index:9999!important;
	top: 5px;
	left: 44%;
	width:100px;
	cursor:pointer;
	margin:5px;
}

.toggle:hover {color:#5cb85c;}

/** toggle place etc ends***/

/*** toggle movements ****/
.toggle > .toggle-open {
	display: block;
	border:1px solid gray;
	background-color:#d4d4d4;
	width:100px;
	height:20px;
	border-radius:5px;
}

.toggle > .toggle-close {
	display: none;
}
.toggle.open  {
	top: 200px;
	transition: all 0.3s ease;
}
.toggle.open > .toggle-open {
	display: none;
}
.toggle.open > .toggle-close {
	display: inline-block;
}

/**** toggle movements enddsss ****/

/*** result form *****/
.result-form.isOpen { margin-top:40px;} /** movement of result form ***/

.result-form {
opacity:0.95;
text-align:left;
padding:20px;
margin:270px 50px 80px 20px;
display:none;
z-index:3;
position:relative;
}

#left-result {
    position:fixed;
    width:550px;
    padding-left:20px;
    height:350px;
}

#result_form {
    padding:20px;
    width:100%;
    border:3px double black;
    border-radius:5px;
    background-color:#FFFFFF;

}

#result_form .form-group {margin-left:30px;}

#result_form .form-group label{text-align: left; white-space: nowrap;}

#result_form .form-group input{margin-left:20px;}

#right-result {
    position:relative;
    margin-left:600px;
    margin-top:-23px;
}

#right-result .items form{
    margin-bottom:20px;
    border:3px solid black;
    background-color:#FFFFFF;
    border-radius:5px;
    padding:20px;
}

.items input,.items textarea {

    width:300px!important;
    resize: none;
}

#cihaz_span { 	font:20px normal Raleway;
		margin-left:100px;
		font-weight:bold;}

#left-result .form-group { display:block;}

span.required {display:none;}

.no-data {font-weight:bold;
          font-size:25px;
         text-align:center;
         margin-top:10px;
       }


text:
define([
    'controllers/module'
], function(controllers) {
    'use strict';

    controllers.controller('projectDetailController', ['$scope', '$state', 'projectsFactory', function($scope, $state, projectsFactory) {
        $scope.projects = [];
        $scope.project = {};
        $scope.project.slides = [{}];

        projectsFactory.getProjects()
            .success(function(response) {
                $scope.projects = response;

                var project = $scope.projects[$scope.projects.length - parseInt($state.params.projectIndex, 10) - 1];

                if(project) {
                    $scope.project = project;

                    $scope.project.slides.forEach(function(slide) {
                        slide.image = slide.image.replace(/&/i, '&');
                    });
                } else {
                    $state.go('404');
                }
            });
    }]);
});


text:
namespace Nez.AI.BehaviorTrees
{
	/// <summary>
	/// root class for all nodes
	/// </summary>
	public abstract class Behavior<T>
	{
		public TaskStatus Status = TaskStatus.Invalid;

		public abstract TaskStatus Update(T context);

		/// <summary>
		/// invalidate the status of the node. Composites can override this and invalidate all of their children.
		/// </summary>
		public virtual void Invalidate()
		{
			Status = TaskStatus.Invalid;
		}

		/// <summary>
		/// called immediately before execution. It is used to setup any variables that need to be reset from the previous run
		/// </summary>
		public virtual void OnStart()
		{
		}

		/// <summary>
		/// called when a task changes state to something other than running
		/// </summary>
		public virtual void OnEnd()
		{
		}

		/// <summary>
		/// tick handles calling through to update where the actual work is done. It exists so that it can call onStart/onEnd when necessary.
		/// </summary>
		/// <param name="context">Context.</param>
		internal TaskStatus Tick(T context)
		{
			if (Status == TaskStatus.Invalid)
				OnStart();

			Status = Update(context);

			if (Status != TaskStatus.Running)
				OnEnd();

			return Status;
		}
	}
}


text:
package provision_test

import (
	"fmt"
	"os"
	"testing"

	"github.com/mainflux/mainflux/errors"
	"github.com/mainflux/mainflux/provision"
	"github.com/mainflux/mainflux/provision/mocks"

	logger "github.com/mainflux/mainflux/logger"
	"github.com/stretchr/testify/assert"
)

var (
	cfg = provision.Config{
		Bootstrap: provision.Bootstrap{
			AutoWhiteList: true,
			Provision:     true,
			Content:       "",
			X509Provision: true,
		},
		Server: provision.ServiceConf{
			MfPass: "test",
			MfUser: "test@example.com",
		},
		Channels: []provision.Channel{
			provision.Channel{
				Name:     "control-channel",
				Metadata: map[string]interface{}{"type": "control"},
			},
			provision.Channel{
				Name:     "data-channel",
				Metadata: map[string]interface{}{"type": "data"},
			},
		},
		Things: []provision.Thing{
			provision.Thing{
				Name:     "thing",
				Metadata: map[string]interface{}{"external_id": "xxxxxx"},
			},
		},
	}
	log, _ = logger.New(os.Stdout, "info")
)

func TestProvision(t *testing.T) {
	// Create multiple services with different configurations.
	sdk := mocks.NewSDK()
	svc := provision.New(cfg, sdk, log)

	cases := []struct {
		desc        string
		externalID  string
		externalKey string
		svc         provision.Service
		err         error
	}{
		{
			desc:        "Provision successfully",
			externalID:  "id",
			externalKey: "key",
			svc:         svc,
			err:         nil,
		},
		{
			desc:        "Provision already existing config",
			externalID:  "id",
			externalKey: "key",
			svc:         svc,
			err:         provision.ErrFailedBootstrap,
		},
	}

	for _, tc := range cases {
		_, err := tc.svc.Provision("", tc.externalID, tc.externalKey)
		assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected `%v` got `%v`", tc.desc, tc.err, err))
	}

}


text:
package jadx.api;

import jadx.api.ResourceFile.ZipRef;
import jadx.core.codegen.CodeWriter;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxException;
import jadx.core.utils.files.InputFile;
import jadx.core.xmlgen.ResContainer;
import jadx.core.xmlgen.ResTableParser;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static jadx.core.utils.files.FileUtils.READ_BUFFER_SIZE;
import static jadx.core.utils.files.FileUtils.close;
import static jadx.core.utils.files.FileUtils.copyStream;

// TODO: move to core package
public final class ResourcesLoader {
	private static final Logger LOG = LoggerFactory.getLogger(ResourcesLoader.class);

	private static final int LOAD_SIZE_LIMIT = 10 * 1024 * 1024;

	private final JadxDecompiler jadxRef;

	ResourcesLoader(JadxDecompiler jadxRef) {
		this.jadxRef = jadxRef;
	}

	List<ResourceFile> load(List<InputFile> inputFiles) {
		List<ResourceFile> list = new ArrayList<ResourceFile>(inputFiles.size());
		for (InputFile file : inputFiles) {
			loadFile(list, file.getFile());
		}
		return list;
	}

	public interface ResourceDecoder {
		ResContainer decode(long size, InputStream is) throws IOException;
	}

	public static ResContainer decodeStream(ResourceFile rf, ResourceDecoder decoder) throws JadxException {
		ZipRef zipRef = rf.getZipRef();
		if (zipRef == null) {
			return null;
		}
		ZipFile zipFile = null;
		InputStream inputStream = null;
		ResContainer result = null;
		try {
			zipFile = new ZipFile(zipRef.getZipFile());
			ZipEntry entry = zipFile.getEntry(zipRef.getEntryName());
			if (entry == null) {
				throw new IOException("Zip entry not found: " + zipRef);
			}
			inputStream = new BufferedInputStream(zipFile.getInputStream(entry));
			result = decoder.decode(entry.getSize(), inputStream);
		} catch (Exception e) {
			throw new JadxException("Error decode: " + zipRef.getEntryName(), e);
		} finally {
			try {
				if (zipFile != null) {
					zipFile.close();
				}
			} catch (Exception e) {
				LOG.error("Error close zip file: {}", zipRef, e);
			}
			close(inputStream);
		}
		return result;
	}

	static ResContainer loadContent(final JadxDecompiler jadxRef, final ResourceFile rf) {
		try {
			return decodeStream(rf, new ResourceDecoder() {
				@Override
				public ResContainer decode(long size, InputStream is) throws IOException {
					return loadContent(jadxRef, rf, is, size);
				}
			});
		} catch (JadxException e) {
			LOG.error("Decode error", e);
			CodeWriter cw = new CodeWriter();
			cw.add("Error decode ").add(rf.getType().toString().toLowerCase());
			cw.startLine(Utils.getStackTrace(e.getCause()));
			return ResContainer.singleFile(rf.getName(), cw);
		}
	}

	private static ResContainer loadContent(JadxDecompiler jadxRef, ResourceFile rf,
			InputStream inputStream, long size) throws IOException {
		switch (rf.getType()) {
			case MANIFEST:
			case XML:
				return ResContainer.singleFile(rf.getName(),
						jadxRef.getXmlParser().parse(inputStream));

			case ARSC:
				return new ResTableParser().decodeFiles(inputStream);

			case IMG:
				return ResContainer.singleImageFile(rf.getName(), inputStream);
		}
		if (size > LOAD_SIZE_LIMIT) {
			return ResContainer.singleFile(rf.getName(),
					new CodeWriter().add("File too big, size: " + String.format("%.2f KB", size / 1024.)));
		}
		return ResContainer.singleFile(rf.getName(), loadToCodeWriter(inputStream));
	}

	private void loadFile(List<ResourceFile> list, File file) {
		if (file == null) {
			return;
		}
		ZipFile zip = null;
		try {
			zip = new ZipFile(file);
			Enumeration<? extends ZipEntry> entries = zip.entries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = entries.nextElement();
				addEntry(list, file, entry);
			}
		} catch (IOException e) {
			LOG.debug("Not a zip file: {}", file.getAbsolutePath());
		} finally {
			if (zip != null) {
				try {
					zip.close();
				} catch (Exception e) {
					LOG.error("Zip file close error: {}", file.getAbsolutePath(), e);
				}
			}
		}
	}

	private void addEntry(List<ResourceFile> list, File zipFile, ZipEntry entry) {
		if (entry.isDirectory()) {
			return;
		}
		String name = entry.getName();
		ResourceType type = ResourceType.getFileType(name);
		ResourceFile rf = new ResourceFile(jadxRef, name, type);
		rf.setZipRef(new ZipRef(zipFile, name));
		list.add(rf);
	}

	public static CodeWriter loadToCodeWriter(InputStream is) throws IOException {
		CodeWriter cw = new CodeWriter();
		ByteArrayOutputStream baos = new ByteArrayOutputStream(READ_BUFFER_SIZE);
		copyStream(is, baos);
		cw.add(baos.toString("UTF-8"));
		return cw;
	}
}


text:
package ru.furry.furview2.drivers;

import android.content.Context;

import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;

import ru.furry.furview2.database.FurryDatabase;
import ru.furry.furview2.images.FurImage;
import ru.furry.furview2.images.RemoteFurImage;
import ru.furry.furview2.system.AsyncHandlerUI;

public abstract class Driver {
    public abstract void search(String searchQuery, AsyncHandlerUI<RemoteFurImage> remoteImagesHandler);
    public abstract void getNext(AsyncHandlerUI<RemoteFurImage> remoteImagesHandler);
    public abstract boolean hasNext();
    public abstract void downloadFurImage(List<RemoteFurImage> images, List<AsyncHandlerUI<FurImage>> furImagesHandlers);
    public abstract void downloadImageFile(FurImage image, ImageAware listener, ImageLoadingListener loadingListener);
    public abstract void downloadPreviewFile(List<? extends RemoteFurImage> images, List<? extends ImageAware> listeners, List<ImageLoadingListener> loadingListeners);
    public abstract void saveToDBandStorage(FurImage image, FurryDatabase database, AsyncHandlerUI<FurImage> furImageHandler);
    public abstract void saveToDBandStorage(FurImage image, FurryDatabase database);
    public abstract void deleteFromDBandStorage(FurImage image, FurryDatabase database);
    public abstract void setSfw(boolean sfw);
    public abstract void init(String permanentStorage, Context context);

}


text:
package org.sf.cafebabe.gadget.classtree;

import javax.swing.JTree;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import org.sf.classfile.Converter;
import org.sf.classfile.Entry;
import org.sf.classfile.AttributeEntry;
import org.sf.classfile.MemberEntry;
import org.sf.classfile.EntryCollection;
import org.sf.classfile.attribute.MethodBody;

public class ClassTreeSelectionListener implements TreeSelectionListener {
  private HexEditor hexEditor;

  public ClassTreeSelectionListener(HexEditor hexEditor) {
    this.hexEditor = hexEditor;
  }

  public void valueChanged(TreeSelectionEvent event) {
    perform((JTree)event.getSource(), hexEditor);
  }

  public static void perform(JTree tree, HexEditor hexEditor) {
    TreePath path = tree.getSelectionPath();

    if(path == null) return;

    TreeNode node   = (TreeNode)path.getLastPathComponent();
    TreeNode parent = node.getParent();

    if(node instanceof MagicNumberNode) {
      MagicNumberNode magicNumberNode = (MagicNumberNode)node;

      int magicNumber = magicNumberNode.getMagicNumber();

      hexEditor.setText(Converter.toHexString(magicNumber));
    }
    else if(node instanceof VersionNode) {
      short version = ((VersionNode)node).getVersion();

      hexEditor.setText(Converter.toHexString(version));
    }
    else if(node instanceof ShortNode) {
      short value = ((ShortNode)node).getValue();

      hexEditor.setText(Converter.toHexString(value));
    }
    else if(node instanceof MethodBodyNode) {
      MethodBody methodBody = ((MethodBodyNode)node).getMethodBody();
      hexEditor.setText(Converter.toHexString((int)methodBody.length()));
    }
    else if(node instanceof ClassReferenceNode) {
      short classReference = ((ClassReferenceNode)node).getClassReference();

      hexEditor.setText(Converter.toHexString(classReference));
    }
    else if(node instanceof AttributeNode) {
      AttributeEntry attributeEntry = ((AttributeNode)node).getAttributeEntry();

      byte[] buffer = attributeEntry.getBytes();

      byte[] buffer2 = new byte[6];
      System.arraycopy(buffer, 0, buffer2, 0, 6);
      hexEditor.setText(Converter.toHexString(buffer2));
    }
    else if(node instanceof EntryNode) {
      EntryNode entryNode = (EntryNode)node;
      Entry entry = entryNode.getEntry();

      byte[] buffer = entry.getBytes();

      if(entry instanceof MemberEntry) {
        byte[] buffer2 = new byte[6];
        System.arraycopy(buffer, 0, buffer2, 0, 6);
        hexEditor.setText(Converter.toHexString(buffer2));
      }
      else {
        hexEditor.setText(Converter.toHexString(buffer));
      }
    }
    else if(node instanceof CollectionNode) {
      EntryCollection entries = ((CollectionNode)node).getEntries();
      hexEditor.setText(Converter.toHexString((short)(entries.size())));
    }
    else if(parent instanceof AttributeNode) {
      AttributeEntry attributeEntry = ((AttributeNode)parent).getAttributeEntry();

      hexEditor.setText(Converter.toHexString(attributeEntry.getBuffer()));
    }
    else {
      hexEditor.setText("");
    }
  }

}


text:
<link rel="import" href="quetzal-infinite-scroll.html">

<polymer-element name="infinite-integers" extends="quetzal-infinite-scroll">

<script>
Polymer( "infinite-integers", {
  addedElements: function( elements ) {
    elements[0].textContent = ++this.counter;
  },
  counter: 0
});
</script>

</polymer-element>


text:
class CreateCoursewareableClassrooms < ActiveRecord::Migration
  def change
    create_table :coursewareable_classrooms do |t|
      t.string      :title
      t.text        :description
      t.string      :slug,                  :null => false
      t.references  :owner
      t.integer     :memberships_count,     default: 0
      t.integer     :collaborations_count,  default: 0
      t.text        :settings

      t.timestamps
    end
    add_index :coursewareable_classrooms, :owner_id
    add_index :coursewareable_classrooms, :slug, :unique => true

  end
end


text:
<?php namespace Comodojo\WPAPI;

use \Comodojo\Exception\WPException;

abstract class WPPostObject extends WPBlogObject {

	/**
     * Wordpress post reference
     *
     * @var WPPost
     */
	protected $post = null;

    /**
     * Class constructor
     *
     * @param   WPPost $post Reference to the wordpress blog post
     * @param   int    $id   Object ID (optional)
     *
     * @throws \Comodojo\Exception\WPException
     */
    public function __construct($post, $id=0) {

        if ( is_null($post) || is_null($post->getWordpress()) || !$post->getWordpress()->isLogged() ) {

        	throw new WPException("You must be logged to access post informations");

        }

        $this->post = $post;

        $this->blog = $post->getBlog();

        $this->wp   = $post->getWordpress();

        $this->id   = intval($id);

        if ($id > 0) $this->loadFromID($id);

    }

    /**
     * Get post reference
     *
     * @return WPPost $post
     */
    public function getPost() {

    	return $this->post;

    }

}


text:
package com.webydo.tools.FailedRerun.jsystem;

import com.webydo.tools.FailedRerun.RepeatScenarioBuilder;
import com.webydo.tools.FailedRerun.Scenario;
import com.webydo.tools.FailedRerun.Test;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.security.InvalidParameterException;
import java.util.List;

/**
 * The builder of a JSystem scenario with failed tests
 */
public class JSystemScenarioBuilder extends RepeatScenarioBuilder {
    private static final Logger logger = LogManager.getLogger(JSystemScenarioBuilder.class);

    public JSystemScenarioBuilder(Scenario scenario, String scenarioName, String failedScenarioPath) throws InvalidParameterException {
        super(scenario, scenarioName, failedScenarioPath);
        logger.info("Constructor for the new JSystem scenario " + scenarioName + " of the failed scenario " + failedScenarioPath);
    }

    @Override
    public void buildNewScenario() {
        logger.info("Build the new JSystem scenario " + scenarioName);
    }

    @Override
    protected Scenario createNewScenario() {
        logger.info("Create the new JSystem scenario " + scenarioName);
        return null;
    }

    @Override
    protected List<Test> getFailedTests() {
        logger.info("Get the the failed test of the JSystem scenario " + failedScenarioPath);
        return null;
    }
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames/bind';
import Dropdown from '../Dropdown';
import styles from './Item.styl';

const cx = styles::classNames;

class Item extends Component {
  static propTypes = {
    item: PropTypes.shape({
      id: PropTypes.string,
      name: PropTypes.string,
      mobileHref: PropTypes.string,
      dropdownClass: PropTypes.string,
      simpleList: PropTypes.bool,
      children: PropTypes.arrayOf(PropTypes.object)
    }),
    theme: PropTypes.string,
    simpleList: PropTypes.bool,
    closeHeaderDropdown: PropTypes.func,
    mobile: PropTypes.bool
  };

  state = {
    openDropdown: false
  };

  handleDropdown = e => {
    const { openDropdown } = this.state;
    const { mobile } = this.props;
    const isMobile = mobile;
    const shouldOpenDropdown = ['mouseenter', 'focus'].indexOf(e.type) > -1;

    if (shouldOpenDropdown === openDropdown || isMobile) return;

    this.setState({ openDropdown: shouldOpenDropdown });
  };

  closeItemDropdown = () => {
    const isDesktop = !this.props.mobile;
    const isDropdownOpen = this.state.openDropdown;

    if (isDesktop && isDropdownOpen) {
      this.setState({ openDropdown: false });
    }
  };

  closeDropdowns = () => {
    this.closeItemDropdown();
    this.props.closeHeaderDropdown();
  };

  render() {
    const { item, theme, simpleList, mobile } = this.props;

    const linkContent = <ItemContent name={item.name} childrens={item.childrens} theme={theme} />;
    const linkHref = (mobile ? item.mobileHref : null) || item.href;
    const linkExternal = item.external ? 'external' : null;

    return (
      <li
        className={cx('item', [`item-${item.id}`], [`theme-${theme}`], {
          'simple-list': simpleList,
          'is-dropdown-open': this.state.openDropdown
        })}
        onMouseEnter={this.handleDropdown}
        onFocus={this.handleDropdown}
        onMouseLeave={this.handleDropdown}
        onBlur={this.handleDropdown}
        role="menuitem"
        aria-haspopup="true"
      >
        {linkHref
          ?
              {linkContent}

          : {linkContent}}
        {item.childrens
          ? <Dropdown
              data={item}
              closeDropdowns={this.closeDropdowns}
              open={this.state.openDropdown}
            />
          : null}

    );
  }
}

export default Item;

const ItemContent = ({ name, childrens, theme }) =>

    {name}
    {childrens
      ? <svg width="8" height="4" viewBox="62 7 10 6" className={cx('item-caret')}>
          <path
            // eslint-disable-next-line max-len
            d="M71.884 7.698l-4.56 5.116c-.013.022-.008.05-.026.07-.083.084-.192.12-.3.116-.106.004-.214-.033-.295-.117-.02-.02-.014-.047-.028-.068L62.115 7.7c-.154-.16-.154-.42 0-.58.156-.16.408-.16.563 0L67 11.97l4.322-4.85c.155-.16.406-.16.56 0 .157.16.157.418.002.578z"
            fill={theme === 'dark' ? '#fff' : '#000'}
          />
        </svg>
      : null}
    {childrens ?  : null}
  ;

ItemContent.propTypes = {
  name: PropTypes.string,
  childrens: PropTypes.array,
  theme: PropTypes.string
};


text:
<?php

class Shortcodes_Exception extends Exception
{

}


text:
namespace net {

namespace {

// TTL for the per-request DNS cache. Applies to both successful and failed
// DNS resolutions.
const unsigned kCacheEntryTTLSeconds = 5 * 60;

// Event parameters for a PAC error message (line number + message).
class ErrorNetlogParams : public NetLog::EventParameters {
 public:
  ErrorNetlogParams(int line_number,
                    const string16& message)
      : line_number_(line_number),
        message_(message) {
  }

  virtual Value* ToValue() const OVERRIDE {
    DictionaryValue* dict = new DictionaryValue();
    dict->SetInteger("line_number", line_number_);
    dict->SetString("message", message_);
    return dict;
  }

 private:
  const int line_number_;
  const string16 message_;

  DISALLOW_COPY_AND_ASSIGN(ErrorNetlogParams);
};

// Event parameters for a PAC alert().
class AlertNetlogParams : public NetLog::EventParameters {
 public:
  explicit AlertNetlogParams(const string16& message) : message_(message) {
  }

  virtual Value* ToValue() const OVERRIDE {
    DictionaryValue* dict = new DictionaryValue();
    dict->SetString("message", message_);
    return dict;
  }

 private:
  const string16 message_;

  DISALLOW_COPY_AND_ASSIGN(AlertNetlogParams);
};

// ProxyResolverJSBindings implementation.
class DefaultJSBindings : public ProxyResolverJSBindings {
 public:
  DefaultJSBindings(SyncHostResolver* host_resolver,
                    NetLog* net_log,
                    ProxyResolverErrorObserver* error_observer)
      : host_resolver_(host_resolver),
        net_log_(net_log),
        error_observer_(error_observer) {
  }

  // Handler for "alert(message)".
  virtual void Alert(const string16& message) OVERRIDE {
    VLOG(1) << "PAC-alert: " << message;

    // Send to the NetLog.
    LogEventToCurrentRequestAndGlobally(NetLog::TYPE_PAC_JAVASCRIPT_ALERT,
                                        new AlertNetlogParams(message));
  }

  // Handler for "myIpAddress()".
  // TODO(eroman): Perhaps enumerate the interfaces directly, using
  // getifaddrs().
  virtual bool MyIpAddress(std::string* first_ip_address) OVERRIDE {
    LogEventToCurrentRequest(NetLog::PHASE_BEGIN,
                             NetLog::TYPE_PAC_JAVASCRIPT_MY_IP_ADDRESS,
                             NULL);

    bool ok = MyIpAddressImpl(first_ip_address);

    LogEventToCurrentRequest(NetLog::PHASE_END,
                             NetLog::TYPE_PAC_JAVASCRIPT_MY_IP_ADDRESS,
                             NULL);
    return ok;
  }

  // Handler for "myIpAddressEx()".
  virtual bool MyIpAddressEx(std::string* ip_address_list) OVERRIDE {
    LogEventToCurrentRequest(NetLog::PHASE_BEGIN,
                             NetLog::TYPE_PAC_JAVASCRIPT_MY_IP_ADDRESS_EX,
                             NULL);

    bool ok = MyIpAddressExImpl(ip_address_list);

    LogEventToCurrentRequest(NetLog::PHASE_END,
                             NetLog::TYPE_PAC_JAVASCRIPT_MY_IP_ADDRESS_EX,
                             NULL);
    return ok;
  }

  // Handler for "dnsResolve(host)".
  virtual bool DnsResolve(const std::string& host,
                          std::string* first_ip_address) OVERRIDE {
    LogEventToCurrentRequest(NetLog::PHASE_BEGIN,
                             NetLog::TYPE_PAC_JAVASCRIPT_DNS_RESOLVE,
                             NULL);

    bool ok = DnsResolveImpl(host, first_ip_address);

    LogEventToCurrentRequest(NetLog::PHASE_END,
                             NetLog::TYPE_PAC_JAVASCRIPT_DNS_RESOLVE,
                             NULL);
    return ok;
  }

  // Handler for "dnsResolveEx(host)".
  virtual bool DnsResolveEx(const std::string& host,
                            std::string* ip_address_list) OVERRIDE {
    LogEventToCurrentRequest(NetLog::PHASE_BEGIN,
                             NetLog::TYPE_PAC_JAVASCRIPT_DNS_RESOLVE_EX,
                             NULL);

    bool ok = DnsResolveExImpl(host, ip_address_list);

    LogEventToCurrentRequest(NetLog::PHASE_END,
                             NetLog::TYPE_PAC_JAVASCRIPT_DNS_RESOLVE_EX,
                             NULL);
    return ok;
  }

  // Handler for when an error is encountered. |line_number| may be -1.
  virtual void OnError(int line_number, const string16& message) OVERRIDE {
    // Send to the chrome log.
    if (line_number == -1)
      VLOG(1) << "PAC-error: " << message;
    else
      VLOG(1) << "PAC-error: " << "line: " << line_number << ": " << message;

    // Send the error to the NetLog.
    LogEventToCurrentRequestAndGlobally(
        NetLog::TYPE_PAC_JAVASCRIPT_ERROR,
        new ErrorNetlogParams(line_number, message));

    if (error_observer_.get())
      error_observer_->OnPACScriptError(line_number, message);
  }

  virtual void Shutdown() OVERRIDE {
    host_resolver_->Shutdown();
  }

 private:
  bool MyIpAddressImpl(std::string* first_ip_address) {
    std::string my_hostname = GetHostName();
    if (my_hostname.empty())
      return false;
    return DnsResolveImpl(my_hostname, first_ip_address);
  }

  bool MyIpAddressExImpl(std::string* ip_address_list) {
    std::string my_hostname = GetHostName();
    if (my_hostname.empty())
      return false;
    return DnsResolveExImpl(my_hostname, ip_address_list);
  }

  bool DnsResolveImpl(const std::string& host,
                      std::string* first_ip_address) {
    // Do a sync resolve of the hostname (port doesn't matter).
    // Disable IPv6 results. We do this because the PAC specification isn't
    // really IPv6 friendly, and Internet Explorer also restricts to IPv4.
    // Consequently a lot of existing PAC scripts assume they will only get
    // IPv4 results, and will misbehave if they get an IPv6 result.
    // See http://crbug.com/24641 for more details.
    HostResolver::RequestInfo info(HostPortPair(host, 80));
    info.set_address_family(ADDRESS_FAMILY_IPV4);
    AddressList address_list;

    int result = DnsResolveHelper(info, &address_list);
    if (result != OK)
      return false;

    // There may be multiple results; we will just use the first one.
    // This returns empty string on failure.
    *first_ip_address = net::NetAddressToString(address_list.head());
    if (first_ip_address->empty())
      return false;

    return true;
  }

  bool DnsResolveExImpl(const std::string& host,
                        std::string* ip_address_list) {
    // Do a sync resolve of the hostname (port doesn't matter).
    HostResolver::RequestInfo info(HostPortPair(host, 80));
    AddressList address_list;
    int result = DnsResolveHelper(info, &address_list);

    if (result != OK)
      return false;

    // Stringify all of the addresses in the address list, separated
    // by semicolons.
    std::string address_list_str;
    const struct addrinfo* current_address = address_list.head();
    while (current_address) {
      if (!address_list_str.empty())
        address_list_str += ";";
      const std::string address_string = NetAddressToString(current_address);
      if (address_string.empty())
        return false;
      address_list_str += address_string;
      current_address = current_address->ai_next;
    }

    *ip_address_list = address_list_str;
    return true;
  }

  // Helper to execute a synchronous DNS resolve, using the per-request
  // DNS cache if there is one.
  int DnsResolveHelper(const HostResolver::RequestInfo& info,
                       AddressList* address_list) {
    HostCache::Key cache_key(info.hostname(),
                             info.address_family(),
                             info.host_resolver_flags());

    HostCache* host_cache = current_request_context() ?
        current_request_context()->host_cache : NULL;

    // First try to service this request from the per-request DNS cache.
    // (we cache DNS failures much more aggressively within the context
    // of a FindProxyForURL() request).
    if (host_cache) {
      const HostCache::Entry* entry =
          host_cache->Lookup(cache_key, base::TimeTicks::Now());
      if (entry) {
        if (entry->error == OK)
          *address_list = entry->addrlist;
        return entry->error;
      }
    }

    // Otherwise ask the host resolver.
    const BoundNetLog* net_log = GetNetLogForCurrentRequest();
    int result = host_resolver_->Resolve(info,
                                         address_list,
                                         net_log ? *net_log : BoundNetLog());

    // Save the result back to the per-request DNS cache.
    if (host_cache) {
      host_cache->Set(cache_key, result, *address_list,
                      base::TimeTicks::Now(),
                      base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds));
    }

    return result;
  }

  // May return NULL.
  const BoundNetLog* GetNetLogForCurrentRequest() {
    if (!current_request_context())
      return NULL;
    return current_request_context()->net_log;
  }

  void LogEventToCurrentRequest(
      NetLog::EventPhase phase,
      NetLog::EventType type,
      scoped_refptr<NetLog::EventParameters> params) {
    const BoundNetLog* net_log = GetNetLogForCurrentRequest();
    if (net_log)
      net_log->AddEntry(type, phase, params);
  }

  void LogEventToCurrentRequestAndGlobally(
      NetLog::EventType type,
      scoped_refptr<NetLog::EventParameters> params) {
    LogEventToCurrentRequest(NetLog::PHASE_NONE, type, params);

    // Emit to the global NetLog event stream.
    if (net_log_)
      net_log_->AddGlobalEntry(type, params);
  }

  scoped_ptr<SyncHostResolver> host_resolver_;
  NetLog* net_log_;
  scoped_ptr<ProxyResolverErrorObserver> error_observer_;
  DISALLOW_COPY_AND_ASSIGN(DefaultJSBindings);
};

}  // namespace

// static
ProxyResolverJSBindings* ProxyResolverJSBindings::CreateDefault(
    SyncHostResolver* host_resolver,
    NetLog* net_log,
    ProxyResolverErrorObserver* error_observer) {
  return new DefaultJSBindings(host_resolver, net_log, error_observer);
}

}  // namespace net


text:
<?xml version="1.0" encoding="UTF-8"?>

<screens xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://ofbiz.apache.org/Widget-Screen" xsi:schemaLocation="http://ofbiz.apache.org/Widget-Screen http://ofbiz.apache.org/dtds/widget-screen.xsd">
    <screen name="CommonPriceDecorator">

            <widgets>
                <decorator-screen name="main-decorator"  location="${parameters.mainDecoratorLocation}">
                    <decorator-section name="left-column">
                        <include-screen name="leftbar" location="component://product/widget/catalog/CommonScreens.xml"/>
                    </decorator-section>
                    <decorator-section name="body">

                            <condition>
                                <if-has-permission permission="CATALOG" action="_VIEW"/>
                            </condition>
                            <widgets>
                                <decorator-section-include name="body"/>
                            </widgets>
                            <fail-widgets>
                                ${uiLabelMap.ProductCatalogViewPermissionError}
                            </fail-widgets>

                    </decorator-section>
                </decorator-screen>
            </widgets>

    </screen>
    <screen name="FindProductPriceRule">

            <actions>
                <set field="titleProperty" value="PageTitleFindProductPriceRule"/>
                <set field="headerItem" value="pricerules"/>
                <set field="viewIndex" from-field="parameters.VIEW_INDEX" type="Integer" default-value="0"/>
                <set field="viewSizeDefaultValue" value="${groovy: modelTheme.getDefaultViewSize()}" type="Integer"/>
                <set field="viewSize" from-field="parameters.VIEW_SIZE" type="Integer" default-value="${viewSizeDefaultValue}"/>
            </actions>
            <widgets>
                <decorator-screen name="CommonPriceDecorator">
                    <decorator-section name="body">
                        <screenlet title="${uiLabelMap.ProductGlobalPriceRules}">
                            <include-form name="FindProductPriceRules" location="component://product/widget/catalog/PriceForms.xml"/>
                        </screenlet>
                        <screenlet title="${uiLabelMap.ProductAddPriceRule}">
                            <include-form name="AddPriceRules" location="component://product/widget/catalog/PriceForms.xml"/>
                        </screenlet>
                    </decorator-section>
                </decorator-screen>
            </widgets>

    </screen>
    <screen name="EditProductPriceRules">

            <actions>
                <set field="titleProperty" value="PageTitleEditProductPriceRules"/>
                <set field="headerItem" value="pricerules"/>


text:
// RequireJS.NET
// Copyright VeriTech.io
// http://veritech.io
// Dual licensed under the MIT and GPL licenses:
// http://www.opensource.org/licenses/mit-license.php
// http://www.gnu.org/licenses/gpl.html

using System.Collections.Generic;

namespace RequireJsNet.Models
{
    public class RequireShim
    {
        public List<ShimEntry> ShimEntries { get; set; }
    }
}


text:
class AddRaceRejectionDefaults < ActiveRecord::Migration[6.1]
  def change
    Race.where(rejected: nil).update_all(rejected: false)
    change_column :races, :rejected, :boolean, null: false, default: false
  end
end


text:
/**
 * Created by Vayne-Lover on 2/21/17.
 */
public class SimpleDotGame {
    private int numberOfHits=0;
    private int[] location;

    public void setLocation(int[] location1){
        location=location1;
    }

    public int[] getLocation(){
        return location;
    }

    public void check(String guessNumber){
        int guess=Integer.parseInt(guessNumber);
        String result="miss";
        for(int loc:location){
            if(guess==loc){
                result="hit";
                numberOfHits+=1;
                break;
            }
        }
        if(numberOfHits==location.length){
            result="kill";
        }
        System.out.println(result);

    }
}