Merging changes

This commit is contained in:
Taha committed 2023-09-04 16:25:40 -04:00
1 parent c4216d2272
commit 797816be7e
437 files changed
+54228 -28

No files matched your search

@@ -0,0 +1,116 @@
using System;
//using BCG.Utilities.BlueConfiguration;
namespace BCG
{
public class DataStreamLoadFileConfig //: ConfigurationRequest
{
private static DataStreamLoadFileConfig myInstance;
private string[] myAssemblies;
private string myIsTestMode = "false";
private bool myProfileStreams = false;
private double myProfileThreshold = 500;
private bool myUseNewJoin, myUseIncrementsForMultipleOps, myUseNewAppend, myUseNewFilter, myUseNewMap,
myUseUncopiedNewRowsInFireEvent, myUseModularizedBridge;
private bool myLogBlobPackets = false;
private bool myUseStaticParser = true;
//[Description("DataStream: list of assemblies providing the streams")]
public string [] loadedAssemblies
{
get { return myAssemblies; }
set { myAssemblies = value; }
}
public bool useStaticParser
{
get { return myUseStaticParser; }
set { myUseStaticParser = value; }
}
public bool logBlobPackets
{
get { return myLogBlobPackets; }
set { myLogBlobPackets = value; }
}
public string isTestMode
{
get {return myIsTestMode;}
set {myIsTestMode = value;}
}
public bool profileStreams
{
get { return myProfileStreams; }
set { myProfileStreams = Convert.ToBoolean(value); }
}
public double profileThreshold
{
get { return myProfileThreshold; }
set { myProfileThreshold = Convert.ToDouble(value); }
}
public bool isValid()
{
return true;
//return myVerify (myAssemblies);
}
public bool useNewJoin
{
get { return myUseNewJoin; }
set { myUseNewJoin = value; }
}
public bool useNewAppend
{
get { return myUseNewAppend; }
set { myUseNewAppend = value; }
}
public bool useNewFilter
{
get { return myUseNewFilter; }
set { myUseNewFilter = value; }
}
public bool useNewMap
{
get { return myUseNewMap; }
set { myUseNewMap = value; }
}
public bool useIncrementsForMultipleOps
{
get { return myUseIncrementsForMultipleOps; }
set { myUseIncrementsForMultipleOps = value; }
}
public bool useUncopiedNewRowsInFireEvent
{
get { return myUseUncopiedNewRowsInFireEvent; }
set { myUseUncopiedNewRowsInFireEvent = value; }
}
public bool useModularizedDataStreamBridge
{
get { return myUseModularizedBridge; }
set { myUseModularizedBridge = value; }
}
public static DataStreamLoadFileConfig instance
{
get
{
return myInstance = new DataStreamLoadFileConfig();
return myInstance;
// myInstance == null ?
// ConfigurationRequester.request (typeof (DataStreamLoadFileConfig)) as DataStreamLoadFileConfig
// as DataStreamLoadFileConfig :
// myInstance;
}
}
}
}
@@ -0,0 +1,316 @@
using System;
using System.Collections;
using System.Data;
using BCG.Utilities.General;
namespace BCG
{
[Serializable]
public class DataPacket : ICloneable, IDataPacket
{
public class BlueRowIdComparator
{
private string[] myIdColumns = new string[]{"id"};
public BlueRowIdComparator(string[] idCols)
{
if ( idCols.Length != 0 )
{
myIdColumns = idCols;
}
}
public bool blueRowIdEqualEvaluator(object a, object b)
{
if ( a == null || b == null )
{
return false;
}
if ( !(a is IBlueRow) || !(b is IBlueRow) )
{
return false;
}
IBlueRow lhs = (IBlueRow)a;
IBlueRow rhs = (IBlueRow)b;
bool result = true;
foreach(string idColumn in myIdColumns)
{
result = result && lhs[idColumn].Equals(rhs[idColumn]);
if ( !result )
break;
}
return result;
}
}
public IBlueRowCollection newRows, addedRows, deletedRows;
public DataPacket () {}
public DataPacket (IBlueRowCollection newRows, IBlueRowCollection addedRows, IBlueRowCollection deletedRows)
{
this.newRows = newRows;
this.addedRows = addedRows;
this.deletedRows = deletedRows;
}
public void get_new_added_deleted(out ICollection new_rows, out ICollection added_rows, out ICollection deleted_rows)
{
new_rows = newRows;
added_rows = addedRows;
deleted_rows = deletedRows;
}
public IBlueRowCollection getTrulyAddedRows(params string[] idColumns)
{
BlueTable truly = new BlueTable(addedRows.schema);
BlueRowIdComparator c = new BlueRowIdComparator(idColumns);
CollectionHelpers.EqualDelegate ed =
new CollectionHelpers.EqualDelegate(c.blueRowIdEqualEvaluator);
ICollection ta = CollectionHelpers.difference(addedRows, deletedRows, ed);
foreach(IBlueRow r in ta)
{
truly.addRow(r);
}
return truly;
}
public virtual IBlueRowCollection getTrulyAddedRows ()
{
BlueTable retVal = new BlueTable (schema);
foreach (IBlueRow r in addedRows)
if (!deletedRows.containsID ((int)r["id"]))
retVal.addRow (r);
return retVal;
}
public virtual IBlueRowCollection getTrulyDeletedRows ()
{
BlueTable retVal = new BlueTable (schema);
foreach (IBlueRow r in deletedRows)
if (!addedRows.containsID ((int)r["id"]))
retVal.addRow (r);
return retVal;
}
public virtual IBlueRowCollection getTrulyChangedRows ()
{
BlueTable retVal = new BlueTable (schema);
foreach (IBlueRow r in addedRows)
if (deletedRows.containsID ((int)r["id"]))
retVal.addRow (r);
return retVal;
}
public IBlueRowCollection getTrulyDeletedRows(params string[] idColumns)
{
BlueTable truly = new BlueTable(deletedRows.schema);
BlueRowIdComparator c = new BlueRowIdComparator(idColumns);
CollectionHelpers.EqualDelegate ed =
new CollectionHelpers.EqualDelegate(c.blueRowIdEqualEvaluator);
ICollection td = CollectionHelpers.difference(deletedRows, addedRows, ed);
foreach(IBlueRow r in td)
{
truly.addRow(r);
}
return truly;
}
public IBlueRowCollection getTrulyChangedRows(params string[] idColumns)
{
BlueTable truly = new BlueTable(addedRows.schema);
BlueRowIdComparator c = new BlueRowIdComparator(idColumns);
CollectionHelpers.EqualDelegate ed =
new CollectionHelpers.EqualDelegate(c.blueRowIdEqualEvaluator);
ICollection ta = CollectionHelpers.difference(addedRows, deletedRows, ed);
ICollection tc = CollectionHelpers.difference(addedRows, ta, ed);
foreach(IBlueRow r in tc)
{
truly.addRow(r);
}
return truly;
}
public IBlueRowCollection getTrulyChangedOldRows(params string[] idColumns)
{
BlueTable truly = new BlueTable(deletedRows.schema);
BlueRowIdComparator c = new BlueRowIdComparator(idColumns);
CollectionHelpers.EqualDelegate ed =
new CollectionHelpers.EqualDelegate(c.blueRowIdEqualEvaluator);
ICollection td = CollectionHelpers.difference(deletedRows, addedRows, ed);
ICollection tco = CollectionHelpers.difference(deletedRows, td, ed);
foreach(IBlueRow r in tco)
{
truly.addRow(r);
}
return truly;
}
public TablePacket toTablePacket ()
{
return new TablePacket (BlueDataUtility.toDataTable (newRows), BlueDataUtility.toDataTable (addedRows),
BlueDataUtility.toDataTable (deletedRows));
}
public IBlueTableSchema schema
{
get
{
IBlueTableSchema retVal = newRows.schema != null ? newRows.schema :
addedRows.schema != null ? addedRows.schema : deletedRows.schema;
return retVal;
}
}
/*
status D total A total D this A This D' total A' Total
x 0 0 0 0 0 0
0 0 0 1 1 this+
0 0 1 0 1this
0 0 1 1 1 this 1 this+
x 0 1 0 0
error 0 1 0 1
0 1 1 0 1 total-
0 1 1 1 1 total-, 1 this +
x 1 0 0 0
1 0 0 1 1 this+
error 1 0 1 0
error 1 0 1 1
x 1 1 0 0
error 1 1 0 1
1 1 1 0 1 total -1 keep the old delete and remove the old add
1 1 1 1 1 total-, 1 this +
d' = dthis - (dthis intersect a) + d // keep the old delete
a' = a - (dthis intersect a) + athis // keep the new add
* */
public static DataPacket combineWithIds(ICollection packets, string[] idColumns)
{
if ( packets.Count == 0 )
{
return new DataPacket(
new BlueTable(new DataTable()),
new BlueTable(new DataTable()),
new BlueTable(new DataTable()));
}
DataPacket.BlueRowIdComparator c = new DataPacket.BlueRowIdComparator(idColumns);
CollectionHelpers.EqualDelegate ed =
new CollectionHelpers.EqualDelegate(c.blueRowIdEqualEvaluator);
ArrayList added = new ArrayList();
ArrayList deleted = new ArrayList();
BlueTable dt = null;
BlueTable at = null;
IBlueRowCollection nt = null;
foreach(DataPacket dp in packets)
{
ArrayList oldDeleted = deleted;
ArrayList oldAdded = added;
added = new ArrayList();
deleted = new ArrayList();
if ( dt == null )
{
dt = new BlueTable(dp.schema);
at = new BlueTable(dp.schema);
}
deleted.AddRange(oldDeleted);
deleted.AddRange( CollectionHelpers.difference(
CollectionHelpers.difference(dp.deletedRows, oldAdded, ed),
oldDeleted, ed) );
added.AddRange(dp.addedRows);
added.AddRange( CollectionHelpers.difference(
CollectionHelpers.difference(oldAdded, dp.deletedRows, ed),
added, ed) );
nt = dp.newRows;
}
foreach ( IBlueRow dr in added )
{
at.addRow(dr);
}
foreach ( IBlueRow dr in deleted )
{
dt.addRow(dr);
}
return new DataPacket(nt,at,dt);
}
public DataPacket deepCopy ()
{
return new DataPacket (new OrderedBlueTable (newRows),
new OrderedBlueTable (newRows),
new BlueTable (deletedRows));
}
public virtual DataPacket createImmutable ()
{
return
new DataPacket(
newRows is IImmutableRowCollection ? newRows : new ImmutableBlueTable(newRows),
addedRows,
deletedRows);
}
#region ICloneable Members
public object Clone()
{
return MemberwiseClone();
}
#endregion
public string toIncrementalIDString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(schema.tableName);
sb.Append ("\ndeleted : ");
foreach (IBlueRow r in deletedRows)
{
sb.Append(r["id"]);
sb.Append(',');
}
sb.Append("\nadded : ");
foreach (IBlueRow r in addedRows)
{
sb.Append(r["id"]);
sb.Append(',');
}
sb.Append("\n");
return sb.ToString();
}
public override string ToString()
{
return String.Format("DataPacket, schema {0} n {1} d {2} a {3}", schema.tableName, newRows.Count, deletedRows.Count, addedRows.Count);
}
}
}
@@ -0,0 +1,180 @@
using System;
using System.Collections;
//using BCG.Utilities;
//using BCG.Utilities.General;
using mbts;
namespace BCG
{
/// <summary>
/// Base class for all the sreams
/// </summary>
public class DataStream
{
internal static event EventHandler onFireStart;
protected bool myTestMode = Convert.ToBoolean (DataStreamLoadFileConfig.instance.isTestMode);
protected bool myFirstSubImplemented = true,
myLastSubImplemented = true;
protected IDictionary myDelMap = new Hashtable ();
private Guid myID = Guid.Empty;
public DateTime last_fired_time = DateTime.MinValue;
public int n_updates = 0;
public DataStream ()
:
this (null)
{}
public DataStream (DataStream realSource)
{
myRealSource = realSource;
myOnChangeDelegate = null;
myPendingAdds = new Stack();
}
public int numberOfSubscribers
{
get
{
return
myOnChangeDelegate != null?
myOnChangeDelegate.GetInvocationList().Length
:
0;
}
}
public delegate void ChangeDelegate(object newValue);
public event ChangeDelegate onChange
{
add
{
ChangeDelegate currValue = value;
if (myTestMode)
{
ChangeDelegateWrapper w = new ChangeDelegateWrapper (value);
currValue = new ChangeDelegate (w.wrapperFunction);
myDelMap.Add (value, currValue);
}
if (myRealSource != null)
myRealSource.onChange += currValue;
else
{
myOnChangeDelegate =
(ChangeDelegate) Delegate.Combine (myOnChangeDelegate,currValue);
if (myOnChangeDelegate.GetInvocationList().Length == 1) // first subscriber
{
myPendingAdds.Push(new ArrayList());
myOnFirstSubscriber();
ArrayList calledDelegates = (ArrayList) myPendingAdds.Pop();
object v = myGetValueForInitialSubscription();
//BlueTrace.WriteViewStreamSubscribe(this.ID, v != null);
if (v != null && calledDelegates.IndexOf(currValue) == -1)
currValue (v);
}
else
{
object v = myGetValueForInitialSubscription();
// BlueTrace.WriteViewStreamSubscribe(this.ID, v != null);
if (v != null)
currValue (v);
}
}
}
remove
{
ChangeDelegate currValue = value;
// BlueTrace.WriteViewStreamUnsubscribe(this.ID);
if (myTestMode)
{
currValue = myDelMap[value] as ChangeDelegate;
myDelMap.Remove (value);
}
if (myRealSource != null)
myRealSource.onChange -= currValue;
else
{
myOnChangeDelegate =
(ChangeDelegate) Delegate.Remove (myOnChangeDelegate,currValue);
// this is need to avoid a callback in a reentrant add.
if (myPendingAdds.Count > 0)
((ArrayList) (myPendingAdds.Peek())).Add(currValue);
if (myOnChangeDelegate == null) // last subscriber
{
myOnLastSubscriber();
myLastValue = null;
}
}
}
}
protected virtual object myGetValueForInitialSubscription()
{return myLastValue;}
protected void mySetRealSource (DataStream src)
{myRealSource = src;}
protected virtual void myOnFirstSubscriber() {myFirstSubImplemented = false;}
protected virtual void myOnLastSubscriber () {myLastSubImplemented = false;}
protected virtual void myFireEvent(object o)
{
last_fired_time = DateTime.Now;
n_updates++;
// BlueEventLog.logAssert (myRealSource == null);
myLastValue = o;
if (myOnChangeDelegate != null)
{
// this is need to avoid a callback in a reentrant add.
if (myPendingAdds.Count > 0)
foreach (Delegate d in myOnChangeDelegate.GetInvocationList())
((ArrayList) (myPendingAdds.Peek())).Add(d);
if (onFireStart != null)
onFireStart(this, EventArgs.Empty);
myOnChangeDelegate (o);
}
}
public Guid ID
{
get
{
if (this.myID == Guid.Empty) // && BlueTraceHelper.IsEnabled(BlueTraceLevel.Verbose, BlueTraceKeywords.Streams))
{
// BlueTraceHelper.FastInitGuid(ref this.myID);
// BlueTrace.WriteViewStreamCreate(this.GetType().ToString(), this.myID);
}
return this.myID;
}
}
// this was made internal for testing purposes only.
// don't mess with it.
internal ChangeDelegate myOnChangeDelegate;
protected object myLastValue;
protected DataStream myRealSource;
private Stack myPendingAdds;
}
internal class ChangeDelegateWrapper
{
private HighPerformanceTimer myTimer = new HighPerformanceTimer ();
private DataStream.ChangeDelegate myDel;
internal ChangeDelegateWrapper (DataStream.ChangeDelegate del) {myDel = del;}
internal void wrapperFunction (object o)
{
myTimer.start ();
myDel (o);
myTimer.stop ();
string minfo = "Type = " + myDel.Method.DeclaringType.FullName + " , method = " + myDel.Method.Name;
// BlueEventLog.logEvent (minfo + " , time = " + myTimer.lastIntervalTime.ToString (), BlueEventLevel.Performance);
}
}
}
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG
{
public delegate void ExportableChangeDelegate(object data_packet);
public interface IExportableDataStream
{
void begin_subscription();
event ExportableChangeDelegate on_change;
}
}
@@ -0,0 +1,51 @@
using System;
using System.Collections;
using System.Data;
using BCG.Utilities;
/* this class reprsents a table stream for use with CppDataStreams. It does not hold on to the last value fired.
* This way, the last value is purged from managed memory and only the slimmer, sexier Cpp implementation of the row remains.
*
*/
namespace BCG
{
public class LightTableStream : TableStream
{
public LightTableStream(string tableName)
:
base(tableName, null, null)
{
}
public LightTableStream(string tableName, ViewStreamDatabase db)
:
base(tableName, db, null)
{}
public LightTableStream(string tableName, string colExp)
:
base(tableName,
null,
colExp)
{}
public LightTableStream(string ttableName, ViewStreamDatabase db, string colExp) :
base(ttableName,db,colExp)
{
}
protected override void myHandleUpdates(IBlueRowCollection newRows, IBlueRowCollection addedRows, IBlueRowCollection deletedRows)
{
base.myHandleUpdates(newRows, addedRows, deletedRows);
//once you've fired the rows, delete them becuase we don't want to hold onto them in memory
myLastValue = null;
}
}
}
@@ -0,0 +1,526 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using BCG.Utilities;
using BCG.Utilities.General;
namespace BCG
{
/// Derive from this class to create a new proxy stream for a stream that
/// should be computed out of process. In the proxy class add constructors
/// that exactly mirror the ones you want to expose from the real stream.
/// Each of the proxy constructors should just call the base constructor
/// passing it a, possibly null VSDB, and the arguments it received in
/// exactly the same order. Only non nullparameters of types string, int, bool or
/// DateTime are supported. DateTime arguments will loose their time portion,
/// string arguments can only have digits or letters and ints have to be positive.
///
/// For example, if you real stream is:
///
/// class TradeLog : ViewStream
/// {
/// public TradeLog(string forAccount, string forTrader) {....}
/// }
///
/// Then your proxy stream would like:
///
/// class TradeLogProxy : ProxyStream
/// {
/// public TradeLogProxy(string forAccount, string forTrader) : base(null,forTrader, forAccount) {}
/// }
///
/// Unfortunatly, PubSub tags have a very limited alphabet, one that does not even support upper and lower
/// case dinstinctions, so some special care needs to be taken by the proxy or the real stream when dealing
/// with case sensitive arguments or with string arguments that can contain _ (the only non alpha numeric
/// character allowed in a string). The proxy tries to help by supporting the following conventions:
///
/// - When passing a symbol, mark the parameter with the kind of symbol you mean, option or
/// underlyier. Example:
/// public TheosProxy([Option] string symbol) : base(symbol) {} or
/// public FuturePositionProxy([Underlyer] string future) : base(symbol) {}
///
/// - When passing an exchange mark it with the Exchange attribute. Example:
/// public QuoteWidthsProxy([Symbol] string symbol,
/// [Exchange] string e) : base(e) {}
///
/// - When passing a group name mark it with the group. Since group names can have _ and presumably numbers
/// there can be only one group argument which has to be last one.
/// attribute. Ex:
/// public RiskTheosProxy([Group] string g) : base(g) {}
///
/// - When passing an instrument type mark it as InstrumentType. Example:
/// public SymbolsOfTypeProxy([InstrumentType] string it) : base(it) {}
///
/// - When passing a trader mark it as trader. Example:
/// public TraderTrades([trader] string joes) : base(joes) {}
///
/// - When passing a string that can contain _, the string argument must
/// be the last one in the constructor and should be marked as [LongString]
/// public WorkerHealth([LongString] string machineName) : base(machineName) {}
///
/// - When passing a symbol, instrument type combo combine both in one string
/// with the symbol:InstrumentType format and market it with BCGSym:
/// public PositionProxy([BCGSym] string bcgsym) : base(bcgsym) {}
/// More complex cases should be handled by the real stream.
public abstract class ProxyStream : ViewStream
{
public enum ProxyParameterType
{
clrType,
optionSymbol,
trader,
underlyerSymbol,
group,
exchange,
instrumentType,
bcgSym
}
public class ProxyParameter
{
public ProxyParameterType type;
public object value;
}
public class MarshallingException : SystemException
{
public MarshallingException (string format, params object [] args)
: base(String.Format(format,args) )
{}
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
protected class ProxyParameterAttribute : Attribute
{}
protected class OptionAttribute : ProxyParameterAttribute
{ }
protected class LongStringAttribute : ProxyParameterAttribute
{ }
protected class UnderlyierAttribute : ProxyParameterAttribute
{ }
protected class BCGSymAttribute : ProxyParameterAttribute
{ }
protected class GroupAttribute : ProxyParameterAttribute
{ }
protected class ExchangeAttribute : ProxyParameterAttribute
{ }
protected class TraderAttribute: ProxyParameterAttribute
{ }
protected class InstrumentTypeAttribute : ProxyParameterAttribute
{ }
public string getTag() { return myTag; }
private string myTag;
protected ProxyStream(params object[] args)
{myInit(null, args);}
protected ProxyStream(ViewStreamDatabase db, params object[] args)
{myInit(db, args);}
class MyException : System.Exception
{
public MyException (string msg) : base (msg)
{
}
}
private static void myThrowIfFalse(bool condition, string msg)
{
if (!condition)
throw new MyException(msg);
}
private void myInit(ViewStreamDatabase db, params object[] args)
{
try
{
ConstructorInfo ci = GetType().GetConstructor(args.Select(t => t.GetType()).ToArray());
foreach (object o in args)
myThrowIfFalse(o != null,
"Null arguments are not supported.");
myTag = myGetTag(ci, args, db != null);
mySetRealSource(new TableStream("prepub_" + myTag, db));
}
catch (MyException e)
{
// BlueEventLog2.instance().logEvent(e.Message, BlueEventLog2Level.Fatal);
mySetRealSource(new TableStream("error_tag"));
}
}
public static string getProxyName(string tag)
{ return tag.Split('_')[0]; }
public static List<ProxyParameter> unmarshal(Type proxyType, string tag)
{
myThrowIfFalse (proxyType.IsSubclassOf(typeof(ProxyStream)),
String.Format("{0} is not a subclass of ProxyStream", proxyType.Name));
myThrowIfFalse (tag.ToLower().StartsWith(proxyType.Name.ToLower()),
String.Format("Tag {0} does not match proxy type {1}.", tag, proxyType.Name));
string encodedParameters =
tag.Length == proxyType.Name.Length ? "" :
tag.Substring((proxyType.Name + "_").Length);
ConstructorInfo ci;
if (myConstructorsNeedToBeEnconded(proxyType))
{
List<Type> signature = myUnmarshalConstructorSignature(ref encodedParameters);
ci = proxyType.GetConstructor(signature.ToArray());
if (ci == null)
{
signature.Insert(0, typeof(ViewStreamDatabase));
ci = proxyType.GetConstructor(signature.ToArray());
if (ci == null)
throw new MarshallingException("Cannot find constructor for {0} matching signature {1}",
proxyType.Name, encodedParameters);
}
}
else
ci = proxyType.GetConstructors()[0];
ParameterInfo[] parameters = ci.GetParameters();
List<ProxyParameter> result = new List<ProxyParameter>();
ParameterInfo [] pars = ci.GetParameters();
// skip VSDB if first parameter
int i = pars.Length > 0 && pars[0].ParameterType.Equals(typeof(ViewStreamDatabase)) ? 1 : 0;
for (;i < pars.Length; i++)
result.Add(new ProxyParameter
{
type = myGetParameterType(pars[i]),
value = myGetParameterValue(pars[i], ref encodedParameters)
});
return result;
}
private static List<Type> myUnmarshalConstructorSignature(ref string encodedParameters)
{
List<Type> result = new List<Type> ();
for (int i = 0; i < encodedParameters.Length; i++)
if (encodedParameters[i] == 's')
result.Add(typeof(string));
else if (encodedParameters[i] == 'd')
result.Add(typeof(DateTime));
else if (encodedParameters[i] == 'i')
result.Add(typeof(Int32));
else if (encodedParameters[i] == 'b')
result.Add(typeof(bool));
else if (encodedParameters[i] == '_')
break;
else
throw new MarshallingException("'{0}' does not start with a valid constructor signature",
encodedParameters);
if (result.Count > 0)
encodedParameters = encodedParameters.Substring(result.Count + 1);
return result;
}
private static ProxyParameterType myGetParameterType(ParameterInfo pi)
{
if (pi.ParameterType == typeof(string))
{
ProxyParameterType result = ProxyParameterType.clrType;
object[] attr = pi.GetCustomAttributes(false);
if (attr.Length > 0)
{
foreach (Attribute a in attr)
if (a is OptionAttribute)
result = ProxyParameterType.optionSymbol;
else if (a is ExchangeAttribute)
result = ProxyParameterType.exchange;
else if (a is TraderAttribute)
result = ProxyParameterType.trader;
else if (a is GroupAttribute)
result = ProxyParameterType.group;
else if (a is InstrumentTypeAttribute)
result = ProxyParameterType.instrumentType;
else if (a is UnderlyierAttribute)
result = ProxyParameterType.underlyerSymbol;
else if (a is BCGSymAttribute)
result = ProxyParameterType.bcgSym;
else if (a is LongStringAttribute)
result = ProxyParameterType.clrType;
}
return result;
}
else if (pi.ParameterType == typeof(Int32) ||
pi.ParameterType == typeof(DateTime) ||
pi.ParameterType == typeof(bool))
return ProxyParameterType.clrType;
else
{
myThrowIfFalse (false,String.Format(
"{0} is not a supported proxy parameter type", pi.ParameterType.Name));
return ProxyParameterType.clrType;
}
}
private static object myGetParameterValue(ParameterInfo pi, ref string encodedParameters)
{
if (pi.ParameterType == typeof(DateTime))
{
string[] parts = encodedParameters.Split('_');
if (parts.Length < 3)
throw new MarshallingException("{0} does not start with a valid date", encodedParameters);
int year;
if (!Int32.TryParse(parts[0], out year))
throw new MarshallingException("{0} is not a valid year string", parts[0]);
int month;
if (!Int32.TryParse(parts[1], out month))
throw new MarshallingException("{0} is not a valid month string", parts[1]);
int day;
if (!Int32.TryParse(parts[2], out day))
throw new MarshallingException("{0} is not a valid day string", parts[2]);
DateTime result;
try {
result = new DateTime(year, month, day);
}
catch (ArgumentException)
{
throw new MarshallingException("{0}/{1}/{2} is not a valid date", year, month, day );
}
if (parts.Length > 3)
encodedParameters = encodedParameters.Substring(parts[0].Length + parts[1].Length + parts[2].Length + 3);
else
encodedParameters = "";
return
result;
}
else
{
if (pi.ParameterType == typeof(string) && myIsBCGSym(pi))
{
string[] parts = encodedParameters.Split('_');
if (parts.Length < 2)
throw new MarshallingException("{0} does not start with a valid BCGSym string", encodedParameters);
else
{
if (parts.Length > 2)
encodedParameters = encodedParameters.Substring(parts[0].Length + parts[1].Length + 2);
else
encodedParameters = "";
return parts[0] + ":" + parts[1];
}
}
else if (pi.ParameterType == typeof(string) && myIsLongString(pi))
{
string result = encodedParameters;
encodedParameters = "";
return result;
}
else
{
string[] parts = encodedParameters.Split('_');
object result = null;
if (pi.ParameterType == typeof(string))
result = parts[0];
else if (pi.ParameterType == typeof(Int32))
{
int n;
if (!Int32.TryParse(parts[0], out n))
throw new MarshallingException("{0} is not a valid int", parts[0]);
result = n;
}
else if (pi.ParameterType == typeof(Boolean))
{
bool b;
if (!bool.TryParse(parts[0], out b))
throw new MarshallingException("{0} is not a valid bool", parts[0]);
result = b;
}
else
myThrowIfFalse (false,
String.Format("{0} is not a supported proxy parameter type", pi.ParameterType.Name));
if (parts.Length > 1)
encodedParameters = encodedParameters.Substring(parts[0].Length + 1);
else
encodedParameters = "";
return result;
}
}
}
private bool myValidateString(string s, bool allowUnderscore)
{
foreach (char c in s)
if (!Char.IsDigit(c) && !Char.IsLetter(c) && !(allowUnderscore && c.Equals('_')))
return false;
return true;
}
private static bool myHasAttribute(ParameterInfo pi, Type attrType)
{
object[] attr = pi.GetCustomAttributes(false);
if (attr.Length > 0)
foreach (Attribute at in attr)
if (at.GetType().Equals(attrType))
return true;
return false;
}
private static bool myIsBCGSym(ParameterInfo pi)
{return myHasAttribute(pi, typeof(BCGSymAttribute));}
private static bool myIsLongString(ParameterInfo pi)
{ return myHasAttribute(pi, typeof(LongStringAttribute)) || myHasAttribute(pi, typeof(GroupAttribute)); }
private static bool myFirstParameterIsVSDB(ConstructorInfo ci)
{
return
ci.GetParameters().Length > 0 &&
ci.GetParameters()[0].ParameterType.Equals(typeof(ViewStreamDatabase));
}
private static bool myIsSameModuloVSDB(ConstructorInfo ci0, ConstructorInfo ci1)
{
if ((ci1.GetParameters().Length - ci0.GetParameters().Length) != 1)
return false;
if (!myFirstParameterIsVSDB(ci1))
return false;
for (int i = 0; i < ci0.GetParameters().Length; i++)
if (!ci1.GetParameters()[i + 1].ParameterType.Equals(
ci0.GetParameters()[i].ParameterType))
return false;
return true;
}
private static bool myConstructorsNeedToBeEnconded(Type t)
{
ConstructorInfo [] cis = t.GetConstructors();
if (cis.Length == 1)
return false;
else if (cis.Length > 2)
return true;
else
{
ConstructorInfo ci0 = cis[0];
ConstructorInfo ci1 = cis[1];
return !(myIsSameModuloVSDB(ci0, ci1) || myIsSameModuloVSDB(ci1, ci0));
}
}
private string myGetConstructorSignature(ConstructorInfo ci)
{
string result ="";
int i = myFirstParameterIsVSDB(ci) ? 1 : 0;
for (; i < ci.GetParameters().Length; i++)
{
Type t = ci.GetParameters()[i].ParameterType;
if (t.Equals(typeof(string)))
result += "s";
else if (t.Equals(typeof(DateTime)))
result += "d";
else if (t.Equals(typeof(bool)))
result += "b";
else if (t.Equals(typeof(Int32)))
result += "i";
else
myThrowIfFalse (false,
String.Format("{0} is not a supported proxy parameter type", t.Name));
}
return result;
}
private string myGetTag(ConstructorInfo ci, object[] args, bool firstArgIsVSDB)
{
Type t = ci.DeclaringType;
string tag = t.Name;
if (myConstructorsNeedToBeEnconded(t))
tag += "_" + myGetConstructorSignature(ci);
int i = myFirstParameterIsVSDB(ci) ? 1 : 0;
foreach (object a in args)
{
Debug.Assert(a != null);
if (a.GetType() == typeof(DateTime))
{
DateTime dt = (DateTime)a;
tag += String.Format("_{0}_{1}_{2}", dt.Year, dt.Month, dt.Day);
}
else if (a.GetType() == typeof(string))
{
if (myIsBCGSym(ci.GetParameters()[i]))
{
string[] parts = a.ToString().Split(':');
myThrowIfFalse (parts.Length == 2,
String.Format("Invalid BCGSym string argument {0}. Use sym:InstrumentType",
a));
if (!myValidateString(parts[0], false) || !myValidateString(parts[1], false))
{
// BlueEventLog2.instance().logEvent(
// String.Format(
// "Invalid string argument {0}. Currently, only letters and digits are supported in string arguments",
// a),BlueEventLog2Level.Error);
return "error_tag";
}
tag += String.Format("_{0}_{1}", parts[0], parts[1]);
}
else if (myIsLongString(ci.GetParameters()[i]))
{
// not a BCGSym
if (!myValidateString(a.ToString(), true))
{
// BlueEventLog2.instance().logEvent(
// String.Format("Invalid string argument {0}. Currently, only letters, digits and _'s are supported in long string arguments",
// a),BlueEventLog2Level.Error);
return "error_tag";
}
//can't do this-- ci.GetParameters() order is undefined
//myThrowIfFalse (i.Equals(ci.GetParameters().Length - 1),
// "Long string argument must be last");
tag += "_" + a.ToString();
}
else
{
// not a BCGSym
if (!myValidateString(a.ToString(), false))
{
// BlueEventLog2.instance().logEvent(String.Format(
// "Invalid string argument {0}. Currently, only letters and digits are supported in string arguments", a),
// BlueEventLog2Level.Error);
return "error_tag";
}
tag += "_" + a.ToString();
}
}
else if (a.GetType() == typeof(Int32))
{
myThrowIfFalse ((int) a >= 0,
String.Format("Invalid int argument {0}. Currently only positive integers are supported.",
a));
tag += "_" + a.ToString();
} else if (a.GetType() == typeof(bool))
tag += "_" + a.ToString();
else
myThrowIfFalse (false,
String.Format("{0} is not a supported proxy parameter type", a.GetType().Name));
i++;
}
return tag;
}
}
}
@@ -0,0 +1,26 @@
using System;
using System.Data;
using System.Collections;
namespace BCG
{
/// <summary>
/// Defines the type that will be passed as the callback from the TableStream class
/// </summary>
public class TablePacket
{
public DataTable newTable = new DataTable();
public DataTable addedRows = new DataTable();
public DataTable deletedRows = new DataTable();
public TablePacket () {}
public TablePacket (DataTable nt, DataTable ar, DataTable dr)
{
newTable = nt;
addedRows = ar;
deletedRows = dr;
}
}
}
@@ -0,0 +1,184 @@
using System;
using System.Collections;
using System.Data;
using BCG.Utilities;
namespace BCG
{
public class TableStream : ViewStream
{
public string tableName;
private ITableAccumulator myTA;
private bool myGotData = false;
public TableStream(string tableName)
:
this(tableName, null, null)
{
}
public TableStream(string tableName, ViewStreamDatabase db)
:
this(tableName, db, null)
{}
public TableStream(string tableName, string colExp)
:
this(tableName,
null,
colExp)
{}
public TableStream(string ttableName, ViewStreamDatabase db, string colExp)
{
tableName = PubStreamPrefixer.prefix (ttableName);
// if (colExp != null)
// mySetRealSource (new ProjectStream (new TableStream (tableName, db), colExp));
// else
{
if (db == null)
myTA = ViewStreamDatabase.instance.getITableAccumulator (tableName);
else
myTA = db.getITableAccumulator (tableName);
}
}
protected override void myOnFirstSubscriber()
{
myTA.onUpdate += new TableUpdateDelegate (myHandleUpdates);
}
protected override void myOnLastSubscriber()
{
myTA.onUpdate -= new TableUpdateDelegate (myHandleUpdates);
}
protected virtual void myHandleUpdates (IBlueRowCollection newRows, IBlueRowCollection addedRows, IBlueRowCollection deletedRows)
{
if (!myGotData)
{
myGotData = true;
// BlueEventLog.logEvent("Received data for " + tableName + " for the first time", BlueEventLevel.Information);
}
myFireEvent (new DataPacket (newRows, addedRows, deletedRows));
}
public override string ToString()
{
return GetType() + " table = " + tableName;
}
}
public class ThreadedTableStream : TableStream, IExportableDataStream
{
static private Lazy<ViewStreamDatabase> _vsd = new Lazy<ViewStreamDatabase>(() => new ViewStreamDatabase(), true);
public ThreadedTableStream(string table) : base(table, _vsd.Value)
{
}
public void begin_subscription()
{
this.onChange += _stream_onChange;
}
public event ExportableChangeDelegate on_change;
void _stream_onChange(object newValue)
{
if(on_change != null)
on_change(newValue);
}
}
// public class ExportableTableStream : IExportableDataStream
// {
// TableStream _stream;
// public ExportableTableStream(string table, IDataPump pump)
// {
// _stream = new TableStream(table, ((ExportableDataPump)pump).vsd.Value);
// }
// public void begin_subscription()
// {
// _stream.onChange += _stream_onChange;
// }
// public event ExportableChangeDelegate on_change;
// void _stream_onChange(object newValue)
// {
// if(on_change != null)
// on_change(newValue);
// }
// }
// public class ExportableQuery : IExportableDataStream
// {
// ViewStream _stream;
// public ExportableQuery(string query, BCG.IDataPump _)
// {
// // BCG.Evaluator.DataStreamExpression.syntax parser = new BCG.Evaluator.DataStreamExpression.syntax();
// // BCG.Evaluator.DataStreamExpression.DataStreamExpression exp =
// // (BCG.Evaluator.DataStreamExpression.DataStreamExpression)parser.Parse(query);
// _stream = exp.getView(new System.Collections.Hashtable());
// }
// public void begin_subscription()
// {
// _stream.onChange += _stream_onChange;
// }
// public event ExportableChangeDelegate on_change;
// void _stream_onChange(object newValue)
// {
// if(on_change != null)
// on_change(newValue);
// }
// }
// public class ExportableDataPump : IDataPump
// {
// public Lazy<ViewStreamDatabase> vsd = new Lazy<ViewStreamDatabase>(() => new ViewStreamDatabase(), true);
// System.Threading.Thread _thread;
// bool _continue = true;
// public ExportableDataPump(string pumpname)
// {
// tag = pumpname;
// _thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart((_) =>
// {
// while(_continue)
// {
// vsd.Value.doWork();
// System.Threading.Thread.Sleep(50);
// }
// }));
// _thread.Name = "DataPump " + pumpname;
// _thread.IsBackground = true;
// }
// public string tag
// {
// get;
// private set;
// }
// public void start()
// {
// try
// {
// if(_thread.ThreadState != System.Threading.ThreadState.Running)
// _thread.Start();
// }
// catch(System.Threading.ThreadStateException) { }
// }
// public void stop()
// {
// try
// {
// _continue = false;
// if(_thread.ThreadState == System.Threading.ThreadState.Running)
// _thread.Join(500);
// }
// catch(System.Threading.ThreadStateException) { }
// }
// }
}
@@ -0,0 +1,97 @@
using System;
//using BCG.Utilities.BlueConfiguration;
using BCG.Utilities;
namespace BCG
{
/// <summary>
/// Marker abstract class
/// </summary>
public abstract class ViewStream : DataStream
{
private IBlueRowCollection myLastValueForTestMode;
protected bool myUseUncopiedNewRowsInFireEvent = DataStreamLoadFileConfig.instance.useUncopiedNewRowsInFireEvent;
public ViewStream (ViewStream sourceStream)
:
base(sourceStream)
{}
public ViewStream()
{}
public IBlueRowCollection rows
{
get
{
if (myRealSource != null)
{
// BlueEventLog.logAssert (myRealSource is ViewStream);
return (myRealSource as ViewStream).rows;
}
else
{
// used to force a computation of a stream which
// happens to have no subscribers
onChange += new DataStream.ChangeDelegate(myDummy);
try
{
if (myLastValue != null)
return ((DataPacket) myLastValue).newRows;
else
return null;
}
finally
{
onChange -= new DataStream.ChangeDelegate(myDummy);
}
}
}
}
protected override object myGetValueForInitialSubscription()
{
if (myLastValue == null)
return null;
else
{
return new DataPacket(
(myLastValue as DataPacket).newRows,
(myLastValue as DataPacket).newRows,
new BlueTable((myLastValue as DataPacket).newRows.schema));
}
}
protected override void myFireEvent(object o)
{
DataPacket dp = (DataPacket) o;
// BlueTrace.WriteViewStreamFireEvent(this.ID,
// dp.newRows == null ? 0 : dp.newRows.Count,
// dp.addedRows == null ? 0 : dp.addedRows.Count,
// dp.deletedRows == null ? 0 : dp.deletedRows.Count);
if (myTestMode)
{
// BlueEventLog.logAssert ((myFirstSubImplemented && myLastSubImplemented) | myRealSource != null,
// @"either myOnFirstSub/myOnLastSub should be implemented or mySetRealSource
// called with a non-null arg in " + this.GetType().FullName);
if (myLastValueForTestMode != null)
BlueDataUtility.checkConsistency(myLastValueForTestMode,
dp.newRows, dp.deletedRows, dp.addedRows);
myLastValueForTestMode = new ImmutableBlueTable(dp.newRows);
}
// the view already garantees that added & deleted are immutable.
// this garantess that new is also immutable
base.myFireEvent(myUseUncopiedNewRowsInFireEvent ? dp : dp.createImmutable());
}
private void myDummy (object o)
{}
}
}
@@ -0,0 +1,312 @@
using System;
using System.Collections;
using System.IO;
using BCG.Utilities;
using BCG.Utilities.General;
//using BCG.Utilities.BlueConfiguration;
using System.Collections.Generic;
using System.Threading;
using mbts;
namespace BCG
{
public class ViewStreamDatabase : IWorker, IDisposable
{
internal delegate void TagFireDelegate(string tag);
public delegate void DoWorkDelegate ();
public event DoWorkDelegate onDoWorkStart,
onDoWorkEnd;
internal event TagFireDelegate onTagFireStart,
onTagFireEnd;
//currently onTagUpdate is usd by the DataStreamPerfRecorder to keep track of how often the updates for various streams come in
//and how big they are.
//public delegate void OnTagUpdateDelegate(PubMetaData metaData);
//public event OnTagUpdateDelegate onTagUpdate;
private IDictionary myITableAccumulatorMap = new Hashtable ();
private static ViewStreamDatabase mySelf;
private ISubscriberCore mySubscriberCore;
private ArrayList myWorkers = new ArrayList ();
private bool myIsDisposed = false;
private bool myIsInDoWork = false;
private static object myTimeInterval;
private HighPerformanceTimer myTimer = new HighPerformanceTimer();
private double myLogTimeThreshold = 10000;
private readonly double _dowork_threshold = 500;
private Thread myThreadOwner = null; // ViewStreamDatabase takes a thread affinity when created. If called from a different thread it will assert.
private static readonly object myInstanceLockObject = new object();
private readonly object myStateLock = new object();
public ViewStreamDatabase ()
: this (new SubscriberCore ())
{
}
public ViewStreamDatabase (ISubscriberCore subscriberCore)
{
mySubscriberCore = subscriberCore;
// if (DataStreamLoadFileConfig.instance.profileStreams)
// new DataStreamPerfRecorder(this);
}
private static int myGetTimeInterval()
{
if (myTimeInterval == null)
{
// TODO
string timeInterval = String.Empty; //ConfigurationRequester.request("viewStreamDatabaseTimeOut");
if (timeInterval == null || timeInterval == "")
myTimeInterval = 0;
else
myTimeInterval = Int32.Parse(timeInterval);
}
return (int) myTimeInterval;
}
public static int instance_hashcode = -1;
public static ViewStreamDatabase instance
{
get
{
if(mySelf == null || mySelf.myIsDisposed)
lock(myInstanceLockObject)
{
if (mySelf == null || mySelf.myIsDisposed)
{
mySelf = new ViewStreamDatabase();
instance_hashcode = mySelf.GetHashCode();
}
}
return mySelf;
}
set
{
lock(myInstanceLockObject)
{
if (mySelf != null)
mySelf.mySubscriberCore.Dispose ();
mySelf = value;
instance_hashcode = mySelf.GetHashCode();
}
}
}
public ICollection<string> getCachedTables()
{
List<string> result = new List<string>();
foreach (string s in myITableAccumulatorMap.Keys)
if (((ITableAccumulator)myITableAccumulatorMap[s]).isActive())
result.Add(s);
return result;
}
public ISubscriberCore subscriber{get{return mySubscriberCore;}}
public ITableAccumulator getITableAccumulator (string tableName)
{
// If theres a ITableAccumulator for the tableName its returned (to share subscriptions), otherwise
// a new one is obtained from the Subscriber factory
myITableAccumulatorMap[tableName] = myITableAccumulatorMap[tableName] == null ?
AccumulatorFactory.getAccumulator(tableName, mySubscriberCore) : myITableAccumulatorMap[tableName];
return myITableAccumulatorMap [tableName] as ITableAccumulator;
}
public void doWork ()
{
verifyAccess();
if (myIsSuspended)
return;
if (myIsInDoWork)
return;
else
{
myIsInDoWork = true; // to allow reentrancy
try
{
if (onDoWorkStart != null)
onDoWorkStart();
ArrayList updateList = mySubscriberCore.getUpdates(myGetTimeInterval());
IDictionary updateMap = myGetUpdateMap(updateList);
foreach (DictionaryEntry de in updateMap)
{
Stream[] allUpdates = (de.Value as ArrayList).ToArray(typeof(Stream)) as Stream[];
string tag = de.Key.ToString();
if (myITableAccumulatorMap[tag] == null){}
// BlueEventLog.logEvent("Received a SubscriberCore's callback for a tag that was never subscribed", BlueEventLevel.Warning);
else
{
myTimer.start();
if (onTagFireStart != null)
onTagFireStart(tag);
(myITableAccumulatorMap[tag] as ITableAccumulator).update(allUpdates);
if (onTagFireEnd != null)
onTagFireEnd(tag);
myTimer.stop();
if (myTimer.lastIntervalTime > myLogTimeThreshold)
{
// BlueEventLog.logEvent("callback on tag " + tag.ToUpper() + " took " +
// myTimer.lastIntervalTime + " msecs", BlueEventLevel.Warning);
}
}
}
// to allow for registering of workers on the worker callback
myIsCallingWorkers = true;
myPendingOps = new ArrayList();
foreach (IWorker w in myWorkers)
{
myTimer.start();
w.doWork();
myTimer.stop();
if (myTimer.lastIntervalTime > _dowork_threshold){}
// mbts.Logger.log (bts.log.Level.Warn, bts.log.Subsystem.gen, String.Format ("VSD.dowork on worker {0} took {1}", w.GetType().ToString (), myTimer.lastIntervalTime));
}
myIsCallingWorkers = false;
foreach (PendingAddRemoveWorker op in myPendingOps)
if (op.isAdd)
addWorker(op.w);
else
removeWorker(op.w);
}
finally
{
myPendingOps = null;
myIsInDoWork = false;
myIsCallingWorkers = false;
if (onDoWorkEnd != null)
onDoWorkEnd ();
}
}//end if we're not in do work
}
private bool myIsSuspended = false;
public void suspend() { myIsSuspended = true; }
public void resume() { myIsSuspended = false; }
public bool checkAccess()
{
if (this.myThreadOwner == null) this.myThreadOwner = Thread.CurrentThread;
return this.myThreadOwner == Thread.CurrentThread;
}
public void verifyAccess()
{
if (!checkAccess())
{
string errorMessage = string.Format("Invalid cross thread access on ViewStreamDatabase. Owning thread: {0}. Accessing thread: {1}", this.myThreadOwner.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);
//#if DEBUG
// BlueEventLog2.instance().assert(false, errorMessage);
//#else
// BlueEventLog2.instance().logEvent(errorMessage, BlueEventLog2Level.Fatal);
//#endif
}
}
private IDictionary myGetUpdateMap (ArrayList updates)
{
IDictionary retVal = new Hashtable ();
foreach (PubSubUpdate update in updates)
{
if (retVal[update.tag] == null)
retVal[update.tag] = new ArrayList ();
(retVal[update.tag] as ArrayList).Add (update.body);
}
if (retVal.Count > 0)
{
string tagString = "";
foreach (string tag in retVal.Keys)
tagString += tag + " , ";
}
return retVal;
}
public bool isConsistent{get {return true;}}
public void addWorker(IWorker w)
{
verifyAccess();
if (myIsCallingWorkers)
myPendingOps.Add(new PendingAddRemoveWorker(true,w));
else
myWorkers.Add(w);
}
public void removeWorker(IWorker w)
{
verifyAccess();
if (myIsCallingWorkers)
myPendingOps.Add(new PendingAddRemoveWorker(false,w));
else
myWorkers.Remove(w);
}
#region IDisposable Members
public void Dispose()
{
if (!myIsDisposed)
{
myIsDisposed = true;
mySubscriberCore.Dispose ();
}
}
private ArrayList myPendingOps;
private bool myIsCallingWorkers = false;
class PendingAddRemoveWorker
{
public PendingAddRemoveWorker(bool isAdd, IWorker w)
{
this.isAdd = isAdd;
this.w = w;
}
public bool isAdd;
public IWorker w;
}
#endregion
}
/*
/// <summary>
/// Returns a subscriber based on the name of the tag. Hardcoded right now, will change to config
/// later
/// </summary>
public class SubscriberFactory
{
public static ITableAccumulator getITableAccumulator (string tag, SubscriberCore subCore)
{
string tableName = tag.Substring (3);
if (!DataStreamGatewaySettings.instance.isSerializableUnderNewScheme (tableName))
return new TableSubscriber (tag, subCore);
else
{
string subName = DataStreamGatewaySettings.instance.getSubscriber (tableName);
if (subName.Equals ("BCG.NonIncrementalTableSubscriber"))
return new NonIncrementalTableSubscriber (tag, subCore);
else
return new TableSubscriber (tag, subCore);
}
}
}*/
}
@@ -1,5 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\DataStreamCore\DataStreamCore.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
@@ -0,0 +1,24 @@
using System;
namespace BCG
{
public class DataStreamUserRespresentation : Attribute
{
private bool myIsVisible = true;
private string myFriendlyName;
public DataStreamUserRespresentation (string friendlyName)
{
myFriendlyName = friendlyName;
}
public DataStreamUserRespresentation (bool isVisible)
{
myIsVisible = isVisible;
}
public bool isVisible {get{return myIsVisible;}}
public string friendlyName {get{return myFriendlyName;}}
}
}
@@ -0,0 +1,192 @@
using System;
using System.Collections;
using System.Reflection;
using System.IO;
//using BCG.Utilities.BlueConfiguration;
//using BCG.Utilities;
namespace BCG
{
public class PrimitiveManager
{
private IDictionary myTypeLookupTable = new Hashtable ();
private static PrimitiveManager mySelf;
private ArrayList myAssemblyNames = new ArrayList ();
private PrimitiveManager()
{
myLoadAllTypes ();
}
private void myLoadAllTypes ()
{
DataStreamLoadFileConfig config = DataStreamLoadFileConfig.instance;
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(myAssemblyResolver);
loadAssembly (this.GetType ().Assembly.FullName);
foreach (string assemblyName in config.loadedAssemblies)
{
string resolvedAssemblyPath = assemblyName;
if (!System.IO.Path.IsPathRooted(assemblyName))
{
string appPath = Path.GetDirectoryName(
Assembly.GetAssembly(typeof(PrimitiveManager)).CodeBase.Substring("file:///".Length));
resolvedAssemblyPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(appPath, assemblyName));
}
loadAssembly(resolvedAssemblyPath);
}
}
private static Assembly myAssemblyResolver(object sender, ResolveEventArgs args)
{
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
if (args.Name.Equals(a.FullName))
return a;
return null;
}
/// <summary>
/// Loads all the Stream types associated with the assembly
/// </summary>
/// <param name="assemblyName"></param>
public void loadAssembly (string assemblyName)
{
if (myAssemblyNames.Contains (assemblyName))
return;
myAssemblyNames.Add (assemblyName);
Assembly loadedAssembly = GetType ().Assembly.FullName.Equals (assemblyName) ?
GetType ().Assembly :
Assembly.LoadFrom (assemblyName);
foreach (Type type in loadedAssembly.GetTypes())
if (!type.IsInterface
&& !type.IsAbstract
&& type.IsSubclassOf (typeof(ViewStream))
&& type.IsPublic)
{
bool isVisible = true;
string userRep = createDefaultName (type.Name);
foreach (Attribute att in type.GetCustomAttributes (false))
if (att is DataStreamUserRespresentation)
{
DataStreamUserRespresentation dsatt = att as DataStreamUserRespresentation;
isVisible = dsatt.isVisible;
userRep = isVisible ?
dsatt.friendlyName == null ? userRep : dsatt.friendlyName
: null;
break;
}
if (isVisible)
{
// BlueEventLog.logAssert(myTypeLookupTable [userRep] == null);
myTypeLookupTable[userRep] = type;
}
}
}
public static string createDefaultName (string typeName)
{
if (!typeName.EndsWith ("Stream"))
return typeName;
string retVal = typeName.Remove (typeName.Length - "Stream".Length, "Stream".Length);
string startString = new String (new char[] {retVal[0]}).ToLower ();
retVal = retVal.Remove (0, 1);
retVal = retVal.Insert (0, startString);
return retVal;
}
public static PrimitiveManager instance
{
get {return mySelf = mySelf == null ? new PrimitiveManager () : mySelf;}
}
/// <summary>
/// Returns the Type name corresponding to the primitive name
/// </summary>
/// <param name="friendlyName"></param>
/// <returns></returns>
public string find (string friendlyName)
{
if (myTypeLookupTable[friendlyName] == null)
throw new ApplicationException (friendlyName + " is not the friendly name of any of the loaded types");
return (myTypeLookupTable[friendlyName] as Type).Name;
}
/// <summary>
/// Constructs and returns a ViewStream of type corresponding to the friendly name
/// </summary>
/// <param name="friendlyName">friendly primitive name </param>
/// <param name="args">args can be null or an empty ICollection if the paramterless constructor
/// is the desired one</param>
/// <returns></returns>
public ViewStream build (string friendlyName, ICollection args)
{
object[] constructorArgs = null;
if (args != null && args.Count > 0)
{
constructorArgs = new object [args.Count];
args.CopyTo (constructorArgs, 0);
}
if (myTypeLookupTable[friendlyName] == null)
throw new ApplicationException (friendlyName + " is not the friendly name of any of the loaded types");
return
constructorArgs == null ?
Activator.CreateInstance (myTypeLookupTable[friendlyName] as Type) as ViewStream :
Activator.CreateInstance (myTypeLookupTable[friendlyName] as Type, constructorArgs) as ViewStream;
}
/// <summary>
/// Returns the name of all the primitives
/// </summary>
/// <returns></returns>
public string[] getPrimitiveNames ()
{
string[] retVal = new string [myTypeLookupTable.Count];
myTypeLookupTable.Keys.CopyTo (retVal, 0);
return retVal;
}
/// <summary>
/// Return the types of all the streams
/// </summary>
/// <returns></returns>
public Type[] getStreamTypes ()
{
Type[] retVal = new Type [myTypeLookupTable.Count];
myTypeLookupTable.Values.CopyTo (retVal, 0);
return retVal;
}
public ICollection getConstructorSigns (string primitiveName)
{
ArrayList retVal = new ArrayList ();
// BlueEventLog.logAssert (myTypeLookupTable[primitiveName] != null);
Type t = myTypeLookupTable[primitiveName] as Type;
foreach (ConstructorInfo ci in t.GetConstructors())
{
string sign = "";
sign = t.Name + " (";
foreach (ParameterInfo pi in ci.GetParameters ())
sign += pi.ParameterType.Name +
" " +
pi.Name + ", ";
sign = sign.Length == (t.Name + " (").Length ? sign + ")": sign.Remove (sign.Length - 2, 2) + ")";
retVal.Add (sign);
}
return retVal;
}
public string getAssemblyName (string primitiveName)
{
// BlueEventLog.logAssert (myTypeLookupTable[primitiveName] != null);
return (myTypeLookupTable[primitiveName] as Type).Assembly.GetName().Name;
}
}
}
@@ -1,14 +0,0 @@
namespace BCG {
using System;
using System.Collections;
public class PrimitiveManager {
public static PrimitiveManager instance => throw new NotImplementedException();
public ViewStream build(string friendlyName, ICollection args) =>
throw new NotImplementedException();
public string find(string friendlyName) =>
throw new NotImplementedException();
}
}
@@ -0,0 +1,105 @@
using System;
using System.Collections;
namespace BCG
{
internal class AddColumnsRow : IBlueRow
{
private IBlueTableSchema mySchema;
private IBlueRow myRow;
//private object[] myCachedValues;
#region Constructors
public AddColumnsRow (IBlueTableSchema schema, IBlueRow row)
{
mySchema = schema;
myRow = row;
//myCachedValues = new object[schema.columnNames.Length];
}
#endregion
#region IBlueRow members
public IBlueTableSchema schema{get{return mySchema;}}
#endregion
#region ICollection members
public int Count {get{return mySchema.columnNames.Length;}}
public bool IsSynchronized {get{return false;}}
public object SyncRoot {get{return this;}}
public void CopyTo (Array array, int index)
{
int i = index;
foreach (object o in this as IEnumerable)
array.SetValue (o, i++);
}
#endregion
#region IDictionary members
public bool IsFixedSize {get{return true;}}
public bool IsReadOnly {get{return true;}}
/// <summary>
/// The key can either be the string corrsponding to the column name or
/// the order of the column
/// </summary>
public object this [object key]
{
get
{
if (key is string)
return this[(string)key];
return this[(int)key];
}
set {throw new NotSupportedException ("The IBlueRow is readonly");}
}
public object this[int index]
{
get
{
//if (myCachedValues[index] == null)
// myCachedValues[index] = mySchema[index].isConstant ? mySchema[index].colValue : myRow[index];
//return myCachedValues[index];
return mySchema[index].isConstant ? mySchema[index].colValue : myRow[index];
}
}
public object this[string colName] {get{return this[mySchema[colName].colNo];}}
public ICollection Keys{get{return mySchema.columnNames;}}
public ICollection Values
{
get
{
object[] retVal = new object[mySchema.columnNames.Length];
CopyTo (retVal, 0);
return retVal;
}
}
public void Add (object key, object value) {throw new NotSupportedException ("The IBlueRow is readonly");}
public void Clear () {throw new NotSupportedException ("The IBlueRow is readonly");}
public bool Contains (object key){return mySchema[(string)key] != null;}
/// <summary>
/// Note, the default enumerator is the IDictionary's enumerator, so if user needs to
/// iterate through the values, typecast this into an IEnumerable
/// </summary>
/// <returns></returns>
public IDictionaryEnumerator GetEnumerator() {return new BlueRowDictionaryEnumerator(this);}
IEnumerator IEnumerable.GetEnumerator () {return new BlueRowEnumerator(this);}
public void Remove (object key) {throw new NotSupportedException ("The IBlueRow is readonly");}
#endregion
}
}
@@ -0,0 +1,13 @@
// using System;
// using System.Data;
// using System.Collections;
// using BCG.Utilities;
// using BCG.Utilities.General;
// namespace BCG
// {
// public class AddColumnsStream : MapStream
// {
// public AddColumnsStream(ViewStream vs, string columnDef) : base (vs, new ColumnAdder (columnDef)) {}
// }
// }
@@ -0,0 +1,13 @@
// using System;
// namespace BCG {
// public class AddRegexColumnsStream : ViewStream {
// public AddRegexColumnsStream (ViewStream vs, string srcCol, string regex, string newColDefs) {
// IStreamMapper mapper = new RegexMatchAdder (srcCol, newColDefs, regex);
// mySetRealSource (new MapStream (vs, mapper));
// }
// }
// }
@@ -0,0 +1,73 @@
// using System;
// using System.Collections;
// using BCG.Utilities;
// using BCG.Evaluator.AddColumnsExpression;
// namespace BCG
// {
// /// <summary>
// /// Provides methods to add columns to the schema
// /// </summary>
// public class ColumnAdder : IStreamMapper
// {
// protected IDictionary myNewColumns;
// protected IBlueTableSchema mySchema;
// static syntax myParser =
// new syntax();
// /// <summary>
// /// string represting the columns to be added to the output table.
// /// </summary>
// /// <param name="colAddExpression"></param>
// public ColumnAdder (string columnDef)
// {
// AddColumnsExpression ace;
// if (DataStreamLoadFileConfig.instance.useStaticParser)
// {
// lock (myParser)
// {
// ace =
// (AddColumnsExpression)myParser.Parse(columnDef);
// }
// }
// else
// {
// syntax parser = new syntax();
// ace =
// (AddColumnsExpression)parser.Parse(columnDef);
// }
// if (ace == null)
// throw new Exception ("Invalid columnn expression: " + columnDef);
// myNewColumns = ace.columns;
// }
// public virtual IBlueRow map (IBlueRow row)
// {
// if (mySchema == null)
// myConstructSchema (row.schema);
// return new AddColumnsRow (mySchema, row);
// }
// public IBlueTableSchema getOutputSchema (IBlueTableSchema inputSchema)
// {
// myConstructSchema (inputSchema);
// return mySchema;
// }
// private void myConstructSchema (IBlueTableSchema schema)
// {
// ColumnInfo[] cis = new ColumnInfo[schema.columnNames.Length + myNewColumns.Count];
// int ciIndex = 0;
// foreach (ColumnInfo ci in schema.columnInfo)
// cis[ciIndex++] = ci;
// foreach (DictionaryEntry de in myNewColumns)
// cis[ciIndex] = new ColumnInfo ((string)de.Key, ciIndex ++,
// ((AddColumnsExpression.ConstantInfo)de.Value).t, ((AddColumnsExpression.ConstantInfo)de.Value).v);
// mySchema = new BlueTableSchema (cis, schema.tableName);
// }
// }
// }
@@ -0,0 +1,100 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// namespace BCG
// {
// public class BooleanStringReplaceStream : ViewStream, IStreamMapper
// {
// private BooleanExpressionFilter _bool;
// private string _column, _value;
// private IBlueTableSchema _schema;
// public BooleanStringReplaceStream(ViewStream vs, string boolean_expression, string column, string value)
// {
// _column = column;
// _value = value;
// if(!string.IsNullOrEmpty(boolean_expression))
// _bool = new BooleanExpressionFilter(boolean_expression);
// mySetRealSource(new MapStream(vs, this));
// }
// public IBlueTableSchema getOutputSchema(IBlueTableSchema inputSchema)
// {
// _schema = inputSchema;
// return inputSchema;
// }
// public IBlueRow map(IBlueRow row)
// {
// MutableBlueRow result = new MutableBlueRow(_schema, row);
// if(_bool == null || _bool.filter(row))
// result.setValue(_column, _value);
// return result;
// }
// }
// public class MathStream : ViewStream, IStreamMapper
// {
// private ArithmeticExpressionEvaluator.ArithmeticExpression myExp;
// private BooleanExpressionFilter _bool;
// List<string> myExtraColumns = new List<string>();
// BlueTableSchema mySchema;
// public MathStream(ViewStream vs, string mathExpression)
// : this(vs, mathExpression, string.Empty)
// {
// }
// public MathStream(ViewStream vs, string mathExpression, string boolean_expression)
// {
// myExp = ArithmeticExpressionEvaluator.compile(mathExpression);
// myExtraColumns = ArithmeticExpressionEvaluator.getOutputIdentifiers(myExp);
// if(!string.IsNullOrEmpty(boolean_expression))
// _bool = new BooleanExpressionFilter(boolean_expression);
// mySetRealSource(new MapStream(vs, this));
// }
// #region IStreamMapper Members
// public IBlueTableSchema getOutputSchema(IBlueTableSchema inputSchema)
// {
// if (mySchema == null)
// {
// Dictionary<string, ColumnInfo> colIdx = new Dictionary<string, ColumnInfo>();
// foreach (ColumnInfo ci in inputSchema.columnInfo)
// colIdx[ci.colName] = ci;
// foreach (string ncn in myExtraColumns)
// {
// ColumnInfo newC;
// if (colIdx.ContainsKey(ncn))
// newC = new ColumnInfo(colIdx[ncn].colName, colIdx[ncn].colNo, typeof(double));
// else
// newC = new ColumnInfo(ncn, colIdx.Count, typeof(double));
// colIdx[ncn] = newC;
// }
// mySchema = new BlueTableSchema(colIdx.Values.ToArray(), "math(" + inputSchema.tableName + ")");
// }
// return mySchema;
// }
// #endregion
// #region IDynamicStreamMapper Members
// public IBlueRow map(IBlueRow row)
// {
// MutableBlueRow result = new MutableBlueRow(mySchema, row);
// if(_bool == null || _bool.filter(row))
// {
// foreach(var kvp in ArithmeticExpressionEvaluator.eval(myExp, (System.Collections.IDictionary)result))
// result.setValue(kvp.Key, kvp.Value);
// }
// return result;
// }
// #endregion
// }
// }
@@ -0,0 +1,48 @@
// using System;
// using System.Collections;
// using System.Collections.Generic;
// using System.Text.RegularExpressions;
// using System.ComponentModel;
// using BCG.Utilities;
// namespace BCG {
// public class RegexMatchAdder : ColumnAdder {
// private int[] myAddedColNos;
// private string mySrcCol;
// private Regex myRegex;
// public RegexMatchAdder (string srcCol, string columnDef, string regex) : base (columnDef) {
// mySrcCol = srcCol;
// myRegex = new Regex (regex);
// }
// public override IBlueRow map (IBlueRow row) {
// MutableBlueRow result = new MutableBlueRow (mySchema, row);
// if (myAddedColNos == null) {
// myAddedColNos = new int[myNewColumns.Count];
// for (int i = 0; i < myAddedColNos.Length; ++i)
// myAddedColNos[i] = i + row.Count;
// }
// object[] values = new object[myNewColumns.Count];
// string src = (string)row[mySrcCol];
// // extract the requested regex substrings
// Match m = myRegex.Match (src);
// for (int icol = 0; icol < myAddedColNos.Length; ++icol) {
// int i = icol + row.Count;
// Group g = m.Groups[mySchema.columnNames[i]];
// object val = TypeDescriptor.GetConverter (mySchema[i].colType)
// .ConvertFromString (g.Success ? g.Value: string.Empty);
// result.setValue (i, val);
// }
// return result;
// }
// }
// }
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG
{
public class XYTranspositionStream : ViewStream
{
private ViewStream _stream;
private IBlueTableSchema _schema;
private string[] _transposed_cols;
public XYTranspositionStream(ViewStream stream, string transposed_cols)
{
_transposed_cols = transposed_cols.Split(' ');
_stream = stream;
}
protected override void myOnFirstSubscriber()
{
_stream.onChange += _stream_onChange;
}
protected override void myOnLastSubscriber()
{
if (_stream != null)
_stream.onChange -= _stream_onChange;
}
private void _stream_onChange(object newValue)
{
DataPacket dp = newValue as DataPacket;
if (dp != null)
{
if (_schema == null)
_make_schema(dp.schema);
BlueTable result = new BlueTable(_schema);
int id = 1;
foreach (IBlueRow row in dp.newRows)
{
foreach (string transposed_col in _transposed_cols)
{
MutableBlueRow mbr = new MutableBlueRow(_schema);
for (int i = 0; i < _schema.columnNames.Length; i++)
{
if (_schema.columnNames[i] == "id")
mbr.setValue(i, id++);
else if (_schema.columnNames[i] == "param_name")
mbr.setValue(i, transposed_col);
else if (_schema.columnNames[i] == "param_value")
mbr.setValue(i, row[transposed_col]);
else
mbr.setValue(i, row[_schema.columnNames[i]]);
}
result.addRow(mbr);
}
}
myFireEvent(new DataPacket(result, result, myLastValue == null ? new BlueTable(_schema) : (myLastValue as DataPacket).newRows));
}
}
private void _make_schema(IBlueTableSchema input_schema)
{
List<ColumnInfo> info = new List<ColumnInfo>();
int col_counter = 0;
info.Add(new ColumnInfo("id", col_counter++, typeof(int)));
info.Add(new ColumnInfo("param_name", col_counter++, typeof(string)));
info.Add(new ColumnInfo("param_value", col_counter++, typeof(object)));
foreach (ColumnInfo ci in input_schema.columnInfo)
if (!_is_transposing_column(ci.colName) && ci.colName != "id")
info.Add(new ColumnInfo(ci.colName, col_counter++, ci.colType));
_schema = new BlueTableSchema(info.ToArray(), String.Format("xy_transposed_{0}", input_schema.tableName));
}
private bool _is_transposing_column(string col_name)
{
foreach (string tc in _transposed_cols)
if (col_name == tc)
return true;
return false;
}
}
}
@@ -0,0 +1,244 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts;
namespace BCG
{
public class YXTranspositionStream : ViewStream, INonIncGroupByEvaluator
{
private class OnlyFireOnceStream : ViewStream
{
private ViewStream _stream;
private bool _hooked = false;
public OnlyFireOnceStream(ViewStream stream)
{
_stream = stream;
}
protected override void myOnFirstSubscriber()
{
_stream.onChange += _stream_onChange;
_hooked = true;
}
protected override void myOnLastSubscriber()
{
if (_hooked && _stream != null)
_stream.onChange -= _stream_onChange;
}
private void _stream_onChange(object newValue)
{
DataPacket dp = newValue as DataPacket;
if (dp != null && dp.newRows.Count > 0)
{
_stream.onChange -= _stream_onChange;
myFireEvent(new DataPacket(dp.newRows, dp.newRows, new BlueTable(dp.newRows.schema)));
}
}
}
public delegate void IncrementValues(object[] current_values, object[] values_to_inc);
public delegate string GetColumnPrefix(object[] transposing_col_values);
public delegate string GetColumnSuffix(string col_name);
private GetColumnSuffix _get_column_suffix = new GetColumnSuffix((cn) => { return cn; });
private IncrementValues _increment_values;
private GetColumnPrefix _get_column_prefix;
private IBlueTableSchema _schema;
private string[] _group_by_cols;
private Pair<string, Type>[] _cols_per_transposed;
private string[] _transposing_cols;
private int[] _transposing_col_indices;
private Comparison<Pair<int, object[]>> _transpsed_col_value_comparer_wrapper;
public YXTranspositionStream(ViewStream stream, string transposed_cols_group, string cols_per_transposed, string group_by_cols,
IncrementValues increment_values_del, GetColumnPrefix get_column_prefix_del, GetColumnSuffix get_column_suffix_del, Comparison<object[]> transposed_col_value_comparer)
: this(stream, transposed_cols_group, cols_per_transposed, group_by_cols, increment_values_del,
get_column_prefix_del, get_column_suffix_del, transposed_col_value_comparer, true)
{ }
public YXTranspositionStream(ViewStream stream, string transposed_cols_group, string cols_per_transposed, string group_by_cols,
IncrementValues increment_values_del, GetColumnPrefix get_column_prefix_del, GetColumnSuffix get_column_suffix_del, Comparison<object[]> transposed_col_value_comparer, bool only_fire_once)
{
if (get_column_suffix_del != null)
_get_column_suffix = get_column_suffix_del;
if (transposed_col_value_comparer != null)
{
_transpsed_col_value_comparer_wrapper = new Comparison<Pair<int, object[]>>((p1,p2) =>
{
return transposed_col_value_comparer(p1.second, p2.second);
});
}
_group_by_cols = group_by_cols.Split(' ');
_transposing_cols = transposed_cols_group.Split(' ');
string[] cols = cols_per_transposed.Split(' ');
_cols_per_transposed = new Pair<string, Type>[cols.Length];
for (int i = 0; i < _cols_per_transposed.Length; i++)
{
string[] name_type = cols[i].Split('\\');
// mbts.Logger.assert(name_type.Length == 2, "Expected cols_per_transposed to be in format name\\type");
_cols_per_transposed[i] = new Pair<string, Type>(name_type[0], Type.GetType(name_type[1]));
}
_increment_values = increment_values_del;
_get_column_prefix = get_column_prefix_del;
if(only_fire_once)
mySetRealSource(new NonIncGroupByStream(new OnlyFireOnceStream(stream), this));
else
mySetRealSource(new NonIncGroupByStream(stream, this));
}
private void _set_schema(List<string> tc_prefixes, Pair<string, Type>[] group_by_col_info, string table_name)
{
int col_index = 0;
List<ColumnInfo> col_info = new List<ColumnInfo>();
col_info.Add(new ColumnInfo("id", col_index++, typeof(int)));
foreach (Pair<string, Type> p in group_by_col_info)
col_info.Add(new ColumnInfo(p.first, col_index++, p.second));
foreach (string tc_prefix in tc_prefixes)
foreach (Pair<string, Type> p in _cols_per_transposed)
col_info.Add(new ColumnInfo(_get_full_column_name(tc_prefix, p.first), col_index++, p.second));
IBlueTableSchema schema = new BlueTableSchema(col_info.ToArray(), "xy_transposed_" + table_name);
if (_schema == null)
_schema = schema;
}
private string _get_full_column_name(string prefix, string col_name)
{
string suffix = _get_column_suffix(col_name);
if (suffix == string.Empty)
return prefix;
else
return prefix + "_" + suffix;
}
#region INonIncGroupByEvaluator Members
public string[] get_group_by_cols()
{
return _group_by_cols;
}
public IBlueRowCollection evaluate(IDictionary<int, List<IBlueRow>> grouped_rows)
{
Dictionary<int, Dictionary<int, object[]>> all_tc_infos_and_values = new Dictionary<int, Dictionary<int, object[]>>();
Dictionary<int, object[]> group_by_cols_value_dict = new Dictionary<int, object[]>();
BlueRowHasher hasher = new BlueRowHasher(_transposing_cols.Length);
Pair<string, Type>[] group_by_col_info = new Pair<string, Type>[_group_by_cols.Length];
string table_name = string.Empty;
if (grouped_rows.Count > 0)
{
IBlueTableSchema schema = null;
foreach (KeyValuePair<int, List<IBlueRow>> kvp in grouped_rows)
{
schema = kvp.Value[0].schema;
break;
}
table_name = schema.tableName;
_transposing_col_indices = BlueDataUtility.get_column_indices(schema, _transposing_cols);
int[] group_by_indices = BlueDataUtility.get_column_indices(schema, _group_by_cols);
for (int i = 0; i < group_by_indices.Length; i++)
{
ColumnInfo ci = schema.columnInfo[group_by_indices[i]];
group_by_col_info[i] = new Pair<string, Type>(ci.colName, ci.colType);
}
}
else
return new BlueTable(new BlueTableSchema(new ColumnInfo[] { new ColumnInfo("id", 0, typeof(int)) }, table_name));
Dictionary<int, string> tc_prefixes = new Dictionary<int, string>();
List<Pair<int, object[]>> tc_values = new List<Pair<int, object[]>>();
foreach (KeyValuePair<int, List<IBlueRow>> kvp in grouped_rows)
{
//Dictionary of trans_col_group_hash -> pair: first=trans_col_group_values second=per_transposing_col_values
Dictionary<int, object[]> incrementing_values = new Dictionary<int, object[]>();
foreach (IBlueRow r in kvp.Value)
{
int hash = hasher.get_hash(r, _transposing_col_indices);
object[] values;
if (!incrementing_values.TryGetValue(hash, out values))
{
incrementing_values.Add(hash, _get_per_transposing_col_values(r));
string prefix = _get_column_prefix(_get_transposing_col_values(r));
if (!tc_prefixes.ContainsKey(hash))
{
tc_prefixes.Add(hash, prefix);
tc_values.Add(new Pair<int,object[]>(hash, _get_transposing_col_values(r)));
}
}
else
_increment_values(values, _get_per_transposing_col_values(r));
}
all_tc_infos_and_values.Add(kvp.Key, incrementing_values);
//An ugly way to extract group information needed to insert values later
foreach (IBlueRow r in kvp.Value)
{
group_by_cols_value_dict.Add(kvp.Key, _get_group_by_cols_values(r));
break;
}
}
//Sort the transposed schema
if (_transpsed_col_value_comparer_wrapper != null)
tc_values.Sort(_transpsed_col_value_comparer_wrapper);
List<string> prefixes = new List<string>();
foreach (Pair<int, object[]> p in tc_values)
prefixes.Add(tc_prefixes[p.first]);
_set_schema(prefixes, group_by_col_info, table_name);
BlueTable result = new BlueTable(_schema);
int id = 1;
foreach (KeyValuePair<int, Dictionary<int, object[]>> kvp in all_tc_infos_and_values)
{
MutableBlueRow mbr = new MutableBlueRow(_schema);
mbr.setValue("id", id++);
for (int i = 0; i < _group_by_cols.Length; i++)
mbr.setValue(_group_by_cols[i], group_by_cols_value_dict[kvp.Key][i]);
foreach (KeyValuePair<int, object[]> tc_cols in kvp.Value)
{
string prefix = tc_prefixes[tc_cols.Key];
for (int i = 0; i < _cols_per_transposed.Length; i++)
{
string column = _get_full_column_name(prefix, _cols_per_transposed[i].first);
if(mbr.schema.columnNames.Contains(column))
mbr.setValue(column, tc_cols.Value[i]);
}
}
result.addRow(mbr);
}
return result;
}
#endregion
private object[] _get_transposing_col_values(IBlueRow row)
{
object[] values = new object[_transposing_cols.Length];
for (int i = 0; i < _transposing_cols.Length; i++)
values[i] = row[_transposing_cols[i]];
return values;
}
private object[] _get_per_transposing_col_values(IBlueRow row)
{
object[] values = new object[_cols_per_transposed.Length];
for (int i = 0; i < _cols_per_transposed.Length; i++)
values[i] = row[_cols_per_transposed[i].first];
return values;
}
private object[] _get_group_by_cols_values(IBlueRow row)
{
object[] values = new object[_group_by_cols.Length];
for (int i = 0; i < values.Length; i++)
values[i] = row[_group_by_cols[i]];
return values;
}
}
}
@@ -0,0 +1,22 @@
// using System;
// using BCG;
// using BCG.Utilities;
// namespace BCG
// {
// public class CartesianProductStream : ViewStream
// {
// public CartesianProductStream(ViewStream v1, ViewStream v2)
// {
// mySetRealSource(
// new JoinStream (new AddColumnsStream (v1,
// "hiddenCartesianColumn=1"),
// "hiddenCartesianColumn",
// "!id hiddenCartesianColumn dateTime:dateBoundary",
// new AddColumnsStream (v2,
// "hiddenCartesianColumn=1"),
// "hiddenCartesianColumn",
// "!id hiddenCartesianColumn"));
// }
// }
// }
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public class CaseChangeStream : ViewStream, IStreamMapper
{
private string[] myCaseChangingColumns;
bool myIsUpperCase;
public CaseChangeStream(ViewStream input, bool toUpper, params string[] columnsToChangeCase)
{
myCaseChangingColumns = columnsToChangeCase;
mySetRealSource(new SuperMapStream(input, this));
myIsUpperCase = toUpper;
}
#region IStreamMapper Members
public IBlueTableSchema getOutputSchema(IBlueTableSchema inputSchema)
{
return inputSchema;
}
#endregion
#region IDynamicStreamMapper Members
public IBlueRow map(IBlueRow row)
{
object[] outValues = new object[row.Count];
row.CopyTo(outValues,0);
foreach (string colName in myCaseChangingColumns)
{
ColumnInfo thisCol = row.schema[colName];
object rowVal = outValues[thisCol.colNo];
if (rowVal is string && !string.IsNullOrEmpty((string)rowVal))
outValues[thisCol.colNo] = myIsUpperCase ? ((string)rowVal).ToUpper() : ((string)rowVal).ToLower();
}
return new BlueRow(row.schema, outValues);
}
#endregion
}
}
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public class ToLowerStream : CaseChangeStream
{
public ToLowerStream(ViewStream input, params string[] colNames)
: base(input, false, colNames) { }
}
}
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public class ToUpperStream : CaseChangeStream
{
public ToUpperStream(ViewStream input, params string[] colNames)
: base(input, true, colNames) { }
}
}
@@ -0,0 +1,135 @@
using System;
using System.Collections;
using System.Text;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class ConcatenateColumnsMapper : IStreamMapper
{
protected IDictionary myTempColMap = new SortedList ();
protected ArrayList myColMap;
protected BlueTableSchema mySchema;
public ConcatenateColumnsMapper(params string [] columnDefs)
{
foreach (string cd in columnDefs)
{
string outColumn =
cd.Substring(0,cd.IndexOf(":"));
string [] inColumns =
cd.Substring(cd.IndexOf(":") + 1).Split(' ');
string [] trimedIn = new string[inColumns.Length];
int n = 0;
foreach (string s in inColumns)
trimedIn[n++] = s.Trim();
myTempColMap[outColumn.Trim()] = trimedIn;
}
}
#region IStreamMapper Members
public IBlueTableSchema getOutputSchema (IBlueTableSchema inputSchema)
{
if (mySchema == null)
{
/*
* The new columns form the first columns, and the existing columns in the input
* schema are appened.
* */
ArrayList cis = new ArrayList ();
foreach (string cn in myTempColMap.Keys)
cis.Add (new ColumnInfo (cn, cis.Count, typeof(string)));
foreach (ColumnInfo ci in inputSchema.columnInfo)
cis.Add (new ColumnInfo (ci.colName, cis.Count, ci.colType));
mySchema = new BlueTableSchema("ConcatenateColumns " + inputSchema.tableName,
cis.ToArray (typeof(ColumnInfo)) as ColumnInfo[]);
/*
* An arraylist is formed which indexes the new columns to the existing ones that form it. Hashtables
* are avoided wherever possible (which is natural as well, as the keys are ordered integers)
* */
myColMap = new ArrayList (myTempColMap.Count);
foreach (DictionaryEntry de in myTempColMap)
{
string[] cols = de.Value as string[];
ArrayList temp = new ArrayList ();
foreach (string col in cols)
temp.Add (inputSchema[col].colNo);
myColMap.Add (temp.ToArray(typeof(int)) as int[]);
}
myTempColMap.Clear ();
}
return mySchema;
}
#endregion
#region IDynamicStreamMapper Members
public virtual IBlueRow map (IBlueRow row)
{
object[] retVal = new object[mySchema.columnInfo.Length];
row.CopyTo (retVal, myColMap.Count);
for (int colNo = 0; colNo < myColMap.Count; colNo ++)
retVal[colNo] = myGetConcatValue (row, colNo);
return new BlueRow (mySchema, retVal);
}
#endregion
/// <summary>
/// Given a row and a column number, the method extracts the constituent columns indices
/// (from the colMap array) and form the resultant value corresponding to colNo and the row passed
/// </summary>
/// <param name="row"></param>
/// <param name="colNo"></param>
/// <returns></returns>
protected virtual object myGetConcatValue (IBlueRow row, int colNo)
{
StringBuilder b = new StringBuilder();
foreach (int cn in myColMap[colNo] as int[])
b.Append(row[cn].ToString());
return b.ToString ();
}
}
public class ConcatenateColumnsMapperForSameDataSet : ConcatenateColumnsMapper
{
private HashTableND[] myDicts;
public ConcatenateColumnsMapperForSameDataSet (params string [] columnDefs)
: base (columnDefs)
{
myDicts = new HashTableND [columnDefs.Length];
int i = 0;
foreach (DictionaryEntry de in myTempColMap)
myDicts[i++] = new HashTableND ((de.Value as string[]).Length);
}
protected override object myGetConcatValue (IBlueRow row, int colNo)
{
int[] cols = myColMap[colNo] as int[];
object[] vals = new object[cols.Length];
for (int i = 0; i < vals.Length; i++)
vals[i] = row[cols[i]];
HashTableND ht = myDicts[colNo];
object rv = ht.getValue (vals);
if (rv != null)
return rv;
else
{
rv = base.myGetConcatValue (row, colNo);
object[] args = new object[vals.Length + 1];
vals.CopyTo (args, 0);
args[args.Length-1] = rv;
ht.add (args);
return rv;
}
}
}
}
@@ -0,0 +1,42 @@
using System;
using BCG;
using BCG.Utilities;
namespace BCG
{
public class ConcatenateColumnsStream : ViewStream
{
// Concatenates the string representation of some of the fields
// in the input stream
// use the following syntax for the columnDef
// a:b c d
// where a is the name of the output column and b, c, and d are
// names of input colums to be concatenated
public ConcatenateColumnsStream(
ViewStream sourceStream,
params string [] columnDefs)
: this (sourceStream, true, columnDefs)
{}
/// <summary>
///
/// </summary>
/// <param name="sourceStream"></param>
/// <param name="isConcatenatedDataConfined">true when the data being appended does not change often</param>
/// <param name="columnDefs"></param>
public ConcatenateColumnsStream (ViewStream sourceStream,
bool isConcatenatedDataConfined,
params string[] columnDefs)
{
mySetRealSource (
new MapStream (sourceStream,
isConcatenatedDataConfined ? new ConcatenateColumnsMapperForSameDataSet (columnDefs) :
new ConcatenateColumnsMapper (columnDefs)
)
);
}
}
}
@@ -0,0 +1,55 @@
using System;
namespace BCG
{
[DataStreamUserRespresentation ("count")]
public class CountStream : ViewStream
{
private DataPacket myLastFiredDataPacket;
private IBlueTableSchema mySchema = new BlueTableSchema ("count",
new ColumnInfo ("id", 0, typeof(int)),
new ColumnInfo ("count", 1, typeof(int)));
private int myId = 0;
private ViewStream myVS;
public CountStream (ViewStream vs)
{
myVS = vs;
}
public CountStream (string tableName)
: this (new TableStream (tableName))
{}
protected override void myOnFirstSubscriber () {
myVS.onChange += new ChangeDelegate(myHandleChanges);
}
protected override void myOnLastSubscriber () {
myVS.onChange -= new ChangeDelegate(myHandleChanges);
}
private void myHandleChanges(object newValue)
{
myFireEvent (
myLastFiredDataPacket =
myLastFiredDataPacket == null ?
new DataPacket (myGetRows (newValue, ++myId), myGetRows (newValue, myId),
new BlueTable (mySchema))
:
new DataPacket (myGetRows (newValue, ++myId), myGetRows (newValue, myId),
myLastFiredDataPacket.newRows)
);
}
private IBlueRowCollection myGetRows (object dp, int id)
{
BlueTable retVal = new BlueTable (mySchema);
retVal.addRow
(new BlueRow (mySchema, id, (dp as DataPacket).newRows.Count));
return retVal;
}
}
}
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public class AverageCollectorStream : ViewStream, ITableCrusher
{
public AverageCollectorStream(ViewStream stream, params string[] columnsToAverage)
{
myAveragingColumns = columnsToAverage;
mySetRealSource(new CrushingCollectorStream(stream, this));
}
private string[] myAveragingColumns;
#region ITableCrusher Members
public IBlueRow crush(IBlueRowCollection rows, int idToUse)
{
IDictionary<string, double> columnSums = new Dictionary<string, double>();
IBlueRow resultRow = null;
foreach (IBlueRow row in rows)
{
resultRow = row;
foreach (string colName in myAveragingColumns)
{
double sum = 0.0f;
columnSums.TryGetValue(colName, out sum);
sum += (double) row[colName];
columnSums[colName] = sum;
}
}
object[] resultValues = new object[rows.schema.columnNames.Length];
if (resultRow != null)
resultRow.CopyTo(resultValues, 0);
resultValues[rows.schema["id"].colNo] = idToUse;
resultRow = new BlueRow(rows.schema, resultValues);
return resultRow;
}
#endregion
}
}
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public class CrushingCollectorStream : ViewStream
{
/* Arguments: a single
* Every time one of input the streams updates, it is crushed down to a single row,
* and added to the collection of output rows.
*
* The column 'tableIdentifierColumnName' is added to the schema, and each row from the viewstream
* is put into the
*
* */
public CrushingCollectorStream(ViewStream toCrush, ITableCrusher crusher)
{
myToCrush = toCrush;
myRows = new List<IBlueRow>();
myCrusher = crusher;
}
private ViewStream myToCrush;
private List<IBlueRow> myRows;
private ITableCrusher myCrusher;
private int myNextId = 0;
protected override void myOnFirstSubscriber()
{
myToCrush.onChange += new ChangeDelegate(myToCrush_onChange);
}
protected override void myOnLastSubscriber()
{
myToCrush.onChange -= myToCrush_onChange;
}
void myToCrush_onChange(object newValue)
{
DataPacket dp = (DataPacket)newValue;
IBlueRow crushed = myCrusher.crush(dp.newRows, myNextId++);
BlueTable newRows = new BlueTable(dp.schema);
newRows.addRows(myRows);
newRows.addRow(crushed);
myRows.Add(crushed);
BlueTable added = new BlueTable(dp.schema);
added.addRow(crushed);
myFireEvent(new DataPacket(newRows, added, new BlueTable(dp.schema)));
}
}
}
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public class CrushingStream : ViewStream
{
public CrushingStream(ITableCrusher crusher, params ViewStream[] streamsToCrush)
{
myToCrush = streamsToCrush;
myCrusher = crusher;
myOldRows = new IBlueRow[myToCrush.Length];
//set up an anonymous delegate for each of the streams
//we do this so that we can unsubscribe
myDelegates = new ChangeDelegate[myToCrush.Length];
for (int i = 0; i < myToCrush.Length; ++i)
{
int tempI = i;
myDelegates[tempI] = new ChangeDelegate((o) => { myHandleChange(tempI, ((DataPacket)o).newRows); });
}
}
private IBlueRow[] myOldRows;
private ViewStream[] myToCrush;
private ITableCrusher myCrusher;
private ChangeDelegate[] myDelegates;
protected override void myOnFirstSubscriber()
{
for (int i = 0; i < myToCrush.Length; ++ i)
myToCrush[i].onChange += myDelegates[i];
}
protected override void myOnLastSubscriber()
{
for (int i = 0; i < myToCrush.Length; ++i)
myToCrush[i].onChange -= myDelegates[i];
}
protected virtual void myHandleChange(int streamIndex, IBlueRowCollection newRows)
{
IBlueRow oldRow = myOldRows[streamIndex];
IBlueRow newRow = myCrusher.crush(newRows, streamIndex);
myOldRows[streamIndex] = newRow;
BlueTable newState = new BlueTable(newRows.schema);
newState.addRows(myOldRows);
BlueTable addedRows = new BlueTable(newRows.schema);
addedRows.addRow(newRow);
BlueTable removedRows = new BlueTable(newRows.schema);
removedRows.addRow(oldRow);
myFireEvent(new DataPacket(newState, addedRows, removedRows));
}
}
}
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public interface ITableCrusher
{
IBlueRow crush(IBlueRowCollection rows, int idToUse);
}
}
@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public class DerivativeStream : ViewStream
{
private IBlueTableSchema mySchema;
private string myDerivandColumn;
private string myOutputColumn;
private string myKeyColumn;
private DateTime myLastPacketArrival = DateTime.MinValue;
private ViewStream myDataSource;
private IDictionary<string, double> myPreviousValues;
public DerivativeStream(ViewStream input, string keyColumn, string columnToDifferentiate, string outputColName)
{
myDerivandColumn = columnToDifferentiate;
myOutputColumn = outputColName;
myKeyColumn = keyColumn;
myDataSource = input;
}
protected override void myOnFirstSubscriber()
{
myDataSource.onChange += new ChangeDelegate(myDataSource_onChange);
}
protected override void myOnLastSubscriber()
{
myDataSource.onChange -= myDataSource_onChange;
}
void myDataSource_onChange(object newValue)
{
DataPacket dp = (DataPacket)newValue;
if (myLastPacketArrival == DateTime.MinValue)
mySchema = myBuildOutputSchema(dp.schema);
else
{
DateTime now = DateTime.Now;
BlueTable thisVersion = new BlueTable(mySchema);
double timeScale = 1.0 / (now - myLastPacketArrival).TotalSeconds;
foreach (IBlueRow r in dp.newRows)
thisVersion.addRow(myMakeRow(r, timeScale));
if (myLastValue == null)
myFireEvent(new DataPacket(thisVersion, new BlueTable(mySchema), new BlueTable(mySchema)));
else
{
IBlueRowCollection deleted, added;
BlueDataUtility.computeDifferences(thisVersion, ((DataPacket)myLastValue).newRows, out deleted, out added);
myFireEvent(new DataPacket(thisVersion, added, deleted));
}
}
myStoreNewPacketInfo(dp);
}
protected IBlueRow myMakeRow(IBlueRow r, double timeScale)
{
object[] outValues = new object[mySchema.columnInfo.Length];
r.Values.CopyTo(outValues, 0);
object derivand = r[myDerivandColumn];
double lastValue = default(double);
if (myPreviousValues.TryGetValue(r[myKeyColumn].ToString(), out lastValue) && derivand != null && derivand != DBNull.Value)
outValues[mySchema.columnInfo.Length - 1] = (Convert.ToDouble(derivand) - lastValue) * timeScale;
else
outValues[mySchema.columnInfo.Length - 1] = 0.0;
return new BlueRow(mySchema, outValues);
}
protected IBlueTableSchema myBuildOutputSchema(IBlueTableSchema inSchema)
{
ColumnInfo[] cols = new ColumnInfo[inSchema.columnInfo.Length + 1];
inSchema.columnInfo.CopyTo(cols, 0);
cols[cols.Length - 1] = new ColumnInfo(myOutputColumn, cols.Length - 1, typeof(double));
return new BlueTableSchema("derviative of " + inSchema.tableName, cols);
}
protected void myStoreNewPacketInfo(DataPacket dp)
{
myPreviousValues = new Dictionary<string, double>();
myLastPacketArrival = DateTime.Now;
foreach (IBlueRow row in dp.newRows)
{
object derivand = row[myDerivandColumn];
if (derivand != null && derivand != DBNull.Value)
myPreviousValues[row[myKeyColumn].ToString()] = Convert.ToDouble(derivand);
}
}
}
}
@@ -0,0 +1,214 @@
using System;
using System.Collections;
using System.Collections.Generic;
using mbts;
namespace BCG
{
[DataStreamUserRespresentation("diff")]
public class DiffStream : ViewStream
{
ViewStream myLStream, myRStream;
DataPacket myLastR = null, myLastL = null;
BlueTable myLastFired = null;
double myThreshold = .00005;
string[] myColumnsToMatch;
public DiffStream(ViewStream v1, ViewStream v2) : this(null, v1, v2, "id") { }
public DiffStream(ViewStream v1, ViewStream v2, params string[] ColumnsToMatch) : this(null, v1, v2, ColumnsToMatch) { }
public DiffStream(ViewStream v1, ViewStream v2, double thresh, params string[] ColumnsToMatch) :
this(null, v1, v2, thresh, ColumnsToMatch) { }
public DiffStream(ViewStreamDatabase db, ViewStream v1, ViewStream v2, double thresh, params string[] columnsToMatch)
{
myThreshold = thresh;
myLStream = v1;
myRStream = v2;
myColumnsToMatch = columnsToMatch;
}
public DiffStream(ViewStreamDatabase db, ViewStream v1, ViewStream v2, params string[] columnsToMatch)
: this(db,v1,v2,.00005,columnsToMatch)
{
}
protected override void myOnFirstSubscriber()
{
myLStream.onChange += myLChange;
myRStream.onChange += myRChange;
}
protected override void myOnLastSubscriber()
{
myLStream.onChange -= myLChange;
myRStream.onChange -= myRChange;
}
struct ListComparer : IEqualityComparer<List<object>>
{
public bool Equals(List<object> x, List<object> y)
{
if (x.Count != y.Count)
return false;
for (int i = 0; i < x.Count; ++i)
if (!x[i].Equals(y[i]))
return false;
return true;
}
public int GetHashCode(List<object> obj)
{
int ret = 0;
for(int i = 0; i < obj.Count; ++i)
ret ^= obj[i].GetHashCode();
return ret;
}
}
void myHandleCallbacks()
{
DataPacket packet = null;
if (myLastL == null || myLastR == null)
{
packet = myLastL == null ? myLastR : myLastL;
if (packet != null)
myFireEvent(packet);
myLastFired = new BlueTable(packet.newRows);
return;
}
BlueTable table = new BlueTable(myLastL.newRows.schema);
Dictionary<List<object>, Pair<BlueRow, BlueRow>> rowPairs = new Dictionary<List<object>, Pair<BlueRow, BlueRow>>(new ListComparer());
foreach(BlueRow row in myLastL.newRows)
{
List<object> hash = new List<object>();
foreach (string column in myColumnsToMatch)
{
try
{
hash.Add(row[column]);
}
catch (Exception)
{
}
}
rowPairs[hash] = new Pair<BlueRow, BlueRow>(row, null);
}
foreach (BlueRow row in myLastR.newRows)
{
List<object> hash = new List<object>();
foreach (string column in myColumnsToMatch)
{
try
{
hash.Add(row[column]);
}
catch (Exception) { }
}
Pair<BlueRow, BlueRow> pair;
rowPairs.TryGetValue(hash, out pair);
if (pair == null)
pair = new Pair<BlueRow, BlueRow>(null, row);
else
pair.second = row;
rowPairs[hash] = pair;
}
int id = 0;
foreach (KeyValuePair<List<object>, Pair<BlueRow, BlueRow>> hashpair in rowPairs)
{
Pair<BlueRow, BlueRow> pair = hashpair.Value;
if (pair.first == null || pair.second == null)
{
BlueRow row = pair.first == null ? pair.second : pair.first;
Dictionary<string, object> newRow = new Dictionary<string, object>();
foreach (ColumnInfo info in row.schema.columnInfo)
{
newRow[info.colName] = row[info.colName];
}
newRow["id"] = ++id;
table.addRow(new BlueRow(newRow));
}
else
{
bool allZeros = true;
Dictionary<string, object> newRow = new Dictionary<string, object>();
foreach (ColumnInfo info in pair.first.schema.columnInfo)
{
if (info.colType != typeof(double))
{
newRow[info.colName] = pair.first[info.colNo];
continue;
}
double l = (double)pair.first[info.colNo];
double r = (double)pair.second[info.colNo];
double value = Math.Abs(l - r);
if (value != 0)
{
double denom = Math.Max(Math.Abs(l), Math.Abs(r));
value /= denom;
if (value > myThreshold)
{
allZeros = false;
}
else value = 0;
}
newRow[info.colName] = value;
}
if (allZeros)
continue;
newRow["id"] = ++id;
table.addRow(new BlueRow(newRow));
}
}
myFireEvent(new DataPacket(table, table, myLastFired == null ? new BlueTable(table.schema) : myLastFired));
myLastFired = table;
}
void myRChange(object newValue)
{
myLastR = (DataPacket)newValue;
myHandleCallbacks();
}
void myLChange(object newValue)
{
myLastL = (DataPacket)newValue;
myHandleCallbacks();
}
}
}
@@ -0,0 +1,36 @@
// using System;
// using System.Collections;
// using BCG.Utilities;
// namespace BCG
// {
// public class DistinctRowEvaluator : GroupByEvaluator
// {
// private int myIdGenerator = 0;
// public DistinctRowEvaluator (string[] columnNames) : base (null, columnNames) {}
// public DistinctRowEvaluator(string colMapExpression, string[] columnNames)
// : base (colMapExpression, null, columnNames) {}
// public override IBlueRow evaluate (DataPacket packet)
// {
// myOutputTable = myOutputTable == null ? new GroupByOutputTable (packet.schema) : myOutputTable;
// string hashString = GroupByStream.getRepString (packet, myGroupByCols);
// if (packet.newRows.Count == 0)
// //if there are no rows for this group we remove the group from the output table
// myOutputTable.removeRow (hashString);
// else if (myOutputTable.getRow (hashString) == null)
// //a row is added for the first time (or first time after the removal of the group)
// myOutputTable.addRow (
// BlueDataUtility.getNewReplacedRow (
// BlueDataUtility.extractRow (packet.newRows, 0),
// myIdGenerator++, "id"),
// hashString);
// return myProject (myOutputTable.getRow (hashString));
// }
// }
// }
@@ -0,0 +1,23 @@
// using System;
// using System.Collections;
// namespace BCG
// {
// /// <summary>
// /// Provides a stream that with distinct rows with respect to the columns
// /// the user specifies in the argument
// /// </summary>
// [DataStreamUserRespresentation ("distinct")]
// public class DistinctRowStream : ViewStream
// {
// public DistinctRowStream (ViewStream stream, params string[] cols)
// {
// ArrayList groupByCols = new ArrayList ();
// foreach (string col in cols)
// foreach (string c in col.Split (' '))
// groupByCols.Add (c);
// mySetRealSource (new GroupByStream (stream,
// new DistinctRowEvaluator (groupByCols.ToArray (typeof(string)) as string[]), false));
// }
// }
// }
@@ -0,0 +1,45 @@
using System;
using System.IO;
namespace BCG
{
public class FileViewStream : ViewStream
{
private DataPacket myDp;
public FileViewStream (string dataFileName,
string schemaFileName)
: this (dataFileName, schemaFileName, Int32.MaxValue)
{}
public FileViewStream (string dataFileName,
string schemaFileName,
int bufferSize)
{
IBlueRowCollection newRows =
new FileRowCollection (dataFileName, schemaFileName, bufferSize);
myFireEvent (new DataPacket (newRows, new BlueTable(newRows), new BlueTable (newRows.schema)));
}
public FileViewStream (StreamReader dataReader,
StreamReader schemaReader)
: this (dataReader, schemaReader, Int32.MaxValue)
{}
public FileViewStream (StreamReader dataReader,
StreamReader schemaReader,
int bufferSize)
{
IBlueRowCollection newRows =
new FileRowCollection (dataReader, schemaReader, bufferSize);
myDp = new DataPacket (newRows, new BlueTable(newRows), new BlueTable (newRows.schema));
}
protected override void myOnFirstSubscriber()
{
if (myDp != null)
myFireEvent (myDp);
}
}
}
@@ -0,0 +1,40 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// using System.IO;
// namespace BCG
// {
// public class CaptureSnapshotStream : ViewStream
// {
// public CaptureSnapshotStream(string basePath,ViewStream sourceStream)
// {
// myBasePath = basePath;
// mySource = sourceStream;
// Directory.CreateDirectory(myBasePath);
// }
// protected override void myOnFirstSubscriber()
// {
// mySource.onChange += new ChangeDelegate(mySource_onChange);
// }
// protected override void myOnLastSubscriber()
// {
// mySource.onChange -= mySource_onChange;
// }
// void mySource_onChange(object newValue)
// {
// DateTime now = DateTime.Now;
// new ViewStreamWaiter(new SaverStream(new BlueRowCollectionStaticStream(((DataPacket)newValue).newRows),
// Path.Combine(myBasePath, String.Format("{0}_{1}.ds", now.ToString("yyyyMMdd_HHmmss"),
// now.Millisecond)))).waitUntilArrived();
// myFireEvent(newValue);
// }
// private string myBasePath;
// private ViewStream mySource;
// }
// }
@@ -0,0 +1,49 @@
// using System;
// using System.Collections.Generic;
// using System.Text;
// using System.IO;
// using System.Runtime.Serialization.Formatters.Binary;
// namespace BCG
// {
// public class DumpLoaderStream : ViewStream, ISideEffectStream
// {
// //wtf
// //public class Exception : System.Exception
// //{public Exception(string msg) : base(msg) { }}
// public DumpLoaderStream(string fileName, int secondsBetweenPolls)
// {
// mySetRealSource(
// new PollStream(() => new LoaderStream(fileName).rows, secondsBetweenPolls,
// ViewStreamDatabase.instance));
// }
// public DumpLoaderStream(string fileName)
// {
// if (fileName == null)
// throw new LoaderStream.Exception("File name cannot be null");
// for (int i = 0; i < 5; i++)
// try
// {
// using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
// {
// IClientDeserializer deser = new ClientUniversalDeserializer();
// byte[] the_ops;
// Array the_rows;
// deser.deserialize(new Stream[] { fs }, out the_ops, out the_rows);
// mySetRealSource(new BlueRowCollectionStaticStream((IBlueRowCollection)the_rows.GetValue(0)));
// }
// break;
// }
// catch (IOException)
// {
// System.Threading.Thread.Sleep(50);
// }
// }
// }
// }
@@ -0,0 +1,46 @@
// using System;
// using System.Collections.Generic;
// using System.Text;
// using System.IO;
// using System.Runtime.Serialization.Formatters.Binary;
// namespace BCG
// {
// [DataStreamUserRespresentation("loader")]
// public class LoaderStream : ViewStream, ISideEffectStream
// {
// public class Exception : System.Exception
// {public Exception(string msg) : base(msg) { }}
// public LoaderStream(string fileName, int secondsBetweenPolls)
// {
// mySetRealSource(
// new PollStream(() => new LoaderStream(fileName).rows, secondsBetweenPolls,
// ViewStreamDatabase.instance));
// }
// public LoaderStream(string fileName)
// {
// if (fileName == null)
// throw new LoaderStream.Exception("File name cannot be null");
// for (int i = 0; i < 5; i++)
// try
// {
// using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
// {
// BinaryFormatter bf = new BinaryFormatter();
// BlueTable bt = (BlueTable)bf.Deserialize(fs);
// mySetRealSource(new BlueRowCollectionStaticStream(bt));
// }
// break;
// }
// catch (IOException)
// {
// System.Threading.Thread.Sleep(50);
// }
// }
// }
// }
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using BCG.Utilities.General;
using BCG.Utilities;
namespace BCG
{
public delegate void PlaybackStreamProgress(long readFar, long totalBytesRead);
public class PlaybackStream : ViewStream, IWorker
{
public PlaybackStream(string fileName) : this(fileName, 1.0) { }
private string myFileName;
private FileStream myFileReader;
private double myPlaybackSpeed;
private DateTime myPlaybackStart;
private DateTime myNextPacketTime;
private IClientDeserializer myDeserializer;
private ITableAccumulator myAccumulator;
private BlueTable myLastTableVersion;
public PlaybackStream(string fileName, double playbackSpeed)
{
myFileName = fileName;
myPlaybackSpeed = playbackSpeed;
}
protected override void myOnFirstSubscriber()
{ myPlaybackStart = DateTime.Now;
myNextPacketTime = DateTime.MinValue;
myFileReader = new FileStream(myFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
myReadNextPacketTime();
ViewStreamDatabase.instance.addWorker(this);
}
protected override void myOnLastSubscriber()
{
if (myFileReader != null)
myFileReader.Close();
ViewStreamDatabase.instance.removeWorker(this);
}
protected void myReadNextPacketTime()
{
if (myFileReader.Position == myFileReader.Length)
{
myNextPacketTime = DateTime.MaxValue;
myFileReader.Dispose();
if (onFileExhausted != null)
onFileExhausted();
}
else
{
double secondsElapsed = new BinaryReader(myFileReader).ReadDouble();
myNextPacketTime = myPlaybackStart + new TimeSpan(0, 0, 0, 0, (int)(1000 * secondsElapsed / myPlaybackSpeed));
if (onProgress != null)
onProgress(myFileReader.Position, myFileReader.Length);
}
}
public event PlaybackStreamProgress onProgress;
public event Action onFileExhausted;
#region IWorker Members
public void doWork()
{
if (myNextPacketTime <= DateTime.Now)
{
if (myDeserializer == null)
{
myDeserializer = new ClientUniversalDeserializer();
myAccumulator = new TableAccumulator(myFileName, null);
}
BinaryReader reader = new BinaryReader(myFileReader);
int numBytes = reader.ReadInt32();
byte[] thisData = reader.ReadBytes(numBytes);
byte[] ops;
Array resultRowCollections;
myDeserializer.deserialize(new Stream[] { new MemoryStream(thisData) }, out ops, out resultRowCollections);
//there should only be one op in there becuae we just read a single update.
// BlueEventLog.logAssert(ops.Length == 1,"Playback stream got " +ops.Length.ToString() + " op codes in one update, from stream file "+myFileName);
//there shoudl only be one set of collections becaue there was just a single op code
//(those two arrays are parallel)
// BlueEventLog.logAssert(resultRowCollections.Length == 1, "StreamOpCode was create, serializer should return exactly 1 set of rows");
if (ops[0] == (byte)StreamOpCode.create)
{
myLastTableVersion = new BlueTable((resultRowCollections.GetValue(0) as IBlueRowCollection[])[0]);
myFireEvent(new DataPacket(myLastTableVersion, new BlueTable(myLastTableVersion.schema), new BlueTable(myLastTableVersion.schema)));
}
else
{
// BlueEventLog.logAssert(ops[0] == (byte)StreamOpCode.multipleRemoveAdd, "Playback stream got unexpected open code " + ops[0].ToString() + " from file " + myFileName);
// BlueEventLog.logAssert(myLastTableVersion != null, "Playback stream for file "+myFileName + "got a non-create before a create");
IBlueRowCollection[] deletedAndAdded = resultRowCollections.GetValue(0) as IBlueRowCollection[];
BlueDataUtility.absorbChanges(myLastTableVersion, deletedAndAdded[0], deletedAndAdded[1]);
myFireEvent(new DataPacket(myLastTableVersion, deletedAndAdded[1], deletedAndAdded[0]));
}
myReadNextPacketTime();
}
}
#endregion
}
}
@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace BCG
{
public class RecorderStream : ViewStream
{
private ViewStream mySource;
private DateTime myStartTime;
private FileStream myOutFile;
private string myFileName;
private IBlueDataSerializer mySerializer;
public RecorderStream(ViewStream src, string recordFile)
{
mySource = src;
myFileName = recordFile;
myFileName = myFileName.Replace("%DATE%", DateTime.Now.ToString("yyyyMMdd_HHmmss"));
}
protected override void myOnFirstSubscriber()
{
myStartTime = DateTime.Now;
mySource.onChange += new ChangeDelegate(mySource_onChange);
myOutFile = new FileStream(myFileName, FileMode.OpenOrCreate);
}
protected override void myOnLastSubscriber()
{
mySource.onChange -= mySource_onChange;
myOutFile.Close();
}
void mySource_onChange(object newValue)
{
DataPacket dp = (DataPacket)newValue;
BlueTable toWrite = new BlueTable(dp.schema);
if (mySerializer == null)
{
mySerializer = new UniversalSerializer(dp.schema);
}
foreach (IBlueRow r in dp.newRows)
toWrite.addRow(r);
byte[] result;
if (myLastValue == null)
mySerializer.serialize(StreamOpCode.create, new IBlueRowCollection[] { dp.newRows }, out result);
else
mySerializer.serialize(StreamOpCode.multipleRemoveAdd, new IBlueRowCollection[] { dp.deletedRows, dp.addedRows }, out result);
BinaryWriter bw = new BinaryWriter(myOutFile);
//write down what time this happened
bw.Write((DateTime.Now - myStartTime).TotalSeconds);
bw.Write(result.Length);
bw.Write(result);
myOutFile.Flush();
myFireEvent(dp);
}
}
}
@@ -0,0 +1,64 @@
// using System;
// using System.Collections.Generic;
// using System.Text;
// using System.IO;
// using System.Runtime.Serialization.Formatters.Binary;
// namespace BCG
// {
// [DataStreamUserRespresentation("saver")]
// public class SaverStream : ViewStream, ISideEffectStream
// {
// private ViewStream myStream;
// private string myFileName;
// public class Exception : System.Exception
// {
// public Exception(string msg) : base(msg) { }
// }
// public SaverStream(ViewStream vs, string fileName)
// {
// if (fileName == null)
// throw new SaverStream.Exception("File name cannot be null");
// myStream = vs;
// myFileName = fileName;
// }
// protected override void myOnFirstSubscriber()
// { myStream.onChange += new ChangeDelegate(myHandleChanges); }
// void myHandleChanges(object newValue)
// {
// DataPacket dp = newValue as DataPacket;
// mySave(dp);
// myFireEvent(newValue);
// }
// protected override void myOnLastSubscriber()
// { myStream.onChange -= new ChangeDelegate(myHandleChanges); }
// protected void mySave(DataPacket dp)
// {
// for (int i = 0; i < 5 ; i++)
// try
// {
// using (FileStream fs = new FileStream(myFileName, FileMode.Create, FileAccess.Write))
// {
// BinaryFormatter bf = new BinaryFormatter();
// BlueTable t = new BlueTable(dp.schema);
// foreach (IBlueRow r in dp.newRows) // to guarantee table is serializable
// t.addRow(new BlueRow(r));
// bf.Serialize(fs, t);
// }
// break;
// }
// catch (IOException)
// {
// System.Threading.Thread.Sleep(5);
// }
// }
// }
// }
@@ -0,0 +1,15 @@
using System;
namespace BCG
{
public class BinaryFilter : IStreamFilter
{
public BinaryFilter(bool filterValue)
{pass = filterValue;}
public bool filter (IBlueRow dr)
{return pass;}
bool pass = true;
}
}
@@ -0,0 +1,18 @@
// using System;
// using System.Collections;
// using BCG.Utilities;
// namespace BCG
// {
// public class BooleanExpressionFilter : IStreamFilter
// {
// public BooleanExpressionFilter(string exp)
// {myInterpreter = new BooleanExpressionsInterpreter(exp);}
// public bool filter(IBlueRow dr)
// { return myInterpreter.eval(dr); }
// private BooleanExpressionsInterpreter myInterpreter;
// }
// }
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCG.Utilities.General;
namespace BCG
{
public class DateBasedFilter: IDynamicStreamFilter, IWorker
{
private ViewStreamDatabase myVSD;
private string myDateColumn;
private int myNDays;
private DateTime myReference;
private DateTime myTodaysDate;
public DateBasedFilter(string dateColumn, int nDays)
: this(dateColumn, nDays, ViewStreamDatabase.instance) { }
public DateBasedFilter(string dateColumn, int nDays, ViewStreamDatabase vsd)
{
myDateColumn = dateColumn;
myNDays = nDays;
myVSD = vsd;
myVSD.addWorker(this);
myTodaysDate = DateTime.Today;
myReference = myTodaysDate.AddDays(-1 * myNDays);
}
public event FilterChangeDelegate onFilterChange;
public bool filter(IBlueRow r)
{
if (DBNull.Value.Equals(r[myDateColumn]))
{
//return false;
return true; //it can be considered as our assumption whenever datecolumn is db null we return true
}
DateTime t = (DateTime)r[myDateColumn];
bool returnVallue = t < myReference ? false : true;
return returnVallue;
}
public void doWork()
{
if (DateTime.Now >= myTodaysDate.AddDays(1))
{
myTodaysDate = DateTime.Today;
myReference = myTodaysDate.AddDays(-1 * myNDays);
onFilterChange();
}
}
}
}
@@ -0,0 +1,15 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// namespace BCG
// {
// public class DateBasedFilterStream: ViewStream
// {
// public DateBasedFilterStream(ViewStream vs, string dateColName, int pastTodayDays)
// {
// mySetRealSource(new FilterStream(vs, new DateBasedFilter(dateColName, pastTodayDays)));
// }
// }
// }
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCG.Utilities.General;
namespace BCG
{
public class DayRollingFilter : IDynamicStreamFilter, IWorker
{
private int myNPastTodayDays;
private string myDateColName;
private DateTime myLastCheckedTime = DateTime.Now;
/// <summary>
/// filters based on how 'old' the date in the dateCol are.
/// </summary>
/// <param name="vsd"></param>
/// <param name="dateColName">specifies the colName from which the date is retrieved</param>
/// <param name="pastTodayDays">rows that removed from today by 'pastTodayDays' will be filtered</param>
public DayRollingFilter(ViewStreamDatabase vsd, string dateColName, int pastTodayDays)
{
myNPastTodayDays = pastTodayDays;
myDateColName = dateColName;
vsd.addWorker(this);
}
#region IDynamicStreamFilter Members
public event FilterChangeDelegate onFilterChange;
#endregion
#region IStreamFilter Members
public bool filter(IBlueRow r)
{
DateTime rowDate = DBNull.Value.Equals (r[myDateColName]) ? DateTime.Now.Date : ((DateTime)r[myDateColName]).Date;
DateTime today = DateTime.Now.Date;
return rowDate > today ? true : !(today.Subtract(rowDate).Days >= myNPastTodayDays);
}
#endregion
#region IWorker Members
public void doWork()
{
if (DateTime.Now.Date != myLastCheckedTime.Date)
{
myLastCheckedTime = DateTime.Now;
onFilterChange();
}
}
#endregion
}
}
@@ -0,0 +1,15 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// namespace BCG
// {
// public class DayRollingStream : ViewStream
// {
// public DayRollingStream(ViewStream vs, string dateColName, int pastTodayDays)
// {
// mySetRealSource(new FilterStream(vs, new DayRollingFilter(ViewStreamDatabase.instance, dateColName, pastTodayDays)));
// }
// }
// }
@@ -0,0 +1,306 @@
// using BCG;
// using System;
// using System.Data;
// using System.Collections;
// using BCG.Utilities;
// using System.Text.RegularExpressions;
// using mbts;
// namespace BCG.StreamWorld.Addition
// {
// [DataStreamUserRespresentation (false)]
// public class FilterStream : ViewStream
// {
// private ViewStream myBaseStream;
// private BlueTable myBaseTable, myStateTable;
// private IStreamFilter myFilter;
// public FilterStream(ViewStream vs)
// : this(vs, "1=1")
// { }
// public FilterStream(ViewStream vs, string filterExp)
// : this(vs, new BooleanExpressionFilter(filterExp))
// { }
// public FilterStream(ViewStream vs, IStreamFilter filter)
// {
// myBaseStream = vs;
// myFilter = filter;
// if (filter is IDynamicStreamFilter)
// (filter as IDynamicStreamFilter).onFilterChange += new FilterChangeDelegate(myHandleFilterChange);
// }
// protected override void myOnFirstSubscriber()
// {
// myBaseStream.onChange += new ChangeDelegate(myHandleChanges);
// }
// protected override void myOnLastSubscriber()
// {
// myBaseStream.onChange -= new ChangeDelegate(myHandleChanges);
// myBaseTable.clear();
// myStateTable.clear();
// }
// private void myHandleChanges(object newValue)
// {
// DataPacket dp = newValue as DataPacket;
// if (myStateTable == null)
// {
// BlueEventLog.logAssert(myBaseTable == null);
// myStateTable = new BlueTable(dp.schema);
// myBaseTable = new BlueTable(dp.schema);
// }
// BlueTable dels = new BlueTable(dp.schema),
// adds = new BlueTable(dp.schema);
// foreach (IBlueRow r in dp.deletedRows)
// {
// myBaseTable.deleteRow(r);
// if (myStateTable.containsID((int)r["id"]))
// {
// dels.addRow(r);
// myStateTable.deleteRow(r);
// }
// }
// foreach (IBlueRow r in dp.addedRows)
// {
// myBaseTable.addRow(r);
// if (myFilter.filter(r))
// {
// adds.addRow(r);
// myStateTable.addRow(r);
// }
// }
// if ((dels.Count > 0 || adds.Count > 0) || (myLastValue == null))
// myFireEvent(new DataPacket(myStateTable, adds, dels));
// }
// public IStreamFilter filter
// {
// set
// {
// myFilter = value;
// if (myBaseTable != null)
// {
// IBlueRowCollection oldState = new BlueTable(myStateTable);
// myStateTable.clear();
// foreach (IBlueRow r in myBaseTable)
// if (myFilter.filter(r))
// myStateTable.addRow(r);
// IBlueRowCollection dels, adds;
// BlueDataUtility.computeDifferences(myStateTable, oldState, out dels, out adds);
// myFireEvent(new DataPacket(myStateTable, adds, dels));
// }
// }
// get { return myFilter; }
// }
// //public string filterString { set { filter = new BooleanExpressionFilter(value); } }
// private void myHandleFilterChange() { filter = myFilter; }
// }
// }
// namespace BCG
// {
// public class RegExpFilter : IStreamFilter
// {
// private Regex[] myRegExps;
// private string[] myCols;
// public RegExpFilter(string col, string regExp)
// : this (new string[]{col}, new string[] {regExp})
// {}
// public RegExpFilter (string[] cols, string[] regExps)
// {
// myCols = cols;
// myRegExps = new Regex[regExps.Length];
// for (int i = 0; i < regExps.Length; i++)
// myRegExps[i] = new Regex(regExps[i]);
// }
// #region IStreamFilter Members
// public bool filter(IBlueRow dr)
// {
// bool rv = true;
// for (int i = 0; i < myCols.Length; i++)
// {
// rv &= myRegExps[i].IsMatch(dr[myCols[i]] is DBNull ? "" : dr[myCols[i]].ToString());
// if (!rv)
// return rv;
// }
// return rv;
// }
// #endregion
// }
// public class FilterStream : ViewStream
// {
// private BlueTable myLastFiredRows;
// private IBlueRowCollection myLastReceivedRows;
// private IStreamFilter myFilter;
// private ViewStream myParentStream;
// private string myFilterString;
// private BCG.StreamWorld.Addition.FilterStream myFilterStream;
// private bool myUseNewFilter = DataStreamLoadFileConfig.instance.useNewFilter;
// private HighPerformanceTimer _timer = new HighPerformanceTimer();
// #region constructors
// public delegate bool OnFilter(IBlueRow r);
// private class OnFilterWrapper : IStreamFilter
// {
// public OnFilterWrapper(OnFilter f)
// { this.f = f; }
// public bool filter(IBlueRow dr)
// { return f(dr); }
// private OnFilter f;
// }
// public FilterStream(ViewStream vs, OnFilter f)
// : this(vs, new OnFilterWrapper(f))
// { }
// public FilterStream(ViewStream vs, IStreamFilter filter)
// {
// if (myUseNewFilter)
// {
// myFilterStream = new BCG.StreamWorld.Addition.FilterStream(vs, filter);
// mySetRealSource(myFilterStream);
// }
// else
// {
// myParentStream = vs;
// myFilter = filter;
// myFilterString = filter.ToString();
// if (filter is IDynamicStreamFilter)
// (filter as IDynamicStreamFilter).onFilterChange += new FilterChangeDelegate(myHandleFilterChange);
// }
// }
// public FilterStream(ViewStream vs, string filterExpression)
// : this(vs, new BooleanExpressionFilter(filterExpression))
// {
// myFilterString = filterExpression;
// }
// public FilterStream(ViewStream vs, string col, string regExp)
// : this(vs, new RegExpFilter(col, regExp))
// {
// myFilterString = col + " , " + regExp;
// }
// public FilterStream(ViewStream vs)
// : this(vs, new BinaryFilter(true))
// {
// myFilterString = true.ToString();
// }
// #endregion
// #region overridden methods
// protected override void myOnFirstSubscriber()
// { myParentStream.onChange += new ChangeDelegate(myHandleCallbacks); }
// protected override void myOnLastSubscriber()
// {
// myLastFiredRows = null;
// myParentStream.onChange -= new ChangeDelegate(myHandleCallbacks);
// }
// protected override void myFireEvent(object o)
// {
// DataPacket dp = o as DataPacket;
// if (myLastValue == null || dp.addedRows.Count + dp.deletedRows.Count > 0)
// base.myFireEvent(o);
// }
// #endregion
// private void myHandleCallbacks(object newValue)
// {
// _timer.start();
// DataPacket retVal;
// DataPacket arrivedPacket = newValue as DataPacket;
// myLastReceivedRows = arrivedPacket.newRows;
// if (myLastFiredRows != null)
// {
// retVal = new DataPacket(myLastFiredRows, new BlueTable(myLastFiredRows.schema),
// new BlueTable(myLastFiredRows.schema));
// foreach (IBlueRow r in arrivedPacket.deletedRows)
// if (myLastFiredRows.containsID((int)r["id"]))
// {
// myLastFiredRows.deleteRow(r);
// (retVal.deletedRows as BlueTable).addRow(r);
// }
// foreach (IBlueRow r in arrivedPacket.addedRows)
// if (myFilter.filter(r))
// {
// myLastFiredRows.addRow(r);
// (retVal.addedRows as BlueTable).addRow(r);
// }
// }
// else
// {
// myLastFiredRows = new BlueTable(arrivedPacket.schema);
// retVal = new DataPacket(myLastFiredRows, myLastFiredRows, new BlueTable(myLastFiredRows.schema));
// foreach (IBlueRow r in arrivedPacket.newRows)
// if (myFilter.filter(r))
// myLastFiredRows.addRow(r);
// }
// _timer.stop();
// myFireEvent(retVal);
// }
// public IStreamFilter filter
// {
// set
// {
// if (myUseNewFilter)
// {
// myFilterStream.filter = filter;
// }
// else
// {
// myFilter = value;
// if (numberOfSubscribers > 0)
// {
// if (myLastReceivedRows != null)
// {
// BlueTable nRows = new BlueTable(myLastReceivedRows.schema);
// foreach (IBlueRow r in myLastReceivedRows)
// if (myFilter.filter(r))
// nRows.addRow(r);
// IBlueRowCollection dRows = new BlueTable(nRows.schema),
// aRows = new BlueTable(nRows.schema);
// BlueDataUtility.computeDifferences(nRows, myLastFiredRows, out dRows, out aRows);
// myLastFiredRows = nRows;
// myFireEvent(new DataPacket(nRows, aRows, dRows));
// }
// }
// }
// }
// get
// {
// if (myUseNewFilter)
// return myFilterStream.filter;
// else
// return myFilter;
// }
// }
// //public string filterString { set { filter = new BooleanExpressionFilter(value); } }
// public override string ToString()
// {
// return GetType().ToString() + " " + myFilterString;
// }
// private void myHandleFilterChange()
// {
// filter = myFilter;
// }
// }
// }
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public delegate void FilterChangeDelegate();
public interface IDynamicStreamFilter : IStreamFilter
{
event FilterChangeDelegate onFilterChange;
}
}
@@ -0,0 +1,16 @@
using System;
using System.Data;
namespace BCG
{
/// <summary>
/// Exposes the function, filter(DataTable) that decides whether a row passes some
/// filter criteria or not. This interface is passed as an argument to the FilterStream
/// as the filtering criteria
///
/// </summary>
public interface IStreamFilter
{
bool filter (IBlueRow dr);
}
}
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCG.Utilities.General;
namespace BCG
{
public class SlidingWindowFilter: IDynamicStreamFilter, IWorker
{
private ViewStreamDatabase myVSD;
private string myDateColumn;
private int myNSecs;
private DateTime myReference;
private DateTime myCurrentTime;
private TimeSpan mySpan = new TimeSpan(0, 0, 0, 0, 500);
private DateTime myLastTimeFilteredApplied;
public SlidingWindowFilter(string dateColumn, int nSecs)
: this(dateColumn, nSecs, ViewStreamDatabase.instance) { }
public SlidingWindowFilter(string dateColumn, int nSecs, ViewStreamDatabase vsd)
{
myDateColumn = dateColumn;
myNSecs = nSecs;
myVSD = vsd;
myVSD.addWorker(this);
myCurrentTime = DateTime.Now;
myReference = myCurrentTime.AddSeconds(-1 * myNSecs);
}
public event FilterChangeDelegate onFilterChange;
public bool filter(IBlueRow r)
{
if (DBNull.Value.Equals(r[myDateColumn]))
{
//it can be considered as our assumption whenever datecolumn is db null we return true
return true; //dont use this for volparamsched use true
}
DateTime t = (DateTime)r[myDateColumn];
bool returnVallue = t < myReference ? false : true;
return returnVallue;
}
public void doWork()
{
if (DateTime.Now - myLastTimeFilteredApplied > mySpan)
{
myCurrentTime = DateTime.Now;
myReference = myCurrentTime.AddSeconds(-1 * myNSecs);
myLastTimeFilteredApplied = DateTime.Now;
onFilterChange();
}
}
}
}
@@ -0,0 +1,16 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// namespace BCG
// {
// public class SlidingWindowFilterStream: ViewStream
// {
// //use this with caution ask Vamsee
// public SlidingWindowFilterStream(ViewStream vs, string dateColName, int secs)
// {
// mySetRealSource(new FilterStream(vs, new SlidingWindowFilter(dateColName, secs)));
// }
// }
// }
@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCG.Utilities.General;
namespace BCG
{
public class TimeBasedFilter : IDynamicStreamFilter, IWorker, IDisposable
{
#region constructors
public TimeBasedFilter(string rowTimeColumnName, TimeSpan rowTimeToLive)
: this (ViewStreamDatabase.instance, rowTimeColumnName, rowTimeToLive, new TimeSpan(0, 1, 0) /* 1 minute */)
{
}
public TimeBasedFilter(string rowTimeColumnName, TimeSpan rowTimeToLive, TimeSpan filterFrequency)
: this (ViewStreamDatabase.instance, rowTimeColumnName, rowTimeToLive, filterFrequency)
{
}
public TimeBasedFilter(ViewStreamDatabase vsd, string rowTimeColumnName, TimeSpan rowTimeToLive)
: this (vsd, rowTimeColumnName, rowTimeToLive, new TimeSpan(0, 1, 0) /* 1 minute */)
{
}
public TimeBasedFilter(ViewStreamDatabase vsd, string rowTimeColumnName, TimeSpan rowTimeToLive, TimeSpan filterFrequency)
{
myVsd = vsd;
myRowTimeColumnName = rowTimeColumnName;
myRowTimeToLive = rowTimeToLive;
myFilterFrequency = filterFrequency;
myNextFilter = DateTime.MinValue;
// add worker
myVsd.addWorker(this);
}
#endregion
public event FilterChangeDelegate onFilterChange;
#region IStreamFilter
public bool filter(IBlueRow row)
{
DateTime now = DateTime.Now;
DateTime timeStamp = (DateTime)row[myRowTimeColumnName];
if (now > timeStamp)
{
TimeSpan span = now - timeStamp;
if (span >= myRowTimeToLive)
{
return (false);
}
}
return (true);
}
#endregion
#region IWorker
public void doWork()
{
DateTime now = DateTime.Now;
if (now > myNextFilter)
{
// fire event
onFilterChange();
myNextFilter = now.Add(myFilterFrequency);
}
}
#endregion
#region IDisposable
public void Dispose()
{
// remove worker
myVsd.removeWorker(this);
}
#endregion
#region state
private ViewStreamDatabase myVsd;
private string myRowTimeColumnName;
private TimeSpan myRowTimeToLive;
private TimeSpan myFilterFrequency;
private DateTime myNextFilter;
#endregion
}
}
@@ -0,0 +1,65 @@
using System;
using System.Collections;
using BCG.Utilities;
namespace BCG
{
public class FreezeDataStream : DataStream
{
public FreezeDataStream(DataStream streamToFreeze)
: this (streamToFreeze, false)
{}
public FreezeDataStream(DataStream streamToFreeze, bool freezeNow)
{
myIsFrozen = freezeNow;
myStreamToFreeze = streamToFreeze;
myPendingChanges = new ArrayList();
}
public bool frozen
{
set
{
if (myIsFrozen != value)
{
myIsFrozen = value;
if (value) // not frozen to frozen
myPendingChanges.Clear();
else // frozen to unfrozen
foreach (object o in myPendingChanges)
myFireEvent(o);
}
}
get{return myIsFrozen;}
}
protected override void myOnFirstSubscriber ()
{myStreamToFreeze.onChange += new DataStream.ChangeDelegate (myCallBack);}
protected override void myOnLastSubscriber ()
{myStreamToFreeze.onChange -= new DataStream.ChangeDelegate (myCallBack);}
internal void myCallBack(object o)
{
if (!myIsFrozen)
myFireEvent(o);
else {
if (o is ICloneable)
o = (o as ICloneable).Clone();
myPendingChanges.Add(o);
}
}
internal ArrayList myPendingChanges;
internal DataStream myStreamToFreeze;
internal bool myIsFrozen;
public void myCallBackTest(object o)
{
myCallBack(o);
}
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections;
using BCG.Utilities;
namespace BCG
{
public class FreezeViewStream : ViewStream
{
public FreezeViewStream(ViewStream streamToFreeze)
: this (streamToFreeze, false)
{}
public FreezeViewStream (ViewStream viewToFreeze, bool isFrozen)
{
myFDS = new FreezeDataStream(viewToFreeze,isFrozen);
mySetRealSource(myFDS);
}
public bool frozen
{
set
{myFDS.frozen = value;}
get
{return myFDS.frozen ;}
}
internal FreezeDataStream myFDS;
}
}
@@ -0,0 +1,447 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCG.Utilities.General;
using FuzzyRowComparer = System.Func<BCG.IBlueRow, BCG.IBlueRow, double>;
using System.Diagnostics;
namespace BCG
{
/// <summary>
/// This Implements a fuzzy join over two streams across a time window. This works by keeping a buffer
/// specified of a few seconds. When a row expires from one buffer
/// (after timeMS) it is compared to all of the entries currently in the other buffer using the supplied
/// fuzzy compare function. The best (closest to 0) non-infinity match is chosen and the two rows are combined into one
/// and fired. Any rows that expire without a match are still fired but with no value in the other columns.
///
/// Requirements:
/// * Both streams have a date/time column for sorting and expiring from the match buffer
/// * FuzzyCompare must be implemented so that rows that match have a value close to 0.
///
/// 1/10/2011 - Changed the code to ensure that the right hand side is only matched once.
/// This was a fairly significant logical re-architecture and has caused some pollution (side-effects) in some of the matching and merging functions. :(
/// Probably need to go back and refactor some of the helper methods to make the code easier to read.
/// </summary>
public class FuzzyJoinOverTimeStream : ViewStream, IWorker
{
private const string NEW_TIME_COLUMN = "FuzzyJoinTimeColumn";
protected ViewStream myLeftSource;
protected ViewStream myRightSource;
protected ViewStreamDatabase myVsd;
protected List<IBlueRow> myLeftRows = new List<IBlueRow>();
protected List<IBlueRow> myRightRows = new List<IBlueRow>();
private Dictionary<IBlueRow, RowMatch> myBestMatch = new Dictionary<IBlueRow, RowMatch>();
private string myLeftTimeColumn;
private string myRightTimeColumn;
private IComparer<IBlueRow> myLeftCompare;
private IComparer<IBlueRow> myRightCompare;
protected FuzzyRowComparer myFuzzyCompare;
protected TimeSpan myTimeWindow;
protected IBlueTableSchema myLeftSchema;
protected IBlueTableSchema myRightSchema;
protected IBlueTableSchema myOutputSchema;
private int myID = 0;
protected TimeWindowTable myStateRows;
private DateTime myNextCull;
const long MinCullIntervalMS = 1000;
// #constructor
public FuzzyJoinOverTimeStream(ViewStream left, string leftTimeColumn, ViewStream right, string rightTimeColumn, int timeMS, FuzzyRowComparer fuzzyCompare, ViewStreamDatabase vsd)
{
this.myLeftSource = left;
this.myRightSource = right;
this.myLeftTimeColumn = leftTimeColumn;
this.myRightTimeColumn = rightTimeColumn;
this.myLeftCompare = new BlueRowComparer(true, leftTimeColumn, "id");
this.myRightCompare = new BlueRowComparer(true, rightTimeColumn, "id");
this.myNextCull = DateTime.Now.AddMilliseconds(MinCullIntervalMS);
this.myTimeWindow = TimeSpan.FromMilliseconds(timeMS);
this.myVsd = vsd;
this.myFuzzyCompare = fuzzyCompare;
}
public virtual IBlueTableSchema OutputSchema
{
get
{
if (this.myOutputSchema == null)
{
if (this.myLeftSchema != null && this.myRightSchema != null)
{
ColumnInfo[] leftColumns = this.myLeftSchema.columnInfo;
ColumnInfo[] rightColumns = this.myRightSchema.columnInfo;
ColumnInfo[] addColumns = new ColumnInfo[] { new ColumnInfo(NEW_TIME_COLUMN, 0, typeof(DateTime)) };
IEnumerable<ColumnInfo> newColumns = leftColumns.Concat(rightColumns).GroupBy(c => c.colName).Select(s => s.First());
newColumns = newColumns.Concat(addColumns);
// BlueTableSchema constructor assumes that each column has a valid non overlapping column number
ColumnInfo[] newColumnsWithIndex = new ColumnInfo[newColumns.Count()];
int x = 0;
foreach (ColumnInfo ci in newColumns)
{
newColumnsWithIndex[x] = new ColumnInfo(ci.colName, x, ci.colType);
x++;
}
this.myOutputSchema = new BlueTableSchema(newColumnsWithIndex, "FuzzyJoin");
}
}
return this.myOutputSchema;
}
}
protected override void myOnFirstSubscriber()
{
this.myLeftSource.onChange += new ChangeDelegate(myLeft_onChange);
this.myRightSource.onChange += new ChangeDelegate(myRight_onChange);
this.myVsd.addWorker(this);
}
protected override void myOnLastSubscriber()
{
this.myLeftSource.onChange -= new ChangeDelegate(myLeft_onChange);
this.myRightSource.onChange -= new ChangeDelegate(myRight_onChange);
this.myVsd.removeWorker(this);
}
void myRight_onChange(object newValue)
{
// Collect all right hand columns
DataPacket dp = (DataPacket)newValue;
AddNewRows(dp.addedRows, this.myRightRows, this.myRightCompare);
this.myRightSchema = dp.schema;
}
void myLeft_onChange(object newValue)
{
DataPacket dp = (DataPacket)newValue;
AddNewRows(dp.addedRows, this.myLeftRows, this.myLeftCompare);
this.myLeftSchema = dp.schema;
}
void AddNewRows(IBlueRowCollection rows, List<IBlueRow> list, IComparer<IBlueRow> compare)
{
// Rows tend to come in in reverse order since they were added as they arrived
// To avoid unnecessary memcpy in array resize add them to our collection backwards
IBlueRow[] rowsArray = new IBlueRow[rows.Count];
rows.CopyTo(rowsArray, 0);
for (int x = rowsArray.Length - 1; x >= 0; x--)
{
SortedInsert(rowsArray[x], list, compare);
}
}
private void SortedInsert(IBlueRow row, List<IBlueRow> list, IComparer<IBlueRow> compare)
{
int index = list.BinarySearch(row, compare);
if (index < 0)
{
list.Insert(~index, row);
}
}
private IBlueRow[] PruneExpiredRows(List<IBlueRow> list, string timeColumn, DateTime expiry)
{
// Linear search is fine here b/c we don't expect the data to be very large
int count;
for (count = 0; count < list.Count; count++)
{
if ((DateTime)list[count][timeColumn] > expiry)
{
// Stop when we find the first row that we can keep. Since this is sorted all others are also kept.
break;
}
}
IBlueRow[] expiredRows = new IBlueRow[count];
list.CopyTo(0, expiredRows, 0, count);
list.RemoveRange(0, count);
return expiredRows;
}
class RowMatch : IComparable<RowMatch>
{
public RowMatch(IBlueRow row, double fitness)
{
this.myRightRow = row;
this.myFitness = fitness;
}
public IBlueRow myRightRow { get; private set; }
public IBlueRow myLeftRow { get; set; }
public double myFitness { get; private set; }
public IBlueRow myMergedRow { get; set; }
#region IComparable<RowMatch> Members
public int CompareTo(RowMatch other)
{
return myFitness.CompareTo(other.myFitness);
}
#endregion
}
public void doWork()
{
DateTime now = DateTime.Now;
if (now < this.myNextCull) return;
this.myNextCull = now.AddMilliseconds(MinCullIntervalMS);
// Create a BlueTable for sending out. Determine schema
DateTime expirationCutoff = now.Subtract(this.myTimeWindow);
// If we haven't heard from one or both of the input streams then we can't formulate a valid output row
if (this.OutputSchema == null) return;
// Get the removed rows from left
IBlueRow[] leftExpired = PruneExpiredRows(this.myLeftRows, this.myLeftTimeColumn, expirationCutoff);
IEnumerable<RowMatch>[] rightMatches = new IEnumerable<RowMatch>[leftExpired.Length];
List<RowMatch> corrections = new List<RowMatch>();
/* Try to find the best match without making this an NP problem
* 1. Find a list of best matches for each expiring trade
* 2. Mark the right row with the 'best' match that was found for it
* 3. When we emit a trade only include the right hand side if we are the best match
* 4. If later a better match is found !! emit a remove row for the merged row and then a new row for the unmatched left hand side
*/
// Search for matches in right
for (int x = 0; x < leftExpired.Length; x++)
{
IBlueRow row = leftExpired[x];
var matches = FindMatches(row, this.myRightRows, corrections);
if (matches != null)
{
rightMatches[x] = matches;
}
}
// get the removed rows from right --
IBlueRow[] rightExpired = PruneExpiredRows(this.myRightRows, this.myRightTimeColumn, expirationCutoff.Subtract(this.myTimeWindow));
// If there's nothing to do go home early
// note: This test has to happen after searching for matches or myRightRows will not be complete
if (rightExpired.Length == 0 && leftExpired.Length == 0) return;
// Lazy initialize of myStateRows now that we know the full schema
if (this.myStateRows == null)
{
this.myStateRows = new TimeWindowTable(this.OutputSchema, (int)TimeSpan.FromHours(12).TotalMilliseconds, NEW_TIME_COLUMN);
}
BlueTable adds;
MergeExpiredRows(leftExpired, rightMatches, rightExpired, out adds);
// Add adds to state
foreach (IBlueRow row in adds)
{
this.myStateRows.addRow(row);
}
BlueTable dels = (BlueTable)this.myStateRows.moveWindow();
HandleCorrection(corrections, adds, dels);
// Fire event
this.myFireEvent(new DataPacket(this.myStateRows, adds, dels));
// remove matched flags for expired rows
foreach (IBlueRow row in rightExpired)
{
this.myBestMatch.Remove(row);
}
}
private void HandleCorrection(List<RowMatch> corrections, BlueTable adds, BlueTable dels)
{
// We already emitted correction.MergedRow so we need to redact that and
// then emit correction.left as an add since it is no longer matched
foreach (RowMatch correction in corrections.Distinct())
{
Debug.Assert(correction.myMergedRow != null);
this.myStateRows.RemoveRow(correction.myMergedRow);
adds.addRow(this.MergeRows(correction.myLeftRow, null));
dels.addRow(correction.myMergedRow);
}
}
private BlueTable MergeExpiredRows(IBlueRow[] leftExpired, IEnumerable<RowMatch>[] rightMatches, IBlueRow[] rightExpired, out BlueTable adds)
{
adds = new BlueTable(this.OutputSchema);
//
// Loop over both left and right expired rows and emit them in order.
// (If they're going to get shuffled on the wire anyway why bother?)
//
int l = 0;
int r = 0;
for (l = 0, r = 0; l < leftExpired.Length && r < rightExpired.Length; )
{
if ((DateTime)leftExpired[l][this.myLeftTimeColumn] <= (DateTime)rightExpired[r][this.myRightTimeColumn])
{
// Advance Left
IEnumerable<RowMatch> rm = rightMatches[l];
IBlueRow leftRow = leftExpired[l];
IBlueRow merged = MergeLeftWithBestRight(leftRow, rm);
// Increment and fire
l++;
adds.addRow(merged);
}
else
{
IBlueRow rightRow = rightExpired[r];
// If a match was found this row will already be emitted with it's left hand counterpart
if (!this.myBestMatch.ContainsKey(rightRow))
{
IBlueRow merged = this.MergeRows(null, rightRow);
adds.addRow(merged);
}
r++;
}
}
// handle remaining rows. Only one of the next two loops will execute
for (; l < leftExpired.Length; l++)
{
IBlueRow merged = this.MergeLeftWithBestRight(leftExpired[l], rightMatches[l]);
adds.addRow(merged);
}
for (; r < rightExpired.Length; r++)
{
if (!this.myBestMatch.ContainsKey(rightExpired[r]))
{
IBlueRow merged = this.MergeRows(null, rightExpired[r]);
adds.addRow(merged);
}
}
return adds;
}
private IBlueRow MergeLeftWithBestRight(IBlueRow leftRow, IEnumerable<RowMatch> rightMatches)
{
IBlueRow merged = null;
if (rightMatches != null)
{
foreach (RowMatch match in rightMatches)
{
RowMatch bestMatch = this.myBestMatch[match.myRightRow];
//if (match.myFitness == bestMatch.myFitness && bestMatch.myLeftRow == null)
if (match == bestMatch)
{
merged = this.MergeRows(leftRow, match.myRightRow);
// store these for later corrections
match.myMergedRow = merged;
match.myLeftRow = leftRow;
// Make sure that we're updating this.myBestMatch[match.myRightRow]
Debug.Assert(match == this.myBestMatch[match.myRightRow]);
break;
}
}
}
// If none of the matches was 'best' emit with empty right hand side
if (merged == null)
{
merged = this.MergeRows(leftRow, null);
}
return merged;
}
/// <summary>
/// Override this function to provide a custom row merge.
/// The overrided function must add a new column called FuzzyJoinOverTimeStream.NEW_TIME_COLUMN which will contain a timestamp for sorting.
/// </summary>
protected virtual IBlueRow MergeRows(IBlueRow left, IBlueRow right)
{
Dictionary<string, object> newRow = new Dictionary<string, object>();
if (left == null && right == null) throw new ArgumentException("oh come on.");
if (left != null)
{
foreach (string columnName in left.schema.columnNames)
{
if (columnName == "id") continue;
newRow[columnName] = left[columnName];
}
}
if (right != null)
{
foreach (string columnName in right.schema.columnNames)
{
if (columnName == "id") continue;
if (!newRow.ContainsKey(columnName))
{
newRow[columnName] = right[columnName];
}
}
}
newRow["id"] = this.myID++;
newRow[NEW_TIME_COLUMN] = (left != null) ? left[this.myLeftTimeColumn] : right[this.myRightTimeColumn];
return new BlueRow(this.OutputSchema, newRow);
}
private IEnumerable<RowMatch> FindMatches(IBlueRow row, List<IBlueRow> list, List<RowMatch> corrections)
{
List<RowMatch> matches = null;
// Search through all rows in list and compare with the fuzzy comparer
for (int x = 0; x < list.Count; x++)
{
IBlueRow match = list[x];
double fitness = Math.Abs(this.myFuzzyCompare(row, match));
if (!double.IsInfinity(fitness))
{
// Lazy allocate list - not having any matches will be fairly common
if (matches == null)
{
matches = new List<RowMatch>();
}
RowMatch currentMatch = new RowMatch(match, fitness);
int insertIndex = matches.BinarySearch(currentMatch);
matches.Insert(insertIndex >= 0 ? insertIndex : ~insertIndex, currentMatch);
// Mark the best match for this particular right hand match
RowMatch oldMatch;
if (this.myBestMatch.TryGetValue(match, out oldMatch))
{
if (currentMatch.myFitness < oldMatch.myFitness)
{
this.myBestMatch[match] = currentMatch;
if (oldMatch.myMergedRow != null)
{
// We already emitted oldMatch.MergedRow so we need to fix it
corrections.Add(oldMatch);
}
}
}
else
{
this.myBestMatch[match] = currentMatch;
}
}
}
return matches;
}
}
}
@@ -0,0 +1,42 @@
// using System;
// using System.Collections;
// namespace BCG
// {
// public class GridBindableViewStream : DataStream
// {
// private ViewStream myStream;
// private GridBindableBlueTable myList;
// public GridBindableViewStream (ViewStream stream)
// {
// myStream = stream;
// myStream.onChange += new ChangeDelegate(myHandleCallbacks);
// }
// private void myHandleCallbacks (object newValue)
// {
// DataPacket dp = newValue as DataPacket;
// if (myList != null)
// {
// foreach (IBlueRow r in dp.deletedRows)
// myList.Remove (r);
// foreach (IBlueRow r in dp.addedRows)
// myList.Add (r);
// }
// else
// {
// myList = myGetBindableCollection (dp.newRows);
// }
// myFireEvent (
// new DataPacket(myList,
// myGetBindableCollection (dp.addedRows),
// myGetBindableCollection (dp.deletedRows)));
// }
// private GridBindableBlueTable myGetBindableCollection (IBlueRowCollection col)
// {
// return new GridBindableBlueTable (col.schema, col);
// }
// }
// }
@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BCG
{
public class AverageGroupsStream : ViewStream
{
public AverageGroupsStream(ViewStream input, string colToAverage, string keyColumn)
{
myColToAverage = colToAverage;
myInput = input;
myKeyColumn = keyColumn;
}
private ViewStream myInput;
private string myColToAverage;
private BlueTableSchema mySchema;
private string myKeyColumn;
protected override void myOnFirstSubscriber()
{
myInput.onChange += new ChangeDelegate(myInput_onChange);
}
protected override void myOnLastSubscriber()
{
myInput.onChange -= myInput_onChange;
}
private void myInput_onChange(object newValue)
{
if (mySchema == null)
myBuildSchema(((DataPacket)newValue).schema);
IBlueRowCollection newRows = myEvaluate((DataPacket)newValue);
if (myLastValue == null)
myFireEvent(new DataPacket(newRows, newRows, new BlueTable(mySchema)));
else
{
IBlueRowCollection added, deleted;
BlueDataUtility.computeDifferences(newRows, ((DataPacket) myLastValue).newRows, out deleted, out added);
myFireEvent(new DataPacket(newRows, added, deleted));
}
}
private void myBuildSchema(IBlueTableSchema schema)
{
List<ColumnInfo> columns = new List<ColumnInfo>();
foreach (ColumnInfo ci in schema.columnInfo)
columns.Add(ci);
columns.Add(new ColumnInfo("average_"+myColToAverage, columns.Count, typeof(double)));
mySchema = new BlueTableSchema("average_of_" + schema.tableName, columns.ToArray());
}
private IBlueRowCollection myEvaluate(DataPacket packet)
{
IDictionary<string, double> colToRunningTotal = new Dictionary<string, double>();
IDictionary<string, int> colToCount = new Dictionary<string, int>();
IDictionary<string, IBlueRow> colToLastRow = new Dictionary<string, IBlueRow>();
foreach (IBlueRow r in packet.newRows)
{
double thisVal = Convert.ToDouble(r[myColToAverage]);
string keyVal = r[myKeyColumn].ToString();
if (!colToCount.ContainsKey(keyVal))
{
colToRunningTotal[keyVal] = thisVal;
colToCount[keyVal] = 1;
}
else
{
colToRunningTotal[keyVal] += thisVal;
colToCount[keyVal] += 1;
}
colToLastRow[keyVal] = r;
}
BlueTable result = new BlueTable(mySchema);
foreach (string key in colToCount.Keys)
{
object[] values = new object[mySchema.columnInfo.Length];
colToLastRow[key].CopyTo(values, 0);
values[values.Length - 1] = packet.newRows.Count > 0 ? colToRunningTotal[key] / packet.newRows.Count : 0.0;
result.addRow(new BlueRow(mySchema, values));
}
return result;
}
}
}
@@ -0,0 +1,82 @@
// using System;
// namespace BCG
// {
// /// <summary>
// /// Serves as an abtraction for some of the functionalities needed in implementations
// /// of IGroupByEvaluator
// /// </summary>
// public abstract class GroupByEvaluator : IGroupByEvaluator
// {
// protected string[] myGroupByCols;
// protected string myOutputColumn;
// protected GroupByOutputTable myOutputTable;
// protected string myColMapExpression;
// #region constructors
// public GroupByEvaluator (string outputCol, string[] groupByCols)
// {
// myOutputColumn = outputCol;
// myGroupByCols = groupByCols;
// }
// public GroupByEvaluator (string colMapExpression, string outputCol, string[] groupByCols)
// : this (outputCol, groupByCols) {myColMapExpression = colMapExpression;}
// #endregion
// #region IGroupByEvaluator methods
// public virtual string[] groupByColumns {get{return myGroupByCols;}}
// public virtual void clear ()
// {
// if ( myOutputTable != null )
// myOutputTable.clear ();
// }
// public virtual IBlueTableSchema getOutputSchema (IBlueTableSchema schema)
// {
// IBlueTableSchema retVal =
// myColMapExpression == null || myColMapExpression.Length < 1 ?
// schema :
// new ProjectHelper (schema, myColMapExpression, schema.tableName).schema;
// return retVal;
// }
// public abstract IBlueRow evaluate (DataPacket dp) ;
// #endregion
// #region Helper methods
// /// <summary>
// /// Projects the r, replacing the id of the returned rows with the id provided in the arg
// /// </summary>
// /// <param name="r"></param>
// /// <param name="id"></param>
// /// <returns></returns>
// protected IBlueRow myProject (IBlueRow r, int id)
// {
// return r == null ? null :
// myColMapExpression == null || myColMapExpression.Length < 1 ?
// BlueDataUtility.getNewReplacedRow (r, id, "id") :
// BlueDataUtility.getNewReplacedRow(myProjectRow (r, myColMapExpression),
// id, "id");
// }
// /// <summary>
// /// Projects the id, conserving the id
// /// </summary>
// /// <param name="r"></param>
// /// <returns></returns>
// protected IBlueRow myProject (IBlueRow r) {return myProject (r, r == null ? Int32.MinValue : (int)r["id"]);}
// #endregion
// private IBlueRow myProjectRow (IBlueRow r, string colMapExpression)
// {
// BlueTable auxTable = new BlueTable (r.schema);
// auxTable.addRow (r);
// BlueRowCollectionStaticStream staticStream = new BlueRowCollectionStaticStream (auxTable);
// ProjectStream projStream = new ProjectStream (staticStream, colMapExpression);
// return BlueDataUtility.extractRow (projStream.rows, 0);
// }
// }
// }
@@ -0,0 +1,77 @@
using System;
using BCG.Utilities;
using System.Collections;
namespace BCG
{
/// <summary>
/// GroupByOutputTable offers a conveniant way to manage a table, where theres one row per hash
/// </summary>
public class GroupByOutputTable : IBlueRowCollection
{
private IDictionary myDict = new Hashtable ();
private BlueTable myTable;
public GroupByOutputTable (IBlueTableSchema schema) {myTable = new BlueTable (schema);}
/// <summary>
/// Adds a row to table, with the hash string defined in the second arg. If theres a row
/// already with the hash code, its replaced (always one row per group)
/// </summary>
/// <param name="row"></param>
/// <param name="groupRepString"></param>
public void addRow (IBlueRow row, string groupRepString)
{
if (myDict[groupRepString] != null)
myTable.deleteRow ((IBlueRow)myDict[groupRepString]);
myTable.addRow (row);
myDict[groupRepString] = myTable[(int)row["id"]];
}
/// <summary>
/// Removes the row present in the hash slot defined by the arg
/// </summary>
/// <param name="groupRepString"></param>
public void removeRow (string groupRepString)
{
// BlueEventLog.logAssert (myDict[groupRepString] != null);
myTable.deleteRow ((IBlueRow)myDict[groupRepString]);
myDict.Remove (groupRepString);
}
/// <summary>
/// Removes all rows from the table, the schema is retained.
/// </summary>
public void clear ()
{
myTable.clear ();
myDict.Clear ();
}
public IBlueRow getRow (string groupRepString)
{
return myDict[groupRepString] == null ? null :
myDict[groupRepString] as IBlueRow;
}
#region IBlueRowCollection members
public IBlueRow this[int id] {get{return myTable[id];}}
public IBlueTableSchema schema {get{return myTable.schema;}}
public bool containsID (int id) {return myTable.containsID (id);}
#endregion
#region ICollection members
public int Count {get{return myTable.Count;}}
public bool IsSynchronized {get{return false;}}
public object SyncRoot {get{return this;}}
public void CopyTo (Array array, int index) {myTable.CopyTo (array, index);}
#endregion
#region IEnumerable members
public IEnumerator GetEnumerator() {return myTable.GetEnumerator ();}
#endregion
}
}
@@ -0,0 +1,261 @@
using System;
using System.Collections;
using BCG.Utilities;
using System.Collections.Generic;
using System.Linq;
namespace BCG
{
public class GroupByStream : MethodDrivenStream
{
private class MyFuncGroupByEvaluator : IGroupByEvaluator
{
private string[] _groupby_cols;
private Func<DataPacket, IBlueRow> _groupby_func;
public MyFuncGroupByEvaluator(IEnumerable<string> groupby_cols, Func<DataPacket, IBlueRow> groupby_func)
{
_groupby_cols = groupby_cols.ToArray();
_groupby_func = groupby_func;
}
public IBlueRow evaluate(DataPacket packet) { return _groupby_func(packet); }
public string[] groupByColumns { get { return _groupby_cols; } }
public void clear() { }
public IBlueTableSchema getOutputSchema(IBlueTableSchema schema) { return schema; }
}
/// <summary>
/// Serves as a quick way to access all rows belonging to the same group
/// </summary>
private bool myIdGuard = true;
private RowDictionaryTable myBookKeepingTable ;
private IGroupByEvaluator myGroupByEvaluator;
private IBlueTableSchema mySchema; //input schema, as output schema can differ (IGroupByEvaluator's
//can map a schema to another
private IBlueTableSchema myOutputSchema;
private int myIdGenerator = 0;
public GroupByStream(ViewStream stream, IEnumerable<string> groupby_cols, Func<DataPacket, IBlueRow> groupby_func)
: this(stream, new MyFuncGroupByEvaluator(groupby_cols, groupby_func))
{ }
public GroupByStream (ViewStream stream, IGroupByEvaluator groupByEvaluator)
: this (stream, groupByEvaluator, true)
{}
public GroupByStream (ViewStream stream, IGroupByEvaluator groupbyEvaluator, bool idGuard)
: base (stream)
{
myGroupByEvaluator = groupbyEvaluator;
myIdGuard = idGuard;
}
protected override void myHandleFirstCall ()
{
mySchema = myLastArrivedPacket.schema;
myOutputSchema = myGroupByEvaluator.getOutputSchema (mySchema);
myBookKeepingTable = new RowDictionaryTable (myLastArrivedPacket.newRows,
myGroupByEvaluator.groupByColumns);
GroupByOutputTable temp = new GroupByOutputTable (myOutputSchema);
foreach (IBlueRowCollection rowGroup in myBookKeepingTable.getGroups())
{
IBlueRow newRow = myEvaluate (new DataPacket (rowGroup,
rowGroup, new BlueTable (mySchema)));
if (newRow != null)
temp.addRow (newRow, myGetGroupString (rowGroup));
}
myLastFiredPacket = new DataPacket (temp, new BlueTable(temp), new BlueTable (temp.schema));
}
/// <summary>
/// Adding need not to anything as deletion already takes care
/// of addition
/// </summary>
protected override void myHandleIncrementalAdd() {}
/// <summary>
/// Both deletes and adds are handled here to make the intermediate results not
/// appear in the spitted fired DataPacket (note this is done only in GroupByStream
/// because of the nature of it)
/// </summary>
protected override void myHandleIncrementalDelete()
{
myFireSwitch = false;
RowDictionaryTable delGroups, addGroups;
//form groups for deleted and added rows
myInitIncrementalChangeData (out delGroups, out addGroups);
ArrayList handledAddGroups = new ArrayList ();
string groupRepString;
foreach (IBlueRowCollection delGroup in delGroups.getGroups ())
{
// BlueEventLog.logAssert (delGroup.Count > 0);
groupRepString = myGetGroupString (delGroup);
IBlueRowCollection addGroup = addGroups.getGroup (groupRepString) == null ?
new BlueTable (mySchema) : addGroups.getGroup (groupRepString);
handledAddGroups.Add (addGroup);
IBlueRowCollection aggGroup = myBookKeepingTable.getGroup (groupRepString) == null ?
new BlueTable (mySchema) : myBookKeepingTable.getGroup (groupRepString);
IBlueRow newRow = myEvaluate (new DataPacket (aggGroup, addGroup, delGroup));
myFireSwitch |= myMergeRow (newRow, groupRepString);
}
foreach (IBlueRowCollection addGroup in addGroups.getGroups ())
{
// BlueEventLog.logAssert (addGroup.Count > 0);
if (!handledAddGroups.Contains (addGroup))
{
//this is the case when there are rows added to a group and none
//have been removed, hence it 'escapes' from being dealt with in
//the loop above
groupRepString = myGetGroupString (addGroup);
IBlueRowCollection aggGroup = myBookKeepingTable.getGroup (groupRepString);
// BlueEventLog.logAssert (aggGroup != null && aggGroup.Count > 0);
IBlueRow newRow = myEvaluate (new DataPacket (aggGroup, addGroup,
new BlueTable (aggGroup.schema)));
myFireSwitch |= myMergeRow (newRow, groupRepString);
}
}
}
private bool myMergeRow (IBlueRow newRow, string groupRepString)
{
IBlueRow existingRow = ((GroupByOutputTable) myLastFiredPacket.newRows).getRow (groupRepString);
//BlueEventLog.logAssert (newRow != null || existingRow != null);
if (existingRow == null && newRow == null)
return false;
else if (existingRow != null && newRow != null && BlueDataUtility.computeRowEquality (existingRow, newRow))
return false;
else if (existingRow == null)
{
//row added for the first time
((GroupByOutputTable) myLastFiredPacket.newRows).addRow (newRow, groupRepString);
((BlueTable) myLastFiredPacket.addedRows).addRow (newRow);
return true;
}
else
{
((GroupByOutputTable) myLastFiredPacket.newRows).removeRow (groupRepString);
((BlueTable) myLastFiredPacket.deletedRows).addRow (existingRow);
if (newRow != null)
{
((GroupByOutputTable) myLastFiredPacket.newRows).addRow (newRow, groupRepString);
((BlueTable) myLastFiredPacket.addedRows).addRow (newRow);
}
return true;
}
}
/// <summary>
/// Divides the added and deletd rows of the input packet into groups, initializes the added and removed rows
/// of the output packet, andupdates the book keeping tables
/// </summary>
/// <param name="delGroups"></param>
/// <param name="addGroups"></param>
private void myInitIncrementalChangeData (out RowDictionaryTable delGroups, out RowDictionaryTable addGroups)
{
delGroups =
new RowDictionaryTable (myLastArrivedPacket.deletedRows, myGroupByEvaluator.groupByColumns);
addGroups =
new RowDictionaryTable (myLastArrivedPacket.addedRows, myGroupByEvaluator.groupByColumns);
foreach (IBlueRow deletedRow in myLastArrivedPacket.deletedRows)
myBookKeepingTable.removeRow (deletedRow);
foreach (IBlueRow addedRow in myLastArrivedPacket.addedRows)
myBookKeepingTable.addRow (addedRow);
myLastFiredPacket.addedRows = new BlueTable (myOutputSchema);
myLastFiredPacket.deletedRows = new BlueTable (myOutputSchema);
}
protected override void myOnTableClear ()
{
if (myBookKeepingTable.Count == 0)
return; //ie there arent any rows, so no need to optimize the 'cleansing' process
myLastFiredPacket.deletedRows = new BlueTable (myLastFiredPacket.newRows);
myLastFiredPacket.addedRows = new BlueTable (myLastFiredPacket.deletedRows.schema);
(myLastFiredPacket.newRows as GroupByOutputTable).clear ();
myBookKeepingTable.clear ();
myGroupByEvaluator.clear ();
}
private IBlueRow myEvaluate (DataPacket dp)
{
IBlueRow evalRow = myGroupByEvaluator.evaluate (dp);
return evalRow == null ? null :
myIdGuard ?
BlueDataUtility.getNewReplacedRow (evalRow, myIdGenerator++, "id") : evalRow;
}
private string myGetGroupString (IBlueRowCollection group)
{
return BlueDataUtility.rowToString(BlueDataUtility.extractRow (group, 0), myGroupByEvaluator.groupByColumns);
}
protected override void myOnLastSubscriber ()
{
//the packets are initialzed to null, so that if the subscription count goes to 0, and then this stream
//gets resubscribed, we start the process of building data again, and treat the callback as the first
//callback.
myInit ();
myStream.onChange -= new DataStream.ChangeDelegate (myChangeHandler);
}
protected override void myInit ()
{
base.myInit ();
if (myBookKeepingTable != null)
{
//to avoid calling init before the first callback
myBookKeepingTable.clear ();
myGroupByEvaluator.clear ();
}
}
public static string getRepString (DataPacket dp, string[] colNames)
{
return BlueDataUtility.rowToString (getRepRow (dp), colNames);
}
public static IBlueRow getRepRow (DataPacket dp)
{
if (dp.newRows.Count > 0)
return BlueDataUtility.extractRow (dp.newRows, 0);
else if (dp.addedRows.Count > 0)
return BlueDataUtility.extractRow (dp.addedRows, 0);
else if (dp.deletedRows.Count > 0)
return BlueDataUtility.extractRow (dp.deletedRows, 0);
// BlueEventLog.logAssert (false, "Illegal Data Packet");
return null;
}
/// <summary>
/// performs an add with the 2 arguments representing the last and new values and boolean indicating
/// an add or remove. If the
/// </summary>
/// <param name="lastValue"></param>
/// <param name="newValue"></param>
/// <param name="isAdd"></param>
/// <returns></returns>
public static object incrementalAdd (object lastValue, object newValue, bool isAdd)
{
if (lastValue == null || lastValue.Equals (DBNull.Value))
return newValue;
// BlueEventLog.logAssert (lastValue.GetType().Equals (typeof(Int32)) && newValue.GetType().Equals (typeof(Int32)) ||
// lastValue.GetType().Equals (typeof(Double)) && newValue.GetType().Equals (typeof(Double)) ||
// lastValue.GetType().Equals (typeof(Decimal)) && newValue.GetType().Equals (typeof(Decimal)));
Object retVal = null;
if (newValue.GetType().Equals (typeof(int)))
retVal = isAdd ? (int)lastValue + (int)newValue : (int)lastValue - (int)newValue;
else if (newValue.GetType().Equals (typeof(Double)))
retVal = isAdd ? (Double)lastValue + (Double)newValue : (Double)lastValue - (Double)newValue;
else if (lastValue.GetType().Equals (typeof(Decimal)))
retVal = isAdd ? (Decimal)lastValue + (Decimal)newValue : (Decimal)lastValue - (Decimal)newValue;
else{}
// BlueEventLog.logAssert (false, "Illegal type");
return retVal;
}
}
}
@@ -0,0 +1,36 @@
using System;
namespace BCG
{
/// <summary>
/// Used by the GroupByStream to evaluate representative rows for groups (ie IGroupByEvaluator will group
/// rows with same values for specified columns in one group, the same as a SQL GroupBy operation)
/// </summary>
public interface IGroupByEvaluator
{
/// <summary>
/// Crunches the group into one row which is the returned value. Here the DataPacket
/// represents a group, with the newRows being the final group (after the additions and
/// deletetion) and the added and deletedRows being the increments. If a group has
/// to be totally removed then a null should be returned
/// </summary>
IBlueRow evaluate (DataPacket packet);
/// <summary>
/// Returns the columns (belonging to the original schema) on which this IGroupByEvaluator
/// distinguishes groups
/// </summary>
string[] groupByColumns {get;}
/// <summary>
/// Clears the Evaluator structure. This is for optimization pusposes, where the reboot of the server
/// is treated as a "clear rows" operation rather than a "delete-all" operation
/// </summary>
void clear ();
/// <summary>
/// Returns the schema into which the this IGroupByEvaluator would map rows into
/// </summary>
IBlueTableSchema getOutputSchema (IBlueTableSchema schema);
}
}
@@ -0,0 +1,79 @@
// using System;
// using BCG.Utilities;
// namespace BCG
// {
// /// <summary>
// /// Abstracts the functionality used to GroupBy rows in an incremental fation,
// /// governed by the delegates passed in the argument
// /// </summary>
// public class IncrementalGroupByEvaluator : GroupByEvaluator
// {
// /// <summary>
// /// Delegate supposed to act incrementally and produce an output object given the last value
// /// of the data, new value and add/remove boolean. If its the first data, then null would be passed
// /// on as the last value. Also if the user wants the group to be removed than null should be returned
// /// </summary>
// public delegate object IncrementalComputeDelegate (object prevData, object newData, bool isAdd);
// private IncrementalGroupByEvaluator.IncrementalComputeDelegate myCompute;
// private int myOutputColIndex = -1, myIdColIndex = -1, myIdGenerator = 0;
// #region constructors
// public IncrementalGroupByEvaluator (IncrementalComputeDelegate compute, string outputCol, string[] groupByCols)
// : base (outputCol, groupByCols)
// {myCompute = compute;}
// public IncrementalGroupByEvaluator (IncrementalComputeDelegate compute, string colMapExpression,
// string outputCol, string[] groupByCols) : base (colMapExpression, outputCol, groupByCols)
// {myCompute = compute;}
// #endregion
// public override IBlueRow evaluate (DataPacket packet)
// {
// myCheckTableState (packet);//initialization, if required
// string hashString = GroupByStream.getRepString (packet, myGroupByCols);//hash of the group repsented by the packet
// foreach (IBlueRow delRow in packet.deletedRows)
// {
// IBlueRow existantRow = myOutputTable.getRow (hashString);
// BlueEventLog.logAssert (existantRow != null);//if rows are to be deleted, there ought to be a rep row for this group
// object newValue = myCompute (existantRow[myOutputColIndex], delRow[myOutputColIndex], false);
// myOutputTable.addRow (
// BlueDataUtility.getNewReplacedRow (
// existantRow,
// new object[]{myIdGenerator++, newValue}, new int[]{myIdColIndex, myOutputColIndex}),
// //BlueDataUtility.getNewReplacedRow (existantRow, newValue, myOutputColIndex),
// hashString);
// }
// foreach (IBlueRow addedRow in packet.addedRows)
// {
// IBlueRow existantRow = myOutputTable.getRow (hashString);
// object newValue = myCompute (existantRow == null ? null : existantRow[myOutputColIndex],
// addedRow[myOutputColIndex], true);
// myOutputTable.addRow (
// //BlueDataUtility.getNewReplacedRow (addedRow, newValue, myOutputColIndex), hashString);
// BlueDataUtility.getNewReplacedRow (
// addedRow,
// new object[]{myIdGenerator++, newValue}, new int[]{myIdColIndex, myOutputColIndex}),
// hashString);
// }
// IBlueRow res = myOutputTable.getRow (hashString);
// //ref to deleted group is kept in myOutputTable
// return res[myOutputColIndex] == null ? null : myProject(res);
// }
// /// <summary>
// /// Initalizes the state of the class, ie by evaluating the output Col Index and initialzing the table
// /// </summary>
// /// <param name="packet"></param>
// private void myCheckTableState (DataPacket packet)
// {
// if (myOutputTable == null)
// {
// myOutputTable = new GroupByOutputTable (packet.schema);
// myOutputColIndex = packet.schema [myOutputColumn].colNo;
// myIdColIndex = packet.schema["id"].colNo;
// }
// }
// }
// }
@@ -0,0 +1,47 @@
// using System;
// using System.Collections;
// using BCG.Utilities;
// namespace BCG
// {
// /// <summary>
// /// Computes the max for a given column
// /// </summary>
// public class MaxGroupByEvaluator : GroupByEvaluator
// {
// public MaxGroupByEvaluator (string outputCol, string[] groupByCols) : base (outputCol, groupByCols)
// {}
// public MaxGroupByEvaluator (string colMapEpression, string outputCol, string[] groupByCols)
// : base (colMapEpression, outputCol, groupByCols) {}
// public override IBlueRow evaluate (DataPacket dp)
// {
// myOutputTable = myOutputTable == null ? new GroupByOutputTable (dp.schema) :
// myOutputTable;
// string hashString = BlueDataUtility.rowToString (GroupByStream.getRepRow (dp), myGroupByCols);
// IBlueRow currMaxRow = myOutputTable.getRow (hashString);
// IBlueRow maxRow = BlueDataUtility.computeMaxRow (dp.deletedRows, myOutputColumn);
// if (maxRow != null)
// {
// BlueEventLog.logAssert (currMaxRow != null);
// BlueEventLog.logAssert (BlueDataUtility.compareRows (maxRow, currMaxRow, myOutputColumn) <= 0);
// if (BlueDataUtility.compareRows (maxRow, currMaxRow, myOutputColumn) == 0)
// {
// maxRow = BlueDataUtility.computeMaxRow (dp.newRows, myOutputColumn);
// if (maxRow == null)
// myOutputTable.removeRow (hashString);
// else
// myOutputTable.addRow (maxRow, hashString);
// }
// }
// maxRow = BlueDataUtility.computeMaxRow (dp.addedRows, myOutputColumn);
// // if the row was replaced in the above lines, then currMaxRow < maxRow, so the if below would never return a true,
// // otherwise if maxRow > currMaxRow then its replaced
// if (maxRow != null && (currMaxRow == null || BlueDataUtility.compareRows (maxRow, currMaxRow, myOutputColumn) > 0))
// myOutputTable.addRow (maxRow, hashString);
// return myProject (myOutputTable.getRow (hashString));
// }
// }
// }
@@ -0,0 +1,20 @@
// using System;
// namespace BCG
// {
// public class MaxStream : ViewStream
// {
// public MaxStream(ViewStream stream, string outputCol, string inputCols) : this(stream, outputCol, inputCols.Split(' '))
// {
// }
// public MaxStream (ViewStream stream, string outputCol, string[] inputCols)
// {
// mySetRealSource (new GroupByStream (stream,
// new MaxGroupByEvaluator (outputCol, inputCols)));
// }
// public MaxStream (ViewStream stream, string outputCol)
// : this (new AddColumnsStream (stream, "fakeCol=0"), outputCol, new string[]{"fakeCol"})
// {}
// }
// }
@@ -0,0 +1,93 @@
using System;
using System.Collections;
using BCG.Utilities;
using System.IO;
namespace BCG
{
/// <summary>
/// Some basic event handling functionality factorred out of any Stream whose behaviour
/// is driven by some interface passed on by the user
/// </summary>
public abstract class MethodDrivenStream : ViewStream
{
protected ViewStream myStream;
protected DataPacket myLastArrivedPacket;
protected DataPacket myLastFiredPacket;
protected bool myFireSwitch = true;
public MethodDrivenStream(ViewStream vs) {myStream = vs;}
/// <summary>
/// Calls the base class's "change handlers". Sets the fireSwitch to true, so if
/// the base class does not want to fire the packet, it should set the switch to false
/// </summary>
/// <param name="o"></param>
internal void myChangeHandler (object o)
{
myFireSwitch = true;
myLastArrivedPacket = (DataPacket)o;
if (myLastFiredPacket == null)
{
myHandleFirstCall ();
myFireEvent (myLastFiredPacket.Clone ());
return;
}
if (myLastArrivedPacket.newRows.Count == 0)
myOnTableClear ();
else
{
myHandleIncrementalDelete ();
myHandleIncrementalAdd ();
}
if (myFireSwitch)
myFireEvent (myLastFiredPacket.Clone());
}
/// <summary>
/// Used for Unit Testing since handler is interal
///
/// </summary>
/// <param name="o"></param>
public void myChangeHandlerTest(object o)
{
myChangeHandler(o);
}
/// <summary>
/// To handle the first call, the LastFiredPacket is supposed to be initialized and filled
/// with data.
/// </summary>
protected abstract void myHandleFirstCall ();
/// <summary>
/// Handle incremenetal adds, and myLastFiredPacket filled with the resulting data
/// </summary>
protected abstract void myHandleIncrementalAdd();
/// <summary>
/// Handle incremenetal deletes, and myLastFiredPacket filled with the resulting data
/// </summary>
protected abstract void myHandleIncrementalDelete();
protected virtual void myInit ()
{
myLastFiredPacket = null;
myLastArrivedPacket = null;
}
protected abstract void myOnTableClear ();
protected override void myOnFirstSubscriber()
{
myStream.onChange += new DataStream.ChangeDelegate (myChangeHandler);
}
protected override void myOnLastSubscriber ()
{
myStream.onChange -= new DataStream.ChangeDelegate (myChangeHandler);
}
}
}
@@ -0,0 +1,40 @@
// using System;
// using BCG.Utilities;
// namespace BCG
// {
// public class MinGroupByEvaluator : MaxGroupByEvaluator
// {
// public MinGroupByEvaluator (string outputCol, string[] groupByCols)
// : base (outputCol, groupByCols) {}
// public MinGroupByEvaluator (string colMapEpression, string outputCol, string[] groupByCols) :
// base (colMapEpression, outputCol, groupByCols) {}
// public override IBlueRow evaluate (DataPacket dp)
// {
// myOutputTable = myOutputTable == null ? new GroupByOutputTable (dp.schema) : myOutputTable;
// string stringRep = BlueDataUtility.rowToString (GroupByStream.getRepRow (dp), myGroupByCols);
// IBlueRow currMinRow = myOutputTable.getRow (stringRep);
// IBlueRow minRow = BlueDataUtility.computeMinRow (dp.deletedRows, myOutputColumn);
// if (minRow != null)
// {
// // BlueEventLog.logAssert (currMinRow != null);
// // BlueEventLog.logAssert (BlueDataUtility.compareRows (minRow, currMinRow, myOutputColumn) >= 0);
// if (BlueDataUtility.compareRows (minRow, currMinRow, myOutputColumn) == 0)
// {
// minRow = BlueDataUtility.computeMinRow (dp.newRows, myOutputColumn);
// if (minRow == null)
// myOutputTable.removeRow (stringRep);
// else
// myOutputTable.addRow (minRow, stringRep);
// }
// }
// minRow = BlueDataUtility.computeMinRow (dp.addedRows, myOutputColumn);
// if (minRow != null && (currMinRow == null || BlueDataUtility.compareRows (minRow, currMinRow, myOutputColumn) < 0))
// myOutputTable.addRow (minRow, stringRep);
// return myOutputTable.getRow (stringRep);
// }
// }
// }
@@ -0,0 +1,17 @@
// using System;
// namespace BCG
// {
// public class MinStream : ViewStream
// {
// public MinStream (ViewStream stream, string outputCol, string[] inputCol)
// {
// mySetRealSource (new GroupByStream (stream,
// new MinGroupByEvaluator (outputCol, inputCol)));
// }
// public MinStream (ViewStream stream, string outputCol)
// : this (new AddColumnsStream (stream, "fakeCol=0"), outputCol, new string[]{"fakeCol"})
// {}
// }
// }
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG
{
public interface INonIncGroupByEvaluator
{
IBlueRowCollection evaluate(IDictionary<int, List<IBlueRow>> grouped_rows);
string[] get_group_by_cols();
}
}
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts;
namespace BCG
{
public class NonIncGroupByStream : ViewStream
{
private ViewStream _main_stream;
private INonIncGroupByEvaluator _groupby_func;
private BlueRowHasher _row_hasher;
private string[] _groupby_cols;
private HighPerformanceTimer _timer = new HighPerformanceTimer();
private int _n_total_fires = 0, _n_expensive_fires = 0;
public NonIncGroupByStream(ViewStream main_stream, INonIncGroupByEvaluator groupby_func)
{
_main_stream = main_stream;
_groupby_func = groupby_func;
_groupby_cols = _groupby_func.get_group_by_cols();
_row_hasher = new BlueRowHasher(_groupby_cols.Length);
}
protected override void myOnFirstSubscriber() { _main_stream.onChange += _main_stream_onchange; }
protected override void myOnLastSubscriber() { _main_stream.onChange -= _main_stream_onchange; }
private void _main_stream_onchange(object nv)
{
DataPacket dp = nv as DataPacket;
///grouping together
_timer.start();
IDictionary<int, List<IBlueRow>> grouped_rows = BlueDataUtility.group_together (dp.newRows, _groupby_cols, ref _row_hasher);
_timer.stop();
// mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, String.Format("Time to group {0} rows into {1} groups = {2}", dp.newRows.Count, grouped_rows.Count, _timer.lastIntervalTime));
/// reducing
_timer.start();
IBlueRowCollection total_state = _groupby_func.evaluate(grouped_rows);
_timer.stop();
_n_total_fires++;
if (_timer.lastIntervalTime > 50)
{
_n_expensive_fires++;
// mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, String.Format("Time to evaluate {0} groups {1} , ratio {2}/{3}", grouped_rows.Count, _timer.lastIntervalTime, _n_expensive_fires, _n_total_fires));
}
myFireEvent(new DataPacket(total_state, total_state, myLastValue == null ? new BlueTable(total_state.schema) : (myLastValue as DataPacket).newRows));
}
}
}
@@ -0,0 +1,127 @@
using System;
using BCG.Utilities;
using System.Collections;
namespace BCG
{
/// <summary>
/// All rows with the same values for designated columns are stored in
/// the same IBlueRowCollection. Such a structure will be useful for operations
/// such as GroupBy, Union and finding distinct rows in a table
/// </summary>
public class RowDictionaryTable : IBlueRowCollection
{
protected IDictionary myRowCollections = new Hashtable ();
protected BlueTable myLinearCollection;
protected string[] myCols;
protected IBlueTableSchema mySchema;
protected RowDictionaryTable () {}
public RowDictionaryTable (IBlueRowCollection rows, params string[] cols)
: this (rows.schema, cols)
{
foreach (IBlueRow row in rows)
addRow (row);
}
public RowDictionaryTable (IBlueTableSchema schema, params string[] cols)
{
mySchema = schema;
myCols = cols;
foreach (string col in myCols)
{
if (mySchema[col] == null){}
// BlueEventLog.logAssert (false,"Unknown col " + col + " in " + mySchema.tableName);
}
myLinearCollection = new BlueTable (mySchema);
}
public virtual void addRow (IBlueRow row)
{
BlueTable rows = (BlueTable)getGroup (row);
if (rows == null)
{
//i.e we dont have any group for this row => we need to create a new group
rows = new BlueTable (mySchema);
myRowCollections [myRowToString (row)] = rows;
}
rows.addRow (row);
myLinearCollection.addRow (row);
}
public virtual void removeRow (IBlueRow row)
{
BlueTable rowGroup = (BlueTable)getGroup (row);
// BlueEventLog.logAssert (rowGroup != null && rowGroup.Count > 0);
rowGroup.deleteRow (row);
myLinearCollection.deleteRow (row);
if (rowGroup.Count == 0)
myRowCollections.Remove (myRowToString (row));
//we dont keep any groups with no rows, if row count goes to 0, we delete the group
//in its entirety
}
public void removeGroup (IBlueRow representativeRow)
{
IBlueRowCollection rowGroup = getGroup (representativeRow);
// BlueEventLog.logAssert (rowGroup != null && rowGroup.Count > 0);
foreach (IBlueRow row in rowGroup)
myLinearCollection.deleteRow (row);
myRowCollections.Remove (myRowToString (representativeRow));
}
public void clear ()
{
myLinearCollection.clear ();
myRowCollections.Clear ();
}
/// <summary>
/// Retuns a group to which the row belong. If theres no such group a null is returned
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
//public IBlueRowCollection getGroup (IBlueRow row) {return getGroup (
public IBlueRowCollection getGroup (IBlueRow r) {return getGroup (myRowToString (r));}
public ICollection getGroups () {return myRowCollections.Values;}
private bool myAreRowsEqual (IBlueRow r1, IBlueRow r2)
{
bool retVal = true;
foreach (string col in myCols)
retVal &= r1[col].Equals(r2[col]);
return retVal;
}
public IBlueRowCollection getGroup (string repString)
{
IBlueRowCollection retVal = myRowCollections[repString] != null ?
(IBlueRowCollection) myRowCollections[repString] : null;
return retVal;
}
private string myRowToString (IBlueRow r) {return BlueDataUtility.rowToString (r, myCols);}
#region IBlueRowCollection members
public IBlueRow this[int id] {get{return myLinearCollection[id];}}
public IBlueTableSchema schema {get{return mySchema;}}
public bool containsID (int id) {return myLinearCollection.containsID (id);}
#endregion
#region ICollection members
public int Count {get{return myLinearCollection.Count;}}
public bool IsSynchronized {get{return false;}}
public object SyncRoot {get{return this;}}
public void CopyTo (Array array, int index) {myLinearCollection.CopyTo (array, index);}
#endregion
#region IEnumerable members
public IEnumerator GetEnumerator() {return myLinearCollection.GetEnumerator ();}
#endregion
}
}
@@ -0,0 +1,94 @@
// using System;
// namespace BCG
// {
// /// <summary>
// /// Computes the sum for a given column
// /// </summary>
// public class SumGroupByEvaluator : GroupByEvaluator
// {
// public SumGroupByEvaluator (string outputCol, string[] groupByCols) : base (outputCol, groupByCols)
// {}
// public SumGroupByEvaluator (string colMapEpression, string outputCol, string[] groupByCols)
// : base (colMapEpression, outputCol, groupByCols) {}
// public override IBlueRow evaluate (DataPacket dp)
// {
// myOutputTable = myOutputTable == null ? new GroupByOutputTable (dp.schema) : myOutputTable;
// IBlueRow sumRow = BlueDataUtility.computeSum(dp.newRows, myOutputColumn);
// return sumRow;
// }
// }
// public class MultiColumnSumGroupByEvaluator : IGroupByEvaluator
// {
// private string[] myOutputCols, myGroupByCols;
// public MultiColumnSumGroupByEvaluator(string spaceSeperatedOutputCols, string spaceSeperatedGroupByCols)
// {
// myOutputCols = spaceSeperatedOutputCols.Split(' ');
// myGroupByCols = spaceSeperatedGroupByCols.Split(' ');
// }
// public MultiColumnSumGroupByEvaluator(string[] output_columns, string[] groupby_columns)
// {
// myOutputCols = output_columns;
// myGroupByCols = groupby_columns;
// }
// #region IGroupByEvaluator Members
// public IBlueRow evaluate(DataPacket packet) {return BlueDataUtility.computeSum(packet.newRows, myOutputCols);}
// public string[] groupByColumns { get { return myGroupByCols; } }
// public void clear() {/*stateless*/}
// public IBlueTableSchema getOutputSchema(IBlueTableSchema schema) {return schema;}
// #endregion
// }
// public class SumGroupByEvaluator<T> : GroupByEvaluator
// {
// public SumGroupByEvaluator(string outputCol, string[] groupByCols)
// : base(outputCol, groupByCols)
// { }
// public SumGroupByEvaluator(string colMapEpression, string outputCol, string[] groupByCols)
// : base(colMapEpression, outputCol, groupByCols) { }
// public override IBlueRow evaluate(DataPacket dp)
// {
// myOutputTable = myOutputTable == null ? new GroupByOutputTable(dp.schema) : myOutputTable;
// IBlueRow sumRow = BlueDataUtility.computeSum<T>(dp.newRows, myOutputColumn);
// return sumRow;
// }
// }
// public class MultiColumnSumGroupByEvaluator<T> : IGroupByEvaluator
// {
// private string[] myOutputCols, myGroupByCols;
// public MultiColumnSumGroupByEvaluator(string spaceSeperatedOutputCols, string spaceSeperatedGroupByCols)
// {
// myOutputCols = spaceSeperatedOutputCols.Split(' ');
// myGroupByCols = spaceSeperatedGroupByCols.Split(' ');
// }
// #region IGroupByEvaluator Members
// public IBlueRow evaluate(DataPacket packet) {return BlueDataUtility.computeSum<T>(packet.newRows, myOutputCols);}
// public string[] groupByColumns { get { return myGroupByCols; } }
// public void clear() {/*stateless*/}
// public IBlueTableSchema getOutputSchema(IBlueTableSchema schema) {return schema;}
// #endregion
// }
// }
@@ -0,0 +1,107 @@
// using System;
// using System.Collections.Generic;
// namespace BCG
// {
// public class NullMapper : IStreamMapper
// {
// private Dictionary<string, bool> _valid_cols = new Dictionary<string, bool>();
// public NullMapper(string[] valid_cols)
// {
// foreach (string c in valid_cols)
// _valid_cols[c] = true;
// _valid_cols["id"] = true;
// }
// public IBlueTableSchema getOutputSchema(IBlueTableSchema input_schema) { return input_schema; }
// public IBlueRow map(IBlueRow row)
// {
// MutableBlueRow out_row = new MutableBlueRow(row);
// foreach (string c in row.schema.columnNames)
// if (!_valid_cols.ContainsKey(c))
// out_row.setValue(c, DBNull.Value);
// return out_row;
// }
// }
// public class SumStream : ViewStream
// {
// public SumStream(ViewStream stream, string spaceSeparatedOutputCols, string spaceSeparatedGroupByCols)
// {
// string[] outputCols = spaceSeparatedOutputCols.Split(' ');
// string[] groupByCols = spaceSeparatedGroupByCols.Split(' ');
// mySetRealSource(new GroupByStream(stream,
// outputCols.Length == 1 ? new SumGroupByEvaluator(outputCols[0], groupByCols) as IGroupByEvaluator :
// new MultiColumnSumGroupByEvaluator(spaceSeparatedOutputCols, spaceSeparatedGroupByCols)));
// }
// public SumStream(ViewStream stream, string[] output_columns)
// {
// ViewStream rs = new AddColumnsStream(stream, "fake_col=0");
// rs = new SumStream(rs, output_columns, new string[] { "fake_col" }, false);
// rs = new ProjectStream(rs, "!fake_col");
// mySetRealSource(rs);
// }
// public SumStream(ViewStream stream, string space_seperated_output_columns, string space_seperated_groupby_columns, bool force_null_into_other_columns)
// {
// string[] output_columns = space_seperated_output_columns.Split(' ');
// string[] groupby_columns = String.IsNullOrEmpty (space_seperated_groupby_columns) ? new string[]{} : space_seperated_groupby_columns.Split (' ');
// mySetRealSource (new SumStream (stream, output_columns, groupby_columns, force_null_into_other_columns));
// }
// public SumStream(ViewStream stream, string[] output_columns, string[] groupby_columns, bool force_null_into_other_columns)
// {
// ViewStream rs = null;
// groupby_columns = groupby_columns ?? new string[] {};
// if (groupby_columns.Length == 0)
// {
// rs = new AddColumnsStream(stream, "fake_col=0");
// rs = new GroupByStream(rs, new MultiColumnSumGroupByEvaluator(output_columns, new string[] {"fake_col"}));
// rs = new ProjectStream(rs, "!fake_col");
// }
// else
// {
// rs = new GroupByStream(stream, new MultiColumnSumGroupByEvaluator(output_columns, groupby_columns));
// }
// if (force_null_into_other_columns)
// {
// List<string> valid_cols = new List<string>(output_columns);
// valid_cols.AddRange(groupby_columns);
// rs = new MapStream(rs, new NullMapper(valid_cols.ToArray()));
// }
// mySetRealSource(rs);
// }
// public SumStream (ViewStream stream, string outputCol)
// : this (new AddColumnsStream (stream, "fakeCol=0"), outputCol, "fakeCol")
// {
// }
// }
// public class IntSumStream : ViewStream
// {
// public IntSumStream (ViewStream stream, string spaceSeparatedOutputCols, string spaceSeparatedGroupByCols)
// {
// string[] outputCols = spaceSeparatedOutputCols.Split(' ');
// string[] groupByCols = spaceSeparatedGroupByCols.Split(' ');
// mySetRealSource(new GroupByStream(stream,
// outputCols.Length == 1 ? new SumGroupByEvaluator<int>(outputCols[0], groupByCols) as IGroupByEvaluator:
// new MultiColumnSumGroupByEvaluator<int>(spaceSeparatedOutputCols, spaceSeparatedGroupByCols)));
// }
// }
// public class SumStream<T> : ViewStream
// {
// public SumStream(ViewStream stream, string outputCol, string spaceSeparatedInputCols)
// {
// string[] inputCols = spaceSeparatedInputCols.Split(' ');
// mySetRealSource(new GroupByStream(stream,
// new SumGroupByEvaluator<T>(outputCol, inputCols)));
// }
// }
// }
@@ -0,0 +1,31 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// namespace BCG
// {
// public class FullJoinStream : ViewStream
// {
// private ViewStream myMainStream;
// public FullJoinStream(ViewStream v1, string joinCol1, string cmExp1,
// ViewStream v2, string joinCol2, string cmExp2, string empty_col)
// {
// myMainStream = new LeftJoinStream(v1, joinCol1, cmExp1, v2, joinCol2, cmExp2);
// ViewStream filtered = new LeftJoinStream(v2, joinCol2, cmExp2, v1, joinCol1, cmExp1);
// filtered = new FilterStream(filtered, String.Format("{0}=null", empty_col));
// myMainStream = new AppendStream(myMainStream, filtered);
// }
// protected override void myOnFirstSubscriber()
// {
// myMainStream.onChange += myHandleMainStreamChange;
// }
// private void myHandleMainStreamChange(object newData)
// {
// IBlueRowCollection result = (newData as DataPacket).newRows;
// myFireEvent(new DataPacket(result, result, myLastValue == null ? new BlueTable(result.schema) : (myLastValue as DataPacket).newRows));
// }
// }
// }
@@ -0,0 +1,35 @@
// using System;
// namespace BCG
// {
// [DataStreamUserRespresentation (false)]
// public class InternalJoinForeignStream : InternalJoinStream
// {
// public InternalJoinForeignStream (ViewStream vsLeft,
// string jcLeft,
// ViewStream vsRight,
// string jcRight)
// : base (vsLeft, jcLeft, vsRight, jcRight) {}
// public InternalJoinForeignStream (ViewStream vsLeft,
// string jcLeft,
// ViewStream vsRight) : this (vsLeft, jcLeft, vsRight, "id") {}
// protected override void myInitFiredPacket ()
// {
// myLastFiredPacket = new DataPacket ();
// myLastFiredPacket.newRows = new JoinForeignTable (mySchema);
// myLastFiredPacket.addedRows = new BlueTable (mySchema);
// myLastFiredPacket.deletedRows = new BlueTable (mySchema);
// }
// public override void onTableClear (bool isLeft)
// {
// //incase of natural join, left or right wont matter, the end result zeroes out
// myLastFiredPacket.deletedRows = myLastFiredPacket.newRows;
// myLastFiredPacket.newRows = new JoinForeignTable (mySchema);
// myLastFiredPacket.addedRows = new BlueTable (mySchema);
// }
// }
// }
@@ -0,0 +1,183 @@
// using System;
// using System.Collections;
// namespace BCG
// {
// /// <summary>
// /// Does all the computations required for performing the Joins. The JoinStream is a wrapper around
// /// InternalJoinStreaming taking caring of the column namings etc
// /// </summary>
// [DataStreamUserRespresentation (false)]
// public class InternalJoinStream : ViewStream
// {
// protected JoinOperand myLeftOperand, myRightOperand;
// protected int myLeftJoinColOrdinal, myRightJoinColOrdinal;
// protected ViewStream myLeftStream, myRightStream;
// protected JoinTableSchema mySchema;
// protected DataPacket myLastFiredPacket;
// protected bool myOnceFired = false;
// public IBlueTableSchema schema {get{return mySchema;}}
// public InternalJoinStream (ViewStream vsLeft, string jcLeft, ViewStream vsRight, string jcRight)
// {
// myLeftStream = vsLeft;
// myRightStream = vsRight;
// myLeftOperand = new JoinOperand (jcLeft, true);
// myRightOperand = new JoinOperand (jcRight, false);
// }
// protected override void myOnFirstSubscriber()
// {
// myLeftOperand.master = this;
// myRightOperand.master = this;
// myLeftStream.onChange += new DataStream.ChangeDelegate (myLeftOperand.changeHandler);
// myRightStream.onChange += new DataStream.ChangeDelegate (myRightOperand.changeHandler);
// }
// protected override void myOnLastSubscriber ()
// {
// myInit ();
// myLeftStream.onChange -= new DataStream.ChangeDelegate (myLeftOperand.changeHandler);
// myRightStream.onChange -= new DataStream.ChangeDelegate (myRightOperand.changeHandler);
// }
// public JoinOperand getOtherOperand (JoinOperand jo)
// {
// JoinOperand retVal = jo == myLeftOperand ? myRightOperand : myLeftOperand;
// return retVal;
// }
// public void startSession ()
// {
// if (myLastFiredPacket != null)
// {
// //reset add and deletes
// myLastFiredPacket.addedRows = new BlueTable (mySchema);
// myLastFiredPacket.deletedRows = new BlueTable (mySchema);
// return;
// }
// //first time case, need to initialize everything
// else if (myLeftOperand.hasReceivedData && myRightOperand.hasReceivedData)
// {
// myLeftJoinColOrdinal = myLeftOperand.joinColOridinal;
// myRightJoinColOrdinal = myRightOperand.joinColOridinal;
// mySchema = new JoinTableSchema (myLeftOperand.operandSchema, myLeftOperand.joinCol,
// myRightOperand.operandSchema, myRightOperand.joinCol);
// myInitFiredPacket ();
// }
// }
// protected virtual void myInitFiredPacket ()
// {
// myLastFiredPacket = new DataPacket ();
// myLastFiredPacket.newRows = new JoinTable (mySchema);
// myLastFiredPacket.addedRows = new BlueTable (mySchema);
// myLastFiredPacket.deletedRows = new BlueTable (mySchema);
// }
// public IBlueTableSchema getSchema (bool isLeft)
// {
// IBlueTableSchema retVal;
// retVal = isLeft ? myLeftOperand.operandSchema : myRightOperand.operandSchema;
// return retVal;
// }
// public void endSession ()
// {
// if (!myOnceFired)
// {
// myOnceFired = true;
// myFireEvent (myLastFiredPacket.Clone());
// }
// else if (myLastFiredPacket.addedRows.Count + myLastFiredPacket.deletedRows.Count != 0)
// myFireEvent (myLastFiredPacket.Clone());
// }
// protected virtual void myInit ()
// {
// myLeftOperand.init ();
// myRightOperand.init ();
// myLastFiredPacket = null;
// }
// public virtual void onTableClear (bool isLeft)
// {
// //incase of natural join, left or right wont matter, the end result zeroes out
// myLastFiredPacket.deletedRows = myLastFiredPacket.newRows;
// myLastFiredPacket.newRows = new JoinTable (mySchema);
// myLastFiredPacket.addedRows = new BlueTable (mySchema);
// }
// public virtual void deleteRows (IBlueRowCollection rows, bool isLeft)
// {
// JoinOperand thisOp, otherOp;
// int joinColOrdinal;
// myAssignAccordingly (out thisOp, out otherOp, out joinColOrdinal, isLeft);
// foreach (IBlueRow row in rows)
// {
// thisOp.deleteRow (row);
// if (otherOp.getMatchingRows (row[joinColOrdinal]).Count == 0)
// continue; //row does not participate in join
// ((JoinTable)(myLastFiredPacket.newRows)).deleteRow (isLeft, row, myLastFiredPacket);
// }
// }
// public virtual void addRows (IBlueRowCollection rows, bool isLeft)
// {
// JoinOperand thisOp, otherOp;
// int joinColOrdinal;
// myAssignAccordingly (out thisOp, out otherOp, out joinColOrdinal, isLeft);
// if (!isLeft)
// {
// thisOp = myRightOperand;
// otherOp = myLeftOperand;
// joinColOrdinal = myRightJoinColOrdinal;
// }
// foreach (IBlueRow row in rows)
// {
// thisOp.addRow (row);
// RowList matchedNodes = otherOp.getMatchingRows (row[joinColOrdinal]);
// if (matchedNodes.Count == 0)
// continue; //this row did not participate in the join
// if (isLeft)
// foreach (RowNode matchedNode in matchedNodes)
// ((JoinTable)myLastFiredPacket.newRows).addRow (row, matchedNode.row, myLastFiredPacket);
// else
// foreach (RowNode matchedNode in matchedNodes)
// ((JoinTable)myLastFiredPacket.newRows).addRow (matchedNode.row, row, myLastFiredPacket);
// }
// }
// private void myAssignAccordingly (out JoinOperand thisOp, out JoinOperand otherOp, out int joinColOrdinal, bool isLeft)
// {
// if (isLeft)
// {
// thisOp = myLeftOperand;
// otherOp = myRightOperand;
// joinColOrdinal = myLeftJoinColOrdinal;
// }
// else
// {
// thisOp = myRightOperand;
// otherOp = myLeftOperand;
// joinColOrdinal = myRightJoinColOrdinal;
// }
// }
// /**************************************TEST METHOD(S)*********************************************/
// /// <summary>
// /// Used for testing purposes only. This enables the test to work without a DataSource (PubServer,
// /// BaseServer etc), by directly calling the test method and passing data
// /// </summary>
// /// <param name="leftPacket"></param>
// /// <param name="rightPacket"></param>
// public void test (DataPacket dp, bool isLeft)
// {
// JoinOperand jo = isLeft ? myLeftOperand : myRightOperand;
// jo.changeHandler (dp);
// }
// /***********************************************************************************************/
// }
// }
@@ -0,0 +1,64 @@
// using System;
// using System.Collections;
// namespace BCG
// {
// /// <summary>
// /// Hashtable of DoubleyLinkedList tailored for the Join deletions
// /// </summary>
// internal class JoinDeletionIndex
// {
// IDictionary myIndex = new Hashtable ();
// private string myOpIdName ;
// private bool myIsLeft;
// /// <summary>
// /// </summary>
// /// <param name="opIdName">opIdName represents the name of the column corresponding to id of the operand table</param>
// /// <param name="isLeft">Indicator for left or right operand table</param>
// public JoinDeletionIndex(string opIdName, bool isLeft)
// {
// myOpIdName = opIdName;
// myIsLeft = isLeft;
// }
// /// <summary>
// /// Adds a joinRow to the hashtable; in addition the joinRow is made to point to the node added
// /// </summary>
// /// <param name="row">JoinRow to add</param>
// public void add (JoinRow row)
// {
// object o = row[myOpIdName];
// if (myIndex[o] == null)
// myIndex[o] = new RowList ();
// RowNode nodeAdded = ((RowList)myIndex[o]).add (row);
// if (myIsLeft)
// row.leftNode = nodeAdded;
// else
// row.rightNode = nodeAdded;
// }
// /// <summary>
// /// To remove a node, if node does not exist exception is thrown
// /// </summary>
// /// <param name="node"></param>
// public void remove (RowNode node) {((RowList)myIndex[node.row[myOpIdName]]).remove (node);}
// public RowList getMatchingRows (object key) {
// RowList retVal = (RowList)myIndex[key];
// if (retVal == null)
// return new RowList ();
// return retVal;
// }
// /// <summary>
// /// Empties the entry for the key provided
// /// </summary>
// /// <param name="obj"></param>
// public void removeAll (object obj) {myIndex.Remove(obj);}
// public void clear () {myIndex.Clear ();}
// }
// }
@@ -0,0 +1,59 @@
// using System;
// using System.Data;
// using System.Collections;
// using System.Text.RegularExpressions;
// using BCG.Utilities;
// using BCG.Utilities.General;
// namespace BCG
// {
// public class ForeignJoinStream : JoinStream
// {
// public ForeignJoinStream (ViewStream v1, string joinCol1, ColumnMap cm1,
// ViewStream v2, string joinCol2, ColumnMap cm2)
// : base (v1, joinCol1, cm1, v2, joinCol2, cm2)
// {}
// public ForeignJoinStream (ViewStream v1, string joinCol1, string cmExp1,
// ViewStream v2, string joinCol2, string cmExp2)
// : base (v1, joinCol1, cmExp1, v2, joinCol2, cmExp2)
// {}
// public ForeignJoinStream (ViewStream v1, string joinCol1, string cmExp1,
// ViewStream v2, string joinCol2)
// :
// this (v1,joinCol1, new ColumnMap(cmExp1), v2, joinCol2)
// {}
// public ForeignJoinStream (ViewStream v1, string joinCol1,
// ViewStream v2, string joinCol2, string cmExp2)
// :
// this (v1,joinCol1, v2, joinCol2, new ColumnMap(cmExp2))
// {}
// public ForeignJoinStream (ViewStream v1, string joinCol1, ViewStream v2, string joinCol2)
// : base (v1, joinCol1, v2, joinCol2)
// {}
// public ForeignJoinStream (ViewStream v1, string joinCol1, ColumnMap cm1, ViewStream v2, string joinCol2)
// : base (v1, joinCol1, cm1, v2, joinCol2)
// {}
// public ForeignJoinStream (ViewStream v1, string joinCol1, ViewStream v2, string joinCol2, ColumnMap cm2)
// : base (v1, joinCol1, v2, joinCol2, cm2)
// {}
// protected override InternalJoinStream myConstructInternalJoinStream (
// ViewStream vs1,
// string jc1,
// ViewStream vs2,
// string jc2)
// {
// return new InternalJoinForeignStream (vs1, jc1, vs2, jc2);
// }
// }
// }
@@ -0,0 +1,20 @@
// using System;
// using BCG.Utilities;
// namespace BCG
// {
// internal class JoinForeignTable : JoinTable
// {
// public JoinForeignTable (JoinTableSchema schema) : base (schema) {}
// public override void addRow (IBlueRow leftRow, IBlueRow rightRow, DataPacket dp)
// {
// JoinRow newRow = new JoinRow (leftRow, rightRow, mySchema);
// BlueEventLog.logAssert (myIdIndex[leftRow["id"]] == null);
// myIdIndex[leftRow["id"]] = newRow;
// ((BlueTable)(dp.addedRows)).addRow (newRow);
// myLeftIndex.add (newRow);
// myRightIndex.add (newRow);
// }
// }
// }
@@ -0,0 +1,211 @@
// using System;
// using System.Collections;
// using BCG.Utilities;
// using BCG.Evaluator.ColumnMapExpression;
// namespace BCG
// {
// /// <summary>
// /// JoinNameResolver is used to bring together the 2 naming processes, ie the one done ny Join to resolve
// /// clashes and the second, that the user does to rename columns
// /// </summary>
// public class JoinNameResolver
// {
// /// <summary>
// /// Internal class to represent a column (ie name) and its association, left or right
// /// </summary>
// internal class OriginalNameInfo
// {
// public bool isLeft;
// public string colName;
// public OriginalNameInfo (string colName, bool isLeft) {this.colName = colName; this.isLeft = isLeft;}
// public override int GetHashCode ()
// {
// string prependString = isLeft ? "left" : "right";
// return String.Concat (prependString, colName).GetHashCode ();
// }
// public override bool Equals (object obj) {return GetHashCode () == obj.GetHashCode ();}
// }
// private ArrayList myJoinNames;
// private JoinNameResolver.OriginalNameInfo[] myOriginalColInfo;
// private JoinTableSchema myJoinSchema;
// private IBlueTableSchema myLeftSchema, myRightSchema;
// private string myLeftColExpression, myRightColExpression;
// private string[] myUserRules, myResolvedNames;
// private IDictionary myFinalMap = new Hashtable ();
// public JoinNameResolver (JoinTableSchema joinSchema, IBlueTableSchema leftSchema, string leftColMapExpression,
// IBlueTableSchema rightSchema, string rightColMapExpression)
// {
// myJoinSchema = joinSchema;
// myLeftSchema = leftSchema;
// myRightSchema = rightSchema;
// myLeftColExpression = leftColMapExpression;
// myRightColExpression = rightColMapExpression;
// /*initialize the joinNames one-D structure. The id is removed as it does not
// * take part in the renaming process */
// myJoinNames = new ArrayList (joinSchema.columnNames);
// /*initialize the originalInfo one-D structure. Its an array of OriginalNameInfo, ie name and a bool indicating that
// * it belongs to the left or right table */
// myOriginalColInfo = new OriginalNameInfo [joinSchema.columnNames.Length - 1];
// myUserRules = new String[myOriginalColInfo.Length];
// myFormOriginalNameInfo (true);
// myFormOriginalNameInfo (false);
// myFormUserRules ();
// myFormResolvedNames ();
// myFormFinalMap ();
// }
// /// <summary>
// /// Forms the array representing the name as they appear in the JoinOperand.
// /// This is done so that its alligned with the myJoinNames
// /// </summary>
// /// <param name="isLeft">indicating whether its the left operand or the right</param>
// private void myFormOriginalNameInfo (bool isLeft)
// {
// IBlueTableSchema operandSchema = isLeft ? myLeftSchema : myRightSchema;
// foreach (string colName in operandSchema.columnNames)
// {
// string joinName = myJoinSchema.getRenamedName (colName, isLeft);
// //joinName is bound to be unique
// int index = myJoinNames.IndexOf (joinName);
// BlueEventLog.logAssert (index >= 0 && index < myOriginalColInfo.Length);
// myOriginalColInfo[index] = new OriginalNameInfo(colName, isLeft);
// }
// }
// static syntax myParser =
// new syntax();
// /// <summary>
// /// Creates the user mapping from the grammer and then actually call the methods that form the array of
// /// user defined names
// /// </summary>
// private void myFormUserRules ()
// {
// if (DataStreamLoadFileConfig.instance.useStaticParser)
// {
// lock (myParser)
// {
// myFormUserRules(true, (ColumnMapExpression)
// myParser.Parse(myLeftColExpression));
// myFormUserRules(false, (ColumnMapExpression)
// myParser.Parse(myRightColExpression));
// }
// }
// else
// {
// syntax parser = new syntax();
// myFormUserRules(true, (ColumnMapExpression)
// parser.Parse(myLeftColExpression));
// myFormUserRules(false, (ColumnMapExpression)
// parser.Parse(myRightColExpression));
// }
// }
// /// <summary>
// /// Forms the array of user defined names
// /// </summary>
// /// <param name="isLeft"></param>
// /// <param name="cme"></param>
// private void myFormUserRules (bool isLeft, ColumnMapExpression cme)
// {
// IDictionary userMap = cme.columns;
// if (cme.isInclusive)
// for(int i = 0; i < myOriginalColInfo.Length ; i++)
// {
// OriginalNameInfo oni = myOriginalColInfo[i];
// if (oni.isLeft == isLeft)
// {
// if (userMap[oni.colName] != null)
// {
// if ((string)userMap[oni.colName] != oni.colName)
// myUserRules[i] = (string)userMap[oni.colName];
// else
// myUserRules[i] = oni.colName;
// }
// }
// }
// else
// {
// for (int i = 0; i < myOriginalColInfo.Length; i ++)
// {
// OriginalNameInfo oni = myOriginalColInfo[i];
// if (oni.isLeft == isLeft)
// {
// if (userMap[oni.colName] == null)
// myUserRules[i] = oni.colName;
// else if ((string)userMap[oni.colName] != oni.colName)
// myUserRules[i] = (string)userMap[oni.colName];
// }
// }
// }
// }
// private void myFormResolvedNames()
// {
// string prependString;
// myResolvedNames = new string[myUserRules.Length];
// Array.Copy (myUserRules, myResolvedNames, myUserRules.Length);
// string[] temp = myUserRules;
// myUserRules = new String[temp.Length + 1];
// Array.Copy (temp, 0, myUserRules, 0, temp.Length);
// myUserRules[myUserRules.Length - 1] = "id";
// for (int i = 0; i < myResolvedNames.Length; i ++)
// {
// ArrayList occurances = myFindAllInCollection (myUserRules, myResolvedNames[i]);
// while (occurances.Count > 1)
// {
// prependString = i < myLeftSchema.columnNames.Length ? "L." : "R.";
// myResolvedNames[i] = prependString + myResolvedNames[i];
// occurances = myFindAllInCollection (myUserRules, myResolvedNames[i]);
// occurances.AddRange (myFindAllInCollection (myResolvedNames, myResolvedNames[i]));
// }
// }
// }
// private void myFormFinalMap ()
// {
// foreach (string resolvedName in myResolvedNames)
// if (resolvedName != null)
// myFinalMap [resolvedName] = myJoinNames[Array.IndexOf (myResolvedNames, resolvedName)];
// }
// /// <summary>
// /// Utility method to invert a hashtable
// /// </summary>
// /// <param name="arg"></param>
// /// <returns></returns>
// private IDictionary reciprocateDictionary (IDictionary arg)
// {
// IDictionary retVal = new Hashtable ();
// foreach (DictionaryEntry de in arg)
// retVal[de.Value] = de.Key;
// return retVal;
// }
// /// <summary>
// /// Utility method to find all occurances of an obkect in an IList
// /// </summary>
// /// <param name="list"></param>
// /// <param name="obj"></param>
// /// <returns></returns>
// private ArrayList myFindAllInCollection (IList list, object obj)
// {
// ArrayList retVal = new ArrayList ();
// for (int i = 0; i < list.Count; i++)
// if (list[i] != null && list[i].Equals (obj))
// retVal.Add (i);
// return retVal;
// }
// public IDictionary getMap () {return myFinalMap;}
// }
// }
@@ -0,0 +1,113 @@
// // using System;
// // using System.Collections;
// // using BCG.Utilities;
// // namespace BCG
// // {
// // /// <summary>
// // /// Represents each operand of the Join Operations. Does some bookkeeping like mantaining indexes on
// // /// rows for fast retrieval and row matching
// // /// </summary>
// // public class JoinOperand
// // {
// // private string myJoinCol;
// // private DataPacket myLastArrivedPacket;
// // private JoinOperand myOtherOperand;
// // private bool myIsLeft;
// // private JoinOperandRowIndex myRowIndex;
// // private InternalJoinStream myMaster;
// // private IBlueTableSchema myOpSchema;
// // public JoinOperand (string joinCol, bool isLeft)
// // {
// // myJoinCol = joinCol;
// // myIsLeft = isLeft;
// // }
// // internal void changeHandler (object o)
// // {
// // DataPacket temp = (DataPacket)o;
// // if (myLastArrivedPacket != null)
// // mySubsequentChangeHandler ((DataPacket)o);
// // else
// // myFirstChangeHandler ((DataPacket)o);
// // }
// // private void myFirstChangeHandler (DataPacket arrivedDp)
// // {
// // myLastArrivedPacket = arrivedDp;
// // myOpSchema = myLastArrivedPacket.newRows.schema;
// // myOtherOperand = myMaster.getOtherOperand (this);
// // myRowIndex = new JoinOperandRowIndex (myOpSchema[myJoinCol].colNo, myOpSchema["id"].colNo);
// // if (myOtherOperand.hasReceivedData)
// // {
// // //the other operand has already received data, so the join would
// // //actually be performed now, note, this is the first and only time
// // //the whole join is being performed. All other joins would be
// // //incremental
// // myMaster.startSession ();
// // myMaster.addRows (myLastArrivedPacket.newRows, myIsLeft);
// // myMaster.endSession ();
// // }
// // else
// // myRowIndex = new JoinOperandRowIndex (myLastArrivedPacket.newRows,
// // myOpSchema[myJoinCol].colNo,
// // myOpSchema["id"].colNo);
// // }
// // private void mySubsequentChangeHandler (DataPacket arrivedDp)
// // {
// // myLastArrivedPacket = arrivedDp;
// // if (!myOtherOperand.hasReceivedData)
// // {
// // //no reason to call the master to actually perform
// // //the join, as the other operand is not there. Though
// // //this case has not been witnessed as yet, but
// // //theoriticaly its possible
// // foreach (IBlueRow row in myLastArrivedPacket.deletedRows)
// // deleteRow (row);
// // foreach (IBlueRow row in myLastArrivedPacket.addedRows)
// // addRow (row);
// // return;
// // }
// // myMaster.startSession ();
// // if (myLastArrivedPacket.newRows.Count == 0)
// // {
// // myRowIndex.clear ();
// // myMaster.onTableClear (myIsLeft);
// // }
// // else
// // {
// // //the only condition when the join will actually take place
// // myMaster.deleteRows (myLastArrivedPacket.deletedRows, myIsLeft);
// // myMaster.addRows (myLastArrivedPacket.addedRows, myIsLeft);
// // }
// // myMaster.endSession ();
// // }
// // internal void addRow (IBlueRow row) {myRowIndex.add (row);}
// // internal void deleteRow (IBlueRow row) {myRowIndex.remove (row);}
// // internal IBlueTableSchema operandSchema {get{return myOpSchema;}}
// // internal InternalJoinStream master {set{myMaster = value;}}
// // internal string joinCol {get{return myJoinCol;}}
// // internal int joinColOridinal {get{return myOpSchema[myJoinCol].colNo;}}
// // internal RowList getMatchingRows (object key) {return (RowList) myRowIndex.getMatchingRows (key);}
// // internal bool hasReceivedData {get{return myLastArrivedPacket != null;}}
// // internal void init ()
// // {
// // ///should be brought back to the the state before the first callback
// // ///(ie the state after construction)
// // myRowIndex = null;
// // myLastArrivedPacket = null;
// // }
// // }
// // }
@@ -0,0 +1,66 @@
using System;
using System.Collections;
using BCG.Utilities;
namespace BCG
{
/// <summary>
/// Datastructure used to mantain the join rows, there would be 2 of those, for right and left operands
/// respectivly. Objective of this data structure is to get all rows belonging to a joinCol value and to
/// delete rows provided their id's.
/// </summary>
internal class JoinOperandRowIndex
{
private IDictionary myJoinColDict = new Hashtable (), myIdDict = new Hashtable ();
private int myJoinColOrdinal, myIdColOrdinal;
/// <summary>
///
/// </summary>
/// <param name="joinColIndex">index of the joinCol</param>
/// <param name="idColindex">index of the id</param>
public JoinOperandRowIndex (int joinColIndex, int idColindex)
{
myJoinColOrdinal = joinColIndex;
myIdColOrdinal = idColindex;
}
public JoinOperandRowIndex(IBlueRowCollection rows, int joinColIndex, int idColIndex) :
this(joinColIndex, idColIndex)
{
foreach (IBlueRow row in rows)
add (row);
}
public void add (IBlueRow row)
{
RowList list;
if (myJoinColDict[row[myJoinColOrdinal]] == null)
myJoinColDict[row[myJoinColOrdinal]] = list = new RowList ();
else
list = (RowList)myJoinColDict[row[myJoinColOrdinal]];
myIdDict[row[myIdColOrdinal]] = list.add (row);
}
public void remove (IBlueRow row)
{
RowNode node = (RowNode)myIdDict[row[myIdColOrdinal]];
((RowList)myJoinColDict[row[myJoinColOrdinal]]).remove (node);
myIdDict.Remove (row[myIdColOrdinal]);
}
public RowList getMatchingRows (object key)
{
RowList retVal = (RowList)myJoinColDict[key];
if (retVal == null)
return new RowList ();
return retVal;
}
public void clear ()
{
myJoinColDict.Clear ();
myIdDict.Clear ();
}
}
}
@@ -0,0 +1,154 @@
// using System;
// using BCG.Utilities;
// using System.Collections;
// namespace BCG
// {
// internal class JoinRow : IBlueRow
// {
// private RowNode myLeftNode, myRightNode;
// protected IBlueRow myLeftRow, myRightRow;
// protected int myId;
// protected JoinTableSchema mySchema;
// private object[] myValues;
// #region Constructor(s)
// /// <summary>
// /// Constructs a row, assigning it the same ID as that of the left row.
// /// </summary>
// /// <param name="leftRow">left row of the join</param>
// /// <param name="rightRow">right row of the join</param>
// /// <param name="schema">schema of the joined row</param>
// public JoinRow (IBlueRow leftRow, IBlueRow rightRow, JoinTableSchema schema)
// : this ((int)leftRow["id"], leftRow, rightRow, schema) {}
// /// <summary>
// /// Constructs a row assigning it the ID provioded as the first argument
// /// </summary>
// /// <param name="id">id of the joined row</param>
// /// <param name="leftRow">left row of the join</param>
// /// <param name="rightRow">right row of the join</param>
// /// <param name="schema">schema of the joined row</param>
// public JoinRow (int id, IBlueRow leftRow, IBlueRow rightRow, JoinTableSchema schema)
// {
// myId = id;
// myLeftRow = leftRow;
// myRightRow = rightRow;
// mySchema = schema;
// myValues = new object [schema.columnNames.Length];
// }
// #endregion
// #region IBlueRow members
// public IBlueTableSchema schema {get{return mySchema;}}
// #endregion
// public bool isPartialJoin{get{return myRightRow == null;}}
// public RowNode leftNode
// {
// get{return myLeftNode;}
// set{myLeftNode = value;}
// }
// public RowNode rightNode
// {
// get{return myRightNode;}
// set{myRightNode = value;}
// }
// #region ICollection members
// public int Count{get{return mySchema.columnNames.Length;}}
// public bool IsSynchronized {get{return false;}}
// public object SyncRoot{get{return this;}}
// public void CopyTo (Array array, int index)
// {
// int i = 0;
// foreach (object o in this as IEnumerable)
// array.SetValue (o, i++);
// }
// #endregion
// #region IDictionary members
// public bool IsFixedSize {get{return true;}}
// public bool IsReadOnly {get{return true;}}
// /// <summary>
// /// The key can either be the string corrsponding to the column name or
// /// the order of the column
// /// </summary>
// public virtual object this [object key]
// {
// get
// {
// if (key is string)
// return this[(string)key];
// return this[(int)key];
// }
// set {throw new NotSupportedException ("The IBlueRow is read only");}
// }
// public object this [int index]
// {
// get
// {
// if (index == mySchema.columnNames.Length - 1)
// return myId;
// else if (index < myLeftRow.Count)
// {
// if (myValues[index] == null)
// myValues[index] = myLeftRow[index];
// return myValues[index];
// }
// else if (index >= myLeftRow.Count && index < mySchema.columnNames.Length - 1)
// {
// if (myValues[index] == null)
// myValues[index] = (myRightRow == null) ? DBNull.Value : myRightRow[index - myLeftRow.Count];
// return myValues[index];
// }
// BlueEventLog.logAssert (false, "Incorrect index in JoinRow");
// return null;
// }
// }
// public object this [string colName] {get{return this[mySchema[colName].colNo];}}
// public ICollection Keys{get{return mySchema.columnNames;}}
// public ICollection Values
// {
// get
// {
// object[] retVal = new object[mySchema.columnNames.Length];
// CopyTo (retVal, 0);
// return retVal;
// }
// }
// public void Add (object key, object value) {throw new NotSupportedException ("The IBlueRow is readonly");}
// public void Clear () {throw new NotSupportedException ("The IBlueRow is readonly");}
// public bool Contains (object key){return mySchema[(string)key] != null;}
// /// <summary>
// /// Note, the default enumerator is the IDictionary's enumerator, so if user needs to
// /// iterate through the values, typecast this into an IEnumerable
// /// </summary>
// /// <returns></returns>
// public IDictionaryEnumerator GetEnumerator() {return new BlueRowDictionaryEnumerator(this);}
// IEnumerator IEnumerable.GetEnumerator () {return new BlueRowEnumerator(this);}
// public void Remove (object key) {throw new NotSupportedException ("The IBlueRow is readonly");}
// #endregion
// }
// }
@@ -0,0 +1,165 @@
// using System;
// using System.Data;
// using System.Collections;
// using System.Text.RegularExpressions;
// using BCG.Utilities;
// using BCG.Utilities.General;
// namespace BCG
// {
// public class JoinStream : ViewStream
// {
// protected InternalJoinStream myIjs;
// protected ProjectStream myPs;
// protected ColumnMap myLeftCm, myRightCm;
// protected bool myIsProject = true;
// private bool myUseSuperJoin = DataStreamLoadFileConfig.instance.useNewJoin;
// protected JoinStream () {}
// public JoinStream (ViewStream v1, string joinCol1, ColumnMap cm1,
// ViewStream v2, string joinCol2, ColumnMap cm2)
// {
// if (myUseSuperJoin)
// {
// ViewStream rs = this is LeftJoinStream ?
// new SuperLeftJoinStream(v1, joinCol1, cm1.columnExpression, v2, joinCol2, cm2.columnExpression) as ViewStream :
// new SuperJoinStream(v1, joinCol1, cm1.columnExpression, v2, joinCol2, cm2.columnExpression) as ViewStream;
// mySetRealSource(rs);
// }
// else
// {
// myLeftCm = cm1;
// myRightCm = cm2;
// //myIjs = new InternalJoinStream (v1, joinCol1, v2, joinCol2);
// myIjs = myConstructInternalJoinStream(v1, joinCol1, v2, joinCol2);
// }
// }
// public JoinStream (ViewStream v1, string joinCol1, string cmExp1,
// ViewStream v2, string joinCol2, string cmExp2)
// :
// this (
// v1,
// joinCol1,
// (cmExp1 == null ? new ColumnMap("!"):new ColumnMap(cmExp1)),
// v2,
// joinCol2,
// (cmExp2 == null ? new ColumnMap("!"):new ColumnMap(cmExp2)))
// {}
// public JoinStream (ViewStream v1, string joinCol1, string cmExp1,
// ViewStream v2, string joinCol2)
// :
// this (v1,joinCol1, new ColumnMap(cmExp1), v2, joinCol2)
// {}
// public JoinStream (ViewStream v1, string joinCol1,
// ViewStream v2, string joinCol2, string cmExp2)
// :
// this (v1,joinCol1, v2, joinCol2, new ColumnMap(cmExp2))
// {}
// public JoinStream (ViewStream v1, string joinCol1, ViewStream v2, string joinCol2)
// {
// if (myUseSuperJoin)
// {
// ViewStream rs = this is LeftJoinStream ?
// new SuperLeftJoinStream(v1, joinCol1, v2, joinCol2) as ViewStream :
// new SuperJoinStream(v1, joinCol1, v2, joinCol2) as ViewStream;
// mySetRealSource(rs);
// }
// else
// {
// //myIjs = new InternalJoinStream (v1, joinCol1, v2, joinCol2);
// myIjs = myConstructInternalJoinStream(v1, joinCol1, v2, joinCol2);
// myIsProject = false;
// }
// }
// public JoinStream (ViewStream v1, string joinCol1, ColumnMap cm1, ViewStream v2, string joinCol2)
// {
// myLeftCm = cm1;
// myRightCm = new ColumnMap ("!");
// //myIjs = new InternalJoinStream (v1, joinCol1, v2, joinCol2);
// myIjs = myConstructInternalJoinStream (v1, joinCol1, v2, joinCol2);
// }
// public JoinStream (ViewStream v1, string joinCol1, ViewStream v2, string joinCol2, ColumnMap cm2)
// {
// myLeftCm = new ColumnMap ("!");
// myRightCm = cm2;
// //myIjs = new InternalJoinStream (v1, joinCol1, v2, joinCol2);
// myIjs = myConstructInternalJoinStream (v1, joinCol1, v2, joinCol2);
// }
// protected virtual InternalJoinStream myConstructInternalJoinStream (
// ViewStream vs1,
// string joinCol1,
// ViewStream vs2,
// string joinCol2)
// {
// return new InternalJoinStream (vs1, joinCol1, vs2, joinCol2);
// }
// protected void myInternalJoinChangeHandler (object o)
// {
// if (myIsProject)
// {
// if (myPs == null)
// {
// JoinNameResolver resolver = new JoinNameResolver ((JoinTableSchema)myIjs.schema, myIjs.getSchema (true), myLeftCm.columnExpression,
// myIjs.getSchema (false), myRightCm.columnExpression);
// IDictionary map = resolver.getMap ();
// map["id"] = "id";
// myPs = new ProjectStream (myIjs, map);
// myPs.onChange += new DataStream.ChangeDelegate (myProjectChangeHandler);
// return;
// }
// else
// BlueEventLog.logAssert (false, "This call back should not have been called");
// }
// else
// myFireEvent ((o as ICloneable).Clone());
// }
// private void myProjectChangeHandler (object o)
// {
// if (myIjs.myOnChangeDelegate.GetInvocationList().Length > 1)
// myIjs.onChange -= new DataStream.ChangeDelegate (myInternalJoinChangeHandler);
// myFireEvent ((o as ICloneable).Clone());
// }
// protected override void myOnFirstSubscriber ()
// {
// myIjs.onChange += new DataStream.ChangeDelegate (myInternalJoinChangeHandler);
// }
// protected override void myOnLastSubscriber ()
// {
// // how does this relate to the -= in myProjectChangeHandler?
// myIjs.onChange -= new DataStream.ChangeDelegate (myInternalJoinChangeHandler);
// // if there is a project after the ijs we need to
// // unsubscribe to it otherwise references will be kept and
// // a memory leak will occur
// if (myPs != null)
// myPs.onChange -= new DataStream.ChangeDelegate (myProjectChangeHandler);
// myPs = null;
// }
// /**************************************TEST METHOD(S)*********************************************/
// /// <summary>
// /// Used for testing purposes only. This enables the test to work without a DataSource (PubServer,
// /// BaseServer etc), by directly calling the test method and passing data
// /// </summary>
// /// <param name="leftPacket"></param>
// /// <param name="rightPacket"></param>
// public void test (DataPacket dp, bool isLeft) {myIjs.test (dp, isLeft);}
// /***********************************************************************************************/
// }
// }
@@ -0,0 +1,84 @@
// // using System;
// // using System.Collections;
// // using System.IO;
// // using BCG.Utilities.General;
// // namespace BCG
// // {
// // internal class JoinTable : IBlueRowCollection
// // {
// // protected JoinTableSchema mySchema;
// // protected IDictionary myIdIndex = new Hashtable ();
// // protected JoinDeletionIndex myLeftIndex, myRightIndex;
// // private int myNewRowId;
// // public JoinTable (JoinTableSchema schema)
// // {
// // mySchema = schema;
// // myLeftIndex = new JoinDeletionIndex (mySchema.getRenamedName ("id", true), true);
// // myRightIndex = new JoinDeletionIndex (mySchema.getRenamedName ("id", false), false);
// // }
// // public IBlueRow this [int id]
// // {
// // get
// // {
// // if (myIdIndex[id] == null)
// // throw new BlueDataException ("ID " + id.ToString() + " does not exist in table " + mySchema.tableName);
// // return (IBlueRow)myIdIndex[id];
// // }
// // }
// // #region JoinTable members
// // public virtual void addRow (IBlueRow leftRow, IBlueRow rightRow, DataPacket dp)
// // {
// // JoinRow newRow = new JoinRow (myNewRowId, leftRow, rightRow, mySchema);
// // myIdIndex[myNewRowId ++] = newRow;
// // ((BlueTable)(dp.addedRows)).addRow (newRow);
// // myLeftIndex.add (newRow);
// // if (rightRow != null) //in case of left joins when right row is null
// // myRightIndex.add (newRow);
// // }
// // public virtual void deleteRow (bool isLeft, IBlueRow deletedRow, DataPacket dp)
// // {
// // JoinDeletionIndex thisIndex = myRightIndex, otherIndex = myLeftIndex;
// // if (isLeft)
// // {
// // thisIndex = myLeftIndex;
// // otherIndex = myRightIndex;
// // }
// // RowList matchingNodes = thisIndex.getMatchingRows (deletedRow["id"]);
// // foreach (RowNode node in matchingNodes)
// // {
// // JoinRow row = (JoinRow)node.row;
// // RowNode correspondingNode = isLeft ? row.rightNode : row.leftNode;
// // if (correspondingNode != null)
// // otherIndex.remove (correspondingNode); //in case of partial left joinss
// // myIdIndex.Remove (row["id"]);
// // ((BlueTable)dp.deletedRows).addRow (row);
// // }
// // thisIndex.removeAll (deletedRow["id"]);
// // }
// // #endregion
// // #region ICollection members
// // public int Count{get{return myIdIndex.Count;}}
// // public bool IsSynchronized {get{return false;}}
// // public object SyncRoot{get{return this;}}
// // public void CopyTo (Array array, int index) {myIdIndex.Values.CopyTo (array, index);}
// // #endregion
// // #region IEnumerable members
// // public IEnumerator GetEnumerator () {return myIdIndex.Values.GetEnumerator ();}
// // #endregion
// // #region IBlueRowCollection members
// // public IBlueTableSchema schema {get{return mySchema;}}
// // public bool containsID (int id) {return myIdIndex[id] != null;}
// // #endregion
// // }
// // }
@@ -0,0 +1,107 @@
// using System;
// using System.Collections;
// using BCG.Utilities;
// namespace BCG
// {
// /// <summary>
// /// Represents the schema of the Join Table. This schema is formed by combining the respective
// /// schemas of the operands.
// /// </summary>
// public class JoinTableSchema : BlueTableSchema
// {
// private string myLeftJc = "", myRightJc = "", myLeftId = "", myRightId = "";
// private IDictionary myLeftNameToAlias = new Hashtable ();
// private IDictionary myRightNameToAlias = new Hashtable ();
// private IDictionary myAliasToLeftName = new Hashtable(),
// myAliasToRightName = new Hashtable();
// /// <summary>
// /// Constructs the schema of the Jointable with the schema of the left and right tables. Incase of
// /// a name being there in both the shemas it prefixes the name with "L." or "R." accordingly. Column "id"
// /// is the last column in the schema
// /// </summary>
// /// <param name="leftSchema"></param>
// /// <param name="leftJc"></param>
// /// <param name="rightSchema"></param>
// /// <param name="rightJc"></param>
// public JoinTableSchema (IBlueTableSchema leftSchema, string leftJc,
// IBlueTableSchema rightSchema, string rightJc)
// {
// myIndexByColOrder = new ColumnInfo[leftSchema.columnNames.Length + rightSchema.columnNames.Length + 1];
// myTableName = leftSchema.tableName + " J " + rightSchema.tableName;
// ColumnInfo[] cis = leftSchema.columnInfo;
// string assignedColName;
// bool renamed = false;
// foreach (ColumnInfo ci in cis)
// {
// assignedColName = ci.colName;
// while (rightSchema[assignedColName] != null)
// {
// assignedColName = "L." + assignedColName;
// renamed = true;
// while (leftSchema[assignedColName] != null)
// assignedColName = "L." + assignedColName;
// }
// ColumnInfo newCi = new ColumnInfo (assignedColName, ci.colNo, ci.colType);
// BlueEventLog.logAssert (myIndexByColName[newCi.colName] == null);
// BlueEventLog.logAssert (myIndexByColOrder[newCi.colNo] == null);
// if (renamed)
// BlueEventLog.logAssert (leftSchema[assignedColName] == null);
// BlueEventLog.logAssert (rightSchema[assignedColName] == null);
// myIndexByColName [newCi.colName] = newCi;
// myIndexByColOrder [newCi.colNo] = newCi;
// myLeftNameToAlias[ci.colName] = newCi.colName;
// myLeftJc = ci.colName == leftJc ? assignedColName : myLeftJc;
// myLeftId = ci.colName == "id" ? assignedColName : myLeftId;
// renamed = false;
// }
// BlueEventLog.logAssert (myLeftJc != "" && myLeftId != "");
// int n = leftSchema.columnNames.Length;
// cis = rightSchema.columnInfo;
// renamed = false;
// foreach (ColumnInfo ci in cis)
// {
// assignedColName = ci.colName;
// while (leftSchema[assignedColName] != null)
// {
// assignedColName = "R." + assignedColName;
// renamed = true;
// while(rightSchema[assignedColName] != null)
// assignedColName = "R." + assignedColName;
// }
// ColumnInfo newCi = new ColumnInfo (assignedColName, ci.colNo + n, ci.colType);
// BlueEventLog.logAssert (myIndexByColName[assignedColName] == null);
// BlueEventLog.logAssert (myIndexByColOrder[newCi.colNo] == null);
// BlueEventLog.logAssert (leftSchema[assignedColName] == null);
// if (renamed)
// BlueEventLog.logAssert (rightSchema[assignedColName] == null);
// myIndexByColName [newCi.colName] = newCi;
// myIndexByColOrder [newCi.colNo] = newCi;
// myRightNameToAlias[ci.colName] = newCi.colName;
// myRightJc = ci.colName == rightJc ? assignedColName : myRightJc;
// myRightId = ci.colName == "id" ? assignedColName : myLeftJc;
// renamed = false;
// }
// myIndexByColName["id"] = new ColumnInfo("id", myIndexByColName.Count, typeof(int));
// myIndexByColOrder[myIndexByColOrder.Length - 1] = (ColumnInfo)myIndexByColName["id"];
// myAliasToLeftName = ProjectHelper.invertDic(myLeftNameToAlias);
// myAliasToRightName = ProjectHelper.invertDic(myRightNameToAlias);
// }
// public string leftJoinCol {get{return myLeftJc;}}
// public string rightJoinCol {get{return myRightJc;}}
// public string getRenamedName (string origName, bool isLeft)
// {
// if (isLeft)
// return (string)myLeftNameToAlias[origName];
// return (string)myRightNameToAlias[origName];
// }
// public string getOriginalName(string rename, bool isLeft)
// {
// return isLeft ? myAliasToLeftName[rename].ToString() : myAliasToRightName[rename].ToString();
// }
// }
// }
@@ -0,0 +1,54 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// namespace BCG
// {
// /// <summary>
// /// Same as a join except can join based on
// /// multiple columns (this abstracts what we
// /// have been doing for ages - concatenating,
// /// joining and then projecting the concatanted
// /// columns out)
// /// </summary>
// public class MultiColumnJoinStream : ViewStream
// {
// public MultiColumnJoinStream(ViewStream leftStream, string leftJoinColumns, string leftProject,
// ViewStream rightStream, string rightJoinColumns, string rightProject)
// : this(leftStream, leftJoinColumns, leftProject,
// rightStream, rightJoinColumns, rightProject, false)
// { }
// public MultiColumnJoinStream(ViewStream leftStream, string leftJoinColumns, string leftProject,
// ViewStream rightStream, string rightJoinColumns, string rightProject, bool leftJoin)
// {
// string[] leftJoinColArray = leftJoinColumns.Split(' ', ',', ';'),
// rightJoinColArray = rightJoinColumns.Split(' ', ',', ';');
// if (leftJoinColArray.Length == 1 && rightJoinColArray.Length == 1)
// /// so that this handles regular joins too
// mySetRealSource(leftJoin ? new SuperLeftJoinStream(leftStream, leftJoinColArray[0], leftProject,
// rightStream, rightJoinColArray[0], rightProject) :
// new SuperJoinStream(leftStream, leftJoinColArray[0], leftProject,
// rightStream, rightJoinColArray[0], rightProject));
// else
// {
// string leftCols = "ljc:";
// foreach (string c in leftJoinColArray)
// leftCols += c + " ";
// leftCols = leftCols.Trim();
// string rightCols = "rjc:";
// foreach (string c in rightJoinColArray)
// rightCols += c + " ";
// rightCols = rightCols.Trim();
// ViewStream res =
// leftJoin ? new SuperLeftJoinStream(new ConcatenateColumnsStream(leftStream, leftCols), "ljc", leftProject,
// new ConcatenateColumnsStream(rightStream, rightCols), "rjc", rightProject) :
// new SuperJoinStream(new ConcatenateColumnsStream(leftStream, leftCols), "ljc", leftProject,
// new ConcatenateColumnsStream(rightStream, rightCols), "rjc", rightProject);
// res = new ProjectStream(res, "!ljc rjc");
// mySetRealSource(res);
// }
// }
// }
// }
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCG
{
public interface INonIncJoinInlineMapper
{
IBlueTableSchema get_output_schema(IBlueTableSchema schema);
IBlueRowCollection map_rows(IBlueRowCollection rows);
event MapperChangeDelegate onMapperChange;
}
}
@@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts;
namespace BCG
{
public class NonIncJoinBookkeeper : IDisposable
{
public Action on_new_data;
private readonly NonIncJoinSpec _join_spec;
private readonly int _join_position;
private readonly int _start_index_in_output;
private readonly BlueRowHasher _row_hasher;
private readonly bool _is_left_most;
private readonly bool _is_tag_along;
private int _n_total_fires = 0, _n_expensive_fires = 0;
private IBlueTableSchema _schema = null;
private IDictionary<int, IBlueRow> _row_map = new Dictionary<int, IBlueRow>();
private List<Pair<int, IBlueRow>> _row_list = new List<Pair<int, IBlueRow>>();
private IBlueRow _solitary_row = null;
private int[] _join_col_indices = null,
_data_col_indices = null;
public NonIncJoinBookkeeper(NonIncJoinSpec the_join_spec, int join_position, int start_index_in_output, BlueRowHasher row_hasher)
{
_join_spec = the_join_spec;
_join_position = join_position;
_start_index_in_output = start_index_in_output;
_row_hasher = row_hasher;
_is_left_most = _join_position == 0;
_is_tag_along = _join_spec.join_col_names.Length == 0;
_join_spec.stream.onChange += _on_stream_cb;
}
public void _on_stream_cb(object dp_obj)
{
HighPerformanceTimer timer = new HighPerformanceTimer();
timer.start();
DataPacket dp = (DataPacket)dp_obj;
if (_schema == null)
{
_schema = dp.schema;
_join_col_indices = BlueDataUtility.get_column_indices(_schema, _join_spec.join_col_names);
_data_col_indices = BlueDataUtility.get_column_indices(_schema, _join_spec.data_col_names);
}
if (_is_left_most)
{
_row_list.Clear();
foreach (IBlueRow r in dp.newRows)
_row_list.Add(new Pair<int, IBlueRow>(_row_hasher.get_hash(r, _join_col_indices), r));
}
else
{
if (_is_tag_along)
_solitary_row = BlueDataUtility.extractRow(dp.newRows, 0);
else
{
_row_map.Clear();
foreach (IBlueRow r in dp.newRows)
_row_map[_row_hasher.get_hash(r, _join_col_indices)] = r;
}
}
timer.stop();
_n_total_fires++;
if (timer.lastIntervalTime > 50)
{
_n_expensive_fires++;
string log_msg = String.Format("NonIncJoinBookkeepingData._on_stream_cb {0} rows {1} key cols {2} join pos time {3} ratio {4}/{5}", dp.newRows.Count, _join_col_indices.Length, _join_position, timer.lastIntervalTime, _n_expensive_fires, _n_total_fires);
// mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, log_msg);
}
if (on_new_data != null)
on_new_data();
}
public bool is_ready { get { return _schema != null; } }
public void constribute_cols_to_schema(List<ColumnInfo> cis)
{
for (int i = 0; i < _join_spec.data_col_names.Length; i++)
cis.Add(new ColumnInfo(_join_spec.projected_col_names[i], cis.Count, _schema[_join_spec.data_col_names[i]].colType));
}
public List<Pair<int, IBlueRow>> get_list() { return _row_list; }
public void copy_master_row_to_output_row(int row_index, object[] output_row)
{
IBlueRow this_row = _row_list[row_index].second;
BlueDataUtility.copy_to_row(this_row, _data_col_indices, output_row, _start_index_in_output);
}
public void copy_matching_row_to_output_row(int row_hash, object[] output_row)
{
if (_is_tag_along)
{
if (_solitary_row != null)
BlueDataUtility.copy_to_row(_solitary_row, _data_col_indices, output_row, _start_index_in_output);
else
copy_dbnull_to_output_row(output_row);
}
else
{
IBlueRow this_row = null;
if (_row_map.TryGetValue(row_hash, out this_row))
BlueDataUtility.copy_to_row(this_row, _data_col_indices, output_row, _start_index_in_output);
else
copy_dbnull_to_output_row(output_row);
}
}
private void copy_dbnull_to_output_row(object[] output_row)
{
for (int i = 0; i < _data_col_indices.Length; i++)
output_row[i + _start_index_in_output] = DBNull.Value;
}
#region IDisposable
public void Dispose() { _join_spec.stream.onChange -= _on_stream_cb; }
#endregion
}
}
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts;
namespace BCG
{
public class NonIncJoinSpec
{
public ViewStream stream;
public string[] join_col_names, data_col_names, projected_col_names;
public NonIncJoinSpec() { }
public NonIncJoinSpec(ViewStream the_stream, string[] the_join_col_names, string[] the_data_col_names)
: this (the_stream, the_join_col_names, the_data_col_names, the_data_col_names)
{ }
public NonIncJoinSpec(ViewStream the_stream, string[] the_join_col_names, string[] the_data_col_names, string[] the_projected_col_names)
{
stream = the_stream;
join_col_names = the_join_col_names;
data_col_names = the_data_col_names;
projected_col_names = the_projected_col_names;
}
public static NonIncJoinSpec[] from_triplet(params Triplet<ViewStream, string, string>[] join_specs)
{
List<NonIncJoinSpec> rv = new List<NonIncJoinSpec>();
foreach (Triplet<ViewStream, string, string> r in join_specs)
{
string[] keys = String.IsNullOrEmpty (r.second) ? new string[] {} : r.second.Split(' ');
string[] visible_cols = r.third.Split(' ');
List<string> data_col_names = new List<string>(), mapped_col_names = new List<string>();
foreach (string s in visible_cols)
{
string[] toks = s.Split(':');
if (toks.Length == 1)
{
data_col_names.Add(toks[0]);
mapped_col_names.Add(toks[0]);
}
else if (toks.Length == 2)
{
data_col_names.Add(toks[0]);
mapped_col_names.Add(toks[1]);
}
}
rv.Add (new NonIncJoinSpec (r.first, keys, data_col_names.ToArray (), mapped_col_names.ToArray()));
}
return rv.ToArray ();
}
}
//[DataStreamUserRespresentation("ninctest")]
//public class NonIncJoinTestStream : ViewStream
//{
// public NonIncJoinTestStream (string key_cols, string data_cols)
// {
// NonIncJoinSpec.from_triplet(new Triplet<ViewStream, string, string>(null, key_cols, data_cols));
// }
//}
}
@@ -0,0 +1,183 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts;
namespace BCG
{
public class NonIncJoinStream : ViewStream, BCG.Utilities.General.IWorker
{
private readonly NonIncJoinSpec[] _join_specs;
private readonly INonIncJoinInlineMapper _output_mapper;
private readonly BlueRowHasher _row_hasher;
private readonly TimeSpan _throttle_period;
private readonly ViewStreamDatabase _vsd;
private List<NonIncJoinBookkeeper> _book_keeping_data = new List<NonIncJoinBookkeeper>();
private IBlueTableSchema _output_schema = null;
private DateTime _last_fire_time = DateTime.MinValue;
private bool _is_dirty = false;
public NonIncJoinStream(ViewStream left, string left_join_cols, string left_proj,
ViewStream right, string right_join_cols, string right_proj)
: this(new Triplet<ViewStream, string, string>[]
{
new Triplet<ViewStream, string, string> (left, left_join_cols, left_proj),
new Triplet<ViewStream, string, string> (right, right_join_cols, right_proj)
})
{ }
public NonIncJoinStream(params Triplet<ViewStream, string, string>[] join_specs)
: this (NonIncJoinSpec.from_triplet (join_specs), null, 0)
{ }
public NonIncJoinStream(ViewStreamDatabase vsd, INonIncJoinInlineMapper output_mapper, int throttles_ms,
params Triplet<ViewStream, string, string>[] join_specs)
: this(vsd, NonIncJoinSpec.from_triplet(join_specs), output_mapper, throttles_ms)
{ }
public NonIncJoinStream(NonIncJoinSpec[] join_specs, INonIncJoinInlineMapper output_mapper, int throttles_ms = 0)
: this(ViewStreamDatabase.instance, join_specs, output_mapper, throttles_ms)
{ }
public NonIncJoinStream(ViewStreamDatabase vsd, NonIncJoinSpec[] join_specs, INonIncJoinInlineMapper output_mapper, int throttles_ms = 0)
{
_join_specs = join_specs;
_output_mapper = output_mapper;
_row_hasher = new BlueRowHasher(_join_specs[0].join_col_names.Length);
_throttle_period = throttles_ms == 0 ? TimeSpan.Zero : new TimeSpan(0, 0, 0, 0, throttles_ms);
_vsd = vsd;
}
protected override void myOnFirstSubscriber()
{
int data_col_no = 1;
for (int jp = 0; jp < _join_specs.Length; jp++)
{
NonIncJoinBookkeeper s = new NonIncJoinBookkeeper(_join_specs[jp], jp, data_col_no, _row_hasher);
data_col_no += _join_specs[jp].data_col_names.Length;
s.on_new_data += _stream_callback;
_book_keeping_data.Add(s);
}
if (_output_mapper != null)
_output_mapper.onMapperChange += _on_mapper_change;
_vsd.addWorker(this);
}
protected override void myOnLastSubscriber()
{
foreach (NonIncJoinBookkeeper d in _book_keeping_data)
d.Dispose();
if (_output_mapper != null)
_output_mapper.onMapperChange -= _on_mapper_change;
_vsd.removeWorker(this);
}
private void _stream_callback()
{
_is_dirty = true;
doWork();
}
private void _on_mapper_change()
{
_is_dirty = true;
doWork();
}
private bool _is_ready()
{
bool rv = true;
foreach (NonIncJoinBookkeeper d in _book_keeping_data)
rv &= d.is_ready;
return rv;
}
private void _construct_schema()
{
if (_output_schema == null)
{
List<ColumnInfo> cis = new List<ColumnInfo>(new ColumnInfo[] { new ColumnInfo("id", 0, typeof(int)) });
foreach (NonIncJoinBookkeeper d in _book_keeping_data)
d.constribute_cols_to_schema (cis);
_output_schema = new BlueTableSchema ("NonIncJoinStream", cis.ToArray());
}
}
private int _n_total_fires = 0, _n_expensive_fires = 0;
private void _form_and_fire()
{
if (_is_ready())
{
_construct_schema();
HighPerformanceTimer timer = new HighPerformanceTimer();
timer.start();
IList<Pair<int, IBlueRow>> left_row_list = _book_keeping_data[0].get_list();
List<object[]> output_rows = new List<object[]>();
for (int i = 0; i < left_row_list.Count; i++)
{
object[] or = new object[_output_schema.columnInfo.Length];
or[0] = i;
output_rows.Add(or);
}
for (int ji = 0; ji < _book_keeping_data.Count; ji++)
{
NonIncJoinBookkeeper bk_data = _book_keeping_data[ji];
for (int i = 0; i < left_row_list.Count; i++)
{
if (ji == 0)
bk_data.copy_master_row_to_output_row(i, output_rows[i]);
else
bk_data.copy_matching_row_to_output_row(left_row_list[i].first, output_rows[i]);
}
}
IBlueRowCollection dp_output_rows = _apply_map(new SequentialIDBlueTable(_output_schema, output_rows));
timer.stop();
_n_total_fires++;
if (timer.lastIntervalTime >= 250)
{
_n_expensive_fires++;
string log_msg = String.Format("Join and map time for {0} tables {1} ratio {2}/{3}", _book_keeping_data.Count, timer.lastIntervalTime, _n_expensive_fires, _n_total_fires);
// mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, log_msg);
}
myFireEvent(new DataPacket(dp_output_rows, dp_output_rows, myLastValue == null ? new BlueTable(_output_schema) : (myLastValue as DataPacket).newRows));
}
}
private IBlueRowCollection _apply_map(IBlueRowCollection unmapped_rows)
{
if (_output_mapper != null)
{
HighPerformanceTimer timer = new HighPerformanceTimer();
IBlueRowCollection output_rows;
timer.start();
output_rows = _output_mapper.map_rows(unmapped_rows);
timer.stop();
if (timer.lastIntervalTime >= 50)
{
// string log_msg = String.Format("Time to map {0} rows into {1} rows {2}", unmapped_rows.Count, output_rows.Count, timer.lastIntervalTime);
// mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, log_msg);
}
return output_rows;
}
else
{
return unmapped_rows;
}
}
public void doWork()
{
if (DateTime.Now - _last_fire_time >= _throttle_period && _is_dirty)
{
_is_dirty = false;
_last_fire_time = DateTime.Now;
_form_and_fire();
}
}
}
}
@@ -0,0 +1,371 @@
// using System;
// using System.Collections;
// using System.Collections.Generic;
// using System.Text;
// using BCG.Utilities.General;
// using BCG.Utilities;
// namespace BCG
// {
// /// <summary>
// /// This class is used to effect a mapping between values in a join column and entries in three different tables:
// /// the left and right tables of a join, as well as the output table (the join table).
// /// </summary>
// class ParallelJoinTestTablePointer
// {
// int myLeftTableId = -1;
// public int LeftTableId
// {
// get { return myLeftTableId; }
// set { myLeftTableId = value; }
// }
// int myRightTableId = -1;
// public int RightTableId
// {
// get { return myRightTableId; }
// set { myRightTableId = value; }
// }
// int myJoinTableId = -1;
// public int JoinTableId
// {
// get { return myJoinTableId; }
// set { myJoinTableId = value; }
// }
// public ParallelJoinTestTablePointer(int leftId, int rightId, int joinId)
// {
// myLeftTableId = leftId;
// myRightTableId = rightId;
// myJoinTableId = joinId;
// }
// public ParallelJoinTestTablePointer() : this(-1,-1,-1)
// {
// }
// }
// #region IBlueRow implementation for join and leftJoin
// public class ParallelJoinTestRow : IBlueRow
// {
// private JoinProjectHelper myHelper;
// private IBlueRow myLeftRow, myRightRow;
// int myID;
// public ParallelJoinTestRow(int id, IBlueRow leftRow, IBlueRow rightRow, JoinProjectHelper joinProjectHelper)
// {
// myID = id;
// myLeftRow = leftRow;
// myRightRow = rightRow;
// myHelper = joinProjectHelper;
// }
// public int leftID { get { return (int)myLeftRow["id"]; } }
// public int rightID { get { return (int)myRightRow["id"]; } }
// public IBlueRow leftRow { get { return myLeftRow; } }
// public IBlueRow rightRow { get { return myRightRow; } }
// #region IBlueRow Members
// public IBlueTableSchema schema { get { return myHelper.schema; } }
// public object this[int index] { get { return this[schema[index].colName]; } }
// public object this[string colName]
// {
// get
// {
// if (colName == "id")
// return myID;
// else
// {
// bool isLeft;
// string col = myHelper.getOriginalCol(colName, out isLeft);
// return isLeft ? myLeftRow[col] : (myRightRow == null ? (object)DBNull.Value : myRightRow[col]);
// }
// }
// }
// #endregion
// #region IDictionary Members
// public void Add(object key, object value) { { throw new NotSupportedException("IBlueRow is readonly"); } }
// public void Clear() { throw new NotSupportedException("IBlueRow is readonly"); }
// public bool Contains(object key) { throw new Exception("The method or operation is not implemented."); }
// public System.Collections.IDictionaryEnumerator GetEnumerator() { return new BlueRowDictionaryEnumerator(this); }
// public bool IsFixedSize { get { return true; } }
// public bool IsReadOnly {get { return true; }}
// public System.Collections.ICollection Keys { get { return schema.columnNames; } }
// public void Remove(object key) { throw new NotSupportedException("IBlueRow is readonly"); }
// public System.Collections.ICollection Values
// {
// get
// {
// List<object> rv = new List<object> ();
// foreach (string col in Keys)
// rv.Add(this[col]);
// return rv;
// }
// }
// public object this[object key]
// {
// get { return key is string ? this[key.ToString()] : this[(int)key]; }
// set { throw new NotSupportedException("IBlueRow is readonly"); }
// }
// #endregion
// #region ICollection Members
// public void CopyTo(Array array, int index) { Values.CopyTo(array, index); }
// public int Count { get { return schema.columnNames.Length; } }
// public bool IsSynchronized { get { return false; } }
// public object SyncRoot { get { return this; } }
// #endregion
// #region IEnumerable Members
// System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new BlueRowEnumerator(this); }
// #endregion
// }
// #endregion
// /// <summary>
// /// This class represents a join on two streams. It works by storing a table with the result of the join.
// /// </summary>
// public class ParallelJoinTestStream : ViewStream
// {
// BlueTable myJoinedTable;
// BlueTable myLeftTable;
// BlueTable myRightTable;
// Hashtable myKeyToTablePointerMap;
// ViewStream myVLeft, myVRight;
// int myIdToUse;
// string myLeftKey, myRightKey, myLeftProj, myRightProj;
// public ParallelJoinTestStream(ViewStream leftStream, string leftKey, ViewStream rightStream, string rightKey)
// : this(leftStream, leftKey, "!", rightStream, rightKey, "!") { }
// public ParallelJoinTestStream(ViewStream leftStream, string leftKey, string leftProj, ViewStream rightStream, string rightKey, string rightProj)
// {
// myVLeft = leftStream;
// myVRight = rightStream;
// myLeftProj = leftProj;
// myRightProj = rightProj;
// myLeftKey = leftKey;
// myRightKey = rightKey;
// myKeyToTablePointerMap = new Hashtable();
// myIdToUse = 0;
// }
// protected override void myOnFirstSubscriber()
// {
// myVLeft.onChange += new ChangeDelegate(myVLeft_onChange);
// myVRight.onChange += new ChangeDelegate(myVRight_onChange);
// }
// void myVRight_onChange(object newValue)
// {
// myHandleChange(newValue as DataPacket, false);
// }
// void myVLeft_onChange(object newValue)
// {
// myHandleChange(newValue as DataPacket, true);
// }
// void myHandleChange(DataPacket dp, bool isLeft)
// {
// int i = 0; // for going throuhg loops and such
// BlueTable addedRows = null, droppedRows = null;
// if (myJoinedTable == null)
// {
// if (isLeft && myLeftTable == null)
// {
// myLeftTable = new BlueTable(dp.addedRows);
// //go through the list of added rows and get the id of each row, storing this in the TablePointer map
// foreach (IBlueRow row in myLeftTable)
// {
// if (myKeyToTablePointerMap.ContainsKey(row[myLeftKey]))
// {
// ((ParallelJoinTestTablePointer)myKeyToTablePointerMap[row[myLeftKey]]).LeftTableId = (int)row["id"];
// }
// else
// {
// myKeyToTablePointerMap[row[myLeftKey]] = new ParallelJoinTestTablePointer((int)row["id"],-1,-1);
// }
// }
// }
// else if (!isLeft && myRightTable == null)
// {
// myRightTable = new BlueTable(dp.addedRows);
// //go through the list of added rows and get the id of each row, storing this in the TablePointer map
// foreach (IBlueRow row in myRightTable)
// {
// if (myKeyToTablePointerMap.ContainsKey(row[myRightKey]))
// {
// ((ParallelJoinTestTablePointer)myKeyToTablePointerMap[row[myRightKey]]).RightTableId = (int)row["id"];
// }
// else
// {
// myKeyToTablePointerMap[row[myRightKey]] = new ParallelJoinTestTablePointer(-1,(int)row["id"],-1);
// }
// }
// }
// if (myLeftTable != null && myRightTable != null)
// {
// //construct the schema for the table based upon the schemas of the two tables that are going to be joined together
// int numColumns = myLeftTable.schema.columnInfo.Length;
// ColumnInfo[] newColumnInfoArray = new ColumnInfo[numColumns * 2 + 1];
// for (i = 0; i < numColumns; i++)
// {
// newColumnInfoArray[i] = new ColumnInfo("L." + myLeftTable.schema.columnNames[i], i, myLeftTable.schema.columnInfo[i].colType);
// newColumnInfoArray[numColumns + i] = new ColumnInfo("R." + myRightTable.schema.columnNames[i], i + numColumns, myRightTable.schema.columnInfo[i].colType);
// }
// newColumnInfoArray[numColumns + i] = new ColumnInfo("id", numColumns + i, (typeof(System.Int64)));
// IBlueTableSchema newSchema = new BlueTableSchema("Joined Table", newColumnInfoArray);
// myJoinedTable = new BlueTable(newSchema);
// addedRows = new BlueTable(newSchema);
// droppedRows = new BlueTable(newSchema);
// //now that we've created the table, we should have some leftover stuff from the side tables
// //that we were storing until now. Add that stuff to the table.
// BlueTable rowsToAdd = isLeft ? myRightTable : myLeftTable;
// foreach (BlueRow row in rowsToAdd)
// {
// Object[] newRowObjects = new Object[newSchema.columnInfo.Length];
// if (isLeft)
// {
// for (i = 0; i < numColumns; i++)
// {
// newRowObjects[i] = row[i];
// newRowObjects[numColumns + i] = null;
// }
// newRowObjects[numColumns + i] = myIdToUse;
// //store the fact that the row with this key value went to this id
// ((ParallelJoinTestTablePointer)myKeyToTablePointerMap[row[myLeftKey]]).JoinTableId = myIdToUse;
// myIdToUse++;
// }
// else
// {
// for (i = 0; i < numColumns; i++)
// {
// newRowObjects[i] = null;
// newRowObjects[numColumns + i] = row[i];
// }
// newRowObjects[numColumns + i] = myIdToUse;
// //store the fact that the row with this key value went to this id
// ((ParallelJoinTestTablePointer)myKeyToTablePointerMap[row[myRightKey]]).JoinTableId = myIdToUse;
// myIdToUse++;
// }
// BlueRow newRow = new BlueRow(newSchema, newRowObjects);
// addedRows.addRow(newRow);
// myJoinedTable.addRow(newRow);
// }
// }
// }
// else
// {
// addedRows = new BlueTable(myJoinedTable.schema);
// droppedRows = new BlueTable(myJoinedTable.schema);
// }
// //setup is complete. At this point, we have to delete all the rows that were deleted, then add in the rows that were added in.
// foreach (BlueRow row in dp.addedRows)
// {
// //check to see if this row has a match in the table already.
// //If it does, get rid of that row in the table because it's OUT OF DATE
// string joinColumn = isLeft ? myLeftKey : myRightKey;
// if (myKeyToTablePointerMap.ContainsKey(row[joinColumn]))
// {
// //the value is already in the hashtable.
// ParallelJoinTestTablePointer tp = (ParallelJoinTestTablePointer) myKeyToTablePointerMap[row[joinColumn]];
// int rowOfExistingGuy = tp.JoinTableId;
// if (rowOfExistingGuy != -1)
// {
// //remove this guy from the table
// IBlueRow rowToDelete = myJoinedTable[rowOfExistingGuy];
// myJoinedTable.deleteRow(rowToDelete);
// droppedRows.addRow(rowToDelete);
// tp.JoinTableId = -1;
// }
// }
// }
// //finally, fire off a packet, but only if you have enough information about the table to do so.
// if (myJoinedTable != null)
// {
// DataPacket outPacket = new DataPacket(myJoinedTable,addedRows, new BlueTable(myJoinedTable.schema));
// myFireEvent(outPacket);
// }
// }
// }
// }
@@ -0,0 +1,135 @@
using System;
using System.Collections;
namespace BCG
{
/// <summary>
/// Implemented as a doubley linked list, it helps in Join operations, where O(1) deletions
/// are required
/// </summary>
internal class RowList : ICollection
{
private RowNode myFirstPtr;
private int myCount = 0;
#region ICollection methods
public int Count{get{return myCount;}}
public bool IsSynchronized {get{return false;}}
public object SyncRoot {get{return this;}}
public void CopyTo (Array array, int index)
{
int i = 0;
foreach (object o in this)
array.SetValue (o, i++);
}
public IEnumerator GetEnumerator () {return new RowListEnumerator (this);}
#endregion
/// <summary>
/// Nodes are added at the start of the collection
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public RowNode add (IBlueRow row)
{
if (myFirstPtr != null) //list is not empty
{
RowNode temp = new RowNode (row, this);
myFirstPtr.previous = temp;
temp.next = myFirstPtr;
myFirstPtr = temp;
}
else //i.e. if the list is empty
{
myFirstPtr = new RowNode (row, this);
}
myCount ++;
return myFirstPtr;
}
public void clear()
{
myCount = 0;
myFirstPtr = null;
}
/// <summary>
/// If node to be removed does not belong to the List, exception is thrown
/// </summary>
/// <param name="node"></param>
public void remove (RowNode node)
{
myCount --;
if (node.isFirst && node.isLast)
{
clear ();
return;
}
else if (node.isFirst)
{
myFirstPtr = myFirstPtr.next;
myFirstPtr.previous = null;
return;
}
else if (node.isLast)
{
node.previous.next = null;
return;
}
else if (!node.isFirst && !node.isLast)
{
node.previous.next = node.next;
node.next.previous = node.previous;
return;
}
else
{
myCount ++;
throw new System.ApplicationException ("node does not belong to the list");
}
}
internal class RowListEnumerator : IEnumerator
{
private RowNode myPointer;
private RowList myList;
private int myPos = -1;
public RowListEnumerator (RowList list) {myList = list;}
public object Current {get{return myPointer;}}
public bool MoveNext()
{
myPointer = myPos == -1 ? myList.myFirstPtr : myPointer.next;
myPos ++;
return myPointer != null;
}
public void Reset() {myPos = -1;}
}
}
internal class RowNode
{
private IBlueRow myRow;
private RowNode myNext;
private RowNode myPrevious;
private RowList myList;
public RowNode (IBlueRow row){myRow = row;}
public RowNode (IBlueRow row, RowList list) : this (row) {myList = list;}
public bool isLast {get{return myNext == null;}}
public bool isFirst {get{return myPrevious == null;}}
public RowList list {get{return myList;}}
public IBlueRow row
{
get{return myRow;}
set{myRow = value;}
}
public RowNode next {
get{return myNext;}
set{myNext = value;}
}
public RowNode previous {
get{return myPrevious;}
set{myPrevious = value;}
}
}
}
@@ -0,0 +1,570 @@
// using System;
// using System.Collections;
// using System.Collections.Generic;
// using System.Text;
// using BCG.Utilities.General;
// using BCG.Utilities;
// using mbts;
// namespace BCG
// {
// internal class SingleRowJoinDicionary<TKey, TValue> : IDictionary<TKey, TValue>
// {
// private TKey myKey;
// private TValue myValue;
// #region IDictionary<TKey,TValue> Members
// public void Add(TKey key, TValue value)
// {
// myKey = key;
// myValue = value;
// }
// public bool ContainsKey(TKey key)
// {
// return myKey.Equals(key);
// }
// public ICollection<TKey> Keys
// {
// get { return new TKey[] { myKey }; }
// }
// public bool Remove(TKey key)
// {
// bool rv = myKey.Equals(key);
// myKey = default(TKey);
// return rv;
// }
// public bool TryGetValue(TKey key, out TValue value)
// {
// bool rv = false;
// value = (rv = myKey.Equals(key)) ? myValue : default(TValue);
// return rv;
// }
// public ICollection<TValue> Values
// {
// get { throw new Exception("The method or operation is not implemented."); }
// }
// public TValue this[TKey key]
// {
// get
// {
// throw new Exception("The method or operation is not implemented.");
// }
// set
// {
// throw new Exception("The method or operation is not implemented.");
// }
// }
// #endregion
// #region ICollection<KeyValuePair<TKey,TValue>> Members
// public void Add(KeyValuePair<TKey, TValue> item)
// {
// throw new Exception("The method or operation is not implemented.");
// }
// public void Clear()
// {
// throw new Exception("The method or operation is not implemented.");
// }
// public bool Contains(KeyValuePair<TKey, TValue> item)
// {
// throw new Exception("The method or operation is not implemented.");
// }
// public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
// {
// throw new Exception("The method or operation is not implemented.");
// }
// public int Count
// {
// get { throw new Exception("The method or operation is not implemented."); }
// }
// public bool IsReadOnly
// {
// get { throw new Exception("The method or operation is not implemented."); }
// }
// public bool Remove(KeyValuePair<TKey, TValue> item)
// {
// throw new Exception("The method or operation is not implemented.");
// }
// #endregion
// #region IEnumerable<KeyValuePair<TKey,TValue>> Members
// public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
// {
// throw new Exception("The method or operation is not implemented.");
// }
// #endregion
// #region IEnumerable Members
// IEnumerator IEnumerable.GetEnumerator()
// {
// throw new Exception("The method or operation is not implemented.");
// }
// #endregion
// }
// #region Helper class to deal with stream projections
// public class JoinProjectHelper
// {
// private IBlueTableSchema mySchema;
// private Dictionary<string, Pair<string, bool>> myAliasToOriginal = new Dictionary<string, Pair<string, bool>>();
// public JoinProjectHelper(IBlueTableSchema leftSchema,
// string leftProj,
// string leftJoinCol,
// IBlueTableSchema rightSchema,
// string rightProj,
// string rightJoinCol)
// {
// JoinTableSchema joinedSchema = new JoinTableSchema(leftSchema, leftJoinCol, rightSchema, rightJoinCol);
// JoinNameResolver resolver = new JoinNameResolver(joinedSchema, leftSchema, leftProj, rightSchema, rightProj);
// IDictionary map = resolver.getMap();
// map["id"] = "id";
// ProjectHelper helper = new ProjectHelper(joinedSchema, ProjectHelper.invertDic(map),
// String.Format("({0} J {1})", leftSchema.tableName, rightSchema.tableName));
// mySchema = helper.schema;
// for (int aliasCol = 0; aliasCol < helper.colMap.Length; aliasCol++)
// {
// string aliasColName = mySchema[aliasCol].colName;
// if (aliasColName != "id")
// {
// int joinedColIndex = helper.colMap[aliasCol];
// bool isLeft = joinedColIndex < leftSchema.columnInfo.Length;
// string originalCol = joinedSchema.getOriginalName(joinedSchema[joinedColIndex].colName, isLeft);
// myAliasToOriginal.Add(aliasColName, new Pair<string, bool>(originalCol, isLeft));
// }
// }
// }
// public IBlueTableSchema schema
// {
// get { return mySchema; }
// }
// public string getOriginalCol(string col, out bool isLeft)
// {
// Pair<string, bool> p = myAliasToOriginal[col];
// isLeft = p.second;
// return p.first;
// }
// }
// #endregion
// #region IBlueRow implementation for join and leftJoin
// public class SuperJoinRow : IBlueRow
// {
// private JoinProjectHelper myHelper;
// private IBlueRow myLeftRow, myRightRow;
// int myID;
// public SuperJoinRow(int id, IBlueRow leftRow, IBlueRow rightRow, JoinProjectHelper joinProjectHelper)
// {
// myID = id;
// myLeftRow = leftRow;
// myRightRow = rightRow;
// myHelper = joinProjectHelper;
// }
// public int leftID { get { return (int)myLeftRow["id"]; } }
// public int rightID { get { return (int)myRightRow["id"]; } }
// public IBlueRow leftRow { get { return myLeftRow; } }
// public IBlueRow rightRow { get { return myRightRow; } }
// #region IBlueRow Members
// public IBlueTableSchema schema { get { return myHelper.schema; } }
// public object this[int index] { get { return this[schema[index].colName]; } }
// public object this[string colName]
// {
// get
// {
// if (colName == "id")
// return myID;
// else
// {
// bool isLeft;
// string col = myHelper.getOriginalCol(colName, out isLeft);
// return isLeft ? myLeftRow[col] : (myRightRow == null ? (object)DBNull.Value : myRightRow[col]);
// }
// }
// }
// #endregion
// #region IDictionary Members
// public void Add(object key, object value) { { throw new NotSupportedException("IBlueRow is readonly"); } }
// public void Clear() { throw new NotSupportedException("IBlueRow is readonly"); }
// public bool Contains(object key)
// {
// return myLeftRow.Contains(key) || myRightRow.Contains(key);
// }
// public System.Collections.IDictionaryEnumerator GetEnumerator() { return new BlueRowDictionaryEnumerator(this); }
// public bool IsFixedSize { get { return true; } }
// public bool IsReadOnly { get { return true; } }
// public System.Collections.ICollection Keys { get { return schema.columnNames; } }
// public void Remove(object key) { throw new NotSupportedException("IBlueRow is readonly"); }
// public System.Collections.ICollection Values
// {
// get
// {
// List<object> rv = new List<object>();
// foreach (string col in Keys)
// rv.Add(this[col]);
// return rv;
// }
// }
// public object this[object key]
// {
// get { return key is string ? this[key.ToString()] : this[(int)key]; }
// set { throw new NotSupportedException("IBlueRow is readonly"); }
// }
// #endregion
// #region ICollection Members
// public void CopyTo(Array array, int index) { Values.CopyTo(array, index); }
// public int Count { get { return schema.columnNames.Length; } }
// public bool IsSynchronized { get { return false; } }
// public object SyncRoot { get { return this; } }
// #endregion
// #region IEnumerable Members
// System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new BlueRowEnumerator(this); }
// #endregion
// }
// #endregion
// /// <summary>
// /// this class is written 3-4 yrs after the original
// /// join, and learning from the past mistakes, is
// /// made super fast and mem efficent
// /// </summary>
// public class SuperJoinStream : ViewStream
// {
// protected Dictionary<int, IBlueRow> myLeftUnmatchedRowsAdds = new Dictionary<int, IBlueRow>(),
// myLeftUnmatchedRowsDels = new Dictionary<int, IBlueRow>();
// private bool myManageUnmappedLeftRows = false;
// protected HighPerformanceTimer myTimer = new HighPerformanceTimer();
// protected string myLeftProj = String.Empty, myRightProj = String.Empty;
// protected IBlueTableSchema myLeftSchema, myRightSchema;
// protected JoinProjectHelper myJoinProjectHelper;
// protected BlueTable myState;
// protected int myID;
// protected ViewStream myLeftStream, myRightStream;
// protected string myLeftKeyCol, myRightKeyCol;
// protected Dictionary<object, IDictionary<int, IBlueRow>> myLeftKeyToLeftRows = new Dictionary<object, IDictionary<int, IBlueRow>>(),
// myRightKeyToRightRows = new Dictionary<object, IDictionary<int, IBlueRow>>();
// protected Dictionary<int, IDictionary<int, SuperJoinRow>> myLeftIDToResultRows = new Dictionary<int, IDictionary<int, SuperJoinRow>>(),
// myRightIDToResultRows = new Dictionary<int, IDictionary<int, SuperJoinRow>>();
// public SuperJoinStream(ViewStream leftStream, string leftKey, ViewStream rightStream, string rightKey)
// : this(leftStream, leftKey, "!", rightStream, rightKey, "!")
// { }
// public SuperJoinStream(ViewStream leftStream, string leftKey, string leftProj,
// ViewStream rightStream, string rightKey, string rightProj)
// : this(leftStream, leftKey, leftProj, rightStream, rightKey, rightProj, false)
// {
// }
// internal SuperJoinStream(ViewStream leftStream, string leftKey, string leftProj,
// ViewStream rightStream, string rightKey, string rightProj, bool manageUnmappedLeftRows)
// {
// myLeftStream = leftStream;
// myRightStream = rightStream;
// myLeftKeyCol = leftKey;
// myRightKeyCol = rightKey;
// myLeftProj = leftProj;
// myRightProj = rightProj;
// myManageUnmappedLeftRows = manageUnmappedLeftRows;
// }
// protected override void myOnFirstSubscriber()
// {
// myLeftStream.onChange += new ChangeDelegate(myHandleLeftStreamChanges);
// myRightStream.onChange += new ChangeDelegate(myHandleRightStreamChanges);
// }
// protected override void myOnLastSubscriber()
// {
// myLeftStream.onChange -= new ChangeDelegate(myHandleLeftStreamChanges);
// myRightStream.onChange -= new ChangeDelegate(myHandleRightStreamChanges);
// myLeftKeyToLeftRows.Clear();
// myRightKeyToRightRows.Clear();
// myLeftIDToResultRows.Clear();
// myRightIDToResultRows.Clear();
// myState = null;
// myLeftSchema = null;
// myRightSchema = null;
// }
// private void myHandleLeftStreamChanges(object newValue)
// {
// myHandleStreamChanges(newValue as DataPacket, true);
// }
// private void myHandleRightStreamChanges(object newValue)
// {
// myHandleStreamChanges(newValue as DataPacket, false);
// }
// private void myHandleStreamChanges(DataPacket dp, bool isLeft)
// {
// myTimer.start();
// myInitSchema(dp.schema, isLeft);
// BlueTable dels = null, adds = null;
// if (myState != null)
// {
// dels = new BlueTable(myState.schema);
// adds = new BlueTable(myState.schema);
// }
// myDeleteRows(dp.deletedRows, isLeft, myState, dels);
// myAddRows(dp.addedRows, isLeft, myState, adds);
// myTimer.stop();
// if (myState != null)
// {
// myFireEvent(new DataPacket(myState, adds, dels));
// myLeftUnmatchedRowsAdds.Clear();
// myLeftUnmatchedRowsDels.Clear();
// }
// }
// private void myInitSchema(IBlueTableSchema schema, bool isLeft)
// {
// if (myState == null)
// {
// if (isLeft)
// {
// myLeftSchema = schema;
// if (myRightSchema != null)
// {
// myJoinProjectHelper = new JoinProjectHelper(myLeftSchema, myLeftProj, myLeftKeyCol,
// myRightSchema, myRightProj, myRightKeyCol);
// myState = new BlueTable(myJoinProjectHelper.schema);
// }
// }
// else
// {
// myRightSchema = schema;
// if (myLeftSchema != null)
// {
// myJoinProjectHelper = new JoinProjectHelper(myLeftSchema, myLeftProj, myLeftKeyCol,
// myRightSchema, myRightProj, myRightKeyCol);
// myState = new BlueTable(myJoinProjectHelper.schema);
// }
// }
// }
// }
// private void myAddRows(IBlueRowCollection addedRows, bool isLeft, BlueTable state, BlueTable addedRowsOut)
// {
// object thisKeyCol = isLeft ? myLeftKeyCol : myRightKeyCol,
// otherSideKeyCol = isLeft ? myRightKeyCol : myLeftKeyCol;
// Dictionary<object, IDictionary<int, IBlueRow>> thisKeyToRows = isLeft ? myLeftKeyToLeftRows : myRightKeyToRightRows,
// otherSideKeyToRows = isLeft ? myRightKeyToRightRows : myLeftKeyToLeftRows;
// Dictionary<int, IDictionary<int, SuperJoinRow>> thisIDToResultRows = isLeft ? myLeftIDToResultRows : myRightIDToResultRows,
// otherIDToResultRows = isLeft ? myRightIDToResultRows : myLeftIDToResultRows;
// foreach (IBlueRow r in addedRows)
// {
// object currentKey = r[thisKeyCol];
// int currentID = (int)r["id"];
// ///add it to 1.
// if (!thisKeyToRows.ContainsKey(currentKey))
// thisKeyToRows.Add(currentKey, new Dictionary<int, IBlueRow>());
// thisKeyToRows[currentKey].Add(currentID, r);
// ///find matching rows, and form result rows
// if (otherSideKeyToRows.ContainsKey(currentKey))
// {
// ICollection<IBlueRow> matchingRows = otherSideKeyToRows[currentKey].Values;
// foreach (IBlueRow mr in matchingRows)
// {
// int mrID = (int)mr["id"];
// SuperJoinRow rr = new SuperJoinRow(myID++, isLeft ? r : mr, isLeft ? mr : r, myJoinProjectHelper);
// state.addRow(rr);
// addedRowsOut.addRow(rr);
// ///add to 3.
// if (!thisIDToResultRows.ContainsKey(currentID))
// thisIDToResultRows.Add(currentID, new Dictionary<int, SuperJoinRow>());
// thisIDToResultRows[currentID].Add((int)rr["id"], rr);
// ///add to 4.
// if (!otherIDToResultRows.ContainsKey(mrID))
// {
// otherIDToResultRows.Add(mrID, new Dictionary<int, SuperJoinRow>());
// if (myManageUnmappedLeftRows && !isLeft)
// myTakeCareOfUnmatachedLeftRows(mr, false);
// }
// otherIDToResultRows[mrID].Add((int)rr["id"], rr);
// }
// }
// else
// {
// if (myManageUnmappedLeftRows && isLeft)
// myTakeCareOfUnmatachedLeftRows(r, true);
// }
// }
// }
// private void myDeleteRows(IBlueRowCollection deletedRows, bool isLeft, BlueTable state, BlueTable delRowsOut)
// {
// string thisKeyCol = isLeft ? myLeftKeyCol : myRightKeyCol,
// otherSideKeyCol = isLeft ? myRightKeyCol : myLeftKeyCol;
// Dictionary<object, IDictionary<int, IBlueRow>> thisKeyToRows = isLeft ? myLeftKeyToLeftRows : myRightKeyToRightRows,
// otherSideKeyToRows = isLeft ? myRightKeyToRightRows : myLeftKeyToLeftRows;
// Dictionary<int, IDictionary<int, SuperJoinRow>> thisIDToResultRows = isLeft ? myLeftIDToResultRows : myRightIDToResultRows,
// otherIDToResultRows = isLeft ? myRightIDToResultRows : myLeftIDToResultRows;
// foreach (IBlueRow r in deletedRows)
// {
// int id = (int)r["id"];
// object key = r[thisKeyCol];
// ///delete it from 1.
// thisKeyToRows[key].Remove(id);
// if (thisKeyToRows[key].Count == 0)
// thisKeyToRows.Remove(key);
// ///form return rows and delete from 3.
// if (thisIDToResultRows.ContainsKey(id))
// {
// ICollection removedResultRows = thisIDToResultRows[id].Values as ICollection;
// thisIDToResultRows.Remove(id);
// foreach (SuperJoinRow rr in removedResultRows)
// {
// ///delete from 4.
// int otherId = isLeft ? rr.rightID : rr.leftID;
// otherIDToResultRows[otherId].Remove((int)rr["id"]);
// if (otherIDToResultRows[otherId].Count == 0)
// otherIDToResultRows.Remove(otherId);
// delRowsOut.addRow(rr);
// state.deleteRow(rr);
// if (myManageUnmappedLeftRows && !isLeft)
// if (!thisKeyToRows.ContainsKey(key))
// myTakeCareOfUnmatachedLeftRows(rr.leftRow, true);
// }
// }
// else
// {
// if (myManageUnmappedLeftRows && isLeft)
// myTakeCareOfUnmatachedLeftRows(r, false);
// }
// }
// }
// private void myTakeCareOfUnmatachedLeftRows(IBlueRow leftRow, bool add)
// {
// int lid = (int)leftRow["id"];
// if (add)
// myLeftUnmatchedRowsAdds.Add(lid, leftRow);
// else
// {
// if (myLeftUnmatchedRowsAdds.ContainsKey(lid))
// myLeftUnmatchedRowsAdds.Remove(lid);
// else
// myLeftUnmatchedRowsDels.Add((int)leftRow["id"], leftRow);
// }
// }
// }
// public class SuperLeftJoinStream : SuperJoinStream
// {
// private Dictionary<int, SuperJoinRow> myLeftIDToHalfRows = new Dictionary<int, SuperJoinRow>();
// public SuperLeftJoinStream(ViewStream leftStream, string leftJoinCol,
// ViewStream rightStream, string rightJoinCol)
// : this(leftStream, leftJoinCol, "!", rightStream, rightJoinCol, "!")
// { }
// public SuperLeftJoinStream(ViewStream leftStream, string leftJoinCol, string leftProjExp,
// ViewStream rightStream, string rightJoinCol, string rightProjExp)
// : base(leftStream, leftJoinCol, leftProjExp, rightStream, rightJoinCol, rightProjExp, true)
// { }
// protected override void myFireEvent(object o)
// {
// myHandleJoinResults(myLeftUnmatchedRowsDels, myLeftUnmatchedRowsAdds, o as DataPacket);
// }
// private void myHandleJoinResults(Dictionary<int, IBlueRow> unmatchedLeftRowsDels,
// Dictionary<int, IBlueRow> unmatchedLeftRowAdds, DataPacket resultPacket)
// {
// BlueTable dels = resultPacket.deletedRows as BlueTable,
// adds = resultPacket.addedRows as BlueTable;
// foreach (IBlueRow lr in unmatchedLeftRowsDels.Values)
// {
// ///an lr will be here if its actually deleted or
// ///a right row is added, so now it has a partner
// ///and is no longer unmatched.
// ///in both cases the half row that this lr
// ///created needs to be removed from this
// ///class's state and added to dels
// ///it means a right is added
// int lid = (int)lr["id"];
// SuperJoinRow rr = myLeftIDToHalfRows[lid];
// myLeftIDToHalfRows.Remove(lid);
// myState.deleteRow(rr);
// dels.addRow(rr);
// }
// foreach (IBlueRow lr in unmatchedLeftRowAdds.Values)
// {
// ///an lr will be here if its added with no
// ///matching right, or a right matching row
// ///is gone so it is unmatched now.
// ///in both cases a half row needs to be
// ///added to this class's state and added
// ///to adds
// int lid = (int)lr["id"];
// SuperJoinRow rr = new SuperJoinRow(myID++, lr, null, myJoinProjectHelper);
// myLeftIDToHalfRows.Add(lid, rr);
// myState.addRow(rr);
// adds.addRow(rr);
// }
// base.myFireEvent(new DataPacket(myState, adds, dels));
// }
// }
// }
@@ -0,0 +1,57 @@
// // // using System;
// // // namespace BCG
// // // {
// // // public class KeyBasedAddStream : KeyBasedMathStream
// // // {
// // // public KeyBasedAddStream(ViewStream vs1, ViewStream vs2, string keyCol, string colToAdd)
// // // : base(vs1, vs2, keyCol, colToAdd, (d1, d2) => { return d1 + d2; }) { }
// // // }
// // // public class KeyBasedSubtractStream : KeyBasedMathStream
// // // {
// // // public KeyBasedSubtractStream(ViewStream vs1, ViewStream vs2, string keyCol, string colToSubtract)
// // // : base(vs1, vs2, keyCol, colToSubtract, (d1, d2) => { return d1 - d2; }) { }
// // // }
// // // public class KeyBasedMultiplyStream : KeyBasedMathStream
// // // {
// // // public KeyBasedMultiplyStream(ViewStream vs1, ViewStream vs2, string keyCol, string colToMultiply)
// // // : base(vs1, vs2, keyCol, colToMultiply, (d1, d2) => { return d1 * d2; }) { }
// // // }
// // // public class KeyBasedDivideStream : KeyBasedMathStream
// // // {
// // // public KeyBasedDivideStream(ViewStream vs1, ViewStream vs2, string keyCol, string colToDivide)
// // // : base(vs1, vs2, keyCol, colToDivide, (d1, d2) => { return d1 / d2; }) { }
// // // }
// // // public abstract class KeyBasedMathStream : ViewStream
// // // {
// // // public KeyBasedMathStream(ViewStream first, ViewStream second, string keyColName, string valueColumn, Func<double, double, double> math)
// // // {
// // // ViewStream j;
// // // ViewStream m;
// // // string lValueTempName = "keysbasedmathtempleft"+valueColumn;
// // // string rValueTempName = "keysbasedmathtempright"+valueColumn;
// // // j = new JoinStream (first,
// // // keyColName,
// // // string.Format("!{0}:{1} {2} id", valueColumn, lValueTempName, keyColName),
// // // second,
// // // keyColName,
// // // string.Format("!{0}:{1} id", valueColumn, rValueTempName));
// // // m = new MathStream (j,
// // // string.Format("{0} = {1} - {2}", valueColumn, lValueTempName, rValueTempName));
// // // m = new ProjectStream(m, string.Format("!{0} {1}", lValueTempName, rValueTempName));
// // // mySetRealSource(m);
// // // }
// // // }
// // // }
@@ -0,0 +1,38 @@
// using System;
// namespace BCG
// {
// [DataStreamUserRespresentation (false)]
// public class LeftInternalJoinForeignStream : LeftInternalJoinStream
// {
// public LeftInternalJoinForeignStream (ViewStream vsLeft,
// string jcLeft,
// ViewStream vsRight,
// string jcRight) :
// base (vsLeft, jcLeft, vsRight, jcRight) {}
// public LeftInternalJoinForeignStream (ViewStream vsLeft,
// string jcLeft,
// ViewStream vsRight) :
// this (vsLeft, jcLeft, vsRight, "id") {}
// public override void onTableClear (bool isLeft)
// {
// myLastFiredPacket.deletedRows = myLastFiredPacket.newRows;
// myLastFiredPacket.newRows = new JoinForeignTable (mySchema);
// myLastFiredPacket.addedRows = new BlueTable (mySchema);
// if (!isLeft)
// foreach (IBlueRow row in myLeftDataPacket.newRows)
// ((JoinTable)myLastFiredPacket.newRows).addRow (row, null, myLastFiredPacket);
// }
// protected override void myInitFiredPacket ()
// {
// myLastFiredPacket = new DataPacket ();
// myLastFiredPacket.newRows = new JoinForeignTable (mySchema);
// myLastFiredPacket.addedRows = new BlueTable (mySchema);
// myLastFiredPacket.deletedRows = new BlueTable (mySchema);
// }
// }
// }
@@ -0,0 +1,182 @@
// using System;
// using System.Collections;
// using BCG.Utilities;
// namespace BCG
// {
// /// <summary>
// /// Stream to internally handle Left Joins. The only difference between this and the left Join is the waty the
// /// DataPacket thats fired is initialized.
// /// </summary>
// [DataStreamUserRespresentation (false)]
// public class LeftInternalJoinStream : InternalJoinStream
// {
// protected DataPacket myLeftDataPacket, myRightDataPacket;
// //Container to contain all the left rows that are orphaned during a deletion operation
// private IDictionary myLeftOrphanedRows;
// public LeftInternalJoinStream (ViewStream vsLeft, string jcLeft, ViewStream vsRight, string jcRight) :
// base (vsLeft, jcLeft, vsRight, jcRight) {}
// protected override void myOnFirstSubscriber()
// {
// myLeftOperand.master = this;
// myRightOperand.master = this;
// //the events are not hooked onto the operands delegate, but rather a level of indirection
// //added in the form on myLeftChangeHandler
// myLeftStream.onChange += new DataStream.ChangeDelegate (myLeftChangeHandler);
// myRightStream.onChange += new DataStream.ChangeDelegate (myRightChangeHandler);
// }
// protected override void myOnLastSubscriber ()
// {
// myInit ();
// myLeftStream.onChange -= new DataStream.ChangeDelegate (myLeftChangeHandler);
// myRightStream.onChange -= new DataStream.ChangeDelegate (myRightChangeHandler);
// }
// protected override void myInit()
// {
// base.myInit ();
// myLeftOrphanedRows = null;
// myLeftDataPacket = myRightDataPacket = null;
// }
// private void myLeftChangeHandler (object o)
// {
// myLeftDataPacket = (DataPacket)o;
// myTestAndFire (true);
// }
// private void myRightChangeHandler (object o)
// {
// myRightDataPacket = (DataPacket)o;
// myTestAndFire (false);
// }
// /// <summary>
// /// enforces the order of firing the events, this is to enforce that first the right operand
// /// has data (possibly 0 rows) before we the join is actually calculated => Performance boost
// /// </summary>
// /// <param name="isLeft"></param>
// private void myTestAndFire (bool isLeft)
// {
// JoinOperand jo = isLeft ? myLeftOperand : myRightOperand;
// DataPacket dp = isLeft ? myLeftDataPacket : myRightDataPacket;
// //to test whether both have received call backs
// if (myLeftOperand.hasReceivedData)
// jo.changeHandler (dp);
// else if (myLeftDataPacket != null && myRightDataPacket != null)
// {
// myRightOperand.changeHandler (myRightDataPacket);
// myLeftOperand.changeHandler (myLeftDataPacket);
// }
// }
// /// <summary>
// /// Called by JoinOperand
// /// </summary>
// /// <param name="rows"></param>
// /// <param name="isLeft"></param>
// public override void addRows (IBlueRowCollection rows, bool isLeft)
// {
// foreach (IBlueRow row in rows)
// myAddRow (row, isLeft);
// if (!isLeft)
// foreach (RowNode node in myLeftOrphanedRows.Values)
// ((JoinTable)myLastFiredPacket.newRows).addRow (node.row, null, myLastFiredPacket);
// }
// /// <summary>
// /// called by JoinOperand
// /// </summary>
// /// <param name="rows"></param>
// /// <param name="isLeft"></param>
// public override void deleteRows (IBlueRowCollection rows, bool isLeft)
// {
// myLeftOrphanedRows = new Hashtable ();
// foreach (IBlueRow row in rows)
// myDeleteRow (row, isLeft);
// }
// private void myAddRow (IBlueRow row, bool isLeft)
// {
// if (isLeft)
// {
// myLeftOperand.addRow (row);
// RowList matchedRows = myRightOperand.getMatchingRows (row[myLeftJoinColOrdinal]);
// if (matchedRows.Count == 0)
// ((JoinTable)myLastFiredPacket.newRows).addRow (row, null, myLastFiredPacket);
// else
// foreach (RowNode matchedNode in matchedRows)
// ((JoinTable)myLastFiredPacket.newRows).addRow (row, matchedNode.row, myLastFiredPacket);
// }
// else
// {
// RowList matchedRows = myLeftOperand.getMatchingRows (row[myRightJoinColOrdinal]);
// int rightMatchingRowCount = myRightOperand.getMatchingRows (row[myRightJoinColOrdinal]).Count;
// myRightOperand.addRow (row);
// int newRightMatchingRowCount = myRightOperand.getMatchingRows (row[myRightJoinColOrdinal]).Count;
// if (matchedRows.Count != 0){
// foreach (RowNode matchedNode in matchedRows)
// {
// //if the left rows were orphaned in this transaction (ie in this callback), they should
// //just be removed from the orphanedlist and we dont need to worry about the consistency of
// //the jointable as a new row will replace it
// if (rightMatchingRowCount == 0 && newRightMatchingRowCount > 0)
// {
// if (myLeftOrphanedRows[matchedNode.row["id"]] == null)
// ((JoinTable)myLastFiredPacket.newRows).deleteRow (true, matchedNode.row, myLastFiredPacket);
// else
// myLeftOrphanedRows.Remove (matchedNode.row["id"]);
// }
// //they were orphaned by a previous transaction and hence the orphans need to be
// //removed from the Jointable and the complete row added
// ((JoinTable)myLastFiredPacket.newRows).addRow (matchedNode.row, row, myLastFiredPacket);
// }
// }
// }
// }
// private void myDeleteRow (IBlueRow row, bool isLeft)
// {
// if (isLeft)
// {
// myLeftOperand.deleteRow (row);
// ((JoinTable)myLastFiredPacket.newRows).deleteRow (true, row, myLastFiredPacket);
// }
// else
// {
// RowList matchedRows = myLeftOperand.getMatchingRows (row[myRightJoinColOrdinal]);
// int rightMatchingRowCount = myRightOperand.getMatchingRows (row[myRightJoinColOrdinal]).Count;
// myRightOperand.deleteRow (row);
// int newRightMatchingRowCount = myRightOperand.getMatchingRows (row[myRightJoinColOrdinal]).Count;
// if (matchedRows.Count != 0)
// {
// if (rightMatchingRowCount > 0 && newRightMatchingRowCount == 0)
// //ie all the matchedRows were joined with 'this' right row (method arg), and hence they need to
// //be handled specially, ie joined with nulls, if there are no right rows with this
// //joincolumn value being inserted.
// foreach (RowNode matchedNode in matchedRows)
// {
// // BlueEventLog.logAssert (myLeftOrphanedRows[matchedNode.row["id"]] == null);
// myLeftOrphanedRows[matchedNode.row["id"]] = matchedNode;
// }
// ((JoinTable)myLastFiredPacket.newRows).deleteRow (false, row, myLastFiredPacket);
// }
// }
// }
// public override void onTableClear (bool isLeft)
// {
// myLastFiredPacket.deletedRows = myLastFiredPacket.newRows;
// myLastFiredPacket.newRows = new JoinTable (mySchema);
// myLastFiredPacket.addedRows = new BlueTable (mySchema);
// if (!isLeft)
// foreach (IBlueRow row in myLeftDataPacket.newRows)
// ((JoinTable)myLastFiredPacket.newRows).addRow (row, null, myLastFiredPacket);
// }
// }
// }
Loaded 100 of 437 files, more files were not shown because too many files have changed in this diff. Show more