Here are the examples of the csharp api System.Collections.Generic.List.GetRange(int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
632 Examples
19
View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
private void WaitForConnectionCallback(IAsyncResult result)
{
if (server == null)
{
return;
}
try
{
server.EndWaitForConnection(result);
}
catch (ObjectDisposedException)
{
return;
}
byte[] replySizeBuffer = new byte[sizeof(int)];
server.ProperRead(replySizeBuffer, 0, replySizeBuffer.Length);
int messageLength = BitConverter.ToInt32(replySizeBuffer, 0);
byte[] messageBytes = new byte[messageLength];
server.ProperRead(messageBytes, 0, messageLength);
List<string> parameters = DecodeMessageBuffer(messageBytes);
if (!TryGetValue(parameters[0], "command=", out string command))
{
throw new InvalidOperationException("The first item must be a command.");
}
if (command.Equals("gmic_qt_get_max_layer_size", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the input mode.");
}
InputMode inputMode = ParseInputMode(mode);
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_get_max_layer_size' received. mode=" + inputMode.ToString());
#endif
string reply = GetMaxLayerSize(inputMode);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_get_cropped_images", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the input mode.");
}
if (!TryGetValue(parameters[2], "croprect=", out string packedCropRect))
{
throw new InvalidOperationException("The third item must be the crop rectangle.");
}
InputMode inputMode = ParseInputMode(mode);
RectangleF cropRect = GetCropRectangle(packedCropRect);
#if DEBUG
System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
"'gmic_qt_get_cropped_images' received. mode={0}, cropRect={1}",
inputMode.ToString(), cropRect.ToString()));
#endif
string reply = PrepareCroppedLayers(inputMode, cropRect);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_output_images", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the output mode.");
}
OutputMode outputMode = ParseOutputMode(mode);
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_output_images' received. mode=" + outputMode.ToString());
#endif
List<string> outputLayers = parameters.GetRange(2, parameters.Count - 2);
string reply = ProcessOutputImage(outputLayers, outputMode);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_release_shared_memory", StringComparison.Ordinal))
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_release_shared_memory' received.");
#endif
for (int i = 0; i < memoryMappedFiles.Count; i++)
{
memoryMappedFiles[i].Dispose();
}
memoryMappedFiles.Clear();
SendMessage(server, "done");
}
else if (command.Equals("gmic_qt_get_max_layer_data_length", StringComparison.Ordinal))
{
// This command is used to prevent images larger than 4GB from being used on a 32-bit version of G'MIC.
// Attempting to map an image that size into memory would cause an integer overflow when casting a 64-bit
// integer to the unsigned 32-bit size_t type.
long maxDataLength = 0;
foreach (GmicLayer layer in layers)
{
maxDataLength = Math.Max(maxDataLength, layer.Surface.Scan0.Length);
}
server.Write(BitConverter.GetBytes(sizeof(long)), 0, 4);
server.Write(BitConverter.GetBytes(maxDataLength), 0, 8);
}
// Wait for the acknowledgment that the client is done reading.
if (server.IsConnected)
{
byte[] doneMessageBuffer = new byte[4];
int bytesRead = 0;
int bytesToRead = doneMessageBuffer.Length;
do
{
int n = server.Read(doneMessageBuffer, bytesRead, bytesToRead);
bytesRead += n;
bytesToRead -= n;
} while (bytesToRead > 0 && server.IsConnected);
}
// Start a new server and wait for the next connection.
server.Dispose();
server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
server.BeginWaitForConnection(WaitForConnectionCallback, null);
}
19
View Source File : PlyHandler.cs
License : MIT License
Project Creator : 3DBear
License : MIT License
Project Creator : 3DBear
private static PlyResult ParseAscii(List<string> plyFile, PlyHeader header)
{
var vertices = new List<Vector3>();
var triangles = new List<int>();
var colors = new List<Color>();
var headerEndIndex = plyFile.IndexOf("end_header");
var vertexStartIndex = headerEndIndex + 1;
var faceStartIndex = vertexStartIndex + header.VertexCount + 1;
plyFile.GetRange(vertexStartIndex, header.VertexCount).ForEach(vertex =>
{
var xyzrgb = vertex.Split(' ');
vertices.Add(ParseVertex(xyzrgb, header));
colors.Add(ParseColor(xyzrgb, header));
});
plyFile.GetRange(faceStartIndex, header.FaceCount).ForEach(face =>
{
triangles.AddRange(GetTriangles(face, header));
});
return new PlyResult(vertices, triangles, colors);
}
19
View Source File : PlyHandler.cs
License : MIT License
Project Creator : 3DBear
License : MIT License
Project Creator : 3DBear
private static List<int> GetTriangles(string faceVertexList, PlyHeader header)
{
switch (header.FaceParseMode)
{
case PlyFaceParseMode.VertexCountVertexIndex:
var split = faceVertexList.Split(' ');
var count = Convert.ToInt32(split.First());
switch (count)
{
case 3: // triangle
return split.ToList().GetRange(1, 3).Select(x => Convert.ToInt32(x)).ToList();
case 4: // face
var triangles = new List<int>();
var indices = split.ToList().GetRange(1, 4).Select(x => Convert.ToInt32(x)).ToList();
triangles.AddRange(QuadToTriangles(indices));
return triangles;
default:
Debug.LogWarning("Warning: Found a face with more than 4 vertices, skipping...");
return new List<int>();
}
default:
Debug.LogWarning("Ply GetTriangles: Unknown parse mode");
return new List<int>();
}
}
19
View Source File : ExternalCommunicator.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void UpdateActions()
{
// TO MODIFY --------------------------------------------
sender.Send(Encoding.ASCII.GetBytes("STEPPING"));
string a = Receive();
AgentMessage agentMessage = JsonConvert.DeserializeObject<AgentMessage>(a);
foreach (Brain brain in brains)
{
if (brain.brainType == BrainType.External)
{
string brainName = brain.gameObject.name;
Dictionary<int, float[]> actionDict = new Dictionary<int, float[]>();
for (int i = 0; i < current_agents[brainName].Count; i++)
{
if (brain.brainParameters.actionSpaceType == StateType.continuous)
{
actionDict.Add(current_agents[brainName][i],
agentMessage.action[brainName].GetRange(i * brain.brainParameters.actionSize, brain.brainParameters.actionSize).ToArray());
}
else
{
actionDict.Add(current_agents[brainName][i],
agentMessage.action[brainName].GetRange(i, 1).ToArray());
}
}
storedActions[brainName] = actionDict;
Dictionary<int, float[]> memoryDict = new Dictionary<int, float[]>();
for (int i = 0; i < current_agents[brainName].Count; i++)
{
memoryDict.Add(current_agents[brainName][i],
agentMessage.memory[brainName].GetRange(i * brain.brainParameters.memorySize, brain.brainParameters.memorySize).ToArray());
}
storedMemories[brainName] = memoryDict;
Dictionary<int, float> valueDict = new Dictionary<int, float>();
for (int i = 0; i < current_agents[brainName].Count; i++)
{
valueDict.Add(current_agents[brainName][i],
agentMessage.value[brainName][i]);
}
storedValues[brainName] = valueDict;
}
}
}
19
View Source File : ExternalCommunicator.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void UpdateActions()
{
// TO MODIFY --------------------------------------------
sender.Send(Encoding.ASCII.GetBytes("STEPPING"));
string a = Receive();
AgentMessage agentMessage = JsonConvert.DeserializeObject<AgentMessage>(a);
foreach (Brain brain in brains)
{
if (brain.brainType == BrainType.External)
{
string brainName = brain.gameObject.name;
Dictionary<int, float[]> actionDict = new Dictionary<int, float[]>();
for (int i = 0; i < current_agents[brainName].Count; i++)
{
if (brain.brainParameters.actionSpaceType == StateType.continuous)
{
actionDict.Add(current_agents[brainName][i],
agentMessage.action[brainName].GetRange(i * brain.brainParameters.actionSize, brain.brainParameters.actionSize).ToArray());
}
else
{
actionDict.Add(current_agents[brainName][i],
agentMessage.action[brainName].GetRange(i, 1).ToArray());
}
}
storedActions[brainName] = actionDict;
Dictionary<int, float[]> memoryDict = new Dictionary<int, float[]>();
for (int i = 0; i < current_agents[brainName].Count; i++)
{
memoryDict.Add(current_agents[brainName][i],
agentMessage.memory[brainName].GetRange(i * brain.brainParameters.memorySize, brain.brainParameters.memorySize).ToArray());
}
storedMemories[brainName] = memoryDict;
Dictionary<int, float> valueDict = new Dictionary<int, float>();
for (int i = 0; i < current_agents[brainName].Count; i++)
{
valueDict.Add(current_agents[brainName][i],
agentMessage.value[brainName][i]);
}
storedValues[brainName] = valueDict;
}
}
}
19
View Source File : GenericExtensions.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
public static List<T> ShiftLeft<T>(this List<T> list, int shiftBy) {
if (list.Count <= shiftBy) {
return list;
}
var result = list.GetRange(shiftBy, list.Count - shiftBy);
result.AddRange(list.GetRange(0, shiftBy));
return result;
}
19
View Source File : GenericExtensions.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
public static List<T> ShiftRight<T>(this List<T> list, int shiftBy) {
if (list.Count <= shiftBy) {
return list;
}
var result = list.GetRange(list.Count - shiftBy, shiftBy);
result.AddRange(list.GetRange(0, list.Count - shiftBy));
return result;
}
19
View Source File : GroupVoiceCallSample.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void Update() {
foreach (var output in agent.PeerOutputs) {
if (peerViews.ContainsKey(output.Key)) {
/*
* This is an inefficient way of showing a part of the
* audio source spectrum. AudioSource.GetSpectrumData returns
* frequency values up to 24000 Hz in some cases. Most human
* speech is no more than 5000 Hz. Showing the entire spectrum
* will therefore lead to a spectrum where much of it doesn't
* change. So we take only the spectrum frequencies between
* the average human vocal range.
*
* Great source of information here:
* http://answers.unity.com/answers/158800/view.html
*/
var size = 512;
var minVocalFrequency = 50;
var maxVocalFrequency = 8000;
var sampleRate = AudioSettings.outputSampleRate;
var frequencyResolution = sampleRate / 2 / size;
var audioSource = (output.Value as InbuiltAudioOutput).AudioSource;
var spectrumData = new float[size];
audioSource.GetSpectrumData(spectrumData, 0, FFTWindow.BlackmanHarris);
var indices = Enumerable.Range(0, size - 1).ToList();
var minVocalFrequencyIndex = indices.Min(x => (Mathf.Abs(x * frequencyResolution - minVocalFrequency), x)).x;
var maxVocalFrequencyIndex = indices.Min(x => (Mathf.Abs(x * frequencyResolution - maxVocalFrequency), x)).x;
var indexRange = maxVocalFrequencyIndex - minVocalFrequency;
spectrumData = spectrumData.Select(x => 1000 * x)
.ToList()
.GetRange(minVocalFrequency, indexRange)
.ToArray();
peerViews[output.Key].DisplaySpectrum(spectrumData);
}
}
}
19
View Source File : TransactionGrouper.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private List<Transaction> GetTransactionsToBeGrouped(List<Transaction> transactions,
out GroupedTransactions groupedTransactions)
{
List<Transaction> toBeGrouped;
groupedTransactions = new GroupedTransactions();
if (transactions.Count > _options.MaxTransactions)
{
groupedTransactions.NonParallelizables.AddRange(
transactions.GetRange(_options.MaxTransactions, transactions.Count - _options.MaxTransactions));
toBeGrouped = transactions.GetRange(0, _options.MaxTransactions);
}
else
{
toBeGrouped = transactions;
}
return toBeGrouped;
}
19
View Source File : PointDefinition.cs
License : MIT License
Project Creator : Aeroluna
License : MIT License
Project Creator : Aeroluna
public static PointDefinition ListToPointDefinition(List<object> list)
{
IEnumerable<List<object>> points;
if (list.FirstOrDefault() is List<object>)
{
points = list.Cast<List<object>>();
}
else
{
points = new List<object>[] { list.Append(0).ToList() };
}
List<PointData> pointData = new List<PointData>();
foreach (List<object> rawPoint in points)
{
int flagIndex = -1;
int cachedCount = rawPoint.Count;
for (int i = cachedCount - 1; i > 0; i--)
{
if (rawPoint[i] is string)
{
flagIndex = i;
}
else
{
break;
}
}
Functions easing = Functions.easeLinear;
bool spline = false;
List<object> copiedList = rawPoint.ToList();
if (flagIndex != -1)
{
List<string> flags = rawPoint.GetRange(flagIndex, cachedCount - flagIndex).Cast<string>().ToList();
copiedList.RemoveRange(flagIndex, cachedCount - flagIndex);
string easingString = flags.Where(n => n.StartsWith("ease")).FirstOrDefault();
if (easingString != null)
{
easing = (Functions)Enum.Parse(typeof(Functions), easingString);
}
// TODO: add more spicy splines
string splineString = flags.Where(n => n.StartsWith("spline")).FirstOrDefault();
if (splineString == "splineCatmullRom")
{
spline = true;
}
}
if (copiedList.Count() == 2)
{
Vector2 vector = new Vector2(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]));
pointData.Add(new PointData(vector, easing));
}
else if (copiedList.Count() == 4)
{
Vector4 vector = new Vector4(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]), Convert.ToSingle(copiedList[2]), Convert.ToSingle(copiedList[3]));
pointData.Add(new PointData(vector, easing, spline));
}
else
{
Vector5 vector = new Vector5(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]), Convert.ToSingle(copiedList[2]), Convert.ToSingle(copiedList[3]), Convert.ToSingle(copiedList[4]));
pointData.Add(new PointData(vector, easing));
}
}
return new PointDefinition(pointData);
}
19
View Source File : HeroesResponsiveCollectionView.xaml.cs
License : MIT License
Project Creator : aimore
License : MIT License
Project Creator : aimore
public static IEnumerable<List<T>> SplitList<T>(List<T> locations, int nSize = 30)
{
for (int i = 0; i < locations.Count; i += nSize)
{
yield return locations.GetRange(i, Math.Min(nSize, locations.Count - i));
}
}
19
View Source File : HeroesResponsiveCollectionView.xaml.cs
License : MIT License
Project Creator : aimore
License : MIT License
Project Creator : aimore
public static List<List<T>> SplitList2<T>(this List<T> me, int size = 50)
{
var list = new List<List<T>>();
for (int i = 0; i < me.Count; i += size)
list.Add(me.GetRange(i, Math.Min(size, me.Count - i)));
return list;
}
19
View Source File : PluginsManager.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
public bool LoadPlugins()
{
var newFilesList = new List<string>(Directory.GetFiles(@"./Plugins/", "*.dll"));
var same = true;
if (newFilesList.Count != _plugins.Count)
{
_plugins = new List<string>(newFilesList.GetRange(0, newFilesList.Count));
same = false;
}
if (same && _container != null) return false;
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new replacedemblyCatalog(typeof(Node).replacedembly));
catalog.Catalogs.Add(new DirectoryCatalog(@"./"));
_container = new CompositionContainer(catalog);
try
{
_container.ComposeExportedValue("host", _host);
_container.ComposeExportedValue("bool", false);
_container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
Hub.LoadedExternalNodes = LoadedNodes;
return true;
}
19
View Source File : DialogNodeEditor.cs
License : MIT License
Project Creator : alee12131415
License : MIT License
Project Creator : alee12131415
public string LoadCanvas(string path) {
//SAME AS SAVE CANVAS
try {
//EditorSaveObject load = Resources.Load(path) as EditorSaveObject;
EditorSaveObject load = replacedetDatabase.LoadreplacedetAtPath(path, typeof(EditorSaveObject)) as EditorSaveObject;
//build new CP / Index
List<ConnectionPoint> CPIndex = new List<ConnectionPoint>();
for (int i = 0; i < load.NumberOfCP; i++) {
CPIndex.Add(new ConnectionPoint());
}
//build nodes
int spent = 0; //tracks index of used CP
nodes = new List<Node>();
for (int i = 0; i < load.nodeinfos.Count; i++) {
Type t = Type.GetType(load.nodeinfos[i].type);
ConstructorInfo ctor = t.GetConstructor(new[] { GetType(), typeof(NodeInfo) });
Node n = (Node)Convert.ChangeType(ctor.Invoke(new object[] { this, load.nodeinfos[i] }), t);
n.Rebuild(CPIndex.GetRange(spent, load.NodeCPIndex[i]));
spent += load.NodeCPIndex[i];
AddNode(n);
}
//build connections
connections = new List<Connection>();
for (int i = 0; i < load.ConnectionIndexIn.Count; i++) {
connections.Add(new Connection(CPIndex[load.ConnectionIndexIn[i]], CPIndex[load.ConnectionIndexOut[i]], RemoveConnection));
}
offset = new Vector2(load.offset.x, load.offset.y);
drag = Vector2.zero;
} catch (Exception e) {
return e.Message;
}
return null;
}
19
View Source File : DialogNode.cs
License : MIT License
Project Creator : alee12131415
License : MIT License
Project Creator : alee12131415
public override void Rebuild(List<ConnectionPoint> cp) {
inPoint = cp[0];
outPoints = cp.GetRange(1, cp.Count - 1);
inPoint.Rebuild(this, ConnectionPointType.In, editor.OnClickInPoint);
for (int i = 0; i < outPoints.Count; i++) {
outPoints[i].Rebuild(this, ConnectionPointType.Out, editor.OnClickOutPoint);
}
}
19
View Source File : DynamicTrendDetector.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private decimal GetValue(List<Candle> candles,int index)
{
if (index <= 2)
{
Period = 0;
}
decimal currentCandleClose = candles[index].Close;
if (Values == null || Values.Count == 0)
{
return currentCandleClose;
}
decimal previousTrendClose = Values[Math.Max(0, index - 2)];
decimal currentTrendClose = Values[Math.Max(0, index - 1)];
decimal previousCandleClose = candles[Math.Max(0, index - 1)].Close;
if (index >= 1)
{
if (currentTrendClose < currentCandleClose)
{
if (currentSide != Side.Buy)
{
Period = 0;
}
currentSide = Side.Buy;
} else if (currentTrendClose >= currentCandleClose)
{
if (currentSide != Side.Sell)
{
Period = 0;
}
currentSide = Side.Sell;
} else
{
currentSide = Side.None;
Period = 0;
}
}
List<Candle> subList;
List<decimal> highs;
List<decimal> lows;
int startIdx;
int numItems;
decimal value;
decimal highest;
decimal lowest;
decimal correctionPercent = Decimal.Divide(CorrectionCoeff, 100);
decimal coeffUp = 1m - correctionPercent;
decimal coeffDown = 1m + correctionPercent;
if (Period < Lenght)
{
if (currentSide != Side.None)
{
startIdx = Math.Max(0, index - Period-1);
numItems = Math.Max(1, Period - 1);
subList = candles.GetRange(startIdx, numItems);
highs = subList.Select(o => o.High).ToList();
lows = subList.Select(o => o.Low).ToList();
Period += 1;
if (currentSide == Side.Buy)
{
highest = highs.Max();
value = highest * coeffUp;
} else
{
lowest = lows.Min();
value = lowest * coeffDown;
}
return value;
} else
{
return currentTrendClose;
}
} else
{
startIdx = Math.Max(0, index - Lenght -1);
numItems = Math.Max(1, Lenght - 1);
subList = candles.GetRange(startIdx, numItems);
highs = subList.Select(o => o.High).ToList();
lows = subList.Select(o => o.Low).ToList();
return currentSide == Side.Buy ? highs.Max() * coeffUp : lows.Min() * coeffDown;
}
}
19
View Source File : ServerCandleStorage.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public List<Candle> GetCandles(string specification, int count)
{
CandleSeriesSaveInfo mySaveInfo = GetSpecInfo(specification);
List<Candle> candles = mySaveInfo.AllCandlesInFile;
if (candles != null &&
candles.Count != 0 &&
candles.Count - 1 - count > 0)
{
candles = candles.GetRange(candles.Count - 1 - count, count);
}
return candles;
}
19
View Source File : ShapeEditor.cs
License : MIT License
Project Creator : all-iver
License : MIT License
Project Creator : all-iver
void EditPath(Shape shape) {
// get the existing verts
PathSegment[] oldSegments = shape.GetPathWorldSegments();
List<PathSegment> segments = new List<PathSegment>(oldSegments);
bool hasMaxSegments = segments.Count == Shape.MaxPathSegments;
// are we in delete mode? what color should handles be?
Color pink = new Color(1, 0, 0.75f);
bool deleteMode = false;
if ((Event.current.control || Event.current.command) && segments.Count > 1) {
Handles.color = Color.red;
deleteMode = true;
} else {
Handles.color = pink;
}
bool splitMode = Event.current.shift;
Vector3 mouseWorldPos = GetMouseWorldPos();
bool isWithinBounds = shape.PointIsWithinShapeBounds(mouseWorldPos);
// drag handle result for getting info from our handles
CustomHandles.DragHandleResult dhResult;
// draw handles for each existing point and check if they've been moved or clicked
bool changed = false;
for (int i = segments.Count * 3 - 1; i >= 0; i--) {
PathSegment segment = segments[i / 3];
Vector3 p = segment.p0;
bool isInfluencePoint = false;
if (i % 3 == 1) {
p = segment.p1;
isInfluencePoint = true;
} else if (i % 3 == 2) {
p = segment.p2;
}
if (deleteMode && isInfluencePoint)
continue;
float size = 0.04f * HandleUtility.GetHandleSize(p);
#if UNITY_5_6_OR_NEWER
Handles.CapFunction cap = Handles.RectangleHandleCap;
#else
Handles.DrawCapFunction cap = Handles.RectangleCap;
#endif
if (isInfluencePoint) {
#if UNITY_5_6_OR_NEWER
cap = Handles.CircleHandleCap;
#else
cap = Handles.CircleCap;
#endif
size = 0.05f * HandleUtility.GetHandleSize(p);
}
if (isInfluencePoint) {
Color oldColor = Handles.color;
Handles.color = Color.grey;
Handles.DrawDottedLine(p, segment.p0, HandleUtility.GetHandleSize(p));
Handles.DrawDottedLine(p, segment.p2, HandleUtility.GetHandleSize(p));
Handles.color = oldColor;
}
Vector3 newPos = CustomHandles.DragHandle(p, size, cap, pink, out dhResult);
if (deleteMode && !isInfluencePoint && dhResult == CustomHandles.DragHandleResult.LMBPress) {
// the user clicked on the handle while in delete mode, so delete the segment
segments.RemoveAt(i / 3);
changed = true;
break;
} else if (!deleteMode && isInfluencePoint && dhResult == CustomHandles.DragHandleResult.LMBDoubleClick) {
segment.MakeLinear();
segments[i / 3] = segment;
changed = true;
} else if (!deleteMode && newPos != p) {
// the handle has been dragged, so move the point to the new position
if (isInfluencePoint || isWithinBounds) {
MovePathPoint(segments, i, newPos, moveConnected: !splitMode);
changed = true;
}
} else if (!splitMode && !deleteMode && !isInfluencePoint
&& dhResult == CustomHandles.DragHandleResult.LMBRelease) {
// the handle has been released. snap it to any nearby points.
for (int c = 0; c < segments.Count; c++) {
PathSegment seg2 = segments[c];
if (seg2.p0 != newPos && Vector2.Distance(seg2.p0, newPos) < HandleUtility.GetHandleSize(newPos) * 0.25f) {
newPos = seg2.p0;
break;
}
if (seg2.p2 != newPos && Vector2.Distance(seg2.p2, newPos) < HandleUtility.GetHandleSize(newPos) * 0.25f) {
newPos = seg2.p2;
break;
}
}
MovePathPoint(segments, i, newPos, moveConnected: true);
changed = true;
}
}
// check if the mouse is hovering over a space where we could add a new point,
// and draw it if so
bool closeToExistingPoint = false;
if (!changed && !hasMaxSegments && !deleteMode) {
foreach (PathSegment s in segments) {
// if close to an existing point, we don't want to add a new one
if (Vector2.Distance(HandleUtility.WorldToGUIPoint(mouseWorldPos),
HandleUtility.WorldToGUIPoint(s.p0)) < 15) {
closeToExistingPoint = true;
break;
}
if (Vector2.Distance(HandleUtility.WorldToGUIPoint(mouseWorldPos),
HandleUtility.WorldToGUIPoint(s.p1)) < 15) {
closeToExistingPoint = true;
break;
}
if (Vector2.Distance(HandleUtility.WorldToGUIPoint(mouseWorldPos),
HandleUtility.WorldToGUIPoint(s.p2)) < 15) {
closeToExistingPoint = true;
break;
}
}
if (!closeToExistingPoint && isWithinBounds) {
// not too close to an existing vert, so draw a new one
// find the closest point
float closestDistance = 99999;
Vector2 closestPoint = Vector2.zero;
for (int i = 0; i < segments.Count; i++) {
float dist = Vector2.Distance(segments[i].p0, (Vector2) mouseWorldPos);
if (dist < closestDistance) {
closestPoint = segments[i].p0;
closestDistance = dist;
}
dist = Vector2.Distance(segments[i].p2, (Vector2) mouseWorldPos);
if (dist < closestDistance) {
closestPoint = segments[i].p2;
closestDistance = dist;
}
}
// don't use an actual handle cause we want to intercept nearby clicks
// and not just clicks directly on the handle.
Rect rect = new Rect();
float dim = 0.05f * HandleUtility.GetHandleSize(mouseWorldPos);
rect.center = mouseWorldPos - new Vector3(dim, dim, 0);
rect.size = new Vector2(dim * 2, dim * 2);
Handles.color = Color.white; // remove the weird tint it does
Handles.DrawSolidRectangleWithOutline(rect, Color.green, Color.clear);
Color oldColor = Handles.color;
Handles.color = Color.grey;
Handles.DrawDottedLine(rect.center, closestPoint, HandleUtility.GetHandleSize(closestPoint));
Handles.color = oldColor;
if (Event.current.type == EventType.MouseDown && !Event.current.alt
&& !Event.current.shift && !Event.current.command && !Event.current.control) {
// the user has clicked to add a new segment, so add it for real
segments.Add(new PathSegment(closestPoint, mouseWorldPos));
changed = true;
}
}
}
// something has been changed, so apply the new points back to the shape
if (changed) {
Undo.RecordObject(shape, "Edit Shapes2D Path Points");
shape.SetPathWorldSegments(segments.GetRange(0, segments.Count).ToArray());
EditorUtility.SetDirty(target);
} else {
HandleUtility.Repaint(); // to draw the new point placeholder handle
if (Event.current.type == EventType.MouseDown && !isWithinBounds)
StopEditingShape(true);
}
}
19
View Source File : ShapeEditor.cs
License : MIT License
Project Creator : all-iver
License : MIT License
Project Creator : all-iver
void EditPolygon(Shape shape) {
HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Preplacedive));
// get the existing verts
Vector3[] oldVerts = shape.GetPolygonWorldVertices();
List<Vector3> verts = new List<Vector3>(oldVerts);
bool hasMaxVerts = verts.Count == Shape.MaxPolygonVertices;
// add the first vert at the end as well so Unity will draw it right etc
verts.Add(verts[0]);
// are we in delete mode? what color should handles be?
Color pink = new Color(1, 0, 0.75f);
bool deleteMode = false;
if ((Event.current.control || Event.current.command) && verts.Count > 4) {
Handles.color = Color.red;
deleteMode = true;
} else {
Handles.color = pink;
}
// draw the shape
Handles.DrawAAPolyLine(3f, verts.ToArray());
// drag handle result for getting info from our handles
CustomHandles.DragHandleResult dhResult;
// draw handles for each existing vert and check if they've been moved or clicked
bool changed = false;
for (int i = verts.Count - 2; i >= 0; i--) {
Vector3 v = verts[i];
#if UNITY_5_6_OR_NEWER
Vector3 newPos = CustomHandles.DragHandle(v, 0.05f * HandleUtility.GetHandleSize(v),
Handles.DotHandleCap, pink, out dhResult);
#else
Vector3 newPos = CustomHandles.DragHandle(v, 0.05f * HandleUtility.GetHandleSize(v),
Handles.DotCap, pink, out dhResult);
#endif
if (deleteMode && dhResult == CustomHandles.DragHandleResult.LMBPress) {
// the user clicked on the handle while in delete mode, so delete the vert
verts.RemoveAt(i);
changed = true;
} else if (!deleteMode && newPos != v) {
// the handle has been dragged, so move the vert to the new position
verts[i] = new Vector2(newPos.x, newPos.y);
changed = true;
}
}
// check if the mouse is hovering over a space where we could add a new vert,
// and draw it if so
bool snapped = false;
Vector3 closestPos = HandleUtility.ClosestPointToPolyLine(verts.ToArray());
float distance = HandleUtility.DistanceToPolyLine(verts.ToArray());
bool isCloseToLine = distance < 25;
if (!changed && isCloseToLine && !hasMaxVerts && !deleteMode) {
// todo - ClosestPointToPolyLine doesn't work very well in 3D...
foreach (Vector3 v in verts) {
// if close to an existing vert, we don't want to add a new one
if (Vector2.Distance(HandleUtility.WorldToGUIPoint(closestPos),
HandleUtility.WorldToGUIPoint(v)) < 15) {
snapped = true;
break;
}
}
if (!snapped) {
// not too close to an existing vert, so draw a new one. don't
// use an actual handle cause we want to intercept nearby clicks
// and not just clicks directly on the handle.
Rect rect = new Rect();
float dim = 0.05f * HandleUtility.GetHandleSize(closestPos);
rect.center = closestPos - new Vector3(dim, dim, 0);
rect.size = new Vector2(dim * 2, dim * 2);
Handles.color = Color.white; // remove the weird tint it does
Handles.DrawSolidRectangleWithOutline(rect, Color.green, Color.clear);
if (Event.current.type == EventType.MouseDown) {
// the user has clicked the new vert, so add it for real
// figure out which line segment it's on
int lineStart = GetClosestLineToPoint(closestPos, verts);
verts.Insert(lineStart + 1, closestPos);
changed = true;
}
}
}
// something has been changed, so apply the new verts back to the shape
if (changed) {
// make sure to remove the duplicated last vert we added
Undo.RecordObject(shape, "Edit Shapes2D Polygon Vertices");
shape.SetPolygonWorldVertices(
verts.GetRange(0, verts.Count - 1).ToArray());
EditorUtility.SetDirty(target);
} else {
HandleUtility.Repaint(); // to draw the new vert placeholder handle
if (Event.current.type == EventType.MouseDown && !isCloseToLine)
StopEditingShape(true);
}
}
19
View Source File : ListExtension.cs
License : MIT License
Project Creator : allartprotocol
License : MIT License
Project Creator : allartprotocol
public static List<T> Splice<T>(this List<T> source, int index, int count)
{
var items = source.GetRange(index, count);
source.RemoveRange(index, count);
return source;
}
19
View Source File : VotingDriver.cs
License : MIT License
Project Creator : altskop
License : MIT License
Project Creator : altskop
public void vote(int livingPlayers)
{
System.Threading.Thread.Sleep(30000);
List<VotingVector> options = votingButtons.GetRange(0, livingPlayers+1);
int randomIndex = new Random().Next(options.Count);
VotingVector randomChoice = options[randomIndex];
var taskInput = new TaskInput();
taskInput.mouseClick(randomChoice.initialButton);
System.Threading.Thread.Sleep(500);
taskInput.mouseClick(randomChoice.confirmButton);
}
19
View Source File : Navigator.cs
License : MIT License
Project Creator : altskop
License : MIT License
Project Creator : altskop
public void followPlayer(Vector2 target)
{
List<Waypoint> route = getWaypoints(target);
if (route == null) return;
try
{
if (route.Count > 5)
route = route.GetRange(0, 5);
walkTheRoute(route);
}
catch (NavigationError e)
{
return;
}
}
19
View Source File : PagingManager.cs
License : MIT License
Project Creator : Analogy-LogViewer
License : MIT License
Project Creator : Analogy-LogViewer
public IEnumerable<List<T>> SplitList<T>(List<T> locations)
{
for (int i = 0; i < locations.Count; i += pageSize)
{
yield return locations.GetRange(i, Math.Min(pageSize, locations.Count - i));
}
}
19
View Source File : FractionSection.cs
License : MIT License
Project Creator : andersnm
License : MIT License
Project Creator : andersnm
static void GetNumerator(List<string> tokens, out List<string> integerPart, out List<string> numeratorPart)
{
var hasPlaceholder = false;
var hreplacedpace = false;
var hasIntegerPart = false;
var numeratorIndex = -1;
var index = tokens.Count - 1;
while (index >= 0)
{
var token = tokens[index];
if (Token.IsPlaceholder(token))
{
hasPlaceholder = true;
if (hreplacedpace)
{
hasIntegerPart = true;
break;
}
}
else
{
if (hasPlaceholder && !hreplacedpace)
{
// First time we get here marks the end of the integer part
hreplacedpace = true;
numeratorIndex = index + 1;
}
}
index--;
}
if (hasIntegerPart)
{
integerPart = tokens.GetRange(0, numeratorIndex);
numeratorPart = tokens.GetRange(numeratorIndex, tokens.Count - numeratorIndex);
}
else
{
integerPart = null;
numeratorPart = tokens;
}
}
19
View Source File : Parser.cs
License : MIT License
Project Creator : andersnm
License : MIT License
Project Creator : andersnm
internal static int ParseNumberTokens(List<string> tokens, int startPosition, out List<string> beforeDecimal, out bool decimalSeparator, out List<string> afterDecimal)
{
beforeDecimal = null;
afterDecimal = null;
decimalSeparator = false;
List<string> remainder = new List<string>();
var index = 0;
for (index = 0; index < tokens.Count; ++index)
{
var token = tokens[index];
if (token == "." && beforeDecimal == null)
{
decimalSeparator = true;
beforeDecimal = tokens.GetRange(0, index); // TODO: why not remainder? has only valid tokens...
remainder = new List<string>();
}
else if (Token.IsNumberLiteral(token))
{
remainder.Add(token);
}
else if (token.StartsWith("["))
{
// ignore
}
else
{
break;
}
}
if (remainder.Count > 0)
{
if (beforeDecimal != null)
{
afterDecimal = remainder;
}
else
{
beforeDecimal = remainder;
}
}
return index;
}
19
View Source File : FractionSection.cs
License : MIT License
Project Creator : andersnm
License : MIT License
Project Creator : andersnm
static bool TryGetDenominator(List<string> tokens, out List<string> denominatorPrefix, out List<string> denominatorPart, out int denominatorConstant, out List<string> denominatorSuffix, out List<string> fractionSuffix)
{
var index = 0;
var hasPlaceholder = false;
var hasConstant = false;
var constant = new StringBuilder();
// Read literals until the first number placeholder or digit
while (index < tokens.Count)
{
var token = tokens[index];
if (Token.IsPlaceholder(token))
{
hasPlaceholder = true;
break;
}
else
if (Token.IsDigit19(token))
{
hasConstant = true;
break;
}
index++;
}
if (!hasPlaceholder && !hasConstant)
{
denominatorPrefix = null;
denominatorPart = null;
denominatorConstant = 0;
denominatorSuffix = null;
fractionSuffix = null;
return false;
}
// The denominator starts here, keep the index
var denominatorIndex = index;
// Read placeholders or digits in sequence
while (index < tokens.Count)
{
var token = tokens[index];
if (hasPlaceholder && Token.IsPlaceholder(token))
{
; // OK
}
else
if (hasConstant && (Token.IsDigit09(token)))
{
constant.Append(token);
}
else
{
break;
}
index++;
}
// 'index' is now at the first token after the denominator placeholders.
// The remaining, if anything, is to be treated in one or two parts:
// Any ultimately terminating literals are considered the "Fraction suffix".
// Anything between the denominator and the fraction suffix is the "Denominator suffix".
// Placeholders in the denominator suffix are treated as insignificant zeros.
// Scan backwards to determine the fraction suffix
int fractionSuffixIndex = tokens.Count;
while (fractionSuffixIndex > index)
{
var token = tokens[fractionSuffixIndex - 1];
if (Token.IsPlaceholder(token))
{
break;
}
fractionSuffixIndex--;
}
// Finally extract the detected token ranges
if (denominatorIndex > 0)
denominatorPrefix = tokens.GetRange(0, denominatorIndex);
else
denominatorPrefix = null;
if (hasConstant)
denominatorConstant = int.Parse(constant.ToString());
else
denominatorConstant = 0;
denominatorPart = tokens.GetRange(denominatorIndex, index - denominatorIndex);
if (index < fractionSuffixIndex)
denominatorSuffix = tokens.GetRange(index, fractionSuffixIndex - index);
else
denominatorSuffix = null;
if (fractionSuffixIndex < tokens.Count)
fractionSuffix = tokens.GetRange(fractionSuffixIndex, tokens.Count - fractionSuffixIndex);
else
fractionSuffix = null;
return true;
}
19
View Source File : ExponentialSection.cs
License : MIT License
Project Creator : andersnm
License : MIT License
Project Creator : andersnm
public static bool TryParse(List<string> tokens, out ExponentialSection format)
{
format = null;
string exponentialToken;
int partCount = Parser.ParseNumberTokens(tokens, 0, out var beforeDecimal, out var decimalSeparator, out var afterDecimal);
if (partCount == 0)
return false;
int position = partCount;
if (position < tokens.Count && Token.IsExponent(tokens[position]))
{
exponentialToken = tokens[position];
position++;
}
else
{
return false;
}
format = new ExponentialSection()
{
BeforeDecimal = beforeDecimal,
DecimalSeparator = decimalSeparator,
AfterDecimal = afterDecimal,
ExponentialToken = exponentialToken,
Power = tokens.GetRange(position, tokens.Count - position)
};
return true;
}
19
View Source File : FractionSection.cs
License : MIT License
Project Creator : andersnm
License : MIT License
Project Creator : andersnm
static public bool TryParse(List<string> tokens, out FractionSection format)
{
List<string> numeratorParts = null;
List<string> denominatorParts = null;
for (var i = 0; i < tokens.Count; i++)
{
var part = tokens[i];
if (part == "/")
{
numeratorParts = tokens.GetRange(0, i);
i++;
denominatorParts = tokens.GetRange(i, tokens.Count - i);
break;
}
}
if (numeratorParts == null)
{
format = null;
return false;
}
GetNumerator(numeratorParts, out var integerPart, out var numeratorPart);
if (!TryGetDenominator(denominatorParts, out var denominatorPrefix, out var denominatorPart, out var denominatorConstant, out var denominatorSuffix, out var fractionSuffix))
{
format = null;
return false;
}
format = new FractionSection()
{
IntegerPart = integerPart,
Numerator = numeratorPart,
DenominatorPrefix = denominatorPrefix,
Denominator = denominatorPart,
DenominatorConstant = denominatorConstant,
DenominatorSuffix = denominatorSuffix,
FractionSuffix = fractionSuffix
};
return true;
}
19
View Source File : Classifier.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
private static void InsertRange(List<char> texts, int startIndex, List<char> textsToInsert, int length)
{
texts.InsertRange(startIndex, textsToInsert.GetRange(0, length));
}
19
View Source File : CharacterDefinitionsCompiler.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
private List<string> GetCategories(string[] values)
{
List<string> temp = new List<string>(values);
return temp.GetRange(1, values.Length - 1);
}
19
View Source File : SearchPage.xaml.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
private void OnPageChanged(int newStartIndex, int length)
{
dictionaryWordViewModel.AddNewWordList(searchResults.GetRange(newStartIndex, length));
dictionaryWordView.ScrollToFirsreplacedem();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : anotherlab
License : MIT License
Project Creator : anotherlab
static IList<List<string>> SplitArgs(List<string> args)
{
var argLists = new List<List<string>>();
for (var startIndex = 0; startIndex < args.Count; )
{
var andIndex = args.FindIndex(startIndex, s => s.Equals("--and", StringComparison.OrdinalIgnoreCase));
if (andIndex < 0)
andIndex = args.Count;
argLists.Add(args.GetRange(startIndex, andIndex - startIndex));
startIndex = andIndex + 1;
}
return argLists;
}
19
View Source File : ExportBoxToShowdown.cs
License : MIT License
Project Creator : architdate
License : MIT License
Project Creator : architdate
private void ExportBoxToShowdown(object sender, EventArgs e)
{
try
{
IList<PKM> BoxData = C_SAV.SAV.BoxData;
List<PKM> BoxList = new List<PKM>(BoxData);
List<PKM> CurrBox = BoxList.GetRange(C_SAV.CurrentBox * C_SAV.SAV.BoxSlotCount, C_SAV.SAV.BoxSlotCount);
var str = ShowdownSet.GetShowdownSets(CurrBox, Environment.NewLine + Environment.NewLine);
if (string.IsNullOrWhiteSpace(str)) return;
Clipboard.SetText(str);
}
catch { }
WinFormsUtil.Alert("Exported the active box to Showdown format");
}
19
View Source File : Polyline.cs
License : MIT License
Project Creator : Autodesk
License : MIT License
Project Creator : Autodesk
public static List<Polyline> ReadFromDUCTPictureFile(File file)
{
List<Polyline> polylines = new List<Polyline>();
string CurCult = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
try
{
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
string strBuff = "";
using (
System.IO.FileStream FS = new System.IO.FileStream(file.Path,
System.IO.FileMode.Open,
System.IO.FileAccess.Read))
{
using (System.IO.StreamReader SR = new System.IO.StreamReader(FS))
{
strBuff = SR.ReadToEnd();
SR.Close();
}
FS.Close();
}
strBuff = strBuff.Replace(Strings.Chr(9).ToString(), "");
strBuff = strBuff.Replace(Strings.Chr(13).ToString(), "");
string[] strSpl = strBuff.Split(Strings.Chr(10));
List<List<int>> instructions = new List<List<int>>();
List<Point> points = new List<Point>();
// Check to see if the file is in inches or mm
bool isInInches = strSpl[1].Trim().ToLower().EndsWith("inches");
// Ignore the header lines just concentrate on the juicy bits
for (int lineIndex = 5; lineIndex <= strSpl.Length - 1; lineIndex++)
{
// Collect up all the numeric values on the line
List<double> elementsOnLine = new List<double>();
foreach (string stringElement in strSpl[lineIndex].Split(' '))
{
double value = 0;
if (double.TryParse(stringElement,
NumberStyles.Any,
CultureInfo.InvariantCulture,
out value))
{
elementsOnLine.Add(value);
}
}
if (elementsOnLine.Count == 2)
{
// If there are two values then it is an instruction line
instructions.Add(new List<int>
{
Convert.ToInt32(elementsOnLine[0]),
Convert.ToInt32(elementsOnLine[1])
});
}
else if (elementsOnLine.Count >= 3)
{
// Otherwise it is a point data line
if (isInInches)
{
points.Add(new Point(elementsOnLine[0] * 25.4, elementsOnLine[1] * 25.4, elementsOnLine[2] * 25.4));
}
else
{
points.Add(new Point(elementsOnLine[0], elementsOnLine[1], elementsOnLine[2]));
}
}
}
// So we have all the data, now we need to populate the polyline and spline lists
// This keeps track of which point we are looking at for the current instruction
int pointIndex = 0;
for (int instructionIndex = 0; instructionIndex <= instructions.Count - 1; instructionIndex++)
{
if ((instructions[instructionIndex][0] & 1024) == 1024)
{
// Bezier curves
Spline spline = new Spline();
int pixelIndex = 1;
if ((instructions[instructionIndex][0] & 24) == 24)
{
pixelIndex = -1;
}
while (pixelIndex < instructions[instructionIndex][1])
if (pixelIndex == -1)
{
// First pixel only has tangency out
Vector directionOut = points[pointIndex + pixelIndex + 1] - points[pointIndex + pixelIndex];
double distanceOut = directionOut.Magnitude;
directionOut.Normalize();
spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
directionOut,
distanceOut,
directionOut,
distanceOut));
pixelIndex += 3;
}
else if (instructions[instructionIndex][1] - pixelIndex == 1)
{
// Last pixel only has tangency in
Vector directionIn = points[pointIndex + pixelIndex] - points[pointIndex + pixelIndex - 1];
double distanceIn = directionIn.Magnitude;
directionIn.Normalize();
spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
directionIn,
distanceIn,
directionIn,
distanceIn));
pixelIndex += 3;
}
else
{
// Pixel has tangency in and out
Vector directionIn = points[pointIndex + pixelIndex] - points[pointIndex + pixelIndex - 1];
double distanceIn = directionIn.Magnitude;
directionIn.Normalize();
Vector directionOut = points[pointIndex + pixelIndex + 1] - points[pointIndex + pixelIndex];
double distanceOut = directionOut.Magnitude;
directionOut.Normalize();
spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
directionIn,
distanceIn,
directionOut,
distanceOut));
pixelIndex += 3;
}
if ((instructions[instructionIndex][0] & 24) == 0)
{
// Starting a new section
Polyline polyline = new Polyline(spline, 0.01);
polylines.Add(polyline);
}
else
{
// Continuing the last section
Polyline polyline = new Polyline(spline, 0.01);
// Add all points apart from the first one
for (int i = 1; i <= polyline.Count - 1; i++)
{
polylines[polylines.Count - 1].Add(polyline[i]);
}
}
pointIndex += instructions[instructionIndex][1];
}
else if ((instructions[instructionIndex][0] & 512) == 512)
{
// Conic arcs
Spline intermediateCurve = new Spline();
Spline spline = new Spline();
int pixelIndex = 0;
if ((instructions[instructionIndex][0] & 24) == 24)
{
pixelIndex = -1;
}
while (pixelIndex < instructions[instructionIndex][1])
{
intermediateCurve.Add(new SplinePoint(points[pointIndex + pixelIndex]));
// If there are three points on the curve
if (intermediateCurve.Count == 3)
{
intermediateCurve.FreeTangentsAndMagnitudes();
if (spline.Count != 0)
{
// If the spline curve already has points then dont add the first one, just set the output tangent and magnitude
spline.Last().MagnitudeAfter = intermediateCurve[0].MagnitudeAfter;
spline.Last().DirectionAfter = intermediateCurve[0].DirectionAfter;
}
else
{
// else add first point
spline.Add(intermediateCurve[0]);
}
// add second and third point
spline.Add(intermediateCurve[1]);
spline.Add(intermediateCurve[2]);
var p = intermediateCurve[2];
// reset intermediate curve and add last point
intermediateCurve.Clear();
intermediateCurve.Add(p.Clone());
}
pixelIndex += 1;
}
if ((instructions[instructionIndex][0] & 24) == 0)
{
// Starting a new section
Polyline polyline = new Polyline(spline, 0.01);
polylines.Add(polyline);
}
else
{
// Continuing the last section
Polyline polyline = new Polyline(spline, 0.01);
// Add all points apart from the first one
for (int i = 1; i <= polyline.Count - 1; i++)
{
polylines[polylines.Count - 1].Add(polyline[i]);
}
}
pointIndex += instructions[instructionIndex][1];
}
else
{
// Polylines
if ((instructions[instructionIndex][0] & 24) == 0)
{
// Starting a new section
Polyline polyline =
new Polyline(
new List<Point>(points.GetRange(pointIndex, instructions[instructionIndex][1]).ToArray()));
polylines.Add(polyline);
}
else
{
// Continuing the last section
polylines[polylines.Count - 1].AddRange(
points.GetRange(pointIndex, instructions[instructionIndex][1]).ToArray());
}
pointIndex += instructions[instructionIndex][1];
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(CurCult);
}
return polylines;
}
19
View Source File : Util.cs
License : MIT License
Project Creator : Autodesk-Forge
License : MIT License
Project Creator : Autodesk-Forge
internal static IEnumerable<List<T>> SplitList<T>(List<T> myList, int nSize = 30)
{
for (int i = 0; i < myList.Count; i += nSize)
{
yield return myList.GetRange(i, Math.Min(nSize, myList.Count - i));
}
}
19
View Source File : MACPDU.cs
License : MIT License
Project Creator : Azer0s
License : MIT License
Project Creator : Azer0s
public static MACPDU FromBytes(byte[] bytes)
{
var byteList = bytes.ToList();
var bytesToCheck = byteList.GetRange(0, byteList.Count - 4);
var fcs = Util.GetFCS(bytesToCheck.ToArray());
var bytesFcs = byteList.GetRange(byteList.Count - 4, 4);
if (!fcs.SequenceEqual(bytesFcs))
{
throw new Exception("FCS must match!");
}
var header = MACHeader.FromBytes(bytes.Take(14).ToArray());
var payload = byteList.GetRange(14, byteList.Count - 18).ToArray();
var protocol = MACRegistry.GetProtocol(header.EtherType);
var frame = new MACPDU
{
Header = header,
Payload = protocol.FromBytes(payload),
FCS = fcs
};
return frame;
}
19
View Source File : DiagnosticTranslatorService.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
private async Task<List<string>> GetGroupTranslations(List<string> textsToTranslate, string languageToTranslate, bool isHtmlTextType = false)
{
int translationGroupCount = textsToTranslate.Count / 100;
int lastGroupSize = textsToTranslate.Count % 100;
List<List<string>> translationGroupList = new List<List<string>>();
for (int i = 0; i <= translationGroupCount; i++)
{
// Don't send empty request body to coginitve API (Bad request)
if (i == translationGroupCount && lastGroupSize == 0)
{
break;
}
int groupSize = i == translationGroupCount ? lastGroupSize : 100;
translationGroupList.Add(textsToTranslate.GetRange(i * 100, groupSize));
}
var translatedTextsGroup = await Task.WhenAll(translationGroupList.Select(textBatch => GetTranslations(textBatch, languageToTranslate, isHtmlTextType)));
return translatedTextsGroup.Where(group => group != null).SelectMany(group => group).ToList();
}
19
View Source File : Rules.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public async Task<List<Rule>> GetListAsync(
string order,
int skip,
int limit,
string groupId,
bool includeDeleted)
{
InputValidator.Validate(order);
if (!string.IsNullOrEmpty(groupId))
{
InputValidator.Validate(groupId);
}
var data = await this.storage.GetAllAsync(STORAGE_COLLECTION);
var ruleList = new List<Rule>();
foreach (var item in data.Items)
{
try
{
var rule = this.Deserialize(item.Data);
rule.ETag = item.ETag;
rule.Id = item.Key;
if ((string.IsNullOrEmpty(groupId) ||
rule.GroupId.Equals(groupId, StringComparison.OrdinalIgnoreCase))
&& (!rule.Deleted || includeDeleted))
{
ruleList.Add(rule);
}
}
catch (Exception e)
{
this.log.Debug("Could not parse result from Key Value Storage",
() => new { e });
throw new InvalidDataException(
"Could not parse result from Key Value Storage", e);
}
}
// sort based on MessageTime, default descending
ruleList.Sort();
if (order.Equals("asc", StringComparison.OrdinalIgnoreCase))
{
ruleList.Reverse();
}
if (skip >= ruleList.Count)
{
this.log.Debug("Skip value greater than size of list returned",
() => new { skip, ruleList.Count });
return new List<Rule>();
}
else if ((limit + skip) >= ruleList.Count)
{
// if requested values are out of range, return remaining items
return ruleList.GetRange(skip, ruleList.Count - skip);
}
return ruleList.GetRange(skip, limit);
}
19
View Source File : ResultQuery.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public Task<QueryResponse<Twin>> GetNextAsTwinAsync(QueryOptions options)
{
this.HasMoreResults = false;
QueryResponse<Twin> resultResponse;
if (string.IsNullOrEmpty(options.ContinuationToken))
{
resultResponse = new QueryResponse<Twin>(this.results, "continuationToken");
}
else
{
var index = int.Parse(options.ContinuationToken);
var count = this.results.Count - index;
var continuedResults = new List<Twin>();
if (index < count)
{
continuedResults = this.results.GetRange(index, count);
}
resultResponse = new QueryResponse<Twin>(continuedResults, "continuationToken");
}
return Task.FromResult(resultResponse);
}
19
View Source File : FpgaPostProcess.cs
License : MIT License
Project Creator : Azure-Samples
License : MIT License
Project Creator : Azure-Samples
public static List<ImageFeature> PostProcess(PredictResponse networkOutput_raw,
float selectThreshold, float jaccardThreshold)
{
List<NDArray> networkOutput = new List<NDArray>();
foreach(string str in tensorOutputs)
{
NDArray ndarray = NDArrayEx.FromTensorProto(networkOutput_raw.Outputs[str]);
if (ndarray.shape.Length != 5)
{
ndarray = np.expand_dims(ndarray, axis: 0);
if (ndarray.shape.Length != 5)
{
throw new ApplicationException($"NDArray shape length expected 5, is {ndarray.shape.Length}");
}
}
networkOutput.Add(ndarray);
}
(NDArray clreplacedes, NDArray scores, NDArray bboxes) =
ExtractDetections(networkOutput.GetRange(0, 6), networkOutput.GetRange(6, 6), g_ssdAnchors,
selectThreshold, jaccardThreshold, imageShape: (300, 300), numClreplacedes: 21);
List<ImageFeature> result = new List<ImageFeature>();
for (int i = 0; i < clreplacedes.size; i++)
{
result.Add(new ImageFeature(clreplacedes[i], scores[i], bboxes[i].ToArray<float>()));
}
return result;
}
19
View Source File : LeftRecursionChecker.cs
License : MIT License
Project Creator : b3b00
License : MIT License
Project Creator : b3b00
private static (bool, string) FindRecursion(List<string> path)
{
for (int i = 0; i < path.Count - 1;i++)
{
string step = path[i];
int next = path.LastIndexOf(step);
if (next > i)
{
string failure = string.Join(" > ",path.GetRange(i, next - i + 1));
return (true, failure);
}
}
return (false, null);
}
19
View Source File : Replay.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team
License : MIT License
Project Creator : Bannerlord-Coop-Team
internal static string Stop()
{
switch (state)
{
case ReplayState.Stop:
return "Nothing happend.";
case ReplayState.Recording:
ReplayRecording -= OnEventRecording;
state = ReplayState.Stop;
RailBitBuffer buffer = new RailBitBuffer();
int count = RecordingEventList.Count / RailBitBuffer.MAX_LIST_COUNT;
for (int i = 0; i < count; i++)
{
buffer.PackAll(
RecordingEventList.GetRange(
i * RailBitBuffer.MAX_LIST_COUNT,
RailBitBuffer.MAX_LIST_COUNT),
q => buffer.WriteReplayEvent(q));
}
buffer.PackAll(
RecordingEventList.GetRange(
count * RailBitBuffer.MAX_LIST_COUNT,
RecordingEventList.Count % RailBitBuffer.MAX_LIST_COUNT),
q => buffer.WriteReplayEvent(q));
byte[] data = new byte[buffer.ByteSize + 4];
Array.Resize(ref data, buffer.Store(data));
string path = Path.Combine(logsDir, currentFilename + recordExt);
File.WriteAllBytes(path, data);
RecordingEventList = null;
return $"Recording stopped and exported in file '{currentFilename}'.";
case ReplayState.Playback:
ReplayPlayback -= OnEventPlayback;
ReplayRecording -= OnEventRecording;
state = ReplayState.Stop;
VerifyEvents();
RecordingEventList = null;
PlaybackEventList = null;
PlaybackMainPartyList = null;
return $"Playback file '{currentFilename}' stopped.";
default:
return null;
}
}
19
View Source File : Main.cs
License : MIT License
Project Creator : Battlerax
License : MIT License
Project Creator : Battlerax
private void CallNative(object[] args)
{
ulong hash = (ulong) args[0];
RAGE.Game.Invoker.Invoke(hash, args.ToList().GetRange(1, args.Length-1).ToArray());
}
19
View Source File : DynamicSlotsFeature.cs
License : GNU Lesser General Public License v2.1
Project Creator : BattletechModders
License : GNU Lesser General Public License v2.1
Project Creator : BattletechModders
private static void AddFillersToSlots(WidgetLayout layout)
{
var location = layout.widget.loadout.Location;
if (!Fillers.TryGetValue(location, out var fillers))
{
fillers = new List<Filler>();
Fillers[location] = fillers;
}
// remove already destroyed fillers
for (var index = fillers.Count - 1; index >= 0; index--)
{
if (fillers[index].IsInvalid())
{
fillers.RemoveAt(index);
}
}
var existingLastIndex = fillers.Count - 1;
var newLastIndex = layout.slots.Count - 1;
// only dispose/new fillers when needed, saves 600ms on my machine on pressing refit
if (existingLastIndex > newLastIndex)
{
var superfluousCount = existingLastIndex - newLastIndex;
foreach (var superfluous in fillers.GetRange(newLastIndex, superfluousCount))
{
superfluous.Dispose();
}
fillers.RemoveRange(newLastIndex, superfluousCount);
}
else
{
for (var newIndex = existingLastIndex + 1; newIndex <= newLastIndex; newIndex++)
{
fillers.Add(new Filler());
}
}
for (var index = 0; index <= newLastIndex; index++)
{
fillers[index].Update(layout.slots[index]);
}
}
19
View Source File : CodeMatcher.cs
License : MIT License
Project Creator : BepInEx
License : MIT License
Project Creator : BepInEx
public List<CodeInstruction> InstructionsInRange(int start, int end)
{
var instructions = codes;
if (start > end)
{
var tmp = start;
start = end;
end = tmp;
}
instructions = instructions.GetRange(start, end - start + 1);
return instructions.Select(c => new CodeInstruction(c)).ToList();
}
19
View Source File : CodeMatcher.cs
License : MIT License
Project Creator : BepInEx
License : MIT License
Project Creator : BepInEx
public List<CodeInstruction> Instructions(int count)
{
return codes.GetRange(Pos, count).Select(c => new CodeInstruction(c)).ToList();
}
19
View Source File : UI_SearchWindow.cs
License : GNU General Public License v3.0
Project Creator : berichan
License : GNU General Public License v3.0
Project Creator : berichan
public void UpdateSearchString(string val)
{
if (stopSearch)
return;
if (val != "")
{
currentSearchString = val.ToLower();
List<ComboItem> list;
if (UI_Settings.GetSearchMode() == StringSearchMode.Contains)
list = FilterToItems(CurrentFilter).FindAll((ComboItem x) => x.Text.ToLower().Contains(currentSearchString));
else
list = FilterToItems(CurrentFilter).FindAll((ComboItem x) => x.Text.ToLower().StartsWith(currentSearchString));
ComboItem fullMatch = list.Find((ComboItem x) => x.Text.ToLower() == currentSearchString);
List<ComboItem> range = list.GetRange(0, Mathf.Min(MAXITEMS, list.Count));
if (fullMatch.Text != null)
{
ComboItem item = range.Find((ComboItem x) => x.Text == fullMatch.Text);
if (item.Text != null)
{
range.Remove(item);
}
range.Insert(0, fullMatch);
}
initFor(range, list.Count > MAXITEMS, currentSearchString);
IsNoItemMode = false;
}
else
{
initFor(new List<ComboItem>(), greaterThanMaxVal: false, currentSearchString);
IsNoItemMode = true;
}
}
19
View Source File : RangeObservableCollection.cs
License : MIT License
Project Creator : beto-rodriguez
License : MIT License
Project Creator : beto-rodriguez
public void RemoveRange(int index, int count)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (index + count > Count)
throw new ArgumentOutOfRangeException(nameof(index));
if (count == 0)
return;
if (count == 1)
{
RemoveItem(index);
return;
}
//Items will always be List<T>, see constructors
var items = (List<T>)Items;
var removedItems = items.GetRange(index, count);
CheckReentrancy();
items.RemoveRange(index, count);
OnEssentialPropertiesChanged();
if (Count == 0)
OnCollectionReset();
else
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, index));
}
19
View Source File : PipeParser.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : bitsadmin
License : BSD 3-Clause "New" or "Revised" License
Project Creator : bitsadmin
public static List<PSCommand> ParseArguments(string[] args, Dictionary<Type, CaseInsensitiveList> commandTypes)
{
List<List<string>> parsedPipes = new List<List<string>>();
List<string> currentPipe = new List<string>();
// Split pipes
foreach (string arg in args)
{
if (arg == "|")
{
parsedPipes.Add(currentPipe);
currentPipe = new List<string>();
}
else
{
currentPipe.Add(arg);
}
}
parsedPipes.Add(currentPipe);
// Parse commands between pipes
List<PSCommand> allCommands = new List<PSCommand>(parsedPipes.Count);
foreach (List<string> pipe in parsedPipes)
{
string command = pipe[0].ToLowerInvariant();
string[] pipeargs = pipe.GetRange(1, pipe.Count - 1).ToArray();
// Locate the command in the aliases of the available commands
bool foundMatchingCommand = false;
foreach (KeyValuePair<Type, CaseInsensitiveList> commandType in commandTypes)
{
if (commandType.Value.Contains(command))
{
object[] parameters = new object[] { pipeargs };
try
{
allCommands.Add((PSCommand)Activator.CreateInstance(commandType.Key, parameters));
}
catch(System.Reflection.TargetInvocationException e)
{
throw e.InnerException;
}
foundMatchingCommand = true;
break;
}
}
if (!foundMatchingCommand)
throw new CommandNotFoundException(pipe[0]);
}
return allCommands;
}
19
View Source File : RangeObservableCollection.cs
License : MIT License
Project Creator : BlazorFluentUI
License : MIT License
Project Creator : BlazorFluentUI
public void RemoveRange(int index, int count)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (index + count > Count)
throw new ArgumentOutOfRangeException(nameof(index));
if (count == 0)
return;
if (count == 1)
{
RemoveItem(index);
return;
}
//Items will always be List<T>, see constructors
List<T> items = (List<T>)Items;
List<T> removedItems = items.GetRange(index, count);
CheckReentrancy();
items.RemoveRange(index, count);
OnEssentialPropertiesChanged();
if (Count == 0)
OnCollectionReset();
else
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, index));
}
See More Examples