Here are the examples of the csharp api System.Collections.Generic.Stack.Peek() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1579 Examples
19
Source : MichelineBinaryConverter.cs
with MIT License
from baking-bad
with MIT License
from baking-bad
static IMicheline ReadFlat(BinaryReader reader)
{
Stack<IMicheline> stack = new();
IMicheline node, top;
MichelinePrim prim;
MichelineArray arr;
int tag, cnt, args, annots;
start:
tag = reader.ReadByte();
if (tag >= 0x80)
{
prim = new() { Prim = (PrimType)reader.ReadByte() };
annots = tag & 0x0F;
if (annots > 0)
{
if (annots == 0x0F)
annots = reader.Read7BitInt();
prim.Annots = new(annots);
}
args = (tag & 0x70) >> 4;
if (args > 0)
{
if (args == 0x07)
args = reader.Read7BitInt();
prim.Args = new(args);
stack.Push(prim);
goto start;
}
if (prim.Annots != null)
ReadAnnots(reader, prim);
node = prim;
}
else
{
cnt = tag & 0x1F;
if (cnt == 0x1F) cnt = reader.Read7BitInt();
switch ((MichelineType)(tag & 0xE0))
{
case MichelineType.Array:
node = new MichelineArray(cnt);
if (cnt > 0)
{
stack.Push(node);
goto start;
}
break;
case MichelineType.Bytes:
node = new MichelineBytes(reader.ReadBytes(cnt));
break;
case MichelineType.Int:
node = new MichelineInt(new BigInteger(reader.ReadBytes(cnt)));
break;
case MichelineType.String:
node = new MichelineString(Utf8.Convert(reader.ReadBytes(cnt)));
break;
default:
throw new FormatException("Invalid micheline tag");
}
}
finish:
if (stack.Count == 0) return node;
top = stack.Peek();
if (top is MichelinePrim p)
{
p.Args.Add(node);
if (p.Args.Count < p.Args.Capacity)
goto start;
if (p.Annots != null)
ReadAnnots(reader, p);
}
else
{
arr = (MichelineArray)top;
arr.Add(node);
if (arr.Count < arr.Capacity)
goto start;
}
node = stack.Pop();
goto finish;
}
19
Source : MichelineConverter.cs
with MIT License
from baking-bad
with MIT License
from baking-bad
public override IMicheline Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Stack<IMicheline> stack = new();
IMicheline node, top;
MichelinePrim prim;
string prop;
start:
switch (reader.TokenType)
{
case JsonTokenType.StartObject:
reader.Read();
if (reader.TokenType != JsonTokenType.PropertyName)
throw new FormatException("Empty Micheline node");
prop = reader.GetString();
reader.Read();
switch (prop)
{
case "prim":
stack.Push(new MichelinePrim { Prim = PrimTypeConverter.ParsePrim(reader.GetString()) });
reader.Read();
goto start;
case "args":
stack.Push(new MichelinePrim());
if (reader.TokenType == JsonTokenType.StartArray)
{
reader.Read();
if (reader.TokenType != JsonTokenType.EndArray)
{
stack.Push(new MichelineArray(2));
goto start;
}
}
else if (reader.TokenType != JsonTokenType.Null)
{
throw new FormatException("Invalid prim args");
}
reader.Read();
goto start;
case "annots":
List<IAnnotation> annots = null;
if (reader.TokenType == JsonTokenType.StartArray)
{
reader.Read();
if (reader.TokenType == JsonTokenType.String)
{
annots = new(2);
annots.Add(AnnotationConverter.ParseAnnotation(reader.GetString()));
reader.Read();
while (reader.TokenType == JsonTokenType.String)
{
annots.Add(AnnotationConverter.ParseAnnotation(reader.GetString()));
reader.Read();
}
}
if (reader.TokenType != JsonTokenType.EndArray)
throw new FormatException("Invalid prim annotation");
}
else if (reader.TokenType != JsonTokenType.Null)
{
throw new FormatException("Invalid prim annots");
}
stack.Push(new MichelinePrim { Annots = annots });
reader.Read();
goto start;
case "bytes":
if (reader.TokenType != JsonTokenType.String)
throw new FormatException("Invalid Micheline bytes node");
node = new MichelineBytes(Hex.Parse(reader.GetString()));
break;
case "string":
if (reader.TokenType != JsonTokenType.String)
throw new FormatException("Invalid Micheline string node");
node = new MichelineString(reader.GetString());
break;
case "int":
if (reader.TokenType != JsonTokenType.String)
throw new FormatException("Invalid Micheline int node");
node = new MichelineInt(BigInteger.Parse(reader.GetString()));
break;
default:
throw new FormatException("Invalid Micheline node");
}
reader.Read();
if (reader.TokenType != JsonTokenType.EndObject)
throw new FormatException($"Invalid Micheline {node.Type} node");
goto endNode;
case JsonTokenType.PropertyName:
prim = (MichelinePrim)stack.Peek();
prop = reader.GetString();
reader.Read();
switch (prop)
{
case "prim":
prim.Prim = PrimTypeConverter.ParsePrim(reader.GetString());
reader.Read();
goto start;
case "args":
if (reader.TokenType == JsonTokenType.StartArray)
{
reader.Read();
if (reader.TokenType != JsonTokenType.EndArray)
{
stack.Push(new MichelineArray(2));
goto start;
}
}
else if (reader.TokenType != JsonTokenType.Null)
{
throw new FormatException("Invalid prim args");
}
reader.Read();
goto start;
case "annots":
List<IAnnotation> annots = null;
if (reader.TokenType == JsonTokenType.StartArray)
{
reader.Read();
if (reader.TokenType == JsonTokenType.String)
{
annots = new(2);
annots.Add(AnnotationConverter.ParseAnnotation(reader.GetString()));
reader.Read();
while (reader.TokenType == JsonTokenType.String)
{
annots.Add(AnnotationConverter.ParseAnnotation(reader.GetString()));
reader.Read();
}
}
if (reader.TokenType != JsonTokenType.EndArray)
throw new FormatException("Invalid prim annotation");
}
else if (reader.TokenType != JsonTokenType.Null)
{
throw new FormatException("Invalid prim annots");
}
prim.Annots = annots;
reader.Read();
goto start;
default:
throw new FormatException();
}
case JsonTokenType.EndObject:
node = stack.Pop();
endNode:
if (stack.Count == 0) return node;
((MichelineArray)stack.Peek()).Add(node);
reader.Read();
goto start;
case JsonTokenType.StartArray:
stack.Push(new MichelineArray());
reader.Read();
goto start;
case JsonTokenType.EndArray:
node = stack.Pop();
if (stack.Count == 0) return node;
top = stack.Peek();
if (top is MichelinePrim pr)
pr.Args = (MichelineArray)node;
else
((MichelineArray)top).Add(node);
reader.Read();
goto start;
default:
throw new FormatException("Invalid Micheline format");
}
}
19
Source : PathStack.cs
with MIT License
from bartoszlenar
with MIT License
from bartoszlenar
public void Pop()
{
if (HasIndexes && _indexesLevelsStack.Peek() == Level)
{
_ = _indexesStack.Pop();
_ = _indexesLevelsStack.Pop();
}
_ = _stack.Pop();
Path = _stack.Count > 0 ? _stack.Peek() : string.Empty;
}
19
Source : SimpleJson.cs
with MIT License
from bbepis
with MIT License
from bbepis
public static JSONNode Parse( string aJSON )
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
StringBuilder Token = new StringBuilder();
string TokenName = "";
bool QuoteMode = false;
bool TokenIsQuoted = false;
while( i < aJSON.Length )
{
switch( aJSON[ i ] )
{
case '{':
if( QuoteMode )
{
Token.Append( aJSON[ i ] );
break;
}
stack.Push( new JSONObject() );
if( ctx != null )
{
ctx.Add( TokenName, stack.Peek() );
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '[':
if( QuoteMode )
{
Token.Append( aJSON[ i ] );
break;
}
stack.Push( new JSONArray() );
if( ctx != null )
{
ctx.Add( TokenName, stack.Peek() );
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '}':
case ']':
if( QuoteMode )
{
Token.Append( aJSON[ i ] );
break;
}
if( stack.Count == 0 )
throw new Exception( "JSON Parse: Too many closing brackets" );
stack.Pop();
if( Token.Length > 0 || TokenIsQuoted )
{
ParseElement( ctx, Token.ToString(), TokenName, TokenIsQuoted );
TokenIsQuoted = false;
}
TokenName = "";
Token.Length = 0;
if( stack.Count > 0 )
ctx = stack.Peek();
break;
case ':':
if( QuoteMode )
{
Token.Append( aJSON[ i ] );
break;
}
TokenName = Token.ToString();
Token.Length = 0;
TokenIsQuoted = false;
break;
case '"':
QuoteMode ^= true;
TokenIsQuoted |= QuoteMode;
break;
case ',':
if( QuoteMode )
{
Token.Append( aJSON[ i ] );
break;
}
if( Token.Length > 0 || TokenIsQuoted )
{
ParseElement( ctx, Token.ToString(), TokenName, TokenIsQuoted );
TokenIsQuoted = false;
}
TokenName = "";
Token.Length = 0;
TokenIsQuoted = false;
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if( QuoteMode )
Token.Append( aJSON[ i ] );
break;
case '\\':
++i;
if( QuoteMode )
{
char C = aJSON[ i ];
switch( C )
{
case 't':
Token.Append( '\t' );
break;
case 'r':
Token.Append( '\r' );
break;
case 'n':
Token.Append( '\n' );
break;
case 'b':
Token.Append( '\b' );
break;
case 'f':
Token.Append( '\f' );
break;
case 'u':
{
string s = aJSON.Substring( i + 1, 4 );
Token.Append( (char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier ) );
i += 4;
break;
}
default:
Token.Append( C );
break;
}
}
break;
default:
Token.Append( aJSON[ i ] );
break;
}
++i;
}
if( QuoteMode )
{
throw new Exception( "JSON Parse: Quotation marks seems to be messed up." );
}
return ctx;
}
19
Source : MenuApp.cs
with MIT License
from BEagle1984
with MIT License
from BEagle1984
[SuppressMessage("ReSharper", "SA1009", Justification = "False positive")]
private IMenuItemInfo[] GetOptions()
{
IEnumerable<IMenuItemInfo> options =
_breadcrumbs
.Peek()
.Children
.Select(type => (IMenuItemInfo)Activator.CreateInstance(type)!)
.ToList();
options = _breadcrumbs.Peek() is RootCategory
? options.Append(new ExitMenu())
: options.Append(new BackMenu());
return options.ToArray();
}
19
Source : DocPrinter.cs
with MIT License
from belav
with MIT License
from belav
private void ProcessGroup(Group group, PrintMode mode, Indent indent)
{
if (mode is PrintMode.Flat or PrintMode.ForceFlat && !ShouldRemeasure)
{
Push(group.Contents, group.Break ? PrintMode.Break : PrintMode.Flat, indent);
}
else
{
ShouldRemeasure = false;
var possibleCommand = new PrintCommand(indent, PrintMode.Flat, group.Contents);
if (!group.Break && Fits(possibleCommand))
{
RemainingCommands.Push(possibleCommand);
}
else if (group is ConditionalGroup conditionalGroup)
{
if (group.Break)
{
Push(conditionalGroup.Options.Last(), PrintMode.Break, indent);
}
else
{
var foundSomethingThatFits = false;
foreach (var option in conditionalGroup.Options.Skip(1))
{
possibleCommand = new PrintCommand(indent, mode, option);
if (!Fits(possibleCommand))
{
continue;
}
RemainingCommands.Push(possibleCommand);
foundSomethingThatFits = true;
break;
}
if (!foundSomethingThatFits)
{
RemainingCommands.Push(possibleCommand);
}
}
}
else
{
Push(group.Contents, PrintMode.Break, indent);
}
}
if (group.GroupId != null)
{
GroupModeMap[group.GroupId] = RemainingCommands.Peek().Mode;
}
}
19
Source : PropagateBreaks.cs
with MIT License
from belav
with MIT License
from belav
public static void RunOn(Doc doreplacedent)
{
var alreadyVisitedSet = new HashSet<Group>();
var groupStack = new Stack<Group>();
var forceFlat = 0;
var canSkipBreak = false;
void BreakParentGroup()
{
if (groupStack.Count > 0)
{
var parentGroup = groupStack.Peek();
if (parentGroup is not ConditionalGroup)
{
parentGroup.Break = true;
}
}
}
bool OnEnter(Doc doc)
{
if (doc is ForceFlat)
{
forceFlat++;
}
if (
doc is IBreakParent && (forceFlat == 0 || (forceFlat > 0 && doc is LiteralLine))
)
{
if (doc is HardLine { SkipBreakIfFirstInGroup: true } && canSkipBreak)
{
if (groupStack.Count > 1)
{
var nextGroup = groupStack.Pop();
groupStack.Peek().Break = true;
groupStack.Push(nextGroup);
}
}
else
{
BreakParentGroup();
}
}
19
Source : MenuRoot.cs
with MIT License
from bengreenier
with MIT License
from bengreenier
private IEnumerator OpenAsync_Internal(Menu menu)
{
var top = history.Count == 0 ? null : history.Peek();
if (top != null)
{
yield return CloseMenuAsync(top, leaveVisible: (menu is OverlayMenu));
}
yield return OpenMenuAsync(menu);
history.Push(menu);
}
19
Source : MenuRoot.cs
with MIT License
from bengreenier
with MIT License
from bengreenier
private IEnumerator CloseAsync_Internal()
{
var top = history.Count == 0 ? null : history.Pop();
if (top != null)
{
yield return CloseMenuAsync(top);
}
var newTop = history.Count == 0 ? null : history.Peek();
if (newTop != null)
{
yield return OpenMenuAsync(newTop);
}
}
19
Source : SymbolNameExt.cs
with MIT License
from bert2
with MIT License
from bert2
public static string PopNamespace(this Stack<ISymbol> nameParts) {
if (nameParts.Peek().Kind != SymbolKind.Namespace) return "";
var sb = new StringBuilder(nameParts.Pop().Name, capacity: 100);
while (nameParts.Peek().Kind == SymbolKind.Namespace) {
_ = sb.Append('.').Append(nameParts.Pop().Name);
}
return sb.ToString();
}
19
Source : IfThenEndBlock.cs
with MIT License
from Big-Endian-32
with MIT License
from Big-Endian-32
public override Operation Process(Decompiler d)
{
if (_statements.Count == 1)
{
Statement statement = _statements[0];
if (statement is replacedignment replacedign)
{
if (replacedign.GetArity() == 1)
{
if (_branch is TestNode node)
{
Declaration decl = _r.GetDeclaration(node.Test, node.Line);
if (replacedign.GetFirstTarget().IsDeclaration(decl))
{
Expression expr;
if (node._Invert)
{
expr = new BinaryExpression
(
"or",
new LocalVariable(decl),
replacedign.GetFirstValue(),
Precedence.OR,
replacedociativity.NONE
);
}
else
{
expr = new BinaryExpression
(
"and",
new LocalVariable(decl),
replacedign.GetFirstValue(),
Precedence.AND,
replacedociativity.NONE
);
}
return new OperationAnonymousInnerClreplaced(this, replacedign, expr);
}
}
}
}
}
else if (_statements.Count == 0 && _stack != null)
{
int test = _branch.GetRegister();
if (test < 0)
{
for (int reg = 0; reg < _r._Registers; reg++)
{
if (_r.GetUpdated(reg, _branch.End - 1) >= _branch.Begin)
{
if (test >= 0)
{
test = -1;
break;
}
test = reg;
}
}
}
if (test >= 0)
{
if (_r.GetUpdated(test, _branch.End - 1) >= _branch.Begin)
{
Expression right = _r.GetValue(test, _branch.End);
Branch setb = d.PopSetCondition(_stack, _stack.Peek().End);
setb.UseExpression(right);
int testreg = test;
return new OperationAnonymousInnerClreplaced2(this, setb, testreg);
}
}
}
return base.Process(d);
}
19
Source : CancellationHandlers.cs
with MIT License
from bilal-fazlani
with MIT License
from bilal-fazlani
public static IDisposable IgnoreCtrlC()
{
// in case the feature isn't enabled but this is called.
if (!SourceStack.Any())
{
return DisposableAction.Null;
}
var handler = SourceStack.Peek().GetHandler()!;
handler.ShouldIgnoreCtrlC = true;
return new DisposableAction(() => handler.ShouldIgnoreCtrlC = false);
}
19
Source : CancellationHandlers.cs
with MIT License
from bilal-fazlani
with MIT License
from bilal-fazlani
private static void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
var handler = SourceStack.Peek().GetHandler();
if (handler == null)
{
return;
}
if (!handler.ShouldIgnoreCtrlC)
{
StopRun(handler);
e.Cancel = true;
}
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
public void Back()
{
if (_uiStack.Count <= 1)
return;
if (_dialog == null)
{
var name = _uiStack.Pop();
HideAll(_views[name]);
name = _uiStack.Peek();
ShowAll(_views[name]);
}
else
{
_dialog.Hide();
_dialog = null;
_views[_uiStack.Peek()].Show();
}
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
public void BackToShow()
{
ShowUI<BasicUI>(data.BasicUI);
if (data.OverlayUIStack.Count > 0)
{
data.OverlayUIStack.Peek().UIState = UIStateEnum.SHOW;
}
if (data.TopUIStack.Count > 0)
{
data.TopUIStack.Peek().UIState = UIStateEnum.SHOW;
}
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
private Transform Hide()
{
if (_uiStack.Count != 0)
{
_uiStack.Peek().UiState = UIState.HIDE;
return _uiStack.Peek().transform;
}
return null;
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
public virtual void ShowUI<T>(T id)
{
Transform uiTrans = SpawnUI(id.ToString());
AUIBase ui = uiTrans.GetComponent<AUIBase>();
if (ui == null)
throw new Exception("Can't find AUIBase component");
if (ui.GetLayer() == UILayer.BasicUI)
{
UIHandler newHandler = new UIHandler(ui);
if (uiStack.Count > 0)
{
uiStack.Peek().Hide(ui.GetLayer());
}
AddListener(ui,id.ToString(), newHandler);
newHandler.Show(ui);
uiStack.Push(newHandler);
}
else
{
AddListener(ui,id.ToString(), uiStack.Peek());
uiStack.Peek().Show(ui);
}
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
public void Back()
{
if (!uiStack.Peek().Back() && uiStack.Count > 1)
{
uiStack.Pop().Hide(UILayer.BasicUI);
UIHandler handler = uiStack.Peek();
handler.BackToShow();
}
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
public IView Show(string path)
{
if (_uiStack.Count > 0)
{
var name = _uiStack.Peek();
if (GetLayer(name) >= GetLayer(path))
HideAll(_views[name]);
}
var view = InitView(path);
ShowAll(view);
if (!_skipViews.Contains(path))
_uiStack.Push(path);
_views[path] = view;
return view;
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
private void ShowUI<T>(AUIBase ui, Stack<T> stack = null) where T : AUIBase
{
if (stack != null)
{
if (stack.Count > 0)
{
stack.Peek().UIState = UIStateEnum.HIDE;
}
stack.Push((T)ui);
}
ui.UIState = UIStateEnum.SHOW;
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
private void HideUI<T>(UILayer showLayer, UILayer targetLayer, Stack<T> stack = null) where T : AUIBase
{
if (showLayer <= targetLayer)
{
if (stack != null)
{
if (stack.Count > 0)
{
stack.Peek().UIState = UIStateEnum.HIDE;
}
}
else
{
data.BasicUI.UIState = UIStateEnum.HIDE;
}
}
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
public Tuple<Transform, Transform> Back()
{
if (_uiStack.Count > 1)
{
UIBase hideUI = _uiStack.Pop();
Transform shouUI = null;
if (hideUI.GetUiLayer() == UILayer.BASIC_UI)
{
hideUI.UiState = UIState.HIDE;
_uiStack.Peek().UiState = UIState.SHOW;
shouUI = _uiStack.Peek().transform;
}
else
{
hideUI.UiState = UIState.HIDE;
}
return new Tuple<Transform, Transform>(shouUI, hideUI.transform);
}
else
{
Debug.LogError("uistack has one or no element");
return null;
}
}
19
Source : UIManager.cs
with MIT License
from BlueMonk1107
with MIT License
from BlueMonk1107
public Transform GetCurrentUiTrans()
{
return _uiStack.Peek().transform;
}
19
Source : JsonTokenizer.cs
with MIT License
from bluexo
with MIT License
from bluexo
private void PopContainer()
{
containerStack.Pop();
var parent = containerStack.Peek();
switch (parent)
{
case ContainerType.Object:
state = State.ObjectAfterProperty;
break;
case ContainerType.Array:
state = State.ArrayAfterValue;
break;
case ContainerType.Doreplacedent:
state = State.ExpectedEndOfDoreplacedent;
break;
default:
throw new InvalidOperationException("Unexpected container type: " + parent);
}
}
19
Source : DirectedGraphExtensions.cs
with MIT License
from bonsai-rx
with MIT License
from bonsai-rx
static IEnumerable<Node<TNodeValue, TEdgeLabel>> DepthFirstSearch<TNodeValue, TEdgeLabel>(Node<TNodeValue, TEdgeLabel> node, HashSet<Node<TNodeValue, TEdgeLabel>> visited, Stack<Node<TNodeValue, TEdgeLabel>> stack)
{
if (visited.Contains(node)) yield break;
stack.Push(node);
while (stack.Count > 0)
{
var current = stack.Peek();
if (!visited.Contains(current))
{
visited.Add(current);
for (int i = current.Successors.Count - 1; i >= 0; i--)
{
if (visited.Contains(current.Successors[i].Target)) continue;
stack.Push(current.Successors[i].Target);
}
}
else yield return stack.Pop();
}
}
19
Source : Message.cs
with MIT License
from bonsai-rx
with MIT License
from bonsai-rx
public IEnumerable GetContents()
{
var chars = TypeTag.ToArray();
var activeArrays = new Stack<ArrayList>();
using (var reader = new BigEndianReader(GetContentStream()))
{
for (int i = 1; i < chars.Length; i++)
{
object content;
switch (chars[i])
{
case Osc.TypeTag.Int32:
content = reader.ReadInt32();
break;
case Osc.TypeTag.Float:
content = reader.ReadSingle();
break;
case Osc.TypeTag.String:
case Osc.TypeTag.Alternate:
content = MessageParser.ReadString(reader);
break;
case Osc.TypeTag.Blob:
content = MessageParser.ReadBlob(reader);
break;
case Osc.TypeTag.Int64:
content = reader.ReadInt64();
break;
case Osc.TypeTag.TimeTag:
content = MessageParser.ReadTimeTag(reader);
break;
case Osc.TypeTag.Double:
content = reader.ReadDouble();
break;
case Osc.TypeTag.Char:
content = MessageParser.ReadChar(reader);
break;
case Osc.TypeTag.True:
content = true;
break;
case Osc.TypeTag.False:
content = false;
break;
case Osc.TypeTag.Infinitum:
content = float.PositiveInfinity;
break;
case Osc.TypeTag.ArrayBegin:
activeArrays.Push(new ArrayList());
continue;
case Osc.TypeTag.ArrayEnd:
var array = activeArrays.Pop();
content = array.ToArray();
break;
default:
case Osc.TypeTag.Nil:
content = null;
break;
}
if (activeArrays.Count > 0)
{
var array = activeArrays.Peek();
array.Add(content);
}
else yield return content;
}
}
}
19
Source : Ac4PatternModelConstraint.cs
with MIT License
from BorisTheBrave
with MIT License
from BorisTheBrave
public void UndoBan(int index, int pattern)
{
// Undo what was done in DoBan
// First restore compatible for this cell
// As it is set a negative value in InteralBan
for (var d = 0; d < directionsCount; d++)
{
compatible[index, pattern, d] += patternCount;
}
// As we always Undo in reverse order, if item is in toPropagate, it'll
// be at the top of the stack.
// If item is in toPropagate, then we haven't got round to processing yet, so there's nothing to undo.
if (toPropagate.Count > 0)
{
var top = toPropagate.Peek();
if(top.Index == index && top.Pattern == pattern)
{
toPropagate.Pop();
return;
}
}
// Not in toPropagate, therefore undo what was done in Propagate
for (var d = 0; d < directionsCount; d++)
{
if (!topology.TryMove(index, (Direction)d, out var i2, out var id, out var el))
{
continue;
}
var patterns = propagatorArray[pattern][(int)el];
foreach (var p in patterns)
{
++compatible[i2, p, (int)id];
}
}
}
19
Source : OneStepPatternModelConstraint.cs
with MIT License
from BorisTheBrave
with MIT License
from BorisTheBrave
public void UndoBan(int index, int pattern)
{
// As we always Undo in reverse order, if item is in toPropagate, it'll
// be at the top of the stack.
// If item is in toPropagate, then we haven't got round to processing yet, so there's nothing to undo.
if (toPropagate.Count > 0)
{
var top = toPropagate.Peek();
if (top.Index == index && top.Pattern == pattern)
{
toPropagate.Pop();
return;
}
}
}
19
Source : EnumerableExtensions.cs
with MIT License
from BotBuilderCommunity
with MIT License
from BotBuilderCommunity
private static IEnumerable<T> SelectRecursiveIterator<T>(IEnumerable<T> source, Func<T, IEnumerable<T>> getChildren)
{
var stack = new Stack<IEnumerator<T>>();
try
{
stack.Push(source.GetEnumerator());
while (0 != stack.Count)
{
var iter = stack.Peek();
if (iter.MoveNext())
{
T current = iter.Current;
yield return current;
var children = getChildren(current);
if (null != children) stack.Push(children.GetEnumerator());
}
else
{
iter.Dispose();
stack.Pop();
}
}
}
finally
{
while (0 != stack.Count)
{
stack.Pop().Dispose();
}
}
}
19
Source : Infection.cs
with MIT License
from Bozar
with MIT License
from Bozar
private void ChooseInfection()
{
bool repeat;
InfectionTag newInfection;
InfectionTag[] candidates = new InfectionTag[]
{ InfectionTag.Mutated, InfectionTag.Slow, InfectionTag.Weak };
// The same infection should not appear 3 times (maxRepeat) in a row.
do
{
newInfection = candidates[random.Next(SeedTag.Infection,
0, candidates.Length)];
if (previousInfection.Count == 0)
{
previousInfection.Push(newInfection);
break;
}
else if (previousInfection.Peek() == newInfection)
{
if (previousInfection.Count < maxRepeat)
{
previousInfection.Push(newInfection);
break;
}
else
{
repeat = true;
}
}
else
{
previousInfection = new Stack<InfectionTag>();
previousInfection.Push(newInfection);
break;
}
} while (repeat);
infectionDict[newInfection] = infectionData.Duration;
}
19
Source : PCAutoExplore.cs
with MIT License
from Bozar
with MIT License
from Bozar
public bool IsValidDestination(int[] check)
{
int[] previous = previousPosition.Peek();
if ((check[0] == previous[0]) && (check[1] == previous[1]))
{
countAutoExplore = 0;
modeline.PrintStaticText(text.GetStringData(node, "Manual"));
return false;
}
previousPosition.Push(coord.Convert(transform.position));
return true;
}
19
Source : TCP2_ExpressionParser.cs
with GNU General Public License v3.0
from brownhci
with GNU General Public License v3.0
from brownhci
public static List<Token> TransformToPolishNotation( List<Token> infixTokenList )
{
var outputQueue = new Queue<Token>();
var stack = new Stack<Token>();
var index = 0;
while (infixTokenList.Count > index)
{
var t = infixTokenList[index];
switch (t.type)
{
case TokenType.LITERAL:
outputQueue.Enqueue(t);
break;
case TokenType.BINARY_OP:
case TokenType.UNARY_OP:
case TokenType.OPEN_PAREN:
stack.Push(t);
break;
case TokenType.CLOSE_PAREN:
while (stack.Peek().type != TokenType.OPEN_PAREN)
{
outputQueue.Enqueue(stack.Pop());
}
stack.Pop();
if (stack.Count > 0 && stack.Peek().type == TokenType.UNARY_OP)
{
outputQueue.Enqueue(stack.Pop());
}
break;
default:
break;
}
index++;
}
while (stack.Count > 0)
{
outputQueue.Enqueue(stack.Pop());
}
var list = new List<Token>(outputQueue);
list.Reverse();
return list;
}
19
Source : TCP2_MaterialInspector_SG.cs
with GNU General Public License v3.0
from brownhci
with GNU General Public License v3.0
from brownhci
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
mMaterialEditor = materialEditor;
#if SHOW_DEFAULT_INSPECTOR
base.OnGUI();
return;
#else
//Header
EditorGUILayout.BeginHorizontal();
var label = (Screen.width > 450f) ? "TOONY COLORS PRO 2 - INSPECTOR (Generated Shader)" : (Screen.width > 300f ? "TOONY COLORS PRO 2 - INSPECTOR" : "TOONY COLORS PRO 2");
TCP2_GUI.HeaderBig(label);
if(TCP2_GUI.Button(TCP2_GUI.CogIcon, "O", "Open in Shader Generator"))
{
if(targetMaterial.shader != null)
{
TCP2_ShaderGenerator.OpenWithShader(targetMaterial.shader);
}
}
EditorGUILayout.EndHorizontal();
TCP2_GUI.Separator();
//Iterate Shader properties
materialEditor.serializedObject.Update();
var mShader = materialEditor.serializedObject.FindProperty("m_Shader");
toggledGroups.Clear();
if(materialEditor.isVisible && !mShader.hasMultipleDifferentValues && mShader.objectReferenceValue != null)
{
//Retina display fix
EditorGUIUtility.labelWidth = TCP2_Utils.ScreenWidthRetina - 120f;
EditorGUIUtility.fieldWidth = 64f;
EditorGUI.BeginChangeCheck();
EditorGUI.indentLevel++;
foreach (var p in properties)
{
var visible = (toggledGroups.Count == 0 || toggledGroups.Peek());
//Hacky way to separate material inspector properties into foldout groups
if(p.name.StartsWith("__BeginGroup"))
{
//Foldout
if(visible)
{
GUILayout.Space(8f);
p.floatValue = EditorGUILayout.Foldout(p.floatValue > 0, p.displayName, TCP2_GUI.FoldoutBold) ? 1 : 0;
}
EditorGUI.indentLevel++;
toggledGroups.Push((p.floatValue > 0) && visible);
}
else if(p.name.StartsWith("__EndGroup"))
{
EditorGUI.indentLevel--;
toggledGroups.Pop();
GUILayout.Space(8f);
}
else
{
//Draw regular property
if(visible && (p.flags & (MaterialProperty.PropFlags.PerRendererData | MaterialProperty.PropFlags.HideInInspector)) == MaterialProperty.PropFlags.None)
mMaterialEditor.ShaderProperty(p, p.displayName);
}
}
EditorGUI.indentLevel--;
if (EditorGUI.EndChangeCheck())
{
materialEditor.PropertiesChanged();
}
}
#endif // !SHOW_DEFAULT_INSPECTOR
#if UNITY_5_5_OR_NEWER
TCP2_GUI.Separator();
materialEditor.RenderQueueField();
#endif
#if UNITY_5_6_OR_NEWER
materialEditor.EnableInstancingField();
#endif
}
19
Source : TCP2_ShaderGenerator.UIFeatures.cs
with GNU General Public License v3.0
from brownhci
with GNU General Public License v3.0
from brownhci
public void DrawGUI(TCP2_Config config)
{
var enabled = Enabled(config);
GUI.enabled = enabled;
var visible = (sHideDisabled && increaseIndent) ? enabled : true;
if(inline)
visible = LastVisible;
visible &= (FoldoutStack.Count > 0) ? FoldoutStack.Peek() : true;
ForceValue(config);
if(customGUI)
{
if(visible || ignoreVisibility)
{
DrawGUI(new Rect(0,0,EditorGUIUtility.currentViewWidth, 0), config);
return;
}
}
else if(visible)
{
//Total line rect
Rect position;
position = inline ? LastPosition : EditorGUILayout.GetControlRect();
if(halfWidth)
{
position.width = (position.width/2f) - 8f;
}
//LastPosition is already halved
if(inline)
{
position.x += position.width + 16f;
}
//Last Position for inlined properties
LastPosition = position;
if(!inline)
{
//Help
if(showHelp)
{
var helpRect = HeaderRect(ref position, 20f);
TCP2_GUI.HelpButton(helpRect, label, string.IsNullOrEmpty(helpTopic) ? label : helpTopic);
}
else
{
HeaderRect(ref position, 20f);
}
//Indent
if(increaseIndent)
{
HeaderRect(ref position, 6f);
}
}
//Label
var guiContent = TempContent((increaseIndent ? "▪ " : "") + label, tooltip);
var labelPosition = HeaderRect(ref position, inline ? (EditorStyles.label.CalcSize(guiContent)).x + 8f : LABEL_WIDTH - position.x);
TCP2_GUI.SubHeader(labelPosition, guiContent, Highlighted(config) && Enabled(config));
//Actual property
DrawGUI(position, config);
LastVisible = visible;
}
GUI.enabled = sGUIEnabled;
}
19
Source : StackMonitor.cs
with MIT License
from bryanperris
with MIT License
from bryanperris
public void PointerUpdate(ulong value)
{
if (m_StackPointers.Count == 0)
{
m_StackPointers.Push(value);
}
else
{
if (value == m_StackPointers.Peek())
{
return;
}
else if (value > m_StackPointers.Peek())
{
m_StackPointers.Push(value);
}
else if (value < m_StackPointers.Peek())
{
while (m_StackPointers.Count > 0 && value < m_StackPointers.Peek())
{
m_StackPointers.Pop();
}
if (m_StackPointers.Count > 0 && value == m_StackPointers.Peek())
{
return;
}
m_StackPointers.Push(value);
}
}
}
19
Source : SimpleJSON.cs
with GNU General Public License v2.0
from Caeden117
with GNU General Public License v2.0
from Caeden117
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
// Used to determine node location (For example: object.childA.childB.node)
Stack<string> locationStack = new Stack<string>();
JSONNode ctx = null;
int i = 0;
StringBuilder Token = new StringBuilder();
string TokenName = "";
bool QuoteMode = false;
bool TokenIsQuoted = false;
bool ValueMode = false;
bool NewLine = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONObject());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
NewLine = false;
ValueMode = false;
break;
case '[':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
NewLine = false;
break;
case '}':
case ']':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (stack.Count == 0)
{
throw new JSONParseException("Too many closing brackets", locationStack, Token.ToString());
}
stack.Pop();
if (locationStack.Any())
{
locationStack.Pop();
}
if (Token.Length > 0 || TokenIsQuoted)
{
ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
}
TokenIsQuoted = false;
NewLine = false;
TokenName = "";
Token.Length = 0;
ValueMode = false;
if (stack.Count > 0)
{
ctx = stack.Peek();
}
break;
case ':':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
TokenName = Token.ToString();
Token.Length = 0;
TokenIsQuoted = false;
ValueMode = true;
NewLine = false;
locationStack.Push(TokenName);
break;
case '"':
QuoteMode ^= true;
// This throws a JSONParseException if one of two conditions are met:
// 1) A new line was detected with no proper closing symbols ("," "]" "}") to say otherwise
// 2) An opening quotation mark is detected when we are already writing a value
if (NewLine || (ValueMode && Token.Length > 0 && QuoteMode))
{
throw new JSONParseException("Node missing a required comma", locationStack, Token.ToString());
}
TokenIsQuoted |= QuoteMode;
break;
case ',':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (Token.Length > 0 || TokenIsQuoted)
{
ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
}
TokenName = "";
Token.Length = 0;
TokenIsQuoted = false;
NewLine = false;
ValueMode = false;
if (locationStack.Any())
{
locationStack.Pop();
}
break;
case '\r':
break;
case '\n':
if (ValueMode && (!string.IsNullOrEmpty(TokenName) || Token.Length > 0))
{
NewLine = true;
}
break;
case ' ':
case '\t':
if (QuoteMode)
{
Token.Append(aJSON[i]);
}
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't':
Token.Append('\t');
break;
case 'r':
Token.Append('\r');
break;
case 'n':
Token.Append('\n');
break;
case 'b':
Token.Append('\b');
break;
case 'f':
Token.Append('\f');
break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token.Append((char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier));
i += 4;
break;
}
default:
Token.Append(C);
break;
}
}
break;
case '/':
if (allowLineComments && !QuoteMode && i + 1 < aJSON.Length && aJSON[i + 1] == '/')
{
while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r')
{
;
}
break;
}
Token.Append(aJSON[i]);
break;
case '\uFEFF': // remove / ignore BOM (Byte Order Mark)
break;
default:
Token.Append(aJSON[i]);
break;
}
++i;
}
if (QuoteMode)
{
throw new JSONParseException("Quotation marks seems to be messed up", locationStack, Token.ToString());
}
if (ctx == null)
{
return ParseElement(Token.ToString(), TokenIsQuoted);
}
return ctx;
}
19
Source : CurrentSectionDisplay.cs
with GNU General Public License v2.0
from Caeden117
with GNU General Public License v2.0
from Caeden117
private void OnTimeChanged()
{
if (isPlaying)
{
if (upcomingBookmarks.Count == 0)
return;
if (upcomingBookmarks.Peek().Data.Time <= atsc.CurrentBeat)
textMesh.text = upcomingBookmarks.Pop().Data.Name;
}
else
{
var lastBookmark = bookmarkManger.bookmarkContainers.FindLast(x => x.Data.Time <= atsc.CurrentBeat);
textMesh.text = lastBookmark != null ? lastBookmark.Data.Name : "";
}
}
19
Source : SimpleJSON.cs
with MIT License
from Caeden117
with MIT License
from Caeden117
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
// Used to determine node location (For example: object.childA.childB.node)
Stack<string> locationStack = new Stack<string>();
JSONNode ctx = null;
int i = 0;
StringBuilder Token = new StringBuilder();
string TokenName = "";
bool QuoteMode = false;
bool TokenIsQuoted = false;
bool ValueMode = false;
bool NewLine = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONObject());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
NewLine = false;
ValueMode = false;
break;
case '[':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
NewLine = false;
break;
case '}':
case ']':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (stack.Count == 0)
throw new JSONParseException("Too many closing brackets", locationStack, Token.ToString());
stack.Pop();
if (locationStack.Any()) locationStack.Pop();
if (Token.Length > 0 || TokenIsQuoted)
ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
TokenIsQuoted = false;
NewLine = false;
TokenName = "";
Token.Length = 0;
ValueMode = false;
if (stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
TokenName = Token.ToString();
Token.Length = 0;
TokenIsQuoted = false;
ValueMode = true;
NewLine = false;
locationStack.Push(TokenName);
break;
case '"':
QuoteMode ^= true;
// This throws a JSONParseException if one of two conditions are met:
// 1) A new line was detected with no proper closing symbols ("," "]" "}") to say otherwise
// 2) An opening quotation mark is detected when we are already writing a value
if (NewLine || (ValueMode && Token.Length > 0 && QuoteMode))
{
throw new JSONParseException("Node missing a required comma", locationStack, Token.ToString());
}
TokenIsQuoted |= QuoteMode;
break;
case ',':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (Token.Length > 0 || TokenIsQuoted)
ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
TokenName = "";
Token.Length = 0;
TokenIsQuoted = false;
NewLine = false;
ValueMode = false;
if (locationStack.Any()) locationStack.Pop();
break;
case '\r':
break;
case '\n':
if (ValueMode && (!string.IsNullOrEmpty(TokenName) || Token.Length > 0))
{
NewLine = true;
}
break;
case ' ':
case '\t':
if (QuoteMode)
Token.Append(aJSON[i]);
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't':
Token.Append('\t');
break;
case 'r':
Token.Append('\r');
break;
case 'n':
Token.Append('\n');
break;
case 'b':
Token.Append('\b');
break;
case 'f':
Token.Append('\f');
break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token.Append((char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier));
i += 4;
break;
}
default:
Token.Append(C);
break;
}
}
break;
case '/':
if (allowLineComments && !QuoteMode && i + 1 < aJSON.Length && aJSON[i + 1] == '/')
{
while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r') ;
break;
}
Token.Append(aJSON[i]);
break;
case '\uFEFF': // remove / ignore BOM (Byte Order Mark)
break;
default:
Token.Append(aJSON[i]);
break;
}
++i;
}
if (QuoteMode)
{
throw new JSONParseException("Quotation marks seems to be messed up", locationStack, Token.ToString());
}
if (ctx == null)
return ParseElement(Token.ToString(), TokenIsQuoted);
return ctx;
}
19
Source : Log.cs
with MIT License
from CatLib
with MIT License
from CatLib
public static void PushIndent(string indent = " ")
{
_indent.Push(_indent.Peek() + indent);
}
19
Source : RuntimeStack.cs
with MIT License
from CatLib
with MIT License
from CatLib
public StackObject* PopFrame(ref StackFrame frame, StackObject* esp)
{
if (frames.Count > 0 && frames.Peek().BasePointer == frame.BasePointer)
frames.Pop();
else
throw new NotSupportedException();
StackObject* returnVal = esp - 1;
var method = frame.Method;
StackObject* ret = ILIntepreter.Minus(frame.LocalVarPointer, method.ParameterCount);
int mStackBase = frame.ManagedStackBase;
if (method.HasThis)
ret--;
if(method.ReturnType != intepreter.AppDomain.VoidType)
{
*ret = *returnVal;
if(ret->ObjectType == ObjectTypes.Object)
{
ret->Value = mStackBase;
managedStack[mStackBase] = managedStack[returnVal->Value];
mStackBase++;
}
else if(ret->ObjectType == ObjectTypes.ValueTypeObjectReference)
{
StackObject* oriAddr = frame.ValueTypeBasePointer;
RelocateValueType(ret, ref frame.ValueTypeBasePointer, ref mStackBase);
*(long*)&ret->Value = (long)oriAddr;
}
ret++;
}
#if DEBUG && !DISABLE_ILRUNTIME_DEBUG
((List<object>)managedStack).RemoveRange(mStackBase, managedStack.Count - mStackBase);
#else
((UncheckedList<object>)managedStack).RemoveRange(mStackBase, managedStack.Count - mStackBase);
#endif
valueTypePtr = frame.ValueTypeBasePointer;
return ret;
}
19
Source : RuntimeStack.cs
with MIT License
from CatLib
with MIT License
from CatLib
public void InitializeFrame(ILMethod method, StackObject* esp, out StackFrame res)
{
if (esp < pointer || esp >= endOfMemory)
throw new StackOverflowException();
if (frames.Count > 0 && frames.Peek().BasePointer > esp)
throw new StackOverflowException();
res = new StackFrame();
res.LocalVarPointer = esp;
res.Method = method;
#if DEBUG && !DISABLE_ILRUNTIME_DEBUG
res.Address = new IntegerReference();
for (int i = 0; i < method.LocalVariableCount; i++)
{
var p = Add(esp, i);
p->ObjectType = ObjectTypes.Null;
}
#endif
res.BasePointer = method.LocalVariableCount > 0 ? Add(esp, method.LocalVariableCount) : esp;
res.ManagedStackBase = managedStack.Count;
res.ValueTypeBasePointer = valueTypePtr;
//frames.Push(res);
}
19
Source : Router.cs
with MIT License
from CatLib
with MIT License
from CatLib
private IRoute RegisterRoute(string uris, RouteAction action)
{
uris = GuardUri(uris);
var uri = new Uri(uris);
if (!schemes.ContainsKey(uri.Scheme))
{
MakeScheme(uri.Scheme);
}
var route = MakeRoute(uri, action);
schemes[uri.Scheme].AddRoute(route);
if (routeGroupStack.Count > 0)
{
routeGroupStack.Peek().AddRoute(route);
}
return route;
}
19
Source : Router.cs
with MIT License
from CatLib
with MIT License
from CatLib
private void EnvironmentPreparation(Route route, Request request, Response response, bool isRollback)
{
if (!isRollback)
{
routeStack.Push(route);
responseStack.Push(response);
requestStack.Push(request);
request.SetRoute(route);
container.Instance(container.Type2Service(typeof(IRequest)), request);
container.Instance(container.Type2Service(typeof(IResponse)), response);
}
else
{
routeStack.Pop();
requestStack.Pop();
responseStack.Pop();
container.Instance(container.Type2Service(typeof(IResponse)),
responseStack.Count > 0 ? responseStack.Peek() : null);
container.Instance(container.Type2Service(typeof(IRequest)),
requestStack.Count > 0 ? requestStack.Peek() : null);
}
}
19
Source : RedisArrayAggregator.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
protected internal override void Decode(IChannelHandlerContext context, IRedisMessage message, List<object> output)
{
if (message is ArrayHeaderRedisMessage)
{
message = this.DecodeRedisArrayHeader((ArrayHeaderRedisMessage)message);
if (message == null)
{
return;
}
}
else
{
ReferenceCountUtil.Retain(message);
}
while (this.depths.Count > 0)
{
AggregateState current = this.depths.Peek();
current.Children.Add(message);
// if current aggregation completed, go to parent aggregation.
if (current.Children.Count == current.Length)
{
message = new ArrayRedisMessage(current.Children);
this.depths.Pop();
}
else
{
// not aggregated yet. try next time.
return;
}
}
output.Add(message);
}
19
Source : CSharpCodeGen.cs
with MIT License
from CefNet
with MIT License
from CefNet
private void GenerateTypeCode(CodeType typeDecl)
{
foreach (CodeComment commentDecl in typeDecl.Comments)
{
GenerateCommentCode(commentDecl);
}
WriteCustomAttributes(typeDecl.CustomAttributes);
WriteAttributes(typeDecl.Attributes);
if (typeDecl is CodeStruct)
{
Output.Write("struct ");
}
else if (typeDecl is CodeEnum)
{
Output.Write("enum ");
}
else if (typeDecl is CodeClreplaced)
{
Output.Write("clreplaced ");
}
Output.Write(typeDecl.Name);
if (typeDecl.BaseType != null)
{
Output.Write(" : ");
Output.Write(typeDecl.BaseType);
}
WriteBlockStart(CodeGenBlockType.Type);
var defines = new Stack<string>();
bool insertLine = false;
foreach (CodeTypeMember memberDecl in typeDecl.Members)
{
if (insertLine)
Output.WriteLine();
if (memberDecl.LegacyDefine is not null)
{
if (defines.Count == 0 || defines.Peek() != memberDecl.LegacyDefine)
{
if (defines.Count > 0)
{
Output.WriteLine("#endif // " + defines.Pop());
}
defines.Push(memberDecl.LegacyDefine);
Output.Write("#if ");
Output.WriteLine(memberDecl.LegacyDefine);
}
}
else if (defines.Count > 0)
{
Output.WriteLine("#endif // " + defines.Pop());
}
if (memberDecl is CodeType clreplacedDecl)
{
GenerateTypeCode(clreplacedDecl);
}
else if (memberDecl is CodeField fieldDecl)
{
GenerateFieldCode(fieldDecl);
}
else if (memberDecl is CodeMethod methodDecl)
{
GenerateMethodCode(methodDecl);
}
else if (memberDecl is CodeEnumItem itemDecl)
{
GenerateEnumItemCode(itemDecl);
}
else if (memberDecl is CodeDelegate delegateDecl)
{
GenerateDelegateCode(delegateDecl);
}
else if (memberDecl is CodeConstructor ctorDecl)
{
GenerateConstructorCode(ctorDecl);
}
else if (memberDecl is CodeProperty propDecl)
{
GeneratePropertyCode(propDecl);
}
else if (memberDecl is CodeOperator operatorDecl)
{
GenerateOperatorCode(operatorDecl);
}
else if (memberDecl is CodeFinalizer dtorDecl)
{
GenerateFinalizerCode(dtorDecl);
}
insertLine = true;
}
while (defines.Count > 0)
{
Output.WriteLine("#endif // " + defines.Pop());
}
WriteBlockEnd(CodeGenBlockType.Type);
}
19
Source : IEnumeratorAwaitExtensions.cs
with GNU Lesser General Public License v3.0
from ChainSafe
with GNU Lesser General Public License v3.0
from ChainSafe
public IEnumerator Run()
{
while (true)
{
var topWorker = _processStack.Peek();
bool isDone;
try
{
isDone = !topWorker.MoveNext();
}
catch (Exception e)
{
// The IEnumerators we have in the process stack do not tell us the
// actual names of the coroutine methods but it does tell us the objects
// that the IEnumerators are replacedociated with, so we can at least try
// adding that to the exception output
var objectTrace = GenerateObjectTrace(_processStack);
if (objectTrace.Any())
{
_awaiter.Complete(
default(T), new Exception(
GenerateObjectTraceMessage(objectTrace), e));
}
else
{
_awaiter.Complete(default(T), e);
}
yield break;
}
if (isDone)
{
_processStack.Pop();
if (_processStack.Count == 0)
{
_awaiter.Complete((T)topWorker.Current, null);
yield break;
}
}
// We could just yield return nested IEnumerator's here but we choose to do
// our own handling here so that we can catch exceptions in nested coroutines
// instead of just top level coroutine
if (topWorker.Current is IEnumerator)
{
_processStack.Push((IEnumerator)topWorker.Current);
}
else
{
// Return the current value to the unity engine so it can handle things like
// WaitForSeconds, WaitToEndOfFrame, etc.
yield return topWorker.Current;
}
}
}
19
Source : CiscoParser.cs
with Apache License 2.0
from CheckPointSW
with Apache License 2.0
from CheckPointSW
private void ParseCommands(string filename)
{
string[] lines = File.ReadAllLines(filename);
ParsedLines = lines.Count();
var parents = new Stack<Indentation>();
var flatList = new List<CiscoCommand>();
parents.Push(new Indentation(null, 0));
int prevIndentationLevel = 0;
int lineId = 0;
foreach (string line in lines)
{
lineId++;
// Check for an empty line or line with just spaces.
if (line.Trim().Length == 0)
{
continue;
}
// Check for weird stuff
if (line.StartsWith("#") || line.StartsWith("<-"))
{
continue;
}
var command = new CiscoCommand
{
Id = lineId,
Text = line
};
int indentationChange = command.IndentationLevel - prevIndentationLevel;
if (indentationChange > 0)
{
parents.Push(new Indentation(flatList.Last().Id, flatList.Last().IndentationLevel));
}
else if (indentationChange < 0 && parents.Count > 0)
{
parents.Pop();
while ((parents.Count > 0) && (parents.Peek().Spaces > command.IndentationLevel))
{
parents.Pop();
}
}
command.ParentId = (parents.Count > 0) ? parents.Peek().Id : null;
prevIndentationLevel = command.IndentationLevel;
flatList.Add(FindCommand(command));
}
_ciscoCommands = flatList.BuildTree();
CiscoCommand prevCommand = null;
foreach (CiscoCommand command in _ciscoCommands)
{
ParseWithChildren(command, prevCommand);
prevCommand = command;
}
// Remove duplicates
foreach (var ciscoId in _ciscoIds)
{
if (_ciscoAliases.ContainsKey(ciscoId.Key))
{
_ciscoAliases.Remove(ciscoId.Key);
}
}
}
19
Source : UndoHandler.cs
with Apache License 2.0
from Chem4Word
with Apache License 2.0
from Chem4Word
public void EndUndoBlock()
{
string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";
try
{
//WriteTelemetry(module, "Debug", $"TransactionLevel: {_transactionLevel}");
_transactionLevel--;
if (_transactionLevel < 0)
{
_telemetry.Write(module, "Exception", "Attempted to unwind empty undo stack.");
return;
}
//we've concluded a transaction block so terminated it
if (_transactionLevel == 0)
{
if (_undoStack.Peek().Equals(_startBracket))
{
_undoStack.Pop(); //no point in committing an empty block so just remove it
}
else
{
_undoStack.Push(_endBracket);
}
}
//tell the parent viewmodel the command status has changed
_editViewModel.UndoCommand.RaiseCanExecChanged();
_editViewModel.RedoCommand.RaiseCanExecChanged();
}
catch (Exception exception)
{
WriteTelemetryException(module, exception);
}
}
19
Source : CollectVariablesVisitor.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public VisitorAction Enter(
FieldNode node,
ISyntaxNode parent,
IReadOnlyList<object> path,
IReadOnlyList<ISyntaxNode> ancestors)
{
if (_type.Peek().NamedType() is IComplexOutputType complexType
&& complexType.Fields.TryGetField(
node.Name.Value, out IOutputField? field))
{
_field.Push(field);
_type.Push(field.Type);
_action.Push(VisitorAction.Continue);
return VisitorAction.Continue;
}
_action.Push(VisitorAction.Skip);
return VisitorAction.Skip;
}
19
Source : CollectVariablesVisitor.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public VisitorAction Enter(
ArgumentNode node,
ISyntaxNode parent,
IReadOnlyList<object> path,
IReadOnlyList<ISyntaxNode> ancestors)
{
if (_field.Peek().Arguments.TryGetField(
node.Name.Value,
out IInputField? field))
{
_type.Push(field.Type);
_action.Push(VisitorAction.Continue);
return VisitorAction.Continue;
}
_action.Push(VisitorAction.Skip);
return VisitorAction.Skip;
}
See More Examples