Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    ArrowInvalid
Message:      JSON parse error: Missing a closing quotation mark in string. in row 533
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 145, in _generate_tables
                  dataset = json.load(f)
                File "/usr/local/lib/python3.9/json/__init__.py", line 293, in load
                  return loads(fp.read(),
                File "/usr/local/lib/python3.9/json/__init__.py", line 346, in loads
                  return _default_decoder.decode(s)
                File "/usr/local/lib/python3.9/json/decoder.py", line 340, in decode
                  raise JSONDecodeError("Extra data", s, end)
              json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2607)
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1995, in _prepare_split_single
                  for _, table in generator:
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 148, in _generate_tables
                  raise e
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 122, in _generate_tables
                  pa_table = paj.read_json(
                File "pyarrow/_json.pyx", line 308, in pyarrow._json.read_json
                File "pyarrow/error.pxi", line 154, in pyarrow.lib.pyarrow_internal_check_status
                File "pyarrow/error.pxi", line 91, in pyarrow.lib.check_status
              pyarrow.lib.ArrowInvalid: JSON parse error: Missing a closing quotation mark in string. in row 533
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

text
string
meta
dict
<?php /** * Created by PhpStorm. * User: Admin * Date: 30.12.2016 * Time: 10:11 */ use kartik\grid\ExpandRowColumn; use kartik\grid\FormulaColumn; use yii\data\ActiveDataProvider; use yii\helpers\Html; use yii\widgets\Pjax; use yiicms\components\core\Url; use yii\web\View; use yiicms\components\core\widgets\Alert; use yiicms\models\core\Log; use yiicms\modules\admin\components\adminlte\GridView; /** * @var View $this * @var \yiicms\modules\admin\models\ErrorsSearch $model * @var ActiveDataProvider $dataProvider Data provider */ $gridConfig = [ 'id' => 'errors-grid', 'dataProvider' => $dataProvider, 'filterModel' => $model, 'responsive' => true, 'hover' => true, 'columns' => [ [ 'class' => ExpandRowColumn::class, 'value' => function () { return GridView::ROW_COLLAPSED; }, 'detail' => function ($model) { /** @var Log $model */ return '<pre>' . $model->message . '</pre>'; }, ], [ 'attribute' => 'log_time', 'class' => FormulaColumn::class, 'format' => 'raw', 'value' => function ($model) { /**@var $model Log */ return Html::a( \Yii::$app->formatter->asDatetime(round($model->log_time)), Url::toWithNewReturn(['/admin/errors/view', 'id' => $model['id']]), ['data-click' => 1] ); }, ], 'level', 'category', 'prefix', ], ]; ?> <div class="row"> <div class="col-md-12 col-sm-12"> <?php Pjax::begin() ?> <?php Alert::widget() ?> <?= GridView::widget($gridConfig); ?> <?php Pjax::end() ?> </div> </div>
{ "content_hash": "6bdf7c2cf315c1481adb9ee2d9012a9f", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 87, "avg_line_length": 26.36231884057971, "alnum_prop": 0.5046728971962616, "repo_name": "muratymt/yiicms", "id": "e78cc543a5abb8e4d003011af9882d361340644e", "size": "1819", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/admin/views/errors/index.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "766" }, { "name": "Batchfile", "bytes": "515" }, { "name": "CSS", "bytes": "129978" }, { "name": "JavaScript", "bytes": "92722" }, { "name": "PHP", "bytes": "1228539" } ] }
package com.amazonaws.services.ec2.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * InstanceMaintenanceOptionsRequest StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InstanceMaintenanceOptionsRequestStaxUnmarshaller implements Unmarshaller<InstanceMaintenanceOptionsRequest, StaxUnmarshallerContext> { public InstanceMaintenanceOptionsRequest unmarshall(StaxUnmarshallerContext context) throws Exception { InstanceMaintenanceOptionsRequest instanceMaintenanceOptionsRequest = new InstanceMaintenanceOptionsRequest(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return instanceMaintenanceOptionsRequest; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("AutoRecovery", targetDepth)) { instanceMaintenanceOptionsRequest.setAutoRecovery(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return instanceMaintenanceOptionsRequest; } } } } private static InstanceMaintenanceOptionsRequestStaxUnmarshaller instance; public static InstanceMaintenanceOptionsRequestStaxUnmarshaller getInstance() { if (instance == null) instance = new InstanceMaintenanceOptionsRequestStaxUnmarshaller(); return instance; } }
{ "content_hash": "af89c88153a38560c7c61ecd38004662", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 148, "avg_line_length": 37.833333333333336, "alnum_prop": 0.7077826725403817, "repo_name": "aws/aws-sdk-java", "id": "fc611779f3cb4ab784326de881ac3fcc07d020e2", "size": "2623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/InstanceMaintenanceOptionsRequestStaxUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [] }
using System; using System.Xml; using System.Drawing; using System.Windows.Forms; using IDE.Common; using IDE.Docking; using IDE.Collections; namespace IDE.Docking { internal class Restore { // Instance fields protected Restore _child; public Restore() { // Default state _child = null; } public Restore(Restore child) { // Remember parameter _child = child; } public Restore Child { get { return _child; } set { _child = value; } } public virtual void PerformRestore(DockingManager dm) {} public virtual void PerformRestore(Window w) {} public virtual void PerformRestore(Zone z) {} public virtual void PerformRestore() {} public virtual void Reconnect(DockingManager dm) { if (_child != null) _child.Reconnect(dm); } public virtual void SaveToXml(XmlTextWriter xmlOut) { // Must define my type so loading can recreate my instance xmlOut.WriteAttributeString("Type", this.GetType().ToString()); SaveInternalToXml(xmlOut); // Output the child object xmlOut.WriteStartElement("Child"); if (_child == null) xmlOut.WriteAttributeString("Type", "null"); else _child.SaveToXml(xmlOut); xmlOut.WriteEndElement(); } public virtual void LoadFromXml(XmlTextReader xmlIn, int formatVersion) { LoadInternalFromXml(xmlIn, formatVersion); // Move to next xml node if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.Name != "Child") throw new ArgumentException("Node 'Child' expected but not found"); string type = xmlIn.GetAttribute(0); if (type != "null") _child = CreateFromXml(xmlIn, false, formatVersion); // Move past the end element if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.NodeType != XmlNodeType.EndElement) throw new ArgumentException("EndElement expected but not found"); } public virtual void SaveInternalToXml(XmlTextWriter xmlOut) {} public virtual void LoadInternalFromXml(XmlTextReader xmlIn, int formatVersion) {} public static Restore CreateFromXml(XmlTextReader xmlIn, bool readIn, int formatVersion) { if (readIn) { // Move to next xml node if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); } // Grab type name of the object to create string attrType = xmlIn.GetAttribute(0); // Convert from string to a Type description object Type newType = Type.GetType(attrType); // Create an instance of this object which must derive from Restore base class Restore newRestore = newType.Assembly.CreateInstance(attrType) as Restore; // Ask the object to load itself newRestore.LoadFromXml(xmlIn, formatVersion); return newRestore; } } internal class RestoreContent : Restore { // Instance fields protected String _title; protected Content _content; public RestoreContent() : base() { // Default state _title = ""; _content = null; } public RestoreContent(Content content) : base() { // Remember parameter _title = content.Title; _content = content; } public RestoreContent(Restore child, Content content) : base(child) { // Remember parameter _title = content.Title; _content = content; } public override void Reconnect(DockingManager dm) { // Connect to the current instance of required content object _content = dm.Contents[_title]; base.Reconnect(dm); } public override void SaveInternalToXml(XmlTextWriter xmlOut) { base.SaveInternalToXml(xmlOut); xmlOut.WriteStartElement("Content"); xmlOut.WriteAttributeString("Name", _content.Title); xmlOut.WriteEndElement(); } public override void LoadInternalFromXml(XmlTextReader xmlIn, int formatVersion) { base.LoadInternalFromXml(xmlIn, formatVersion); // Move to next xml node if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.Name != "Content") throw new ArgumentException("Node 'Content' expected but not found"); // Grab type name of the object to create _title = xmlIn.GetAttribute(0); } } internal class RestoreContentState : RestoreContent { // Instance fields protected State _state; public RestoreContentState() : base() { } public RestoreContentState(State state, Content content) : base(content) { // Remember parameter _state = state; } public RestoreContentState(Restore child, State state, Content content) : base(child, content) { // Remember parameter _state = state; } public override void PerformRestore(DockingManager dm) { // Use the existing DockingManager method that will create a Window appropriate for // this Content and then add a new Zone for hosting the Window. It will always place // the Zone at the inner most level dm.AddContentWithState(_content, _state); } public override void SaveInternalToXml(XmlTextWriter xmlOut) { base.SaveInternalToXml(xmlOut); xmlOut.WriteStartElement("State"); xmlOut.WriteAttributeString("Value", _state.ToString()); xmlOut.WriteEndElement(); } public override void LoadInternalFromXml(XmlTextReader xmlIn, int formatVersion) { base.LoadInternalFromXml(xmlIn, formatVersion); // Move to next xml node if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.Name != "State") throw new ArgumentException("Node 'State' expected but not found"); // Grab type state of the object to create string attrState = xmlIn.GetAttribute(0); // Convert from string to enumeration value _state = (State)Enum.Parse(typeof(State), attrState); } } internal class RestoreAutoHideState : RestoreContentState { // Instance fields public RestoreAutoHideState() : base() { } public RestoreAutoHideState(State state, Content content) : base(state, content) { } public RestoreAutoHideState(Restore child, State state, Content content) : base(child, state, content) { } public override void PerformRestore(DockingManager dm) { // Create collection of Contents to auto hide ContentCollection cc = new ContentCollection(); // In this case, there is only one cc.Add(_content); // Add to appropriate AutoHidePanel based on _state dm.AutoHideContents(cc, _state); } } internal class RestoreAutoHideAffinity : RestoreAutoHideState { // Instance fields protected StringCollection _next; protected StringCollection _previous; protected StringCollection _nextAll; protected StringCollection _previousAll; public RestoreAutoHideAffinity() : base() { // Must always point to valid reference _next = new StringCollection(); _previous = new StringCollection(); _nextAll = new StringCollection(); _previousAll = new StringCollection(); } public RestoreAutoHideAffinity(Restore child, State state, Content content, StringCollection next, StringCollection previous, StringCollection nextAll, StringCollection previousAll) : base(child, state, content) { // Remember parameters _next = next; _previous = previous; _nextAll = nextAll; _previousAll = previousAll; } public override void PerformRestore(DockingManager dm) { // Get the correct target panel from state AutoHidePanel ahp = dm.AutoHidePanelForState(_state); ahp.AddContent(_content, _next, _previous, _nextAll, _previousAll); } public override void SaveInternalToXml(XmlTextWriter xmlOut) { base.SaveInternalToXml(xmlOut); _next.SaveToXml("Next", xmlOut); _previous.SaveToXml("Previous", xmlOut); _nextAll.SaveToXml("NextAll", xmlOut); _previousAll.SaveToXml("PreviousAll", xmlOut); } public override void LoadInternalFromXml(XmlTextReader xmlIn, int formatVersion) { base.LoadInternalFromXml(xmlIn, formatVersion); _next.LoadFromXml("Next", xmlIn); _previous.LoadFromXml("Previous", xmlIn); _nextAll.LoadFromXml("NextAll", xmlIn); _previousAll.LoadFromXml("PreviousAll", xmlIn); } } internal class RestoreContentDockingAffinity : RestoreContentState { // Instance fields protected Size _size; protected Point _location; protected StringCollection _best; protected StringCollection _next; protected StringCollection _previous; protected StringCollection _nextAll; protected StringCollection _previousAll; public RestoreContentDockingAffinity() : base() { // Must always point to valid reference _best = new StringCollection(); _next = new StringCollection(); _previous = new StringCollection(); _nextAll = new StringCollection(); _previousAll = new StringCollection(); } public RestoreContentDockingAffinity(Restore child, State state, Content content, StringCollection best, StringCollection next, StringCollection previous, StringCollection nextAll, StringCollection previousAll) : base(child, state, content) { // Remember parameters _best = best; _next = next; _previous = previous; _nextAll = nextAll; _previousAll = previousAll; _size = content.DisplaySize; _location = content.DisplayLocation; } public override void PerformRestore(DockingManager dm) { int count = dm.Container.Controls.Count; int min = -1; int max = count; if (dm.InnerControl != null) min = dm.Container.Controls.IndexOf(dm.InnerControl); if (dm.OuterControl != null) max = dm.OuterControlIndex(); int beforeIndex = -1; int afterIndex = max; int beforeAllIndex = -1; int afterAllIndex = max; // Create a collection of the Zones in the appropriate direction for(int index=0; index<count; index++) { Zone z = dm.Container.Controls[index] as Zone; if (z != null) { StringCollection sc = ZoneHelper.ContentNames(z); if (_state == z.State) { if (sc.Contains(_best)) { // Can we delegate to a child Restore object if (_child != null) _child.PerformRestore(z); else { // Just add an appropriate Window to start of the Zone dm.AddContentToZone(_content, z, 0); } return; } // If the WindowContent contains a Content previous to the target if (sc.Contains(_previous)) { if (index > beforeIndex) beforeIndex = index; } // If the WindowContent contains a Content next to the target if (sc.Contains(_next)) { if (index < afterIndex) afterIndex = index; } } else { // If the WindowContent contains a Content previous to the target if (sc.Contains(_previousAll)) { if (index > beforeAllIndex) beforeAllIndex = index; } // If the WindowContent contains a Content next to the target if (sc.Contains(_nextAll)) { if (index < afterAllIndex) afterAllIndex = index; } } } } dm.Container.SuspendLayout(); // Create a new Zone with correct State Zone newZ = dm.CreateZoneForContent(_state); // Restore the correct content size/location values _content.DisplaySize = _size; _content.DisplayLocation = _location; // Add an appropriate Window to start of the Zone dm.AddContentToZone(_content, newZ, 0); // Did we find a valid 'before' Zone? if (beforeIndex != -1) { // Try and place more accurately according to other edge Zones if (beforeAllIndex > beforeIndex) beforeIndex = beforeAllIndex; // Check against limits if (beforeIndex >= max) beforeIndex = max - 1; dm.Container.Controls.SetChildIndex(newZ, beforeIndex + 1); } else { // Try and place more accurately according to other edge Zones if (afterAllIndex < afterIndex) afterIndex = afterAllIndex; // Check against limits if (afterIndex <= min) afterIndex = min + 1; if (afterIndex > min) dm.Container.Controls.SetChildIndex(newZ, afterIndex); else { // Set the Zone to be the least important of our Zones dm.ReorderZoneToInnerMost(newZ); } } dm.Container.ResumeLayout(); } public override void SaveInternalToXml(XmlTextWriter xmlOut) { base.SaveInternalToXml(xmlOut); xmlOut.WriteStartElement("Position"); xmlOut.WriteAttributeString("Size", ConversionHelper.SizeToString(_size)); xmlOut.WriteAttributeString("Location", ConversionHelper.PointToString(_location)); xmlOut.WriteEndElement(); _best.SaveToXml("Best", xmlOut); _next.SaveToXml("Next", xmlOut); _previous.SaveToXml("Previous", xmlOut); _nextAll.SaveToXml("NextAll", xmlOut); _previousAll.SaveToXml("PreviousAll", xmlOut); } public override void LoadInternalFromXml(XmlTextReader xmlIn, int formatVersion) { base.LoadInternalFromXml(xmlIn, formatVersion); // Move to next xml node if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.Name != "Position") throw new ArgumentException("Node 'Position' expected but not found"); // Grab raw position information string attrSize = xmlIn.GetAttribute(0); string attrLocation = xmlIn.GetAttribute(1); // Convert from string to proper types _size = ConversionHelper.StringToSize(attrSize); _location = ConversionHelper.StringToPoint(attrLocation); _best.LoadFromXml("Best", xmlIn); _next.LoadFromXml("Next", xmlIn); _previous.LoadFromXml("Previous", xmlIn); _nextAll.LoadFromXml("NextAll", xmlIn); _previousAll.LoadFromXml("PreviousAll", xmlIn); } } internal class RestoreContentFloatingAffinity : RestoreContentState { // Instance fields protected Size _size; protected Point _location; protected StringCollection _best; protected StringCollection _associates; public RestoreContentFloatingAffinity() : base() { // Must always point to valid reference _best = new StringCollection(); _associates = new StringCollection(); } public RestoreContentFloatingAffinity(Restore child, State state, Content content, StringCollection best, StringCollection associates) : base(child, state, content) { // Remember parameters _best = best; _associates = associates; _size = content.DisplaySize; _location = content.DisplayLocation; // Remove target from collection of friends if (_best.Contains(content.Title)) _best.Remove(content.Title); // Remove target from collection of associates if (_associates.Contains(content.Title)) _associates.Remove(content.Title); } public override void PerformRestore(DockingManager dm) { // Grab a list of all floating forms Form[] owned = dm.Container.FindForm().OwnedForms; FloatingForm target = null; // Find the match to one of our best friends foreach(Form f in owned) { FloatingForm ff = f as FloatingForm; if (ff != null) { if (ZoneHelper.ContentNames(ff.Zone).Contains(_best)) { target = ff; break; } } } // If no friends then try associates as second best option if (target == null) { // Find the match to one of our best friends foreach(Form f in owned) { FloatingForm ff = f as FloatingForm; if (ff != null) { if (ZoneHelper.ContentNames(ff.Zone).Contains(_associates)) { target = ff; break; } } } } // If we found a friend/associate, then restore to it if (target != null) { // We should have a child and be able to restore to its Zone _child.PerformRestore(target.Zone); } else { // Restore its location/size _content.DisplayLocation = _location; _content.DisplaySize = _size; // Use the docking manage method to create us a new Floating Window at correct size/location dm.AddContentWithState(_content, State.Floating); } } public override void SaveInternalToXml(XmlTextWriter xmlOut) { base.SaveInternalToXml(xmlOut); xmlOut.WriteStartElement("Position"); xmlOut.WriteAttributeString("Size", ConversionHelper.SizeToString(_size)); xmlOut.WriteAttributeString("Location", ConversionHelper.PointToString(_location)); xmlOut.WriteEndElement(); _best.SaveToXml("Best", xmlOut); _associates.SaveToXml("Associates", xmlOut); } public override void LoadInternalFromXml(XmlTextReader xmlIn, int formatVersion) { base.LoadInternalFromXml(xmlIn, formatVersion); // Move to next xml node if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.Name != "Position") throw new ArgumentException("Node 'Position' expected but not found"); // Grab raw position information string attrSize = xmlIn.GetAttribute(0); string attrLocation = xmlIn.GetAttribute(1); // Convert from string to proper types _size = ConversionHelper.StringToSize(attrSize); _location = ConversionHelper.StringToPoint(attrLocation); _best.LoadFromXml("Best", xmlIn); _associates.LoadFromXml("Associates", xmlIn); } } internal class RestoreZoneAffinity : RestoreContent { // Instance fields protected Decimal _space; protected StringCollection _best; protected StringCollection _next; protected StringCollection _previous; public RestoreZoneAffinity() : base() { // Default state _space = 50m; // Must always point to valid reference _best = new StringCollection(); _next = new StringCollection(); _previous = new StringCollection(); } public RestoreZoneAffinity(Restore child, Content content, StringCollection best, StringCollection next, StringCollection previous) : base(child, content) { // Remember parameters _best = best; _next = next; _previous = previous; if (content.Visible) _space = content.ParentWindowContent.ZoneArea; else _space = 50m; } public override void PerformRestore(Zone z) { int count = z.Windows.Count; int beforeIndex = - 1; int afterIndex = count; // Find the match to one of our best friends for(int index=0; index<count; index++) { WindowContent wc = z.Windows[index] as WindowContent; if (wc != null) { // If this WindowContent contains a best friend, then add ourself here as well if (wc.Contents.Contains(_best)) { if (_child == null) { // If we do not have a Restore object for the Window then just add // into the WindowContent at the end of the existing Contents wc.Contents.Add(_content); } else { // Get the child to restore as best as possible inside WindowContent _child.PerformRestore(wc); } return; } // If the WindowContent contains a Content previous to the target if (wc.Contents.Contains(_previous)) { if (index > beforeIndex) beforeIndex = index; } // If the WindowContent contains a Content next to the target if (wc.Contents.Contains(_next)) { if (index < afterIndex) afterIndex = index; } } } // If we get here then we did not find any best friends, this // means we need to create a new WindowContent to host the Content. Window newW = z.DockingManager.CreateWindowForContent(_content); ZoneSequence zs = z as ZoneSequence; // If this is inside a ZoneSequence instance if (zs != null) { // Do not reposition the Windows on the .Insert but instead ignore the // reposition and let it happen in the .ModifyWindowSpace. This reduces // the flicker that would occur otherwise zs.SuppressReposition(); } // Need to find the best place in the order for the Content, start by // looking for the last 'previous' content and place immediately after it if (beforeIndex >= 0) { // Great, insert after it z.Windows.Insert(beforeIndex + 1, newW); } else { // No joy, so find the first 'next' content and place just before it, if // none are found then just add to the end of the collection. z.Windows.Insert(afterIndex, newW); } // If this is inside a ZoneSequence instance if (zs != null) { // We want to try and allocate the correct Zone space zs.ModifyWindowSpace(newW, _space); } } public override void SaveInternalToXml(XmlTextWriter xmlOut) { base.SaveInternalToXml(xmlOut); xmlOut.WriteStartElement("Space"); xmlOut.WriteAttributeString("Value", _space.ToString()); xmlOut.WriteEndElement(); _best.SaveToXml("Best", xmlOut); _next.SaveToXml("Next", xmlOut); _previous.SaveToXml("Previous", xmlOut); } public override void LoadInternalFromXml(XmlTextReader xmlIn, int formatVersion) { base.LoadInternalFromXml(xmlIn, formatVersion); // Move to next xml node if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.Name != "Space") throw new ArgumentException("Node 'Space' expected but not found"); // Grab raw position information string attrSpace = xmlIn.GetAttribute(0); // Convert from string to proper type _space = Decimal.Parse(attrSpace); _best.LoadFromXml("Best", xmlIn); _next.LoadFromXml("Next", xmlIn); _previous.LoadFromXml("Previous", xmlIn); } } internal class RestoreWindowContent : RestoreContent { // Instance fields protected bool _selected; protected StringCollection _next; protected StringCollection _previous; public RestoreWindowContent() : base() { // Must always point to valid reference _selected = false; _next = new StringCollection(); _previous = new StringCollection(); } public RestoreWindowContent(Restore child, Content content, StringCollection next, StringCollection previous, bool selected) : base(child, content) { // Remember parameters _selected = selected; _next = next; _previous = previous; } public override void PerformRestore(Window w) { // We are only ever called for a WindowContent object WindowContent wc = w as WindowContent; int bestIndex = -1; foreach(String s in _previous) { if (wc.Contents.Contains(s)) { int previousIndex = wc.Contents.IndexOf(wc.Contents[s]); if (previousIndex > bestIndex) bestIndex = previousIndex; } } // Did we find a previous Content? if (bestIndex >= 0) { // Great, insert after it wc.Contents.Insert(bestIndex + 1, _content); } else { bestIndex = wc.Contents.Count; foreach(String s in _next) { if (wc.Contents.Contains(s)) { int nextIndex = wc.Contents.IndexOf(wc.Contents[s]); if (nextIndex < bestIndex) bestIndex = nextIndex; } } // Insert before the found entry (or at end if non found) wc.Contents.Insert(bestIndex, _content); } // Should this content become selected? if (_selected) _content.BringToFront(); } public override void SaveInternalToXml(XmlTextWriter xmlOut) { base.SaveInternalToXml(xmlOut); _next.SaveToXml("Next", xmlOut); _previous.SaveToXml("Previous", xmlOut); xmlOut.WriteStartElement("Selected"); xmlOut.WriteAttributeString("Value", _selected.ToString()); xmlOut.WriteEndElement(); } public override void LoadInternalFromXml(XmlTextReader xmlIn, int formatVersion) { base.LoadInternalFromXml(xmlIn, formatVersion); _next.LoadFromXml("Next", xmlIn); _previous.LoadFromXml("Previous", xmlIn); // _selected added in version 4 format if (formatVersion >= 4) { // Move to next xml node if (!xmlIn.Read()) throw new ArgumentException("Could not read in next expected node"); // Check it has the expected name if (xmlIn.Name != "Selected") throw new ArgumentException("Node 'Selected' expected but not found"); // Convert attribute value to boolean value _selected = Convert.ToBoolean(xmlIn.GetAttribute(0)); } } } }
{ "content_hash": "cb40855974763962f7daf11cb9248c83", "timestamp": "", "source": "github", "line_count": 938, "max_line_length": 96, "avg_line_length": 27.33582089552239, "alnum_prop": 0.6478296478296478, "repo_name": "jugstalt/gViewGisOS", "id": "541b9923bd6882cb8bcc62f0b5b63ea0765d2499", "size": "26138", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gView.GeoProcessing.UI/IDE/Docking/Restore.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "14359299" }, { "name": "CSS", "bytes": "934" }, { "name": "HTML", "bytes": "4270" }, { "name": "NSIS", "bytes": "30399" }, { "name": "Visual Basic", "bytes": "17387" }, { "name": "XSLT", "bytes": "13865" } ] }
package br.edu.ifpb.notificationconect.asynctask; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import br.edu.ifpb.notificationwear.util.HttpService; import br.edu.ifpb.notificationwear.util.StringUtil; public class LoginAsyncTask extends AsyncTask<String, Void, HttpURLConnection>{ Context context; public LoginAsyncTask(Context activity) { this.context = activity; } @Override protected void onPreExecute() { Log.i("Notificationconect", "OnPreExecute"); } @Override protected HttpURLConnection doInBackground(String... valores) { Log.i("Notificationconect", "doInBackground: " + valores[0]); HttpURLConnection connection = null; try { connection = HttpService.sendGetRequest("servicoservlet"); } catch (MalformedURLException ex) { Log.e("Notificationconect","MalformedURLException"); } catch (IOException ex) { Log.e("Notificationconect","MalformedURLException"); } return connection; } @Override protected void onPostExecute(HttpURLConnection connection) { try { int status = connection.getResponseCode(); Log.i("Notificationconect", "Status HTTP-Response: " + status); String contentValue = HttpService.getHttpContent(connection); JSONObject json = new JSONObject(contentValue); String nome = json.getString("nome"); Toast.makeText(context, nome, Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { Log.e("Notificationconect", "JSONException"); } } }
{ "content_hash": "031c7fac9d0f93eb3314ed7b3fb2327a", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 79, "avg_line_length": 24.28235294117647, "alnum_prop": 0.6739341085271318, "repo_name": "rafaelbelarmino/Conexao", "id": "1de9a8bbb6bd6f63534145d2d2b6a45e79f57536", "size": "2064", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NotificationConect/app/src/main/java/br/edu/ifpb/notificationconect/asynctask/LoginAsyncTask.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10691" } ] }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-real-closed: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / mathcomp-real-closed - 1.0.5</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-real-closed <small> 1.0.5 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-14 08:21:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-14 08:21:45 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 3.1.1 Fast, portable, and opinionated build system ocaml 4.12.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.12.1 Official release 4.12.1 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-mathcomp-real-closed&quot; maintainer: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; homepage: &quot;https://github.com/math-comp/real-closed&quot; bug-reports: &quot;https://github.com/math-comp/real-closed/issues&quot; dev-repo: &quot;git+https://github.com/math-comp/real-closed.git&quot; license: &quot;CeCILL-B&quot; build: [ make &quot;-j&quot; &quot;%{jobs}%&quot; ] install: [ make &quot;install&quot; ] depends: [ &quot;coq&quot; { (&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.12~&quot;) } &quot;coq-mathcomp-field&quot; {(&gt;= &quot;1.11&quot; &amp; &lt;= &quot;1.12~&quot;)} &quot;coq-mathcomp-bigenough&quot; {(&gt;= &quot;1.0.0&quot; &amp; &lt; &quot;1.1~&quot;)} ] tags: [ &quot;keyword:real closed field&quot; &quot;keyword:small scale reflection&quot; &quot;keyword:mathematical components&quot; &quot;date:2019-05-23&quot; &quot;logpath:mathcomp&quot;] authors: [ &quot;Cyril Cohen &lt;&gt;&quot; &quot;Assia Mahboubi &lt;&gt;&quot; ] synopsis: &quot;Mathematical Components Library on real closed fields&quot; description: &quot;&quot;&quot; This library contains definitions and theorems about real closed fields, with a construction of the real closure and the algebraic closure (including a proof of the fundamental theorem of algebra). It also contains a proof of decidability of the first order theory of real closed field, through quantifier elimination. &quot;&quot;&quot; url { http: &quot;https://github.com/math-comp/real-closed/archive/1.0.5.tar.gz&quot; checksum: &quot;sha512=e1bbd636162275edc2a578cf3c3e0f2fae2deac3faa4535e2aaaef9208e544aaed2c2750787dfb34e8925df0c3ac34295363050e10fc9995f9513c18ad2ddcd0&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-real-closed.1.0.5 coq.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is dev). The following dependencies couldn&#39;t be met: - coq-mathcomp-real-closed -&gt; coq &lt; 8.12~ -&gt; ocaml &lt; 4.12 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-real-closed.1.0.5</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "6e19a70de3825cbde4fab0d6fafd66c1", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 190, "avg_line_length": 45.07602339181287, "alnum_prop": 0.5631811105345096, "repo_name": "coq-bench/coq-bench.github.io", "id": "5801b6ea41261dc45e73a63d1c80104bb80358f3", "size": "7733", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.12.1-2.0.8/extra-dev/dev/mathcomp-real-closed/1.0.5.html", "mode": "33188", "license": "mit", "language": [] }
; <?php /* ; Use the values below to specify alternate environment variables ; that Elefant should look at for each setting. For example, to look ; for the database host in MYSQL_HOST, change the following: ; ; ELEFANT_DB_HOST = MYSQL_HOST ; ; Leave the defaults in the form `ENV_VAR = ENV_VAR`. ELEFANT_SITE_NAME = ELEFANT_SITE_NAME ELEFANT_EMAIL_FROM = ELEFANT_EMAIL_FROM ELEFANT_DOMAIN = ELEFANT_DOMAIN ELEFANT_DB_DRIVER = ELEFANT_DB_DRIVER ELEFANT_DB_FILE = ELEFANT_DB_FILE ELEFANT_DB_HOST = ELEFANT_DB_HOST ELEFANT_DB_NAME = ELEFANT_DB_NAME ELEFANT_DB_USER = ELEFANT_DB_USER ELEFANT_DB_PASS = ELEFANT_DB_PASS ELEFANT_TIMEZONE = ELEFANT_TIMEZONE ELEFANT_UPDATES = ELEFANT_UPDATES ELEFANT_SITE_KEY = ELEFANT_SITE_KEY ELEFANT_SESSION_NAME = ELEFANT_SESSION_NAME ELEFANT_SESSION_HANDLER = ELEFANT_SESSION_HANDLER ELEFANT_SESSION_DOMAIN = ELEFANT_SESSION_DOMAIN ELEFANT_SESSION_DURATION = ELEFANT_SESSION_DURATION ; */
{ "content_hash": "87e24b9828d062d7538bcee666f0147e", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 68, "avg_line_length": 32.892857142857146, "alnum_prop": 0.7741585233441911, "repo_name": "jbroadway/elefant", "id": "72377a05058485abbd966956cf38d2803bf9a55b", "size": "921", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "conf/envmap.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "194608" }, { "name": "CoffeeScript", "bytes": "2266" }, { "name": "HTML", "bytes": "626910" }, { "name": "JavaScript", "bytes": "2001040" }, { "name": "Makefile", "bytes": "895" }, { "name": "PHP", "bytes": "2432497" }, { "name": "PLpgSQL", "bytes": "21437" }, { "name": "SCSS", "bytes": "39308" }, { "name": "Shell", "bytes": "267" } ] }
FROM balenalib/revpi-core-3-ubuntu:cosmic-build ENV NODE_VERSION 12.21.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "6edc31a210e47eb72b0a2a150f7fe604539c1b2a45e8c81d378ac9315053a54f node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu cosmic \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.21.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "350d45d2abe5c298774c41c43e0e0fc8", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 694, "avg_line_length": 66.92682926829268, "alnum_prop": 0.7099125364431487, "repo_name": "nghiant2710/base-images", "id": "f8d100c97d15c4dd1543ccb6e793aa885d6cc83a", "size": "2765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/revpi-core-3/ubuntu/cosmic/12.21.0/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ] }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Testing Actor Systems &mdash; Akka Documentation</title> <link rel="stylesheet" href="../_static/style.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/prettify.css" type="text/css" /> <link rel="stylesheet" href="../_static/base.css" type="text/css" /> <link rel="stylesheet" href="../_static/docs.css" type="text/css" /> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Exo:300,400,600,700" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '2.2.3', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/toc.js"></script> <script type="text/javascript" src="../_static/prettify.js"></script> <script type="text/javascript" src="../_static/highlightCode.js"></script> <script type="text/javascript" src="../_static/effects.core.js"></script> <script type="text/javascript" src="../_static/effects.highlight.js"></script> <script type="text/javascript" src="../_static/scrollTo.js"></script> <script type="text/javascript" src="../_static/contentsFix.js"></script> <script type="text/javascript" src="../_static/ga.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="top" title="Akka Documentation" href="../index.html" /> <link rel="up" title="Actors" href="index-actors.html" /> <link rel="next" title="TestKit Example" href="testkit-example.html" /> <link rel="prev" title="FSM" href="fsm.html" /> </head> <body> <div class="navbar"> <div class="navbar-inner"> <div class="container"> <div class="navbar-logo"> <a href="http://akka.io"><img src="../_static/logo-small.png" /></a> </div> <ul class="nav"> <li><a href="http://akka.io/docs">Documentation</a></li> <li><a href="http://akka.io/faq">FAQ</a></li> <li><a href="http://typesafe.com/stack/downloads/akka">Download</a></li> <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li> <li><a href="http://github.com/akka/akka">Code</a></li> <li><a href="http://typesafe.com/products/typesafe-subscription">Commercial Support</a></li> </ul> </div> </div> </div> <div class="main"> <div class="container"> <div class="page-title">Testing Actor Systems</div> <div class="pdf-link"><a href="../AkkaScala.pdf" title="Akka Scala Documentation"><img src="../_static/pdf-scala-icon.png" style="height: 40px;" /></a></div> <div class="pdf-link"><a href="../AkkaJava.pdf" title="Akka Java Documentation"><img src="../_static/pdf-java-icon.png" style="height: 40px;" /></a></div> </div> <div class="main-container"> <div class="container"> <div class="row"> <div class="span12"> <ul class="breadcrumb"> <li> <span class="divider">|</span> <a href="testkit-example.html">TestKit Example</a> <span class="divider">»</span> </li> <li> <a href="../index.html">Contents</a> </li> <li> <span class="divider">«</span> <a href="fsm.html">FSM</a> <span class="divider">|</span> </li> <li> Version 2.2.3 </li> </ul> </div> </div> <div class="row"><div class="span9"> <div class="section" id="testing-actor-systems"> <span id="akka-testkit"></span><h1>Testing Actor Systems</h1> <div class="toctree-wrapper compound"> <ul> <li class="toctree-l1"><a class="reference internal" href="testkit-example.html">TestKit Example</a></li> </ul> </div> <p>As with any piece of software, automated tests are a very important part of the development cycle. The actor model presents a different view on how units of code are delimited and how they interact, which has an influence on how to perform tests.</p> <p>Akka comes with a dedicated module <tt class="xref py py-mod docutils literal"><span class="pre">akka-testkit</span></tt> for supporting tests at different levels, which fall into two clearly distinct categories:</p> <blockquote> <div><ul class="simple"> <li>Testing isolated pieces of code without involving the actor model, meaning without multiple threads; this implies completely deterministic behavior concerning the ordering of events and no concurrency concerns and will be called <strong>Unit Testing</strong> in the following.</li> <li>Testing (multiple) encapsulated actors including multi-threaded scheduling; this implies non-deterministic order of events but shielding from concurrency concerns by the actor model and will be called <strong>Integration Testing</strong> in the following.</li> </ul> </div></blockquote> <p>There are of course variations on the granularity of tests in both categories, where unit testing reaches down to white-box tests and integration testing can encompass functional tests of complete actor networks. The important distinction lies in whether concurrency concerns are part of the test or not. The tools offered are described in detail in the following sections.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Be sure to add the module <tt class="xref py py-mod docutils literal"><span class="pre">akka-testkit</span></tt> to your dependencies.</p> </div> <div class="section" id="synchronous-unit-testing-with-testactorref"> <h2>Synchronous Unit Testing with <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt></h2> <p>Testing the business logic inside <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> classes can be divided into two parts: first, each atomic operation must work in isolation, then sequences of incoming events must be processed correctly, even in the presence of some possible variability in the ordering of events. The former is the primary use case for single-threaded unit testing, while the latter can only be verified in integration tests.</p> <p>Normally, the <tt class="xref py py-class docutils literal"><span class="pre">ActorRef</span></tt> shields the underlying <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> instance from the outside, the only communications channel is the actor's mailbox. This restriction is an impediment to unit testing, which led to the inception of the <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt>. This special type of reference is designed specifically for test purposes and allows access to the actor in two ways: either by obtaining a reference to the underlying actor instance, or by invoking or querying the actor's behaviour (<tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt>). Each one warrants its own section below.</p> <div class="section" id="obtaining-a-reference-to-an-actor"> <h3>Obtaining a Reference to an <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt></h3> <p>Having access to the actual <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> object allows application of all traditional unit testing techniques on the contained methods. Obtaining a reference is done like this:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestActorRef</span> <span class="k">val</span> <span class="n">actorRef</span> <span class="k">=</span> <span class="nc">TestActorRef</span><span class="o">[</span><span class="kt">MyActor</span><span class="o">]</span> <span class="k">val</span> <span class="n">actor</span> <span class="k">=</span> <span class="n">actorRef</span><span class="o">.</span><span class="n">underlyingActor</span> </pre></div> </div> <p>Since <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> is generic in the actor type it returns the underlying actor with its proper static type. From this point on you may bring any unit testing tool to bear on your actor as usual.</p> </div> <div class="section" id="testing-finite-state-machines"> <span id="testfsmref"></span><h3>Testing Finite State Machines</h3> <p>If your actor under test is a <tt class="xref py py-class docutils literal"><span class="pre">FSM</span></tt>, you may use the special <tt class="xref py py-class docutils literal"><span class="pre">TestFSMRef</span></tt> which offers all features of a normal <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> and in addition allows access to the internal state:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestFSMRef</span> <span class="k">import</span> <span class="nn">akka.actor.FSM</span> <span class="k">import</span> <span class="nn">scala.concurrent.duration._</span> <span class="k">val</span> <span class="n">fsm</span> <span class="k">=</span> <span class="nc">TestFSMRef</span><span class="o">(</span><span class="k">new</span> <span class="nc">TestFsmActor</span><span class="o">)</span> <span class="k">val</span> <span class="n">mustBeTypedProperly</span><span class="k">:</span> <span class="kt">TestActorRef</span><span class="o">[</span><span class="kt">TestFsmActor</span><span class="o">]</span> <span class="k">=</span> <span class="n">fsm</span> <span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateName</span> <span class="o">==</span> <span class="mi">1</span><span class="o">)</span> <span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateData</span> <span class="o">==</span> <span class="s">&quot;&quot;</span><span class="o">)</span> <span class="n">fsm</span> <span class="o">!</span> <span class="s">&quot;go&quot;</span> <span class="c1">// being a TestActorRef, this runs also on the CallingThreadDispatcher</span> <span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateName</span> <span class="o">==</span> <span class="mi">2</span><span class="o">)</span> <span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateData</span> <span class="o">==</span> <span class="s">&quot;go&quot;</span><span class="o">)</span> <span class="n">fsm</span><span class="o">.</span><span class="n">setState</span><span class="o">(</span><span class="n">stateName</span> <span class="k">=</span> <span class="mi">1</span><span class="o">)</span> <span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">stateName</span> <span class="o">==</span> <span class="mi">1</span><span class="o">)</span> <span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">isTimerActive</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">)</span> <span class="o">==</span> <span class="kc">false</span><span class="o">)</span> <span class="n">fsm</span><span class="o">.</span><span class="n">setTimer</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">,</span> <span class="mi">12</span><span class="o">,</span> <span class="mi">10</span> <span class="n">millis</span><span class="o">,</span> <span class="kc">true</span><span class="o">)</span> <span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">isTimerActive</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">)</span> <span class="o">==</span> <span class="kc">true</span><span class="o">)</span> <span class="n">fsm</span><span class="o">.</span><span class="n">cancelTimer</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">)</span> <span class="n">assert</span><span class="o">(</span><span class="n">fsm</span><span class="o">.</span><span class="n">isTimerActive</span><span class="o">(</span><span class="s">&quot;test&quot;</span><span class="o">)</span> <span class="o">==</span> <span class="kc">false</span><span class="o">)</span> </pre></div> </div> <p>Due to a limitation in Scala’s type inference, there is only the factory method shown above, so you will probably write code like <tt class="docutils literal"><span class="pre">TestFSMRef(new</span> <span class="pre">MyFSM)</span></tt> instead of the hypothetical <tt class="xref py py-class docutils literal"><span class="pre">ActorRef</span></tt>-inspired <tt class="docutils literal"><span class="pre">TestFSMRef[MyFSM]</span></tt>. All methods shown above directly access the FSM state without any synchronization; this is perfectly alright if the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> is used and no other threads are involved, but it may lead to surprises if you were to actually exercise timer events, because those are executed on the <tt class="xref py py-obj docutils literal"><span class="pre">Scheduler</span></tt> thread.</p> </div> <div class="section" id="testing-the-actor-s-behavior"> <h3>Testing the Actor's Behavior</h3> <p>When the dispatcher invokes the processing behavior of an actor on a message, it actually calls <tt class="xref py py-meth docutils literal"><span class="pre">apply</span></tt> on the current behavior registered for the actor. This starts out with the return value of the declared <tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt> method, but it may also be changed using <tt class="xref py py-meth docutils literal"><span class="pre">become</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">unbecome</span></tt> in response to external messages. All of this contributes to the overall actor behavior and it does not lend itself to easy testing on the <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> itself. Therefore the <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> offers a different mode of operation to complement the <tt class="xref py py-class docutils literal"><span class="pre">Actor</span></tt> testing: it supports all operations also valid on normal <tt class="xref py py-class docutils literal"><span class="pre">ActorRef</span></tt>. Messages sent to the actor are processed synchronously on the current thread and answers may be sent back as usual. This trick is made possible by the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> described below (see <a class="reference internal" href="#callingthreaddispatcher">CallingThreadDispatcher</a>); this dispatcher is set implicitly for any actor instantiated into a <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt>.</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestActorRef</span> <span class="k">import</span> <span class="nn">scala.concurrent.duration._</span> <span class="k">import</span> <span class="nn">scala.concurrent.Await</span> <span class="k">import</span> <span class="nn">akka.pattern.ask</span> <span class="k">val</span> <span class="n">actorRef</span> <span class="k">=</span> <span class="nc">TestActorRef</span><span class="o">(</span><span class="k">new</span> <span class="nc">MyActor</span><span class="o">)</span> <span class="c1">// hypothetical message stimulating a &#39;42&#39; answer</span> <span class="k">val</span> <span class="n">future</span> <span class="k">=</span> <span class="n">actorRef</span> <span class="o">?</span> <span class="nc">Say42</span> <span class="k">val</span> <span class="nc">Success</span><span class="o">(</span><span class="n">result</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span> <span class="k">=</span> <span class="n">future</span><span class="o">.</span><span class="n">value</span><span class="o">.</span><span class="n">get</span> <span class="n">result</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">42</span><span class="o">)</span> </pre></div> </div> <p>As the <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> is a subclass of <tt class="xref py py-class docutils literal"><span class="pre">LocalActorRef</span></tt> with a few special extras, also aspects like supervision and restarting work properly, but beware that execution is only strictly synchronous as long as all actors involved use the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt>. As soon as you add elements which include more sophisticated scheduling you leave the realm of unit testing as you then need to think about asynchronicity again (in most cases the problem will be to wait until the desired effect had a chance to happen).</p> <p>One more special aspect which is overridden for single-threaded tests is the <tt class="xref py py-meth docutils literal"><span class="pre">receiveTimeout</span></tt>, as including that would entail asynchronous queuing of <tt class="xref py py-obj docutils literal"><span class="pre">ReceiveTimeout</span></tt> messages, violating the synchronous contract.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">To summarize: <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> overwrites two fields: it sets the dispatcher to <tt class="xref py py-obj docutils literal"><span class="pre">CallingThreadDispatcher.global</span></tt> and it sets the <tt class="xref py py-obj docutils literal"><span class="pre">receiveTimeout</span></tt> to None.</p> </div> </div> <div class="section" id="the-way-in-between-expecting-exceptions"> <h3>The Way In-Between: Expecting Exceptions</h3> <p>If you want to test the actor behavior, including hotswapping, but without involving a dispatcher and without having the <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> swallow any thrown exceptions, then there is another mode available for you: just use the <tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt> method <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt>, which will be forwarded to the underlying actor:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestActorRef</span> <span class="k">val</span> <span class="n">actorRef</span> <span class="k">=</span> <span class="nc">TestActorRef</span><span class="o">(</span><span class="k">new</span> <span class="nc">Actor</span> <span class="o">{</span> <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span> <span class="k">case</span> <span class="s">&quot;hello&quot;</span> <span class="k">⇒</span> <span class="k">throw</span> <span class="k">new</span> <span class="nc">IllegalArgumentException</span><span class="o">(</span><span class="s">&quot;boom&quot;</span><span class="o">)</span> <span class="o">}</span> <span class="o">})</span> <span class="n">intercept</span><span class="o">[</span><span class="kt">IllegalArgumentException</span><span class="o">]</span> <span class="o">{</span> <span class="n">actorRef</span><span class="o">.</span><span class="n">receive</span><span class="o">(</span><span class="s">&quot;hello&quot;</span><span class="o">)</span> <span class="o">}</span> </pre></div> </div> </div> <div class="section" id="use-cases"> <h3>Use Cases</h3> <p>You may of course mix and match both modi operandi of <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> as suits your test needs:</p> <blockquote> <div><ul class="simple"> <li>one common use case is setting up the actor into a specific internal state before sending the test message</li> <li>another is to verify correct internal state transitions after having sent the test message</li> </ul> </div></blockquote> <p>Feel free to experiment with the possibilities, and if you find useful patterns, don't hesitate to let the Akka forums know about them! Who knows, common operations might even be worked into nice DSLs.</p> </div> </div> <div class="section" id="asynchronous-integration-testing-with-testkit"> <h2>Asynchronous Integration Testing with <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt></h2> <p>When you are reasonably sure that your actor's business logic is correct, the next step is verifying that it works correctly within its intended environment (if the individual actors are simple enough, possibly because they use the <tt class="xref py py-mod docutils literal"><span class="pre">FSM</span></tt> module, this might also be the first step). The definition of the environment depends of course very much on the problem at hand and the level at which you intend to test, ranging for functional/integration tests to full system tests. The minimal setup consists of the test procedure, which provides the desired stimuli, the actor under test, and an actor receiving replies. Bigger systems replace the actor under test with a network of actors, apply stimuli at varying injection points and arrange results to be sent from different emission points, but the basic principle stays the same in that a single procedure drives the test.</p> <p>The <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> class contains a collection of tools which makes this common task easy.</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.actor.ActorSystem</span> <span class="k">import</span> <span class="nn">akka.actor.Actor</span> <span class="k">import</span> <span class="nn">akka.actor.Props</span> <span class="k">import</span> <span class="nn">akka.testkit.TestKit</span> <span class="k">import</span> <span class="nn">org.scalatest.WordSpec</span> <span class="k">import</span> <span class="nn">org.scalatest.matchers.MustMatchers</span> <span class="k">import</span> <span class="nn">org.scalatest.BeforeAndAfterAll</span> <span class="k">import</span> <span class="nn">akka.testkit.ImplicitSender</span> <span class="k">object</span> <span class="nc">MySpec</span> <span class="o">{</span> <span class="k">class</span> <span class="nc">EchoActor</span> <span class="k">extends</span> <span class="nc">Actor</span> <span class="o">{</span> <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span> <span class="k">case</span> <span class="n">x</span> <span class="k">⇒</span> <span class="n">sender</span> <span class="o">!</span> <span class="n">x</span> <span class="o">}</span> <span class="o">}</span> <span class="o">}</span> <span class="k">class</span> <span class="nc">MySpec</span><span class="o">(</span><span class="nc">_system</span><span class="k">:</span> <span class="kt">ActorSystem</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">TestKit</span><span class="o">(</span><span class="nc">_system</span><span class="o">)</span> <span class="k">with</span> <span class="nc">ImplicitSender</span> <span class="k">with</span> <span class="nc">WordSpec</span> <span class="k">with</span> <span class="nc">MustMatchers</span> <span class="k">with</span> <span class="nc">BeforeAndAfterAll</span> <span class="o">{</span> <span class="k">def</span> <span class="k">this</span><span class="o">()</span> <span class="k">=</span> <span class="k">this</span><span class="o">(</span><span class="nc">ActorSystem</span><span class="o">(</span><span class="s">&quot;MySpec&quot;</span><span class="o">))</span> <span class="k">import</span> <span class="nn">MySpec._</span> <span class="k">override</span> <span class="k">def</span> <span class="n">afterAll</span> <span class="o">{</span> <span class="nc">TestKit</span><span class="o">.</span><span class="n">shutdownActorSystem</span><span class="o">(</span><span class="n">system</span><span class="o">)</span> <span class="o">}</span> <span class="s">&quot;An Echo actor&quot;</span> <span class="n">must</span> <span class="o">{</span> <span class="s">&quot;send back messages unchanged&quot;</span> <span class="n">in</span> <span class="o">{</span> <span class="k">val</span> <span class="n">echo</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">EchoActor</span><span class="o">])</span> <span class="n">echo</span> <span class="o">!</span> <span class="s">&quot;hello world&quot;</span> <span class="n">expectMsg</span><span class="o">(</span><span class="s">&quot;hello world&quot;</span><span class="o">)</span> <span class="o">}</span> <span class="o">}</span> <span class="o">}</span> </pre></div> </div> <p>The <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> contains an actor named <tt class="xref py py-obj docutils literal"><span class="pre">testActor</span></tt> which is the entry point for messages to be examined with the various <tt class="docutils literal"><span class="pre">expectMsg...</span></tt> assertions detailed below. When mixing in the trait <tt class="docutils literal"><span class="pre">ImplicitSender</span></tt> this test actor is implicitly used as sender reference when dispatching messages from the test procedure. The <tt class="xref py py-obj docutils literal"><span class="pre">testActor</span></tt> may also be passed to other actors as usual, usually subscribing it as notification listener. There is a whole set of examination methods, e.g. receiving all consecutive messages matching certain criteria, receiving a whole sequence of fixed messages or classes, receiving nothing for some time, etc.</p> <p>The ActorSystem passed in to the constructor of TestKit is accessible via the <tt class="xref py py-obj docutils literal"><span class="pre">system</span></tt> member. Remember to shut down the actor system after the test is finished (also in case of failure) so that all actors—including the test actor—are stopped.</p> <div class="section" id="built-in-assertions"> <h3>Built-In Assertions</h3> <p>The above mentioned <tt class="xref py py-meth docutils literal"><span class="pre">expectMsg</span></tt> is not the only method for formulating assertions concerning received messages. Here is the full list:</p> <blockquote> <div><ul> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsg[T](d:&nbsp;Duration,&nbsp;msg:&nbsp;T):&nbsp;T</span></tt></p> <p>The given message object must be received within the specified time; the object will be returned.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgPF[T](d:&nbsp;Duration)(pf:&nbsp;PartialFunction[Any,&nbsp;T]):&nbsp;T</span></tt></p> <p>Within the given time period, a message must be received and the given partial function must be defined for that message; the result from applying the partial function to the received message is returned. The duration may be left unspecified (empty parentheses are required in this case) to use the deadline from the innermost enclosing <a class="reference internal" href="#testkit-within"><em>within</em></a> block instead.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgClass[T](d:&nbsp;Duration,&nbsp;c:&nbsp;Class[T]):&nbsp;T</span></tt></p> <p>An object which is an instance of the given <tt class="xref py py-class docutils literal"><span class="pre">Class</span></tt> must be received within the allotted time frame; the object will be returned. Note that this does a conformance check; if you need the class to be equal, have a look at <tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAllClassOf</span></tt> with a single given class argument.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgType[T:&nbsp;Manifest](d:&nbsp;Duration)</span></tt></p> <p>An object which is an instance of the given type (after erasure) must be received within the allotted time frame; the object will be returned. This method is approximately equivalent to <tt class="docutils literal"><span class="pre">expectMsgClass(implicitly[ClassTag[T]].runtimeClass)</span></tt>.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAnyOf[T](d:&nbsp;Duration,&nbsp;obj:&nbsp;T*):&nbsp;T</span></tt></p> <p>An object must be received within the given time, and it must be equal ( compared with <tt class="docutils literal"><span class="pre">==</span></tt>) to at least one of the passed reference objects; the received object will be returned.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAnyClassOf[T](d:&nbsp;Duration,&nbsp;obj:&nbsp;Class[_&nbsp;&lt;:&nbsp;T]*):&nbsp;T</span></tt></p> <p>An object must be received within the given time, and it must be an instance of at least one of the supplied <tt class="xref py py-class docutils literal"><span class="pre">Class</span></tt> objects; the received object will be returned.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAllOf[T](d:&nbsp;Duration,&nbsp;obj:&nbsp;T*):&nbsp;Seq[T]</span></tt></p> <p>A number of objects matching the size of the supplied object array must be received within the given time, and for each of the given objects there must exist at least one among the received ones which equals (compared with <tt class="docutils literal"><span class="pre">==</span></tt>) it. The full sequence of received objects is returned.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAllClassOf[T](d:&nbsp;Duration,&nbsp;c:&nbsp;Class[_&nbsp;&lt;:&nbsp;T]*):&nbsp;Seq[T]</span></tt></p> <p>A number of objects matching the size of the supplied <tt class="xref py py-class docutils literal"><span class="pre">Class</span></tt> array must be received within the given time, and for each of the given classes there must exist at least one among the received objects whose class equals (compared with <tt class="docutils literal"><span class="pre">==</span></tt>) it (this is <em>not</em> a conformance check). The full sequence of received objects is returned.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectMsgAllConformingOf[T](d:&nbsp;Duration,&nbsp;c:&nbsp;Class[_&nbsp;&lt;:&nbsp;T]*):&nbsp;Seq[T]</span></tt></p> <p>A number of objects matching the size of the supplied <tt class="xref py py-class docutils literal"><span class="pre">Class</span></tt> array must be received within the given time, and for each of the given classes there must exist at least one among the received objects which is an instance of this class. The full sequence of received objects is returned.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">expectNoMsg(d:&nbsp;Duration)</span></tt></p> <p>No message must be received within the given time. This also fails if a message has been received before calling this method which has not been removed from the queue using one of the other methods.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">receiveN(n:&nbsp;Int,&nbsp;d:&nbsp;Duration):&nbsp;Seq[AnyRef]</span></tt></p> <p><tt class="docutils literal"><span class="pre">n</span></tt> messages must be received within the given time; the received messages are returned.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">fishForMessage(max:&nbsp;Duration,&nbsp;hint:&nbsp;String)(pf:&nbsp;PartialFunction[Any,&nbsp;Boolean]):&nbsp;Any</span></tt></p> <p>Keep receiving messages as long as the time is not used up and the partial function matches and returns <tt class="docutils literal"><span class="pre">false</span></tt>. Returns the message received for which it returned <tt class="docutils literal"><span class="pre">true</span></tt> or throws an exception, which will include the provided hint for easier debugging.</p> </li> </ul> </div></blockquote> <p>In addition to message reception assertions there are also methods which help with message flows:</p> <blockquote> <div><ul> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">receiveOne(d:&nbsp;Duration):&nbsp;AnyRef</span></tt></p> <p>Tries to receive one message for at most the given time interval and returns <tt class="docutils literal"><span class="pre">null</span></tt> in case of failure. If the given Duration is zero, the call is non-blocking (polling mode).</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">receiveWhile[T](max:&nbsp;Duration,&nbsp;idle:&nbsp;Duration,&nbsp;messages:&nbsp;Int)(pf:&nbsp;PartialFunction[Any,&nbsp;T]):&nbsp;Seq[T]</span></tt></p> <p>Collect messages as long as</p> <ul class="simple"> <li>they are matching the given partial function</li> <li>the given time interval is not used up</li> <li>the next message is received within the idle timeout</li> <li>the number of messages has not yet reached the maximum</li> </ul> <p>All collected messages are returned. The maximum duration defaults to the time remaining in the innermost enclosing <a class="reference internal" href="#testkit-within"><em>within</em></a> block and the idle duration defaults to infinity (thereby disabling the idle timeout feature). The number of expected messages defaults to <tt class="docutils literal"><span class="pre">Int.MaxValue</span></tt>, which effectively disables this limit.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">awaitCond(p:&nbsp;=&gt;&nbsp;Boolean,&nbsp;max:&nbsp;Duration,&nbsp;interval:&nbsp;Duration)</span></tt></p> <p>Poll the given condition every <tt class="xref py py-obj docutils literal"><span class="pre">interval</span></tt> until it returns <tt class="docutils literal"><span class="pre">true</span></tt> or the <tt class="xref py py-obj docutils literal"><span class="pre">max</span></tt> duration is used up. The interval defaults to 100 ms and the maximum defaults to the time remaining in the innermost enclosing <a class="reference internal" href="#testkit-within"><em>within</em></a> block.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">awaitAssert(a:&nbsp;=&gt;&nbsp;Any,&nbsp;max:&nbsp;Duration,&nbsp;interval:&nbsp;Duration)</span></tt></p> <p>Poll the given assert function every <tt class="xref py py-obj docutils literal"><span class="pre">interval</span></tt> until it does not throw an exception or the <tt class="xref py py-obj docutils literal"><span class="pre">max</span></tt> duration is used up. If the timeout expires the last exception is thrown. The interval defaults to 100 ms and the maximum defaults to the time remaining in the innermost enclosing <a class="reference internal" href="#testkit-within"><em>within</em></a> block.The interval defaults to 100 ms and the maximum defaults to the time remaining in the innermost enclosing <a class="reference internal" href="#testkit-within"><em>within</em></a> block.</p> </li> <li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">ignoreMsg(pf:&nbsp;PartialFunction[AnyRef,&nbsp;Boolean])</span></tt></p> <p><tt class="xref py py-meth docutils literal"><span class="pre">ignoreNoMsg</span></tt></p> <p>The internal <tt class="xref py py-obj docutils literal"><span class="pre">testActor</span></tt> contains a partial function for ignoring messages: it will only enqueue messages which do not match the function or for which the function returns <tt class="docutils literal"><span class="pre">false</span></tt>. This function can be set and reset using the methods given above; each invocation replaces the previous function, they are not composed.</p> <p>This feature is useful e.g. when testing a logging system, where you want to ignore regular messages and are only interested in your specific ones.</p> </li> </ul> </div></blockquote> </div> <div class="section" id="expecting-log-messages"> <h3>Expecting Log Messages</h3> <p>Since an integration test does not allow to the internal processing of the participating actors, verifying expected exceptions cannot be done directly. Instead, use the logging system for this purpose: replacing the normal event handler with the <tt class="xref py py-class docutils literal"><span class="pre">TestEventListener</span></tt> and using an <tt class="xref py py-class docutils literal"><span class="pre">EventFilter</span></tt> allows assertions on log messages, including those which are generated by exceptions:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.EventFilter</span> <span class="k">import</span> <span class="nn">com.typesafe.config.ConfigFactory</span> <span class="k">implicit</span> <span class="k">val</span> <span class="n">system</span> <span class="k">=</span> <span class="nc">ActorSystem</span><span class="o">(</span><span class="s">&quot;testsystem&quot;</span><span class="o">,</span> <span class="nc">ConfigFactory</span><span class="o">.</span><span class="n">parseString</span><span class="o">(</span><span class="s">&quot;&quot;&quot;</span> <span class="s"> akka.loggers = [&quot;akka.testkit.TestEventListener&quot;]</span> <span class="s"> &quot;&quot;&quot;</span><span class="o">))</span> <span class="k">try</span> <span class="o">{</span> <span class="k">val</span> <span class="n">actor</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">.</span><span class="n">empty</span><span class="o">)</span> <span class="nc">EventFilter</span><span class="o">[</span><span class="kt">ActorKilledException</span><span class="o">](</span><span class="n">occurrences</span> <span class="k">=</span> <span class="mi">1</span><span class="o">)</span> <span class="n">intercept</span> <span class="o">{</span> <span class="n">actor</span> <span class="o">!</span> <span class="nc">Kill</span> <span class="o">}</span> <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span> <span class="n">shutdown</span><span class="o">(</span><span class="n">system</span><span class="o">)</span> <span class="o">}</span> </pre></div> </div> <p>If a number of occurrences is specific—as demonstrated above—then <tt class="docutils literal"><span class="pre">intercept</span></tt> will block until that number of matching messages have been received or the timeout configured in <tt class="docutils literal"><span class="pre">akka.test.filter-leeway</span></tt> is used up (time starts counting after the passed-in block of code returns). In case of a timeout the test fails.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>Be sure to exchange the default logger with the <tt class="xref py py-class docutils literal"><span class="pre">TestEventListener</span></tt> in your <tt class="docutils literal"><span class="pre">application.conf</span></tt> to enable this function:</p> <div class="last highlight-scala"><div class="highlight"><pre><span class="n">akka</span><span class="o">.</span><span class="n">loggers</span> <span class="k">=</span> <span class="o">[</span><span class="kt">akka.testkit.TestEventListener</span><span class="o">]</span> </pre></div> </div> </div> </div> <div class="section" id="timing-assertions"> <span id="testkit-within"></span><h3>Timing Assertions</h3> <p>Another important part of functional testing concerns timing: certain events must not happen immediately (like a timer), others need to happen before a deadline. Therefore, all examination methods accept an upper time limit within the positive or negative result must be obtained. Lower time limits need to be checked external to the examination, which is facilitated by a new construct for managing time constraints:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="n">within</span><span class="o">([</span><span class="kt">min</span>, <span class="o">]</span><span class="n">max</span><span class="o">)</span> <span class="o">{</span> <span class="o">...</span> <span class="o">}</span> </pre></div> </div> <p>The block given to <tt class="xref py py-meth docutils literal"><span class="pre">within</span></tt> must complete after a <a class="reference internal" href="../common/duration.html#duration"><em>Duration</em></a> which is between <tt class="xref py py-obj docutils literal"><span class="pre">min</span></tt> and <tt class="xref py py-obj docutils literal"><span class="pre">max</span></tt>, where the former defaults to zero. The deadline calculated by adding the <tt class="xref py py-obj docutils literal"><span class="pre">max</span></tt> parameter to the block's start time is implicitly available within the block to all examination methods, if you do not specify it, it is inherited from the innermost enclosing <tt class="xref py py-meth docutils literal"><span class="pre">within</span></tt> block.</p> <p>It should be noted that if the last message-receiving assertion of the block is <tt class="xref py py-meth docutils literal"><span class="pre">expectNoMsg</span></tt> or <tt class="xref py py-meth docutils literal"><span class="pre">receiveWhile</span></tt>, the final check of the <tt class="xref py py-meth docutils literal"><span class="pre">within</span></tt> is skipped in order to avoid false positives due to wake-up latencies. This means that while individual contained assertions still use the maximum time bound, the overall block may take arbitrarily longer in this case.</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.actor.Props</span> <span class="k">import</span> <span class="nn">scala.concurrent.duration._</span> <span class="k">val</span> <span class="n">worker</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">Worker</span><span class="o">])</span> <span class="n">within</span><span class="o">(</span><span class="mi">200</span> <span class="n">millis</span><span class="o">)</span> <span class="o">{</span> <span class="n">worker</span> <span class="o">!</span> <span class="s">&quot;some work&quot;</span> <span class="n">expectMsg</span><span class="o">(</span><span class="s">&quot;some result&quot;</span><span class="o">)</span> <span class="n">expectNoMsg</span> <span class="c1">// will block for the rest of the 200ms</span> <span class="nc">Thread</span><span class="o">.</span><span class="n">sleep</span><span class="o">(</span><span class="mi">300</span><span class="o">)</span> <span class="c1">// will NOT make this block fail</span> <span class="o">}</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">All times are measured using <tt class="docutils literal"><span class="pre">System.nanoTime</span></tt>, meaning that they describe wall time, not CPU time.</p> </div> <p>Ray Roestenburg has written a great article on using the TestKit: <a class="reference external" href="http://roestenburg.agilesquad.com/2011/02/unit-testing-akka-actors-with-testkit_12.html">http://roestenburg.agilesquad.com/2011/02/unit-testing-akka-actors-with-testkit_12.html</a>. His full example is also available <a class="reference internal" href="testkit-example.html#testkit-example"><em>here</em></a>.</p> <div class="section" id="accounting-for-slow-test-systems"> <h4>Accounting for Slow Test Systems</h4> <p>The tight timeouts you use during testing on your lightning-fast notebook will invariably lead to spurious test failures on the heavily loaded Jenkins server (or similar). To account for this situation, all maximum durations are internally scaled by a factor taken from the <a class="reference internal" href="../general/configuration.html#configuration"><em>Configuration</em></a>, <tt class="docutils literal"><span class="pre">akka.test.timefactor</span></tt>, which defaults to 1.</p> <p>You can scale other durations with the same factor by using the implicit conversion in <tt class="docutils literal"><span class="pre">akka.testkit</span></tt> package object to add dilated function to <tt class="xref py py-class docutils literal"><span class="pre">Duration</span></tt>.</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">scala.concurrent.duration._</span> <span class="k">import</span> <span class="nn">akka.testkit._</span> <span class="mf">10.</span><span class="n">milliseconds</span><span class="o">.</span><span class="n">dilated</span> </pre></div> </div> </div> </div> <div class="section" id="resolving-conflicts-with-implicit-actorref"> <h3>Resolving Conflicts with Implicit ActorRef</h3> <p>If you want the sender of messages inside your TestKit-based tests to be the <tt class="docutils literal"><span class="pre">testActor</span></tt> simply mix in <tt class="docutils literal"><span class="pre">ÌmplicitSender</span></tt> into your test.</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MySpec</span><span class="o">(</span><span class="nc">_system</span><span class="k">:</span> <span class="kt">ActorSystem</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">TestKit</span><span class="o">(</span><span class="nc">_system</span><span class="o">)</span> <span class="k">with</span> <span class="nc">ImplicitSender</span> <span class="k">with</span> <span class="nc">WordSpec</span> <span class="k">with</span> <span class="nc">MustMatchers</span> <span class="k">with</span> <span class="nc">BeforeAndAfterAll</span> <span class="o">{</span> </pre></div> </div> </div> <div class="section" id="using-multiple-probe-actors"> <h3>Using Multiple Probe Actors</h3> <p>When the actors under test are supposed to send various messages to different destinations, it may be difficult distinguishing the message streams arriving at the <tt class="xref py py-obj docutils literal"><span class="pre">testActor</span></tt> when using the <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> as a mixin. Another approach is to use it for creation of simple probe actors to be inserted in the message flows. To make this more powerful and convenient, there is a concrete implementation called <tt class="xref py py-class docutils literal"><span class="pre">TestProbe</span></tt>. The functionality is best explained using a small example:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">scala.concurrent.duration._</span> <span class="k">import</span> <span class="nn">akka.actor._</span> <span class="k">import</span> <span class="nn">scala.concurrent.Future</span> </pre></div> </div> <div class="highlight-scala"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyDoubleEcho</span> <span class="k">extends</span> <span class="nc">Actor</span> <span class="o">{</span> <span class="k">var</span> <span class="n">dest1</span><span class="k">:</span> <span class="kt">ActorRef</span> <span class="o">=</span> <span class="k">_</span> <span class="k">var</span> <span class="n">dest2</span><span class="k">:</span> <span class="kt">ActorRef</span> <span class="o">=</span> <span class="k">_</span> <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span> <span class="k">case</span> <span class="o">(</span><span class="n">d1</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">,</span> <span class="n">d2</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">)</span> <span class="k">⇒</span> <span class="n">dest1</span> <span class="k">=</span> <span class="n">d1</span> <span class="n">dest2</span> <span class="k">=</span> <span class="n">d2</span> <span class="k">case</span> <span class="n">x</span> <span class="k">⇒</span> <span class="n">dest1</span> <span class="o">!</span> <span class="n">x</span> <span class="n">dest2</span> <span class="o">!</span> <span class="n">x</span> <span class="o">}</span> <span class="o">}</span> </pre></div> </div> <div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">probe1</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span> <span class="k">val</span> <span class="n">probe2</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span> <span class="k">val</span> <span class="n">actor</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">MyDoubleEcho</span><span class="o">])</span> <span class="n">actor</span> <span class="o">!</span> <span class="o">((</span><span class="n">probe1</span><span class="o">.</span><span class="n">ref</span><span class="o">,</span> <span class="n">probe2</span><span class="o">.</span><span class="n">ref</span><span class="o">))</span> <span class="n">actor</span> <span class="o">!</span> <span class="s">&quot;hello&quot;</span> <span class="n">probe1</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="mi">500</span> <span class="n">millis</span><span class="o">,</span> <span class="s">&quot;hello&quot;</span><span class="o">)</span> <span class="n">probe2</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="mi">500</span> <span class="n">millis</span><span class="o">,</span> <span class="s">&quot;hello&quot;</span><span class="o">)</span> </pre></div> </div> <p>Here a the system under test is simulated by <tt class="xref py py-class docutils literal"><span class="pre">MyDoubleEcho</span></tt>, which is supposed to mirror its input to two outputs. Attaching two test probes enables verification of the (simplistic) behavior. Another example would be two actors A and B which collaborate by A sending messages to B. In order to verify this message flow, a <tt class="xref py py-class docutils literal"><span class="pre">TestProbe</span></tt> could be inserted as target of A, using the forwarding capabilities or auto-pilot described below to include a real B in the test setup.</p> <p>Probes may also be equipped with custom assertions to make your test code even more concise and clear:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">case</span> <span class="k">class</span> <span class="nc">Update</span><span class="o">(</span><span class="n">id</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">value</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">TestProbe</span><span class="o">(</span><span class="n">system</span><span class="o">)</span> <span class="o">{</span> <span class="k">def</span> <span class="n">expectUpdate</span><span class="o">(</span><span class="n">x</span><span class="k">:</span> <span class="kt">Int</span><span class="o">)</span> <span class="k">=</span> <span class="o">{</span> <span class="n">expectMsgPF</span><span class="o">()</span> <span class="o">{</span> <span class="k">case</span> <span class="nc">Update</span><span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="k">_</span><span class="o">)</span> <span class="k">if</span> <span class="n">id</span> <span class="o">==</span> <span class="n">x</span> <span class="k">⇒</span> <span class="kc">true</span> <span class="o">}</span> <span class="n">sender</span> <span class="o">!</span> <span class="s">&quot;ACK&quot;</span> <span class="o">}</span> <span class="o">}</span> </pre></div> </div> <p>You have complete flexibility here in mixing and matching the <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> facilities with your own checks and choosing an intuitive name for it. In real life your code will probably be a bit more complicated than the example given above; just use the power!</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">Any message send from a <tt class="docutils literal"><span class="pre">TestProbe</span></tt> to another actor which runs on the CallingThreadDispatcher runs the risk of dead-lock, if that other actor might also send to this probe. The implementation of <tt class="xref py py-meth docutils literal"><span class="pre">TestProbe.watch</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">TestProbe.unwatch</span></tt> will also send a message to the watchee, which means that it is dangerous to try watching e.g. <tt class="xref py py-class docutils literal"><span class="pre">TestActorRef</span></tt> from a <tt class="xref py py-meth docutils literal"><span class="pre">TestProbe</span></tt>.</p> </div> <div class="section" id="watching-other-actors-from-probes"> <h4>Watching Other Actors from Probes</h4> <p>A <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> can register itself for DeathWatch of any other actor:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span> <span class="n">probe</span> <span class="n">watch</span> <span class="n">target</span> <span class="n">target</span> <span class="o">!</span> <span class="nc">PoisonPill</span> <span class="n">probe</span><span class="o">.</span><span class="n">expectTerminated</span><span class="o">(</span><span class="n">target</span><span class="o">)</span> </pre></div> </div> </div> <div class="section" id="replying-to-messages-received-by-probes"> <h4>Replying to Messages Received by Probes</h4> <p>The probes keep track of the communications channel for replies, if possible, so they can also reply:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span> <span class="k">val</span> <span class="n">future</span> <span class="k">=</span> <span class="n">probe</span><span class="o">.</span><span class="n">ref</span> <span class="o">?</span> <span class="s">&quot;hello&quot;</span> <span class="n">probe</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="mi">0</span> <span class="n">millis</span><span class="o">,</span> <span class="s">&quot;hello&quot;</span><span class="o">)</span> <span class="c1">// TestActor runs on CallingThreadDispatcher</span> <span class="n">probe</span><span class="o">.</span><span class="n">reply</span><span class="o">(</span><span class="s">&quot;world&quot;</span><span class="o">)</span> <span class="n">assert</span><span class="o">(</span><span class="n">future</span><span class="o">.</span><span class="n">isCompleted</span> <span class="o">&amp;&amp;</span> <span class="n">future</span><span class="o">.</span><span class="n">value</span> <span class="o">==</span> <span class="nc">Some</span><span class="o">(</span><span class="nc">Success</span><span class="o">(</span><span class="s">&quot;world&quot;</span><span class="o">)))</span> </pre></div> </div> </div> <div class="section" id="forwarding-messages-received-by-probes"> <h4>Forwarding Messages Received by Probes</h4> <p>Given a destination actor <tt class="docutils literal"><span class="pre">dest</span></tt> which in the nominal actor network would receive a message from actor <tt class="docutils literal"><span class="pre">source</span></tt>. If you arrange for the message to be sent to a <tt class="xref py py-class docutils literal"><span class="pre">TestProbe</span></tt> <tt class="docutils literal"><span class="pre">probe</span></tt> instead, you can make assertions concerning volume and timing of the message flow while still keeping the network functioning:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Source</span><span class="o">(</span><span class="n">target</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Actor</span> <span class="o">{</span> <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span> <span class="k">case</span> <span class="s">&quot;start&quot;</span> <span class="k">⇒</span> <span class="n">target</span> <span class="o">!</span> <span class="s">&quot;work&quot;</span> <span class="o">}</span> <span class="o">}</span> <span class="k">class</span> <span class="nc">Destination</span> <span class="k">extends</span> <span class="nc">Actor</span> <span class="o">{</span> <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="o">{</span> <span class="k">case</span> <span class="n">x</span> <span class="k">⇒</span> <span class="c1">// Do something..</span> <span class="o">}</span> <span class="o">}</span> </pre></div> </div> <div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span> <span class="k">val</span> <span class="n">source</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">(</span><span class="n">classOf</span><span class="o">[</span><span class="kt">Source</span><span class="o">],</span> <span class="n">probe</span><span class="o">.</span><span class="n">ref</span><span class="o">))</span> <span class="k">val</span> <span class="n">dest</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">Destination</span><span class="o">])</span> <span class="n">source</span> <span class="o">!</span> <span class="s">&quot;start&quot;</span> <span class="n">probe</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="s">&quot;work&quot;</span><span class="o">)</span> <span class="n">probe</span><span class="o">.</span><span class="n">forward</span><span class="o">(</span><span class="n">dest</span><span class="o">)</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">dest</span></tt> actor will receive the same message invocation as if no test probe had intervened.</p> </div> <div class="section" id="auto-pilot"> <h4>Auto-Pilot</h4> <p>Receiving messages in a queue for later inspection is nice, but in order to keep a test running and verify traces later you can also install an <tt class="xref py py-class docutils literal"><span class="pre">AutoPilot</span></tt> in the participating test probes (actually in any <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt>) which is invoked before enqueueing to the inspection queue. This code can be used to forward messages, e.g. in a chain <tt class="docutils literal"><span class="pre">A</span> <span class="pre">--&gt;</span> <span class="pre">Probe</span> <span class="pre">--&gt;</span> <span class="pre">B</span></tt>, as long as a certain protocol is obeyed.</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span> <span class="n">probe</span><span class="o">.</span><span class="n">setAutoPilot</span><span class="o">(</span><span class="k">new</span> <span class="nc">TestActor</span><span class="o">.</span><span class="nc">AutoPilot</span> <span class="o">{</span> <span class="k">def</span> <span class="n">run</span><span class="o">(</span><span class="n">sender</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">,</span> <span class="n">msg</span><span class="k">:</span> <span class="kt">Any</span><span class="o">)</span><span class="k">:</span> <span class="kt">TestActor.AutoPilot</span> <span class="o">=</span> <span class="n">msg</span> <span class="k">match</span> <span class="o">{</span> <span class="k">case</span> <span class="s">&quot;stop&quot;</span> <span class="k">⇒</span> <span class="nc">TestActor</span><span class="o">.</span><span class="nc">NoAutoPilot</span> <span class="k">case</span> <span class="n">x</span> <span class="k">⇒</span> <span class="n">testActor</span><span class="o">.</span><span class="n">tell</span><span class="o">(</span><span class="n">x</span><span class="o">,</span> <span class="n">sender</span><span class="o">);</span> <span class="nc">TestActor</span><span class="o">.</span><span class="nc">KeepRunning</span> <span class="o">}</span> <span class="o">})</span> </pre></div> </div> <p>The <tt class="xref py py-meth docutils literal"><span class="pre">run</span></tt> method must return the auto-pilot for the next message, which may be <tt class="xref py py-class docutils literal"><span class="pre">KeepRunning</span></tt> to retain the current one or <tt class="xref py py-class docutils literal"><span class="pre">NoAutoPilot</span></tt> to switch it off.</p> </div> <div class="section" id="caution-about-timing-assertions"> <h4>Caution about Timing Assertions</h4> <p>The behavior of <tt class="xref py py-meth docutils literal"><span class="pre">within</span></tt> blocks when using test probes might be perceived as counter-intuitive: you need to remember that the nicely scoped deadline as described <a class="reference internal" href="#testkit-within"><em>above</em></a> is local to each probe. Hence, probes do not react to each other's deadlines or to the deadline set in an enclosing <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> instance:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">probe</span> <span class="k">=</span> <span class="nc">TestProbe</span><span class="o">()</span> <span class="n">within</span><span class="o">(</span><span class="mi">1</span> <span class="n">second</span><span class="o">)</span> <span class="o">{</span> <span class="n">probe</span><span class="o">.</span><span class="n">expectMsg</span><span class="o">(</span><span class="s">&quot;hello&quot;</span><span class="o">)</span> <span class="o">}</span> </pre></div> </div> <p>Here, the <tt class="docutils literal"><span class="pre">expectMsg</span></tt> call will use the default timeout.</p> </div> </div> </div> <div class="section" id="callingthreaddispatcher"> <span id="scala-callingthreaddispatcher"></span><h2>CallingThreadDispatcher</h2> <p>The <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> serves good purposes in unit testing, as described above, but originally it was conceived in order to allow contiguous stack traces to be generated in case of an error. As this special dispatcher runs everything which would normally be queued directly on the current thread, the full history of a message's processing chain is recorded on the call stack, so long as all intervening actors run on this dispatcher.</p> <div class="section" id="how-to-use-it"> <h3>How to use it</h3> <p>Just set the dispatcher as you normally would:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.CallingThreadDispatcher</span> <span class="k">val</span> <span class="n">ref</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">[</span><span class="kt">MyActor</span><span class="o">].</span><span class="n">withDispatcher</span><span class="o">(</span><span class="nc">CallingThreadDispatcher</span><span class="o">.</span><span class="nc">Id</span><span class="o">))</span> </pre></div> </div> </div> <div class="section" id="how-it-works"> <h3>How it works</h3> <p>When receiving an invocation, the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> checks whether the receiving actor is already active on the current thread. The simplest example for this situation is an actor which sends a message to itself. In this case, processing cannot continue immediately as that would violate the actor model, so the invocation is queued and will be processed when the active invocation on that actor finishes its processing; thus, it will be processed on the calling thread, but simply after the actor finishes its previous work. In the other case, the invocation is simply processed immediately on the current thread. Futures scheduled via this dispatcher are also executed immediately.</p> <p>This scheme makes the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> work like a general purpose dispatcher for any actors which never block on external events.</p> <p>In the presence of multiple threads it may happen that two invocations of an actor running on this dispatcher happen on two different threads at the same time. In this case, both will be processed directly on their respective threads, where both compete for the actor's lock and the loser has to wait. Thus, the actor model is left intact, but the price is loss of concurrency due to limited scheduling. In a sense this is equivalent to traditional mutex style concurrency.</p> <p>The other remaining difficulty is correct handling of suspend and resume: when an actor is suspended, subsequent invocations will be queued in thread-local queues (the same ones used for queuing in the normal case). The call to <tt class="xref py py-meth docutils literal"><span class="pre">resume</span></tt>, however, is done by one specific thread, and all other threads in the system will probably not be executing this specific actor, which leads to the problem that the thread-local queues cannot be emptied by their native threads. Hence, the thread calling <tt class="xref py py-meth docutils literal"><span class="pre">resume</span></tt> will collect all currently queued invocations from all threads into its own queue and process them.</p> </div> <div class="section" id="limitations"> <h3>Limitations</h3> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">In case the CallingThreadDispatcher is used for top-level actors, but without going through TestActorRef, then there is a time window during which the actor is awaiting construction by the user guardian actor. Sending messages to the actor during this time period will result in them being enqueued and then executed on the guardian’s thread instead of the caller’s thread. To avoid this, use TestActorRef.</p> </div> <p>If an actor's behavior blocks on a something which would normally be affected by the calling actor after having sent the message, this will obviously dead-lock when using this dispatcher. This is a common scenario in actor tests based on <tt class="xref py py-class docutils literal"><span class="pre">CountDownLatch</span></tt> for synchronization:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">latch</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">CountDownLatch</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span> <span class="n">actor</span> <span class="o">!</span> <span class="n">startWorkAfter</span><span class="o">(</span><span class="n">latch</span><span class="o">)</span> <span class="c1">// actor will call latch.await() before proceeding</span> <span class="n">doSomeSetupStuff</span><span class="o">()</span> <span class="n">latch</span><span class="o">.</span><span class="n">countDown</span><span class="o">()</span> </pre></div> </div> <p>The example would hang indefinitely within the message processing initiated on the second line and never reach the fourth line, which would unblock it on a normal dispatcher.</p> <p>Thus, keep in mind that the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> is not a general-purpose replacement for the normal dispatchers. On the other hand it may be quite useful to run your actor network on it for testing, because if it runs without dead-locking chances are very high that it will not dead-lock in production.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">The above sentence is unfortunately not a strong guarantee, because your code might directly or indirectly change its behavior when running on a different dispatcher. If you are looking for a tool to help you debug dead-locks, the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> may help with certain error scenarios, but keep in mind that it has may give false negatives as well as false positives.</p> </div> </div> <div class="section" id="thread-interruptions"> <h3>Thread Interruptions</h3> <p>If the CallingThreadDispatcher sees that the current thread has its <tt class="docutils literal"><span class="pre">isInterrupted()</span></tt> flag set when message processing returns, it will throw an <tt class="xref py py-class docutils literal"><span class="pre">InterruptedException</span></tt> after finishing all its processing (i.e. all messages which need processing as described above are processed before this happens). As <tt class="xref py py-meth docutils literal"><span class="pre">tell</span></tt> cannot throw exceptions due to its contract, this exception will then be caught and logged, and the thread’s interrupted status will be set again.</p> <p>If during message processing an <tt class="xref py py-class docutils literal"><span class="pre">InterruptedException</span></tt> is thrown then it will be caught inside the CallingThreadDispatcher’s message handling loop, the thread’s interrupted flag will be set and processing continues normally.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The summary of these two paragraphs is that if the current thread is interrupted while doing work under the CallingThreadDispatcher, then that will result in the <tt class="docutils literal"><span class="pre">isInterrupted</span></tt> flag to be <tt class="docutils literal"><span class="pre">true</span></tt> when the message send returns and no <tt class="xref py py-class docutils literal"><span class="pre">InterruptedException</span></tt> will be thrown.</p> </div> </div> <div class="section" id="benefits"> <h3>Benefits</h3> <p>To summarize, these are the features with the <tt class="xref py py-class docutils literal"><span class="pre">CallingThreadDispatcher</span></tt> has to offer:</p> <blockquote> <div><ul class="simple"> <li>Deterministic execution of single-threaded tests while retaining nearly full actor semantics</li> <li>Full message processing history leading up to the point of failure in exception stack traces</li> <li>Exclusion of certain classes of dead-lock scenarios</li> </ul> </div></blockquote> </div> </div> <div class="section" id="tracing-actor-invocations"> <span id="actor-logging-scala"></span><h2>Tracing Actor Invocations</h2> <p>The testing facilities described up to this point were aiming at formulating assertions about a system’s behavior. If a test fails, it is usually your job to find the cause, fix it and verify the test again. This process is supported by debuggers as well as logging, where the Akka toolkit offers the following options:</p> <ul> <li><p class="first"><em>Logging of exceptions thrown within Actor instances</em></p> <p>This is always on; in contrast to the other logging mechanisms, this logs at <tt class="docutils literal"><span class="pre">ERROR</span></tt> level.</p> </li> <li><p class="first"><em>Logging of message invocations on certain actors</em></p> <p>This is enabled by a setting in the <a class="reference internal" href="../general/configuration.html#configuration"><em>Configuration</em></a> — namely <tt class="docutils literal"><span class="pre">akka.actor.debug.receive</span></tt> — which enables the <tt class="xref py py-meth docutils literal"><span class="pre">loggable</span></tt> statement to be applied to an actor’s <tt class="xref py py-meth docutils literal"><span class="pre">receive</span></tt> function:</p> </li> </ul> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.event.LoggingReceive</span> <span class="k">def</span> <span class="n">receive</span> <span class="k">=</span> <span class="nc">LoggingReceive</span> <span class="o">{</span> <span class="k">case</span> <span class="n">msg</span> <span class="k">⇒</span> <span class="c1">// Do something...</span> <span class="o">}</span> </pre></div> </div> <dl class="docutils"> <dt>.</dt> <dd><p class="first">If the abovementioned setting is not given in the <a class="reference internal" href="../general/configuration.html#configuration"><em>Configuration</em></a>, this method will pass through the given <tt class="xref py py-class docutils literal"><span class="pre">Receive</span></tt> function unmodified, meaning that there is no runtime cost unless actually enabled.</p> <p class="last">The logging feature is coupled to this specific local mark-up because enabling it uniformly on all actors is not usually what you need, and it would lead to endless loops if it were applied to event bus logger listeners.</p> </dd> </dl> <ul> <li><p class="first"><em>Logging of special messages</em></p> <p>Actors handle certain special messages automatically, e.g. <tt class="xref py py-obj docutils literal"><span class="pre">Kill</span></tt>, <tt class="xref py py-obj docutils literal"><span class="pre">PoisonPill</span></tt>, etc. Tracing of these message invocations is enabled by the setting <tt class="docutils literal"><span class="pre">akka.actor.debug.autoreceive</span></tt>, which enables this on all actors.</p> </li> <li><p class="first"><em>Logging of the actor lifecycle</em></p> <p>Actor creation, start, restart, monitor start, monitor stop and stop may be traced by enabling the setting <tt class="docutils literal"><span class="pre">akka.actor.debug.lifecycle</span></tt>; this, too, is enabled uniformly on all actors.</p> </li> </ul> <p>All these messages are logged at <tt class="docutils literal"><span class="pre">DEBUG</span></tt> level. To summarize, you can enable full logging of actor activities using this configuration fragment:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="n">akka</span> <span class="o">{</span> <span class="n">loglevel</span> <span class="k">=</span> <span class="s">&quot;DEBUG&quot;</span> <span class="n">actor</span> <span class="o">{</span> <span class="n">debug</span> <span class="o">{</span> <span class="n">receive</span> <span class="k">=</span> <span class="n">on</span> <span class="n">autoreceive</span> <span class="k">=</span> <span class="n">on</span> <span class="n">lifecycle</span> <span class="k">=</span> <span class="n">on</span> <span class="o">}</span> <span class="o">}</span> <span class="o">}</span> </pre></div> </div> </div> <div class="section" id="different-testing-frameworks"> <h2>Different Testing Frameworks</h2> <p>Akka’s own test suite is written using <a class="reference external" href="http://scalatest.org">ScalaTest</a>, which also shines through in documentation examples. However, the TestKit and its facilities do not depend on that framework, you can essentially use whichever suits your development style best.</p> <p>This section contains a collection of known gotchas with some other frameworks, which is by no means exhaustive and does not imply endorsement or special support.</p> <div class="section" id="when-you-need-it-to-be-a-trait"> <h3>When you need it to be a trait</h3> <p>If for some reason it is a problem to inherit from <tt class="xref py py-class docutils literal"><span class="pre">TestKit</span></tt> due to it being a concrete class instead of a trait, there’s <tt class="xref py py-class docutils literal"><span class="pre">TestKitBase</span></tt>:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.testkit.TestKitBase</span> <span class="k">class</span> <span class="nc">MyTest</span> <span class="k">extends</span> <span class="nc">TestKitBase</span> <span class="o">{</span> <span class="k">implicit</span> <span class="k">lazy</span> <span class="k">val</span> <span class="n">system</span> <span class="k">=</span> <span class="nc">ActorSystem</span><span class="o">()</span> <span class="c1">// put your test code here ...</span> <span class="n">shutdown</span><span class="o">(</span><span class="n">system</span><span class="o">)</span> <span class="o">}</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">implicit&nbsp;lazy&nbsp;val&nbsp;system</span></tt> must be declared exactly like that (you can of course pass arguments to the actor system factory as needed) because trait <tt class="xref py py-class docutils literal"><span class="pre">TestKitBase</span></tt> needs the system during its construction.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">Use of the trait is discouraged because of potential issues with binary backwards compatibility in the future, use at own risk.</p> </div> </div> <div class="section" id="specs2"> <h3>Specs2</h3> <p>Some <a class="reference external" href="http://specs2.org">Specs2</a> users have contributed examples of how to work around some clashes which may arise:</p> <ul class="simple"> <li>Mixing TestKit into <tt class="xref py py-class docutils literal"><span class="pre">org.specs2.mutable.Specification</span></tt> results in a name clash involving the <tt class="docutils literal"><span class="pre">end</span></tt> method (which is a private variable in TestKit and an abstract method in Specification); if mixing in TestKit first, the code may compile but might then fail at runtime. The work-around—which is actually beneficial also for the third point—is to apply the TestKit together with <tt class="xref py py-class docutils literal"><span class="pre">org.specs2.specification.Scope</span></tt>.</li> <li>The Specification traits provide a <tt class="xref py py-class docutils literal"><span class="pre">Duration</span></tt> DSL which uses partly the same method names as <tt class="xref py py-class docutils literal"><span class="pre">scala.concurrent.duration.Duration</span></tt>, resulting in ambiguous implicits if <tt class="docutils literal"><span class="pre">scala.concurrent.duration._</span></tt> is imported. There are two work-arounds:<ul> <li>either use the Specification variant of Duration and supply an implicit conversion to the Akka Duration. This conversion is not supplied with the Akka distribution because that would mean that our JAR files would dependon Specs2, which is not justified by this little feature.</li> <li>or mix <tt class="xref py py-class docutils literal"><span class="pre">org.specs2.time.NoTimeConversions</span></tt> into the Specification.</li> </ul> </li> <li>Specifications are by default executed concurrently, which requires some care when writing the tests or alternatively the <tt class="docutils literal"><span class="pre">sequential</span></tt> keyword.</li> </ul> </div> </div> <div class="section" id="testing-custom-router-logic"> <h2>Testing Custom Router Logic</h2> <p>Given the following custom (dummy) router:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.actor.</span><span class="o">{</span> <span class="nc">ActorRef</span><span class="o">,</span> <span class="nc">Props</span><span class="o">,</span> <span class="nc">SupervisorStrategy</span> <span class="o">}</span> <span class="k">import</span> <span class="nn">akka.dispatch.Dispatchers</span> <span class="k">class</span> <span class="nc">MyRouter</span><span class="o">(</span><span class="n">target</span><span class="k">:</span> <span class="kt">ActorRef</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">RouterConfig</span> <span class="o">{</span> <span class="k">override</span> <span class="k">def</span> <span class="n">createRoute</span><span class="o">(</span><span class="n">provider</span><span class="k">:</span> <span class="kt">RouteeProvider</span><span class="o">)</span><span class="k">:</span> <span class="kt">Route</span> <span class="o">=</span> <span class="o">{</span> <span class="n">provider</span><span class="o">.</span><span class="n">createRoutees</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span> <span class="o">{</span> <span class="k">case</span> <span class="o">(</span><span class="n">sender</span><span class="o">,</span> <span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">⇒</span> <span class="nc">List</span><span class="o">(</span><span class="nc">Destination</span><span class="o">(</span><span class="n">sender</span><span class="o">,</span> <span class="n">target</span><span class="o">))</span> <span class="k">case</span> <span class="o">(</span><span class="n">sender</span><span class="o">,</span> <span class="n">message</span><span class="o">)</span> <span class="k">⇒</span> <span class="n">toAll</span><span class="o">(</span><span class="n">sender</span><span class="o">,</span> <span class="n">provider</span><span class="o">.</span><span class="n">routees</span><span class="o">)</span> <span class="o">}</span> <span class="o">}</span> <span class="k">override</span> <span class="k">def</span> <span class="n">supervisorStrategy</span> <span class="k">=</span> <span class="nc">SupervisorStrategy</span><span class="o">.</span><span class="n">defaultStrategy</span> <span class="k">override</span> <span class="k">def</span> <span class="n">routerDispatcher</span> <span class="k">=</span> <span class="nc">Dispatchers</span><span class="o">.</span><span class="nc">DefaultDispatcherId</span> <span class="o">}</span> </pre></div> </div> <p>This might be tested by dispatching messages and asserting their reception at the right destinations, but that can be inconvenient. Therefore exists the <tt class="xref py py-obj docutils literal"><span class="pre">ExtractRoute</span></tt> extractor, which can be used like so:</p> <div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.pattern.ask</span> <span class="k">import</span> <span class="nn">akka.testkit.ExtractRoute</span> <span class="k">import</span> <span class="nn">scala.concurrent.Await</span> <span class="k">import</span> <span class="nn">scala.concurrent.duration._</span> <span class="k">val</span> <span class="n">target</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">.</span><span class="n">empty</span><span class="o">)</span> <span class="k">val</span> <span class="n">router</span> <span class="k">=</span> <span class="n">system</span><span class="o">.</span><span class="n">actorOf</span><span class="o">(</span><span class="nc">Props</span><span class="o">.</span><span class="n">empty</span><span class="o">.</span><span class="n">withRouter</span><span class="o">(</span><span class="k">new</span> <span class="nc">MyRouter</span><span class="o">(</span><span class="n">target</span><span class="o">)))</span> <span class="k">val</span> <span class="n">route</span> <span class="k">=</span> <span class="nc">ExtractRoute</span><span class="o">(</span><span class="n">router</span><span class="o">)</span> <span class="k">val</span> <span class="n">r</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">router</span><span class="o">.</span><span class="n">ask</span><span class="o">(</span><span class="nc">CurrentRoutees</span><span class="o">)(</span><span class="mi">1</span> <span class="n">second</span><span class="o">).</span> <span class="n">mapTo</span><span class="o">[</span><span class="kt">RouterRoutees</span><span class="o">],</span> <span class="mi">1</span> <span class="n">second</span><span class="o">)</span> <span class="n">r</span><span class="o">.</span><span class="n">routees</span><span class="o">.</span><span class="n">size</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span> <span class="n">route</span><span class="o">(</span><span class="n">testActor</span> <span class="o">-&gt;</span> <span class="s">&quot;hallo&quot;</span><span class="o">)</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="nc">List</span><span class="o">(</span><span class="nc">Destination</span><span class="o">(</span><span class="n">testActor</span><span class="o">,</span> <span class="n">target</span><span class="o">)))</span> <span class="n">route</span><span class="o">(</span><span class="n">testActor</span> <span class="o">-&gt;</span> <span class="mi">12</span><span class="o">)</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="nc">List</span><span class="o">(</span><span class="nc">Destination</span><span class="o">(</span><span class="n">testActor</span><span class="o">,</span> <span class="n">r</span><span class="o">.</span><span class="n">routees</span><span class="o">.</span><span class="n">head</span><span class="o">)))</span> </pre></div> </div> </div> </div> </div> <div class="span3"><p class="contents-title">Contents</p> <div id="scroller-anchor"> <div id="scroller"> <div id="toc"></div> </div> </div></div> </div> </div> </div> </div> <div class="footer"> <div class="container"> <ul> <li><h5>Akka</h5></li> <li><a href="http://akka.io/docs">Documentation</a></li> <li><a href="http://akka.io/faq">FAQ</a></li> <li><a href="http://typesafe.com/stack/downloads/akka">Downloads</a></li> <li><a href="http://akka.io/news">News</a></li> <li><a href="http://letitcrash.com">Blog</a></li> </ul> <ul> <li><h5>Contribute</h5></li> <li><a href="http://akka.io/community">Community Projects</a></li> <li><a href="http://github.com/akka/akka">Source Code</a></li> <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li> <li><a href="http://doc.akka.io/docs/akka/current/project/issue-tracking.html">Report a Bug</a></li> </ul> <ul> <li><h5>Company</h5></li> <li><a href="http://typesafe.com/products/typesafe-subscription">Commercial Support</a></li> <li><a href="http://akka.io/team">Team</a></li> <li><a href="mailto:info@typesafe.com">Contact</a></li> </ul> <ul> <li><img src="../_static/watermark.png" align="center"/></li> </ul> </div> <div class="container copyright"> <p style="float: left;"> © 2013 <a href="http://typesafe.com/">Typesafe Inc.</a> <span class="license">Akka is Open Source and available under the Apache 2 License.</span> </p> <p style="float: right; font-size: 12px;"> Last updated: Feb 22, 2014 </p> </div> </div> <script type="text/javascript"> $('#toc').toc(); </script> </body> </html>
{ "content_hash": "2fd6e4002d3597a0f72ea7562f70ed03", "timestamp": "", "source": "github", "line_count": 1074, "max_line_length": 565, "avg_line_length": 84.26722532588454, "alnum_prop": 0.6979105665005579, "repo_name": "knutwalker/akka-html-docset", "id": "c41b37ffaa0206465af43e5ac541061618594411", "size": "90569", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "akka-html.docset/Contents/Resources/Documents/scala/testing.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12650" }, { "name": "JavaScript", "bytes": "33165" }, { "name": "Python", "bytes": "4542" } ] }
<?php namespace Google\Service\GoogleAnalyticsAdmin; class GoogleAnalyticsAdminV1alphaExpandedDataSetFilter extends \Google\Model { /** * @var string */ public $fieldName; protected $inListFilterType = GoogleAnalyticsAdminV1alphaExpandedDataSetFilterInListFilter::class; protected $inListFilterDataType = ''; protected $stringFilterType = GoogleAnalyticsAdminV1alphaExpandedDataSetFilterStringFilter::class; protected $stringFilterDataType = ''; /** * @param string */ public function setFieldName($fieldName) { $this->fieldName = $fieldName; } /** * @return string */ public function getFieldName() { return $this->fieldName; } /** * @param GoogleAnalyticsAdminV1alphaExpandedDataSetFilterInListFilter */ public function setInListFilter(GoogleAnalyticsAdminV1alphaExpandedDataSetFilterInListFilter $inListFilter) { $this->inListFilter = $inListFilter; } /** * @return GoogleAnalyticsAdminV1alphaExpandedDataSetFilterInListFilter */ public function getInListFilter() { return $this->inListFilter; } /** * @param GoogleAnalyticsAdminV1alphaExpandedDataSetFilterStringFilter */ public function setStringFilter(GoogleAnalyticsAdminV1alphaExpandedDataSetFilterStringFilter $stringFilter) { $this->stringFilter = $stringFilter; } /** * @return GoogleAnalyticsAdminV1alphaExpandedDataSetFilterStringFilter */ public function getStringFilter() { return $this->stringFilter; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(GoogleAnalyticsAdminV1alphaExpandedDataSetFilter::class, 'Google_Service_GoogleAnalyticsAdmin_GoogleAnalyticsAdminV1alphaExpandedDataSetFilter');
{ "content_hash": "2ba12870527b8b7096b7e49c57c8de4e", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 157, "avg_line_length": 28.096774193548388, "alnum_prop": 0.7663605051664754, "repo_name": "googleapis/google-api-php-client-services", "id": "ec9c1bf670bfe550873f04088b8b717fea3e95cb", "size": "2332", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/GoogleAnalyticsAdmin/GoogleAnalyticsAdminV1alphaExpandedDataSetFilter.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "55414116" }, { "name": "Python", "bytes": "427325" }, { "name": "Shell", "bytes": "787" } ] }
import './App.scss'; import Component from 'react-pure-render/component'; import Footer from './Footer.react'; import Header from './Header.react'; import Helmet from 'react-helmet'; import React, { PropTypes } from 'react'; import favicon from '../../common/app/favicon'; import start from '../../common/app/start'; import { connect } from 'react-redux'; import { locationShape } from 'react-router'; // v4-alpha.getbootstrap.com/getting-started/introduction/#starter-template const bootstrap4Metas = [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1, shrink-to-fit=no' }, { 'http-equiv': 'x-ua-compatible', content: 'ie=edge' } ]; class App extends Component { static propTypes = { children: PropTypes.object.isRequired, currentLocale: PropTypes.string.isRequired, location: locationShape }; render() { const { children, currentLocale, location } = this.props; return ( <div className="container"> <Helmet htmlAttributes={{ lang: currentLocale }} titleTemplate="%s - Este.js" meta={[ ...bootstrap4Metas, { name: 'description', content: 'Dev stack and starter kit for functional and universal React apps' }, ...favicon.meta ]} link={[ ...favicon.link ]} /> {/* Pass location to ensure header active links are updated. */} <Header location={location} /> {children} <Footer /> </div> ); } } App = start(App); export default connect(state => ({ currentLocale: state.intl.currentLocale }))(App);
{ "content_hash": "d1c596bb0f4db9bcfe9b57696095cb13", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 90, "avg_line_length": 25.507462686567163, "alnum_prop": 0.5997659449970744, "repo_name": "nikolalosic/este-app--assignment", "id": "edf91da9a6eb489839854af813d707cf010a7ab8", "size": "1709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/browser/app/App.react.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7684" }, { "name": "Java", "bytes": "1222" }, { "name": "JavaScript", "bytes": "251418" }, { "name": "Objective-C", "bytes": "5183" }, { "name": "Python", "bytes": "1632" } ] }
package features import ( "crypto/sha256" "fmt" "k8s.io/ingress-gce/pkg/composite" "k8s.io/ingress-gce/pkg/utils" "k8s.io/klog/v2" ) // EnsureIAP reads the IAP configuration specified in the BackendConfig // and applies it to the BackendService if it is stale. It returns true // if there were existing settings on the BackendService that were overwritten. func EnsureIAP(sp utils.ServicePort, be *composite.BackendService) bool { if sp.BackendConfig.Spec.Iap == nil { return false } beTemp := &composite.BackendService{} applyIAPSettings(sp, beTemp) // We need to compare the SHA256 of the client secret instead of the client secret itself // since that field is redacted when getting a BackendService. beTemp.Iap.Oauth2ClientSecretSha256 = fmt.Sprintf("%x", sha256.Sum256([]byte(beTemp.Iap.Oauth2ClientSecret))) if be.Iap == nil || beTemp.Iap.Enabled != be.Iap.Enabled || beTemp.Iap.Oauth2ClientId != be.Iap.Oauth2ClientId || beTemp.Iap.Oauth2ClientSecretSha256 != be.Iap.Oauth2ClientSecretSha256 { applyIAPSettings(sp, be) klog.V(2).Infof("Updated IAP settings for service %v/%v.", sp.ID.Service.Namespace, sp.ID.Service.Name) return true } return false } // applyIAPSettings applies the IAP settings specified in the BackendConfig // to the passed in compute.BackendService. A GCE API call still needs to be // made to actually persist the changes. func applyIAPSettings(sp utils.ServicePort, be *composite.BackendService) { beConfig := sp.BackendConfig // Apply the boolean switch be.Iap = &composite.BackendServiceIAP{Enabled: beConfig.Spec.Iap.Enabled} // Apply the OAuth credentials be.Iap.Oauth2ClientId = beConfig.Spec.Iap.OAuthClientCredentials.ClientID be.Iap.Oauth2ClientSecret = beConfig.Spec.Iap.OAuthClientCredentials.ClientSecret }
{ "content_hash": "bc34c6250289cce2bcb7d3120ce8b370", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 187, "avg_line_length": 40.54545454545455, "alnum_prop": 0.7713004484304933, "repo_name": "kubernetes/ingress-gce", "id": "502ff7ac33e7bdf1f18437ef83e4f8b272e26262", "size": "2353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/backends/features/iap.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "3692620" }, { "name": "Makefile", "bytes": "11142" }, { "name": "Shell", "bytes": "20057" } ] }
exports.defineAutoTests = function () { describe('Battery (navigator.battery)', function () { it("battery.spec.1 should exist", function () { expect(navigator.battery).toBeDefined(); }); }); describe('Battery Events', function () { // BatteryStatus beforeEach(function () { // Custom Matcher jasmine.Expectation.addMatchers({ toBatteryStatus : function () { return { compare : function (status, message) { var pass = status; return { pass : pass, message : message }; } }; } }); }); it("battery.spec.2 should fire batterystatus events", function (done) { var onEvent = function () { window.removeEventListener("batterystatus", onEvent, false); onEventFlag = true; }, onEventFlag = false; // batterystatus -> 30 window.addEventListener("batterystatus", onEvent, false); navigator.battery._status({ level : 30, isPlugged : false }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterystatus" event, it did not fire'); done(); }, 100); }); it("battery.spec.3 should fire batterylow event (30 -> 20)", function (done) { var onEvent = function () { window.removeEventListener("batterylow", onEvent, false); onEventFlag = true; }, onEventFlag = false; // batterylow 30 -> 20 navigator.battery._status({ level : 30, isPlugged : false }); window.addEventListener("batterylow", onEvent, false); navigator.battery._status({ level : 20, isPlugged : false }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterylow" event (30 -> 20), it did not fire'); done(); }, 100); }); it("battery.spec.3.1 should fire batterylow event (30 -> 19)", function (done) { var onEvent = function () { window.removeEventListener("batterylow", onEvent, false); onEventFlag = true; }, onEventFlag = false; // batterylow 30 -> 19 navigator.battery._status({ level : 30, isPlugged : false }); window.addEventListener("batterylow", onEvent, false); navigator.battery._status({ level : 19, isPlugged : false }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterylow" event (30 -> 19), it did not fire'); done(); }, 100); }); it("battery.spec.3.2 should not fire batterylow event (5 -> 20)", function (done) { var onEvent = function () { window.removeEventListener("batterylow", onEvent, false); onEventFlag = false; }, onEventFlag = true; // batterylow should not fire when level increases (5->20) ( CB-4519 ) navigator.battery._status({ level : 5, isPlugged : false }); window.addEventListener("batterylow", onEvent, false); navigator.battery._status({ level : 20, isPlugged : false }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterylow" event (5 -> 20), should not be fired'); done(); }, 100); }); it("battery.spec.3.3 batterylow event(21 -> 20) should not fire if charging", function (done) { var onEvent = function () { window.removeEventListener("batterylow", onEvent, false); onEventFlag = false; }, onEventFlag = true; // batterylow should NOT fire if we are charging ( CB-4520 ) navigator.battery._status({ level : 21, isPlugged : true }); window.addEventListener("batterylow", onEvent, false); navigator.battery._status({ level : 20, isPlugged : true }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterylow" event (21 -> 20), should not be fired if charging'); done(); }, 100); }); it("battery.spec.4 should fire batterycritical events (19 -> 5)", function (done) { var onEvent = function () { window.removeEventListener("batterycritical", onEvent, false); onEventFlag = true; }, onEventFlag = false; // batterycritical 19->5 navigator.battery._status({ level : 19, isPlugged : false }); window.addEventListener("batterycritical", onEvent, false); navigator.battery._status({ level : 5, isPlugged : false }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterycritical" event (19 -> 5), it did not fire'); done(); }, 100); }); it("battery.spec.4.1 should fire batterycritical (19 -> 4) events", function (done) { var onEvent = function () { window.removeEventListener("batterycritical", onEvent, false); onEventFlag = true; }, onEventFlag = false; // batterycritical 19->4 navigator.battery._status({ level : 19, isPlugged : false }); window.addEventListener("batterycritical", onEvent, false); navigator.battery._status({ level : 4, isPlugged : false }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterycritical" event (19 -> 4), it did not fire'); done(); }, 100); }); it("battery.spec.4.2 should fire batterycritical event (100 -> 4) when decreases", function (done) { var onEvent = function () { window.removeEventListener("batterycritical", onEvent, false); onEventFlag = true; }, onEventFlag = false; // setup: batterycritical should fire when level decreases (100->4) ( CB-4519 ) navigator.battery._status({ level : 100, isPlugged : false }); window.addEventListener("batterycritical", onEvent, false); navigator.battery._status({ level : 4, isPlugged : false }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterycritical" event (100 -> 4), it did not fire'); done(); }, 100); }); it("battery.spec.4.3 should not fire batterycritical event (4 -> 5) when increasing", function (done) { var onEvent = function () { window.removeEventListener("batterycritical", onEvent, false); onEventFlag = false; }, onEventFlag = true; // batterycritical should not fire when level increases (4->5)( CB-4519 ) navigator.battery._status({ level : 4, isPlugged : false }); window.addEventListener("batterycritical", onEvent, false); navigator.battery._status({ level : 5, isPlugged : false }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterycritical" event (4 -> 5), should not be fired'); done(); }, 100); }); it("battery.spec.4.4 should not fire batterycritical event (6 -> 5) if charging", function (done) { var onEvent = function () { window.removeEventListener("batterycritical", onEvent, false); onEventFlag = false; }, onEventFlag = true; // batterycritical should NOT fire if we are charging ( CB-4520 ) navigator.battery._status({ level : 6, isPlugged : true }); window.addEventListener("batterycritical", onEvent, false); navigator.battery._status({ level : 5, isPlugged : true }); setTimeout(function () { expect(onEventFlag).toBatteryStatus('Listener: "batterycritical" event (6 -> 5), should not be fired if charging'); done(); }, 100); }); }); }; //****************************************************************************************** //***************************************Manual Tests*************************************** //****************************************************************************************** exports.defineManualTests = function (contentEl, createActionButton) { /* Battery */ function updateInfo(info) { document.getElementById('levelValue').innerText = info.level; document.getElementById('pluggedValue').innerText = info.isPlugged; if (info.level > 5) { document.getElementById('criticalValue').innerText = "false"; } if (info.level > 20) { document.getElementById('lowValue').innerText = "false"; } } function batteryLow(info) { document.getElementById('lowValue').innerText = "true"; } function batteryCritical(info) { document.getElementById('criticalValue').innerText = "true"; } function addBattery() { window.addEventListener("batterystatus", updateInfo, false); } function removeBattery() { window.removeEventListener("batterystatus", updateInfo, false); } function addLow() { window.addEventListener("batterylow", batteryLow, false); } function removeLow() { window.removeEventListener("batterylow", batteryLow, false); } function addCritical() { window.addEventListener("batterycritical", batteryCritical, false); } function removeCritical() { window.removeEventListener("batterycritical", batteryCritical, false); } //Generate Dynamic Table function generateTable(tableId, rows, cells, elements) { var table = document.createElement('table'); for (var r = 0; r < rows; r++) { var row = table.insertRow(r); for (var c = 0; c < cells; c++) { var cell = row.insertCell(c); cell.setAttribute("align", "center"); for (var e in elements) { if (elements[e].position.row == r && elements[e].position.cell == c) { var htmlElement = document.createElement(elements[e].tag); var content; if (elements[e].content !== "") { content = document.createTextNode(elements[e].content); htmlElement.appendChild(content); } if (elements[e].type) { htmlElement.type = elements[e].type; } htmlElement.setAttribute("id", elements[e].id); cell.appendChild(htmlElement); } } } } table.setAttribute("align", "center"); table.setAttribute("id", tableId); return table; } // Battery Elements var batteryElements = [{ id : "tableName", content : "Battery", tag : "h2", position : { row : 0, cell : 0 } }, { id : "statusTag", content : "Status:", tag : "div", position : { row : 1, cell : 0 } }, { id : "statusValue", content : "", tag : "div", position : { row : 1, cell : 1 } }, { id : "levelTag", content : "Level:", tag : "div", position : { row : 2, cell : 0 } }, { id : "levelValue", content : "", tag : "div", position : { row : 2, cell : 1 } }, { id : "pluggedTag", content : "Plugged:", tag : "div", position : { row : 3, cell : 0 } }, { id : "pluggedValue", content : "", tag : "div", position : { row : 3, cell : 1 } }, { id : "lowTag", content : "Low:", tag : "div", position : { row : 4, cell : 0 } }, { id : "lowValue", content : "", tag : "div", position : { row : 4, cell : 1 } }, { id : "criticalTag", content : "Critical:", tag : "div", position : { row : 5, cell : 0 } }, { id : "criticalValue", content : "", tag : "div", position : { row : 5, cell : 1 } }, { id : "actionTag", content : "Actions", tag : "h2", position : { row : 6, cell : 0 } }, { id : "addBS", content : "", tag : "div", position : { row : 7, cell : 0 } }, { id : "remBs", content : "", tag : "div", position : { row : 7, cell : 1 } }, { id : "addBl", content : "", tag : "div", position : { row : 8, cell : 0 } }, { id : "remBl", content : "", tag : "div", position : { row : 8, cell : 1 } }, { id : "addBc", content : "", tag : "div", position : { row : 9, cell : 0 } }, { id : "remBc", content : "", tag : "div", position : { row : 9, cell : 1 } } ]; batteryTable = generateTable('batteryContent', 10, 3, batteryElements); contentEl.appendChild(batteryTable); createActionButton('Add "batterystatus" listener', function () { addBattery(); }, 'addBS'); createActionButton('Remove "batterystatus" listener', function () { removeBattery(); }, 'remBs'); createActionButton('Add "batterylow" listener', function () { addLow(); }, 'addBl'); createActionButton('Remove "batterylow" listener', function () { removeLow(); }, 'remBl'); createActionButton('Add "batterycritical" listener', function () { addCritical(); }, 'addBc'); createActionButton('Remove "batterycritical" listener', function () { removeCritical(); }, 'remBc'); };
{ "content_hash": "359d50bfeff0042ad8f3631989976e52", "timestamp": "", "source": "github", "line_count": 530, "max_line_length": 131, "avg_line_length": 31.40377358490566, "alnum_prop": 0.4406392694063927, "repo_name": "paperdev7/mobile-project", "id": "c991f674a93c0be3110eb4c5fd60b7406567079d", "size": "17457", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/org.apache.cordova.battery-status/test/tests.js", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "3152" }, { "name": "C#", "bytes": "395160" }, { "name": "C++", "bytes": "431788" }, { "name": "CSS", "bytes": "466537" }, { "name": "D", "bytes": "133310" }, { "name": "Erlang", "bytes": "3284" }, { "name": "Java", "bytes": "1908226" }, { "name": "JavaScript", "bytes": "5224029" }, { "name": "Objective-C", "bytes": "582797" }, { "name": "PHP", "bytes": "222" }, { "name": "Perl", "bytes": "333" }, { "name": "Shell", "bytes": "11293" } ] }
<?php namespace frontend\services; use yii\base\Object; use app\models\RoadSection; interface IRoadSectionService { public function findBySerialNumber($serialNumber); } class RoadSectionService extends Object implements IRoadSectionService { function findBySerialNumber($serialNumber) { if (($model = RoadSection::find()->where(['serial_number' => $serialNumber])->one()) !== null) { return $model; } else { return null; } } }
{ "content_hash": "5d83e76b6a6dde438991c921a77b8b88", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 104, "avg_line_length": 21.47826086956522, "alnum_prop": 0.6578947368421053, "repo_name": "boylee1111/SupplyChain", "id": "0cde1c27b5c7fc3af73b8ae69520496c76c58203", "size": "494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/services/IRoadSectionService.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "199" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "2728" }, { "name": "PHP", "bytes": "871649" } ] }
from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.test import TestCase class TestView(TestCase): def test_project_home(self): response = self.client.get(reverse('project.home')) self.assertEqual(response.status_code, 200)
{ "content_hash": "7faf128a0c5c0a26a9d813ffc791704e", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 59, "avg_line_length": 26.636363636363637, "alnum_prop": 0.7372013651877133, "repo_name": "pkimber/mail", "id": "9b54968f499971cc183ec80142c91c5400372a83", "size": "319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example_mail/tests/test_view.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "14988" }, { "name": "Python", "bytes": "89271" }, { "name": "Shell", "bytes": "1112" } ] }
Imports System.Data 'Imports System.Data.SqlClient Imports System.Data.Common Imports bv.common.db.Core Imports bv.common.Core Imports EIDSS.model.Core.Security Imports bv.common.db.Security Public Class Person_DB Inherits BaseDbService Public Const TablePerson As String = "Person" Public Const TableUser As String = "UserTable" Public Const PersonKeyFieldName As String = "idfPerson" Public Sub New() ObjectName = "Person" End Sub Public Overrides Function GetDetail(ByVal ID As Object) As DataSet Dim ds As New DataSet Try Dim cmd As IDbCommand = CreateSPCommand("spPerson_SelectDetail") AddParam(cmd, "@idfPerson", ID) AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage) Dim PersonDetail_Adapter As DbDataAdapter = CreateAdapter(cmd, False) PersonDetail_Adapter.Fill(ds, TablePerson) CorrectTable(ds.Tables(0), TablePerson) CorrectTable(ds.Tables(1), TableUser) ClearColumnsAttibutes(ds) ds.EnforceConstraints = False If ID Is Nothing Then ID = NewIntID() Dim r As DataRow = ds.Tables(TablePerson).NewRow r(PersonKeyFieldName) = ID ds.Tables(TablePerson).Rows.Add(r) m_IsNewObject = True End If m_ID = ID Dim dbs As BaseDbService = New SecurityPolicy_DB ds.Merge(dbs.GetDetail(Nothing)) Dim t As DataTable = ds.Tables(TableUser) t.Columns.Add("idfsSite1", GetType(Long), "idfsSite") t.Columns.Add("idfsSite2", GetType(Long), "idfsSite") 'cmd = CreateSPCommand("spPasswordPolicy_List") 'CreateAdapter(cmd, False).Fill(ds, TablePolicy) Return ds Catch ex As Exception m_Error = New ErrorMessage(StandardError.FillDatasetError, ex) Return Nothing End Try End Function Public Overrides Function PostDetail(ByVal ds As DataSet, ByVal PostType As Integer, Optional ByVal transaction As IDbTransaction = Nothing) As Boolean If ds Is Nothing Then Return True Try Dim changes As DataTable = ds.Tables(TableUser).GetChanges(DataRowState.Added Or DataRowState.Modified) ExecPostProcedure("spPerson_Post", ds.Tables(TablePerson), Connection, transaction) ExecPostProcedure("spUser_Post", ds.Tables(TableUser), Connection, transaction) If Not (changes Is Nothing) Then For Each row As DataRow In changes.Rows Dim pass As Object = row("strPassword") If Utils.IsEmpty(pass) Then Continue For Dim manager As New SecurityManager2() Dim res As Integer = manager.SetPassword( _ row("idfUserID"), _ Utils.Str(pass), _ Connection, _ transaction) If (res <> 0) Then Me.m_Error = SecurityMessages.GetLoginErrorMessage(res) Return False End If Next End If 'Add any other posting here if needed ' Alexander - Oct 2008 'If (Utils.IsPACS) Then ' SetPasswordExpiration(ds.Tables(TableUser).Rows(0), transaction) 'End If bv.common.db.Core.LookupCache.NotifyChange("Person", transaction, ID) 'SecurityCache_DB.NewUser(UserID) Catch ex As Exception m_Error = New ErrorMessage(StandardError.PostError, ex) Return False End Try Return True End Function Public Function SetLogin(ByVal ds As DataSet, ByVal login As String, ByVal passowrd As String) As Boolean If ds.Tables(Person_DB.TableUser).Rows.Count = 0 Then Dim r As DataRow = ds.Tables(Person_DB.TableUser).NewRow r.BeginEdit() r("idfUserID") = NewIntID() r("idfPerson") = ID r("idfsSite") = EIDSS.model.Core.EidssSiteContext.Instance.SiteID r("strAccountName") = login r("strPassword") = passowrd r.EndEdit() ds.Tables(Person_DB.TableUser).Rows.Add(r) Else Dim r As DataRow = ds.Tables(Person_DB.TableUser).Rows(0) r.BeginEdit() r("strAccountName") = login r("strPassword") = passowrd r.EndEdit() End If Return True End Function Public Sub DeleteLogin(ByVal ds As DataSet) If ds.Tables(Person_DB.TableUser).Rows.Count > 0 Then For i As Integer = ds.Tables(Person_DB.TableUser).Rows.Count - 1 To 0 If ds.Tables(Person_DB.TableUser).Rows(i).RowState <> DataRowState.Deleted Then ds.Tables(Person_DB.TableUser).Rows(i).Delete() End If Next End If End Sub '0 - no such login '1 - empty UserName/organization '2 - login exists '-1 - db error Public Function ValidateLogin(ByVal login As String) As Integer Dim cmd As IDbCommand = BaseDbService.CreateSPCommand("dbo.spLogin_Validate", Connection) BaseDbService.AddParam(cmd, "@idfPerson", ID) BaseDbService.AddParam(cmd, "@UserName", login) BaseDbService.AddParam(cmd, "@Result", 0, ParameterDirection.Output) m_Error = ExecCommand(cmd, Connection) If m_Error Is Nothing Then Return CInt(BaseDbService.GetParamValue(cmd, "@Result")) Else Return -1 End If End Function '0 - no such login '1 - empty UserName/organization '2 - login exists '-1 - db error Public Function ValidateLogin(ByVal Employee As Object, ByVal Site As Object, ByVal login As String) As Integer Dim cmd As IDbCommand = BaseDbService.CreateSPCommand("dbo.spLogin_Validate", Connection) BaseDbService.AddParam(cmd, "@idfPerson", Employee) BaseDbService.AddParam(cmd, "@idfsSite", Site) BaseDbService.AddParam(cmd, "@strAccountName", login) BaseDbService.AddParam(cmd, "@Result", 0, ParameterDirection.Output) m_Error = ExecCommand(cmd, Connection) If m_Error Is Nothing Then Return CInt(BaseDbService.GetParamValue(cmd, "@Result")) Else Return -1 End If End Function Public Sub SetPasswordExpiration(ByVal dr As DataRow, Optional ByVal transaction As IDbTransaction = Nothing) Dim UserID As Integer = CType(dr("idfUserID"), Integer) Dim UserMustChange As Boolean = CType(dr("MustChangePassword"), Boolean) Dim ExpirMonths As Integer = CType(dr("intExpirationPeriod"), Integer) SetPasswordExpiration(UserID, ExpirMonths, UserMustChange, transaction) End Sub Public Sub SetPasswordExpiration(ByVal UserID As Integer, ByVal UserMustChange As Boolean) SetPasswordExpiration(UserID, -1, UserMustChange) End Sub Sub SetPasswordExpiration(ByVal UserID As Integer, ByVal ExpirMonths As Integer, ByVal UserMustChange As Boolean, Optional ByVal transaction As IDbTransaction = Nothing) Dim ExpirationDate As DateTime If (ExpirMonths = 0) Then ExpirMonths = 12 * 100 ' Pass Never Expired ;) ExpirationDate = New DateTime(2100, 1, 1) Else ExpirationDate = New DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddMonths(ExpirMonths) End If If (UserMustChange) Then ExpirationDate = DateTime.Now() Dim cmd As IDbCommand = BaseDbService.CreateSPCommand("spPerson_SetPasswordExpiration", Connection) BaseDbService.AddParam(cmd, "@UserID", UserID) BaseDbService.AddParam(cmd, "@ExpirationDate", ExpirationDate) If (ExpirMonths > -1) Then ' do not change ExpirationPerion if ExpirMonths= -1 BaseDbService.AddParam(cmd, "@ExpirationPeriod", ExpirMonths) End If BaseDbService.ExecCommand(cmd, Connection, transaction, True) End Sub Public Sub GetPasswordExpiration(ByVal EmployeeID As Object, ByVal LoginName As String, ByRef ExpirationDate As DateTime) ExpirationDate = New DateTime(2100, 1, 1) Dim cmd As IDbCommand = BaseDbService.CreateSPCommand("spPerson_CheckNeedChangePassword", Connection) BaseDbService.AddParam(cmd, "@EmployeeID", EmployeeID) BaseDbService.AddParam(cmd, "@LoginName", LoginName) Dim dt As DataTable = BaseDbService.ExecTable(cmd) If (dt.Rows.Count = 0) Then Return If (IsDBNull(dt.Rows(0)("ExpirationDate")) = False) Then ExpirationDate = CType(dt.Rows(0)("ExpirationDate"), DateTime) End If End Sub Public Function IsPasswordAlreadyUsed(ByVal EmployeeID As Object, ByVal Password As String) As Boolean Dim cmd As IDbCommand = BaseDbService.CreateSPCommand("spPerson_CheckPasswordReuse", Connection) BaseDbService.AddParam(cmd, "@EmployeeID", EmployeeID) BaseDbService.AddParam(cmd, "@Password", Password) Dim dt As DataTable = BaseDbService.ExecTable(cmd) Dim IsExists As Boolean = CType(dt.Rows(0)("IsExists"), Boolean) Return IsExists End Function Private Function GetSecurityQuestion(ByVal UserID As Object, ByVal Login As String, ByVal SiteName As String) As DataRow Dim IsExists As Boolean = False Dim cmd As IDbCommand = BaseDbService.CreateSPCommand("spPerson_GetSecurityQuestion", Connection) If (UserID Is Nothing) Then BaseDbService.AddParam(cmd, "@Login", Login) BaseDbService.AddParam(cmd, "@SiteName", SiteName) Else BaseDbService.AddParam(cmd, "@UserID", UserID) End If Dim dt As DataTable = BaseDbService.ExecTable(cmd) If (dt.Rows.Count = 0) Then Return Nothing Return dt.Rows(0) End Function Public Function GetSecurityQuestion(ByVal UserID As Object) As DataRow Return GetSecurityQuestion(UserID, "", "") End Function Public Function GetSecurityQuestion(ByVal Login As String, ByVal SiteName As String) As DataRow Return GetSecurityQuestion(Nothing, Login, SiteName) End Function Public Sub UpdatePassword(ByVal EmployeeID As Object, ByVal Password As String, ByVal Question As String, ByVal Answer As String) Dim IsExists As Boolean = False Dim cmd As IDbCommand = BaseDbService.CreateSPCommand("spPerson_UpdatePassword", Connection) BaseDbService.AddParam(cmd, "@UserID", EmployeeID) BaseDbService.AddParam(cmd, "@Password", Password) BaseDbService.AddParam(cmd, "@Question", Question) BaseDbService.AddParam(cmd, "@Answer", Answer) BaseDbService.ExecCommand(cmd, Connection, Nothing, True) End Sub End Class
{ "content_hash": "b1b67959247426c0cde91d7d7a3b76b1", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 173, "avg_line_length": 39.08650519031142, "alnum_prop": 0.6271246458923513, "repo_name": "EIDSS/EIDSS-Legacy", "id": "28f95d5b8f8c7759aa13ee4faf02828b631ea53f", "size": "11298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EIDSS v5/vb/EIDSS/EIDSS_Admin_Db/Person/Person_DB.vb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "256377" }, { "name": "Batchfile", "bytes": "30009" }, { "name": "C#", "bytes": "106160789" }, { "name": "CSS", "bytes": "833586" }, { "name": "HTML", "bytes": "7507" }, { "name": "Java", "bytes": "2188690" }, { "name": "JavaScript", "bytes": "17000221" }, { "name": "PLSQL", "bytes": "2499" }, { "name": "PLpgSQL", "bytes": "6422" }, { "name": "Pascal", "bytes": "159898" }, { "name": "PowerShell", "bytes": "339522" }, { "name": "Puppet", "bytes": "3758" }, { "name": "SQLPL", "bytes": "12198" }, { "name": "Smalltalk", "bytes": "301266" }, { "name": "Visual Basic", "bytes": "20819564" }, { "name": "XSLT", "bytes": "4253600" } ] }
""" make_confidence_report.py Usage: python make_confidence_report.py model.joblib where model.joblib is a file created by cleverhans.serial.save containing a picklable cleverhans.model.Model instance. This script will run the model on a variety of types of data and save an instance of cleverhans.confidence_report.ConfidenceReport to model_report.joblib. The report can be later loaded by another script using cleverhans.serial.load. This script puts the following entries in the report: clean : Clean data semantic : Semantic adversarial examples mc: MaxConfidence adversarial examples This script works by running a single MaxConfidence attack on each example. ( https://openreview.net/forum?id=H1g0piA9tQ ) This provides a reasonable estimate of the true failure rate quickly, so long as the model does not suffer from gradient masking. However, this estimate is mostly intended for development work and not for publication. A more accurate estimate may be obtained by running make_confidence_report_bundled.py instead. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import tensorflow as tf from cleverhans.utils_tf import silence silence() # silence call must precede this imports. pylint doesn't like that # pylint: disable=C0413 from cleverhans.compat import flags from cleverhans.confidence_report import make_confidence_report from cleverhans.confidence_report import BATCH_SIZE from cleverhans.confidence_report import MC_BATCH_SIZE from cleverhans.confidence_report import TRAIN_START from cleverhans.confidence_report import TRAIN_END from cleverhans.confidence_report import TEST_START from cleverhans.confidence_report import TEST_END from cleverhans.confidence_report import WHICH_SET from cleverhans.confidence_report import NB_ITER from cleverhans.confidence_report import BASE_EPS_ITER from cleverhans.confidence_report import REPORT_PATH from cleverhans.confidence_report import SAVE_ADVX FLAGS = flags.FLAGS def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) make_confidence_report(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_set, report_path=FLAGS.report_path, mc_batch_size=FLAGS.mc_batch_size, nb_iter=FLAGS.nb_iter, base_eps_iter=FLAGS.base_eps_iter, batch_size=FLAGS.batch_size, save_advx=FLAGS.save_advx) if __name__ == '__main__': flags.DEFINE_integer('train_start', TRAIN_START, 'Starting point (inclusive)' 'of range of train examples to use') flags.DEFINE_integer('train_end', TRAIN_END, 'Ending point (non-inclusive) ' 'of range of train examples to use') flags.DEFINE_integer('test_start', TEST_START, 'Starting point (inclusive) ' 'of range of test examples to use') flags.DEFINE_integer('test_end', TEST_END, 'End point (non-inclusive) of ' 'range of test examples to use') flags.DEFINE_integer('nb_iter', NB_ITER, 'Number of iterations of PGD') flags.DEFINE_string('which_set', WHICH_SET, '"train" or "test"') flags.DEFINE_string('report_path', REPORT_PATH, 'Path to save to') flags.DEFINE_integer('mc_batch_size', MC_BATCH_SIZE, 'Batch size for MaxConfidence') flags.DEFINE_integer('batch_size', BATCH_SIZE, 'Batch size for most jobs') flags.DEFINE_float('base_eps_iter', BASE_EPS_ITER, 'epsilon per iteration, if data were in [0, 1]') flags.DEFINE_integer('save_advx', SAVE_ADVX, 'If True, saves the adversarial examples to the ' 'filesystem.') tf.app.run()
{ "content_hash": "dd2d760284cb5f55a0a7a23cb94009cf", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 79, "avg_line_length": 42.59574468085106, "alnum_prop": 0.7007992007992008, "repo_name": "openai/cleverhans", "id": "59d9a5de3ed1cc29bc72fcebb7bda7363d618922", "size": "4027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/make_confidence_report.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "143522" } ] }
require 'aws-sdk-core' require 'aws-sigv4' require_relative 'aws-sdk-codestarnotifications/types' require_relative 'aws-sdk-codestarnotifications/client_api' require_relative 'aws-sdk-codestarnotifications/plugins/endpoints.rb' require_relative 'aws-sdk-codestarnotifications/client' require_relative 'aws-sdk-codestarnotifications/errors' require_relative 'aws-sdk-codestarnotifications/resource' require_relative 'aws-sdk-codestarnotifications/endpoint_parameters' require_relative 'aws-sdk-codestarnotifications/endpoint_provider' require_relative 'aws-sdk-codestarnotifications/endpoints' require_relative 'aws-sdk-codestarnotifications/customizations' # This module provides support for AWS CodeStar Notifications. This module is available in the # `aws-sdk-codestarnotifications` gem. # # # Client # # The {Client} class provides one method for each API operation. Operation # methods each accept a hash of request parameters and return a response # structure. # # code_star_notifications = Aws::CodeStarNotifications::Client.new # resp = code_star_notifications.create_notification_rule(params) # # See {Client} for more information. # # # Errors # # Errors returned from AWS CodeStar Notifications are defined in the # {Errors} module and all extend {Errors::ServiceError}. # # begin # # do stuff # rescue Aws::CodeStarNotifications::Errors::ServiceError # # rescues all AWS CodeStar Notifications API errors # end # # See {Errors} for more information. # # @!group service module Aws::CodeStarNotifications GEM_VERSION = '1.21.0' end
{ "content_hash": "7e2ba4b812c9bf4f3803e146adba012b", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 94, "avg_line_length": 33.638297872340424, "alnum_prop": 0.7798861480075902, "repo_name": "aws/aws-sdk-ruby", "id": "d5767e8cb61c0d53cdcb6bb6c1b93608e788d0fc", "size": "1824", "binary": false, "copies": "1", "ref": "refs/heads/version-3", "path": "gems/aws-sdk-codestarnotifications/lib/aws-sdk-codestarnotifications.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Gherkin", "bytes": "109092" }, { "name": "HTML", "bytes": "1253" }, { "name": "JavaScript", "bytes": "10266" }, { "name": "Mustache", "bytes": "51225" }, { "name": "Ruby", "bytes": "183956484" } ] }
End of preview.

No dataset card yet

Downloads last month
3