Here are the examples of the csharp api System.Array.IndexOf(T[], T, int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
809 Examples
19
View Source File : AvifFileType.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public override PropertyCollection OnCreateSavePropertyCollection()
{
Property[] props = new Property[]
{
new Int32Property(PropertyNames.Quality, 85, 0, 100, false),
new BooleanProperty(PropertyNames.LosslessAlphaCompression, true),
StaticListChoiceProperty.CreateForEnum(PropertyNames.CompressionSpeed, CompressionSpeed.Fast),
CreateChromaSubsampling(),
new BooleanProperty(PropertyNames.PreserveExistingTileSize, true),
new BooleanProperty(PropertyNames.PremultipliedAlpha, false),
new UriProperty(PropertyNames.ForumLink, new Uri("https://forums.getpaint.net/topic/116233-avif-filetype")),
new UriProperty(PropertyNames.GitHubLink, new Uri("https://github.com/0xC0000054/pdn-avif"))
};
List<PropertyCollectionRule> rules = new List<PropertyCollectionRule>
{
new ReadOnlyBoundToValueRule<int, Int32Property>(PropertyNames.PremultipliedAlpha,
PropertyNames.Quality,
100,
false),
new ReadOnlyBoundToValueRule<int, Int32Property>(PropertyNames.YUVChromaSubsampling,
PropertyNames.Quality,
100,
false),
new ReadOnlyBoundToValueRule<int, Int32Property>(PropertyNames.LosslessAlphaCompression,
PropertyNames.Quality,
100,
false)
};
return new PropertyCollection(props, rules);
StaticListChoiceProperty CreateChromaSubsampling()
{
// The list is created manually because some of the YUVChromaSubsampling enumeration values
// are used for internal signaling.
object[] choiceValues = new object[]
{
YUVChromaSubsampling.Subsampling420,
YUVChromaSubsampling.Subsampling422,
YUVChromaSubsampling.Subsampling444
};
int defaultChoiceIndex = Array.IndexOf(choiceValues, YUVChromaSubsampling.Subsampling422);
return new StaticListChoiceProperty(PropertyNames.YUVChromaSubsampling, choiceValues, defaultChoiceIndex);
}
}
19
View Source File : DiscordRPforVSPackage.cs
License : GNU Affero General Public License v3.0
Project Creator : 1thenikita
License : GNU Affero General Public License v3.0
Project Creator : 1thenikita
public async System.Threading.Tasks.Task UpdatePresenceAsync(Doreplacedent doreplacedent, Boolean overrideTimestampReset = false)
{
try
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!Settings.enabled)
{
if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
if (!this.Discord.Initialize())
ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");
this.Discord.ClearPresence();
return;
}
this.Presence.Details = this.Presence.State = this.replacedets.LargeImageKey = this.replacedets.LargeImageText = this.replacedets.SmallImageKey = this.replacedets.SmallImageText = String.Empty;
if (Settings.secretMode)
{
this.Presence.Details = Translates.PresenceDetails(Settings.Default.translates);
this.Presence.State = Translates.PresenceState(Settings.Default.translates);
this.replacedets.LargeImageKey = this.versionImageKey;
this.replacedets.LargeImageText = this.versionString;
this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
goto finish;
}
this.Presence.Details = this.Presence.State = "";
String[] language = Array.Empty<String>();
if (doreplacedent != null)
{
String filename = Path.GetFileName(path: doreplacedent.FullName).ToUpperInvariant(), ext = Path.GetExtension(filename);
List<KeyValuePair<String[], String[]>> list = Constants.Languages.Where(lang => Array.IndexOf(lang.Key, filename) > -1 || Array.IndexOf(lang.Key, ext) > -1).ToList();
language = list.Count > 0 ? list[0].Value : Array.Empty<String>();
}
Boolean supported = language.Length > 0;
this.replacedets.LargeImageKey = Settings.largeLanguage ? supported ? language[0] : "text" : this.versionImageKey;
this.replacedets.LargeImageText = Settings.largeLanguage ? supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates) : this.versionString;
this.replacedets.SmallImageKey = Settings.largeLanguage ? this.versionImageKey : supported ? language[0] : "text";
this.replacedets.SmallImageText = Settings.largeLanguage ? this.versionString : supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates);
if (Settings.showFileName)
this.Presence.Details = !(doreplacedent is null) ? Path.GetFileName(doreplacedent.FullName) : Translates.NoFile(Settings.Default.translates);
if (Settings.showSolutionName)
{
Boolean idling = ide.Solution is null || String.IsNullOrEmpty(ide.Solution.FullName);
this.Presence.State = idling ? Translates.Idling(Settings.Default.translates) : $"{Translates.Developing(Settings.Default.translates)} {Path.GetFileNameWithoutExtension(ide.Solution.FileName)}";
if (idling)
{
this.replacedets.LargeImageKey = this.versionImageKey;
this.replacedets.LargeImageText = this.versionString;
this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
}
}
if (Settings.showTimestamp && doreplacedent != null)
{
if (!this.InitializedTimestamp)
{
this.InitialTimestamps = this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
this.InitializedTimestamp = true;
}
if (Settings.resetTimestamp && !overrideTimestampReset)
this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
else if (Settings.resetTimestamp && overrideTimestampReset)
this.Presence.Timestamps = this.CurrentTimestamps;
else if (!Settings.resetTimestamp && !overrideTimestampReset)
this.Presence.Timestamps = this.InitialTimestamps;
this.CurrentTimestamps = this.Presence.Timestamps;
}
finish:;
this.Presence.replacedets = this.replacedets;
if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
if (!this.Discord.Initialize())
ActivityLog.LogError("DiscordRPforVS", Translates.LogError(Settings.Default.translates));
this.Discord.SetPresence(this.Presence);
}
catch (ArgumentException e)
{
ActivityLog.LogError(e.Source, e.Message);
}
}
19
View Source File : DOTweenAnimationInspector.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
int DOTweenAnimationTypeToPopupId(DOTweenAnimationType animation)
{
return Array.IndexOf(_animationTypeNoSlashes, animation.ToString());
}
19
View Source File : LiteralClass.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static ExpressionSyntax Bind(MemberAccessExpressionSyntax node)
{
int index = Array.IndexOf(SupportedNumbers, node.Name.Identifier.Text);
if (index == -1)
throw new DiagnosticException("Invalid property", node.GetLocation());
return SyntaxFactory.LiteralExpression(
SyntaxKind.NumerireplacederalExpression,
SyntaxFactory.Literal(index)
);
}
19
View Source File : MorphSetDnaConverterBehaviour.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void ApplyDNA(UMAData data, UMASkeleton skeleton)
{
if (morphSet == null)
{
Debug.LogError("Missing morph set replacedet for: " + this.name);
return;
}
UMADnaBase activeDNA = data.GetDna(this.dnaTypeHash);
if (activeDNA == null)
{
Debug.LogError("Could not get DNA values for: "+ this.name);
return;
}
if (morphSet.startingPose != null)
{
morphSet.startingPose.ApplyPose(skeleton, 1f);
}
if (!String.IsNullOrEmpty(morphSet.startingBlendShape))
{
data.SetBlendShape(morphSet.startingBlendShape, 1f);
}
if (activeDNA.Count == morphSet.dnaMorphs.Length)
{
float[] dnaValues = activeDNA.Values;
for (int i = 0; i < dnaValues.Length; i++)
{
float dnaValue = dnaValues[i];
MorphSetDnareplacedet.DNAMorphSet morph = morphSet.dnaMorphs[i];
if (dnaValue > 0.51f)
{
float morphWeight = (dnaValue - 0.5f) * 2f;
if (morph.poseOne != null)
morph.poseOne.ApplyPose(skeleton, morphWeight);
if (!String.IsNullOrEmpty(morph.blendShapeOne))
data.SetBlendShape(morph.blendShapeOne, morphWeight);
}
else if (dnaValue < 0.49f)
{
float morphWeight = (0.5f - dnaValue) * 2f;
if (morph.poseZero != null)
morph.poseZero.ApplyPose(skeleton, morphWeight);
if (!String.IsNullOrEmpty(morph.blendShapeZero))
data.SetBlendShape(morph.blendShapeZero, morphWeight);
}
}
}
else
{
Debug.LogWarning("DNA length mismatch, trying names. This is SLOW!");
string[] dnaNames = activeDNA.Names;
for (int i = 0; i < morphSet.dnaMorphs.Length; i++)
{
if (String.IsNullOrEmpty(morphSet.dnaMorphs[i].dnaEntryName))
continue;
int dnaIndex = System.Array.IndexOf(dnaNames, morphSet.dnaMorphs[i].dnaEntryName);
if (dnaIndex < 0)
continue;
float dnaValue = activeDNA.GetValue(dnaIndex);
MorphSetDnareplacedet.DNAMorphSet morph = morphSet.dnaMorphs[i];
if (dnaValue > 0.51f)
{
float morphWeight = (dnaValue - 0.5f) * 2f;
if (morph.poseOne != null)
morph.poseOne.ApplyPose(skeleton, morphWeight);
if (!String.IsNullOrEmpty(morph.blendShapeOne))
data.SetBlendShape(morph.blendShapeOne, morphWeight);
}
else if (dnaValue < 0.49f)
{
float morphWeight = (0.5f - dnaValue) * 2f;
if (morph.poseZero != null)
morph.poseZero.ApplyPose(skeleton, morphWeight);
if (!String.IsNullOrEmpty(morph.blendShapeZero))
data.SetBlendShape(morph.blendShapeZero, morphWeight);
}
}
}
}
19
View Source File : Rope.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public int IndexOf(T item, int startIndex, int count)
{
VerifyRange(startIndex, count);
while (count > 0) {
var entry = FindNodeUsingCache(startIndex).PeekOrDefault();
T[] contents = entry.node.contents;
int startWithinNode = startIndex - entry.nodeStartIndex;
int nodeLength = Math.Min(entry.node.length, startWithinNode + count);
int r = Array.IndexOf(contents, item, startWithinNode, nodeLength - startWithinNode);
if (r >= 0)
return entry.nodeStartIndex + r;
count -= nodeLength - startWithinNode;
startIndex = entry.nodeStartIndex + nodeLength;
}
return -1;
}
19
View Source File : MixedRealityControllerMappingProfileInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private void RenderControllerList(SerializedProperty controllerList)
{
if (thisProfile.MixedRealityControllerMappings.Length != controllerList.arraySize) { return; }
if (InspectorUIUtility.RenderIndentedButton(ControllerAddButtonContent, EditorStyles.miniButton))
{
AddController(controllerList, typeof(GenericJoystickController));
return;
}
controllerRenderList.Clear();
showControllerDefinitions = EditorGUILayout.Foldout(showControllerDefinitions, "Controller Definitions", true);
if (showControllerDefinitions)
{
using (var outerVerticalScope = new GUILayout.VerticalScope())
{
GUILayout.HorizontalScope horizontalScope = null;
for (int i = 0; i < thisProfile.MixedRealityControllerMappings.Length; i++)
{
MixedRealityControllerMapping controllerMapping = thisProfile.MixedRealityControllerMappings[i];
Type controllerType = controllerMapping.ControllerType;
if (controllerType == null) { continue; }
Handedness handedness = controllerMapping.Handedness;
bool useCustomInteractionMappings = controllerMapping.HasCustomInteractionMappings;
SupportedControllerType supportedControllerType = controllerMapping.SupportedControllerType;
var controllerMappingProperty = controllerList.GetArrayElementAtIndex(i);
var handednessProperty = controllerMappingProperty.FindPropertyRelative("handedness");
#region Profile Migration
// Between MRTK v2 RC2 and GA, the HoloLens clicker and HoloLens voice select input were migrated from
// SupportedControllerType.WindowsMixedReality && Handedness.None to SupportedControllerType.GGVHand && Handedness.None
if (supportedControllerType == SupportedControllerType.WindowsMixedReality && handedness == Handedness.None)
{
for (int j = 0; j < thisProfile.MixedRealityControllerMappings.Length; j++)
{
if (thisProfile.MixedRealityControllerMappings[j].SupportedControllerType == SupportedControllerType.GGVHand &&
thisProfile.MixedRealityControllerMappings[j].Handedness == Handedness.None)
{
if (horizontalScope != null) { horizontalScope.Dispose(); horizontalScope = null; }
serializedObject.ApplyModifiedProperties();
for (int k = 0; k < controllerMapping.Interactions.Length; k++)
{
MixedRealityInteractionMapping currentMapping = controllerMapping.Interactions[k];
if (currentMapping.InputType == DeviceInputType.Select)
{
thisProfile.MixedRealityControllerMappings[j].Interactions[0].MixedRealityInputAction = currentMapping.MixedRealityInputAction;
}
else if (currentMapping.InputType == DeviceInputType.SpatialGrip)
{
thisProfile.MixedRealityControllerMappings[j].Interactions[1].MixedRealityInputAction = currentMapping.MixedRealityInputAction;
}
}
serializedObject.Update();
controllerList.DeleteArrayElementAtIndex(i);
EditorUtility.DisplayDialog("Mappings updated", "The \"HoloLens Voice and Clicker\" mappings have been migrated to a new serialization. Please save this replacedet.", "Okay, thanks!");
return;
}
}
}
#endregion Profile Migration
if (!useCustomInteractionMappings)
{
bool skip = false;
// Merge controllers with the same supported controller type.
for (int j = 0; j < controllerRenderList.Count; j++)
{
if (controllerRenderList[j].SupportedControllerType == supportedControllerType &&
controllerRenderList[j].Handedness == handedness)
{
try
{
thisProfile.MixedRealityControllerMappings[i].SynchronizeInputActions(controllerRenderList[j].Interactions);
}
catch (ArgumentException e)
{
Debug.LogError($"Controller mappings between {thisProfile.MixedRealityControllerMappings[i].Description} and {controllerMapping.Description} do not match. Error message: {e.Message}");
}
serializedObject.ApplyModifiedProperties();
skip = true;
}
}
if (skip) { continue; }
}
controllerRenderList.Add(new ControllerRenderProfile(supportedControllerType, handedness, thisProfile.MixedRealityControllerMappings[i].Interactions));
string controllerreplacedle = thisProfile.MixedRealityControllerMappings[i].Description;
var interactionsProperty = controllerMappingProperty.FindPropertyRelative("interactions");
if (useCustomInteractionMappings)
{
if (horizontalScope != null) { horizontalScope.Dispose(); horizontalScope = null; }
GUILayout.Space(24f);
using (var verticalScope = new GUILayout.VerticalScope())
{
using (horizontalScope = new GUILayout.HorizontalScope())
{
EditorGUILayout.LabelField(controllerreplacedle, EditorStyles.boldLabel);
if (GUILayout.Button(ControllerMinusButtonContent, EditorStyles.miniButtonRight, GUILayout.Width(24f)))
{
controllerList.DeleteArrayElementAtIndex(i);
return;
}
}
EditorGUI.BeginChangeCheck();
// Generic Type dropdown
Type[] genericTypes = MixedRealityControllerMappingProfile.CustomControllerMappingTypes;
var genericTypeListContent = new GUIContent[genericTypes.Length];
var genericTypeListIds = new int[genericTypes.Length];
int currentGenericType = -1;
for (int genericTypeIdx = 0; genericTypeIdx < genericTypes.Length; genericTypeIdx++)
{
var attribute = MixedRealityControllerAttribute.Find(genericTypes[genericTypeIdx]);
if (attribute != null)
{
genericTypeListContent[genericTypeIdx] = new GUIContent(attribute.SupportedControllerType.ToString().Replace("Generic", "").ToProperCase() + " Controller");
}
else
{
genericTypeListContent[genericTypeIdx] = new GUIContent("Unknown Controller");
}
genericTypeListIds[genericTypeIdx] = genericTypeIdx;
if (controllerType == genericTypes[genericTypeIdx])
{
currentGenericType = genericTypeIdx;
}
}
Debug.replacedert(currentGenericType != -1);
currentGenericType = EditorGUILayout.IntPopup(GenericTypeContent, currentGenericType, genericTypeListContent, genericTypeListIds);
controllerType = genericTypes[currentGenericType];
{
// Handedness dropdown
var attribute = MixedRealityControllerAttribute.Find(controllerType);
if (attribute != null && attribute.SupportedHandedness.Length >= 1)
{
// Make sure handedness is valid for the selected controller type.
if (Array.IndexOf(attribute.SupportedHandedness, (Handedness)handednessProperty.intValue) < 0)
{
handednessProperty.intValue = (int)attribute.SupportedHandedness[0];
}
if (attribute.SupportedHandedness.Length >= 2)
{
var handednessListContent = new GUIContent[attribute.SupportedHandedness.Length];
var handednessListIds = new int[attribute.SupportedHandedness.Length];
for (int handednessIdx = 0; handednessIdx < attribute.SupportedHandedness.Length; handednessIdx++)
{
handednessListContent[handednessIdx] = new GUIContent(attribute.SupportedHandedness[handednessIdx].ToString());
handednessListIds[handednessIdx] = (int)attribute.SupportedHandedness[handednessIdx];
}
handednessProperty.intValue = EditorGUILayout.IntPopup(HandednessTypeContent, handednessProperty.intValue, handednessListContent, handednessListIds);
}
}
else
{
handednessProperty.intValue = (int)Handedness.None;
}
}
if (EditorGUI.EndChangeCheck())
{
interactionsProperty.ClearArray();
serializedObject.ApplyModifiedProperties();
thisProfile.MixedRealityControllerMappings[i].ControllerType.Type = genericTypes[currentGenericType];
thisProfile.MixedRealityControllerMappings[i].SetDefaultInteractionMapping(true);
serializedObject.ApplyModifiedProperties();
return;
}
if (InspectorUIUtility.RenderIndentedButton("Edit Input Action Map"))
{
ControllerPopupWindow.Show(controllerMapping, interactionsProperty, handedness);
}
if (InspectorUIUtility.RenderIndentedButton("Reset Input Actions"))
{
interactionsProperty.ClearArray();
serializedObject.ApplyModifiedProperties();
thisProfile.MixedRealityControllerMappings[i].SetDefaultInteractionMapping(true);
serializedObject.ApplyModifiedProperties();
}
}
}
else
{
if (handedness != Handedness.Right)
{
if (horizontalScope != null) { horizontalScope.Dispose(); horizontalScope = null; }
horizontalScope = new GUILayout.HorizontalScope();
}
var buttonContent = new GUIContent(controllerreplacedle, ControllerMappingLibrary.GetControllerTextureScaled(controllerType, handedness));
if (GUILayout.Button(buttonContent, MixedRealityStylesUtility.ControllerButtonStyle, GUILayout.Height(128f), GUILayout.MinWidth(32f), GUILayout.ExpandWidth(true)))
{
ControllerPopupWindow.Show(controllerMapping, interactionsProperty, handedness);
}
}
}
if (horizontalScope != null) { horizontalScope.Dispose(); horizontalScope = null; }
}
}
}
19
View Source File : InteractableEventInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static bool RenderEvent(SerializedProperty evenreplacedem, bool canRemove = true)
{
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
SerializedProperty uEvent = evenreplacedem.FindPropertyRelative("Event");
SerializedProperty eventName = evenreplacedem.FindPropertyRelative("Name");
SerializedProperty clreplacedName = evenreplacedem.FindPropertyRelative("ClreplacedName");
SerializedProperty replacedemblyQualifiedName = evenreplacedem.FindPropertyRelative("replacedemblyQualifiedName");
Type receiverType;
InspectorUIUtility.DrawHeader("Event Receiver Type");
using (new EditorGUILayout.HorizontalScope())
{
Rect position = EditorGUILayout.GetControlRect();
using (new EditorGUI.PropertyScope(position, SelectEventLabel, clreplacedName))
{
var receiverTypes = TypeCacheUtility.GetSubClreplacedes<ReceiverBase>();
var recevierClreplacedNames = receiverTypes.Select(t => t?.Name).ToArray();
int id = Array.IndexOf(recevierClreplacedNames, clreplacedName.stringValue);
int newId = EditorGUI.Popup(position, id, recevierClreplacedNames);
if (newId == -1) { newId = 0; }
receiverType = receiverTypes[newId];
// Temporary workaround to fix bug shipped in GA where replacedemblyQualifiedName was never set
if (string.IsNullOrEmpty(replacedemblyQualifiedName.stringValue))
{
replacedemblyQualifiedName.stringValue = receiverType.replacedemblyQualifiedName;
}
if (id != newId)
{
EventChanged(receiverType, evenreplacedem);
}
}
if (canRemove)
{
if (InspectorUIUtility.FlexButton(new GUIContent("Remove Event")))
{
return true;
}
}
}
EditorGUILayout.Space();
InspectorUIUtility.DrawHeader("Event Properties");
ReceiverBase receiver = (ReceiverBase)Activator.CreateInstance(receiverType, new UnityEvent());
if (!receiver.HideUnityEvents)
{
EditorGUILayout.PropertyField(uEvent, new GUIContent(receiver.Name));
}
SerializedProperty eventSettings = evenreplacedem.FindPropertyRelative("Settings");
// If fields for given receiver clreplaced type have been changed, update the related inspector field data
var fieldList = InspectorFieldsUtility.GetInspectorFields(receiver);
if (!InspectorFieldsUtility.AreFieldsSame(eventSettings, fieldList))
{
InspectorFieldsUtility.UpdateSettingsList(eventSettings, fieldList);
}
for (int index = 0; index < eventSettings.arraySize; index++)
{
SerializedProperty propertyField = eventSettings.GetArrayElementAtIndex(index);
bool isEvent = InspectorFieldsUtility.IsPropertyType(propertyField, InspectorField.FieldTypes.Event);
if (!receiver.HideUnityEvents || !isEvent)
{
InspectorFieldsUtility.DisplayPropertyField(eventSettings.GetArrayElementAtIndex(index));
}
}
}
return false;
}
19
View Source File : SeriesWithMetadata.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void OnSeriesWithMetadataLoaded(object sender, RoutedEventArgs e)
{
var startDate = new DateTime(1995, 1, 1);
// Budget data
var yearsData = Enumerable.Range(0, 18).Select(startDate.AddYears).ToArray();
var gainLossData = new [] {0, -20.5, -30.06, -70.1, -100.22, 10.34, 30.00, 60.12, 50.1, 70.4, 40.55, 30.76, -50.2, -60.00, -20.01, 50.01, 60.32, 60.44};
// Metadata
var executivesData = new [] {"Emerson Irwin", "Reynold Harding", "Carl Carpenter", "Merle Godfrey", "Karl Atterberry"};
var checkPointIndicies = new []{0, 4, 9, 13, 16};
var ceo = executivesData[0];
var budgetMetadata = gainLossData.Select((value, index) =>
{
var metadata = new BudgetPointMetadata(value);
if (checkPointIndicies.Contains(index))
{
metadata.IsCheckPoint = true;
var ceoIndex = checkPointIndicies.IndexOf(index);
ceo = executivesData[ceoIndex];
}
metadata.CEO = ceo;
return metadata;
}).ToArray();
var budgetDataSeries = new XyDataSeries<DateTime, double>();
budgetDataSeries.Append(yearsData, gainLossData, budgetMetadata);
lineSeries.DataSeries = budgetDataSeries;
sciChart.ZoomExtents();
}
19
View Source File : YouTubeVideoIdExtension.cs
License : MIT License
Project Creator : adamfisher
License : MIT License
Project Creator : adamfisher
public object ProvideValue(IServiceProvider serviceProvider)
{
try
{
Debug.WriteLine($"Acquiring YouTube stream source URL from VideoId='{VideoId}'...");
var videoInfoUrl = $"http://www.youtube.com/get_video_info?video_id={VideoId}";
using (var client = new HttpClient())
{
var videoPageContent = client.GetStringAsync(videoInfoUrl).Result;
var videoParameters = HttpUtility.ParseQueryString(videoPageContent);
var encodedStreamsDelimited = WebUtility.HtmlDecode(videoParameters["url_encoded_fmt_stream_map"]);
var encodedStreams = encodedStreamsDelimited.Split(',');
var streams = encodedStreams.Select(HttpUtility.ParseQueryString);
var streamsByPriority = streams
.OrderBy(s =>
{
var type = s["type"];
if (type.Contains("video/mp4")) return 10;
if (type.Contains("video/3gpp")) return 20;
if (type.Contains("video/x-flv")) return 30;
if (type.Contains("video/webm")) return 40;
return int.MaxValue;
})
.ThenBy(s =>
{
var quality = s["quality"];
switch (Device.Idiom)
{
case TargetIdiom.Phone:
return Array.IndexOf(new[] { "medium", "high", "small" }, quality);
default:
return Array.IndexOf(new[] { "high", "medium", "small" }, quality);
}
})
.FirstOrDefault();
Debug.WriteLine($"Stream URL: {streamsByPriority["url"]}");
return VideoSource.FromUri(streamsByPriority["url"]);
}
}
catch (Exception ex)
{
Debug.WriteLine("Error occured while attempting to convert YouTube video ID into a remote stream path.");
Debug.WriteLine(ex);
}
return null;
}
19
View Source File : VariableInlining.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
public void Transform(ILASTTransformer tr)
{
var varUsage = new Dictionary<ILASTVariable, int>();
for(var i = 0; i < tr.Tree.Count; i++)
{
var st = tr.Tree[i];
var expr = GetExpression(st);
if(expr == null)
continue;
if(st is ILASTExpression && expr.ILCode == Code.Nop)
{
tr.Tree.RemoveAt(i);
i--;
continue;
}
if(st is ILASTreplacedignment)
{
var replacedignment = (ILASTreplacedignment) st;
if(Array.IndexOf(tr.Tree.StackRemains, replacedignment.Variable) != -1)
continue;
Debug.replacedert(replacedignment.Variable.VariableType == ILASTVariableType.StackVar);
}
foreach(var arg in expr.Arguments)
{
Debug.replacedert(arg is ILASTVariable);
var argVar = (ILASTVariable) arg;
if(argVar.VariableType == ILASTVariableType.StackVar)
varUsage.Increment(argVar);
}
}
// If a variable is remained on stack, it cannot be inlined since it would be pushed on the stack.
foreach(var remain in tr.Tree.StackRemains)
varUsage.Remove(remain);
var simpleVars = new HashSet<ILASTVariable>(varUsage.Where(usage => usage.Value == 1).Select(pair => pair.Key));
bool modified;
do
{
modified = false;
for(var i = 0; i < tr.Tree.Count - 1; i++)
{
var replacedignment = tr.Tree[i] as ILASTreplacedignment;
if(replacedignment == null)
continue;
if(!simpleVars.Contains(replacedignment.Variable))
continue;
var expr = GetExpression(tr.Tree[i + 1]);
if(expr == null || expr.ILCode.ToOpCode().Name.StartsWith("stelem"))
continue;
for(var argIndex = 0; argIndex < expr.Arguments.Length; argIndex++)
{
var argVar = expr.Arguments[argIndex] as ILASTVariable;
// If previous arguments are not variables (ie. expression),
// there might be side-effect inlining succeeding arguments.
if(argVar == null)
break;
if(argVar == replacedignment.Variable)
{
expr.Arguments[argIndex] = replacedignment.Value;
tr.Tree.RemoveAt(i);
i--;
modified = true;
break;
}
}
// Ensure the block is processed sequentially.
if(modified)
break;
}
} while(modified);
}
19
View Source File : SimulationIslandMemberList.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
public int IndexOf(SimulationIslandMember item)
{
return Array.IndexOf(entries.Elements, item, 0, entries.Count);
}
19
View Source File : RawList.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
public int IndexOf(T item)
{
return Array.IndexOf(Elements, item, 0, Count);
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int IndexOf(T element, int start, int count)
{
return System.Array.IndexOf(Memory, element, start, count);
}
19
View Source File : Array.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int IndexOf(ref T element, int start, int count)
{
return System.Array.IndexOf(Memory, element, start, count);
}
19
View Source File : CertificatePinner.cs
License : MIT License
Project Creator : alexrainman
License : MIT License
Project Creator : alexrainman
public bool Check(string hostname, List<X509Certificate2> peerCertificates)
{
if (!HasPins(hostname))
{
Debug.WriteLine($"No certificate pin found for {hostname}");
return false;
}
hostname = Pins.FirstOrDefault(p => Utility.MatchHostnameToPattern(hostname, p.Key)).Key;
// Get pins
string[] pins = Pins[hostname];
// Skip pinning with empty array
if (pins == null || pins.Length == 0)
{
return true;
}
foreach(var certificate in peerCertificates)
{
// Compute sha256
var sha256Fingerprint = SpkiFingerprint.ComputeSHA256(certificate.RawData);
// Check pins for sha256
if (Array.IndexOf(pins, sha256Fingerprint) > -1)
{
Debug.WriteLine($"Certificate pin {sha256Fingerprint} is ok for {hostname}");
return true;
}
// Compute sha1
var sha1Fingerprint = SpkiFingerprint.ComputeSHA1(certificate.RawData);
// Check pins for sha1
if (Array.IndexOf(pins, sha1Fingerprint) > -1)
{
Debug.WriteLine($"Certificate pin {sha1Fingerprint} is ok for {hostname}");
return true;
}
}
Debug.WriteLine($"Certificate pinning failure! Peer certificate chain for {hostname}: {string.Join("|", pins)}");
return false;
}
19
View Source File : ShapeVisualMesh.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
protected virtual void HandleMeshSource( Mesh source, bool added )
{
var shapeMesh = Shape as Collide.Mesh;
if ( added ) {
var material = GetMaterials().LastOrDefault() ?? DefaultMaterial;
var sourceIndex = Array.IndexOf( shapeMesh.SourceObjects, source );
AddChildMesh( Shape,
gameObject,
source,
gameObject.name + "_" + ( sourceIndex + 1 ).ToString(),
material,
sourceIndex > 0 );
}
else {
var filters = GetComponentsInChildren<MeshFilter>();
GameObject goToDestroy = null;
foreach ( var filter in filters ) {
if ( filter.sharedMesh == source ) {
goToDestroy = filter.gameObject;
break;
}
}
if ( goToDestroy == gameObject ) {
GetComponent<MeshFilter>().sharedMesh = null;
GetComponent<MeshRenderer>().sharedMaterials = new Material[] { };
}
else if ( goToDestroy != null )
DestroyImmediate( goToDestroy );
}
}
19
View Source File : ExpRoomEditor.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
public static List<(SimObjPhysics, string)> AddAllPrefabsAsOnlyChildrenOfObject(
GameObject parent,
bool onlyPickupable,
bool onlyReceptacles,
string tag = ""
) {
List <(SimObjPhysics, string)> sopAndPrefabTuples = new List <(SimObjPhysics, string)>();
string[] allPrefabs = GetAllPrefabs();
int numAdded = 0;
foreach (string prefab in allPrefabs) {
GameObject go = null;
try {
Debug.Log($"Checking {prefab}");
go = (GameObject) replacedetDatabase.LoadMainreplacedetAtPath(prefab);
SimObjPhysics sop = go.GetComponent<SimObjPhysics>();
// if (sop != null && sop.Type.ToString() == "Box" && sop.GetComponent<CanOpen_Object>()) {
if (sop != null) {
bool pickupable = sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup;
bool isReceptacle = Array.IndexOf(
sop.SecondaryProperties,
SimObjSecondaryProperty.Receptacle
) > -1 && sop.ReceptacleTriggerBoxes != null;
if (
(pickupable || !onlyPickupable)
&& (isReceptacle || !onlyReceptacles)
) {
sopAndPrefabTuples.Add((go.GetComponent<SimObjPhysics>(), prefab));
numAdded += 1;
}
}
} catch {
try {
if (go) {
DestroyImmediate(go);
}
} catch {}
Debug.LogWarning($"Prefab {prefab} failed to load.");
}
}
sopAndPrefabTuples = sopAndPrefabTuples.OrderBy(
sopAndPath => (
sopAndPath.Item1.Type.ToString(),
int.Parse("0" + new string(
sopAndPath.Item1.name
.Split('/')
.Last()
.Where(c => char.IsDigit(c))
.ToArray()))
)
).ToList();
Debug.Log(
$"Found {allPrefabs.Length} total prefabs of which {sopAndPrefabTuples.Count} were SimObjPhysics satisfying"
+ $"onlyPickupable=={onlyPickupable} and onlyReceptacles=={onlyReceptacles}."
);
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
// Note that you cannot (unfortunately) combine the two below loops into
// a single loop as doing something like
// foreach (Transform child in parent.transform) {
// DestroyImmediate(child.gameObject);
// }
// Will actually miss a large number of children because the way that looping through
// parent.transform works (deleting while iterating results in missing elements).
List<GameObject> toDestroy = new List<GameObject>();
foreach (Transform child in parent.transform) {
toDestroy.Add(child.gameObject);
}
foreach (GameObject child in toDestroy) {
Debug.Log($"Attempting to destroy {child.gameObject}");
DestroyImmediate(child);
}
if (tag != "") {
tag = $"_{tag}";
}
for (int i = 0; i < sopAndPrefabTuples.Count; i++) {
SimObjPhysics sop = sopAndPrefabTuples[i].Item1;
string path = sopAndPrefabTuples[i].Item2;
string hash = CreateSHA256Hash(path).Substring(0, 8);
GameObject go = (GameObject) PrefabUtility.InstantiatePrefab(sop.gameObject);
SimObjPhysics newSop = go.GetComponent<SimObjPhysics>();
if (onlyReceptacles && sop.Type.ToString() == "Box") {
OpenBoxFlapsMore(newSop);
}
FixBoundingBox(newSop);
go.name = $"{sop.Type.ToString()}{tag}_{hash}";
go.SetActive(false);
go.transform.position = new Vector3(-5f, i * 0.05f, -5f);
go.transform.parent = parent.transform;
sopAndPrefabTuples[i] = (newSop, path);
}
return sopAndPrefabTuples;
}
19
View Source File : TMP_EditorPanel.cs
License : MIT License
Project Creator : Alword
License : MIT License
Project Creator : Alword
protected void DrawSortingLayer()
{
Undo.RecordObject(m_Renderer, "Sorting Layer Change");
EditorGUI.BeginChangeCheck();
// SORTING LAYERS
var sortingLayerNames = SortingLayerHelper.sortingLayerNames;
var textComponent = (TextMeshPro)m_TextComponent;
// Look up the layer name using the current layer ID
string oldName = SortingLayerHelper.GetSortingLayerNameFromID(textComponent.sortingLayerID);
// Use the name to look up our array index into the names list
int oldLayerIndex = System.Array.IndexOf(sortingLayerNames, oldName);
// Show the pop-up for the names
EditorGUIUtility.fieldWidth = 0f;
int newLayerIndex = EditorGUILayout.Popup(k_SortingLayerLabel, oldLayerIndex, sortingLayerNames);
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex)
{
textComponent.sortingLayerID = SortingLayerHelper.GetSortingLayerIDForIndex(newLayerIndex);
}
// Expose the manual sorting order
int newSortingLayerOrder = EditorGUILayout.IntField(k_OrderInLayerLabel, textComponent.sortingOrder);
if (newSortingLayerOrder != textComponent.sortingOrder)
{
textComponent.sortingOrder = newSortingLayerOrder;
}
if (EditorGUI.EndChangeCheck())
m_HavePropertiesChanged = true;
EditorGUILayout.Space();
}
19
View Source File : TMP_SubMesh_Editor.cs
License : MIT License
Project Creator : Alword
License : MIT License
Project Creator : Alword
public override void OnInspectorGUI()
{
EditorGUI.indentLevel = 0;
GUI.enabled = false;
EditorGUILayout.PropertyField(fontreplacedet_prop);
EditorGUILayout.PropertyField(spritereplacedet_prop);
GUI.enabled = true;
EditorGUI.BeginChangeCheck();
// SORTING LAYERS
var sortingLayerNames = SortingLayerHelper.sortingLayerNames;
// Look up the layer name using the current layer ID
string oldName = SortingLayerHelper.GetSortingLayerNameFromID(m_Renderer.sortingLayerID);
// Use the name to look up our array index into the names list
int oldLayerIndex = System.Array.IndexOf(sortingLayerNames, oldName);
// Show the pop-up for the names
int newLayerIndex = EditorGUILayout.Popup("Sorting Layer", oldLayerIndex, sortingLayerNames);
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex)
{
//Undo.RecordObject(renderer, "Edit Sorting Layer");
m_Renderer.sortingLayerID = SortingLayerHelper.GetSortingLayerIDForIndex(newLayerIndex);
//EditorUtility.SetDirty(renderer);
}
// Expose the manual sorting order
int newSortingLayerOrder = EditorGUILayout.IntField("Order in Layer", m_Renderer.sortingOrder);
if (newSortingLayerOrder != m_Renderer.sortingOrder)
{
//Undo.RecordObject(renderer, "Edit Sorting Order");
m_Renderer.sortingOrder = newSortingLayerOrder;
}
}
19
View Source File : SvnItemTest.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
[Test]
public void TestGetPaths()
{
SvnItem item1 = this.Gereplacedem( this.WcPath );
SvnItem item2 = this.Gereplacedem( Path.Combine(this.WcPath, "Form1.cs" ));
SvnItem item3 = this.Gereplacedem( Path.Combine(this.WcPath, "replacedemblyInfo.cs" ));
string[] paths = SvnItem.GetPaths(new SvnItem[]{item1, item2, item3});
replacedert.AreEqual( 3, paths.Length );
replacedert.IsTrue( Array.IndexOf( paths, this.WcPath ) >= 0 );
replacedert.IsTrue( Array.IndexOf( paths, Path.Combine(this.WcPath, "Form1.cs" ) ) >= 0 );
replacedert.IsTrue( Array.IndexOf( paths, Path.Combine(this.WcPath, "Form1.cs" ) ) >= 0 );
}
19
View Source File : ConnectionItemView.cs
License : MIT License
Project Creator : AndreiMisiukevich
License : MIT License
Project Creator : AndreiMisiukevich
private void SetupWidgets(string[] availableProtocols, string protocol, string address, string port)
{
_protocolComboBox = new ComboBox(availableProtocols)
{
WidthRequest = 70
};
_ipEntry = new IpEntry
{
WidthChars = 30,
WidthRequest = 210
};
_portEntry = new Entry
{
WidthRequest = 60,
WidthChars = 5
};
var removeButton = new Button {Label = "-"};
removeButton.WidthRequest = 30;
removeButton.Clicked += OnRemoveButtonClicked;
Add(_protocolComboBox);
Add(new Label {Text = TextResources.MainDialog_ProtocolPostfix});
Add(_ipEntry);
Add(new Label {Text = TextResources.MainDialog_IpAddressPostfix});
Add(_portEntry);
Add(removeButton);
_ipEntry.Text = address;
_portEntry.Text = port;
_protocolComboBox.Active = availableProtocols.IndexOf(protocol);
_protocolComboBox.Changed += OnProtocolComboboxChanged;
_ipEntry.Changed += OnIpEntryChanged;
_portEntry.Changed += OnPortEntryChanged;
}
19
View Source File : HologramShaderGUI.cs
License : MIT License
Project Creator : andydbc
License : MIT License
Project Creator : andydbc
void DrawScanlinesSettings()
{
GUILayout.Space(-3);
GUILayout.Label("Scanlines", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
bool toggle = Array.IndexOf(_material.shaderKeywords, "_SCAN_ON") != -1;
EditorGUI.BeginChangeCheck();
toggle = EditorGUILayout.Toggle("Enable", toggle);
if (EditorGUI.EndChangeCheck())
{
if (toggle)
_material.EnableKeyword("_SCAN_ON");
else
_material.DisableKeyword("_SCAN_ON");
}
var ofs = EditorGUIUtility.labelWidth;
_materialEditor.SetDefaultGUIWidths();
_materialEditor.ShaderProperty(ScanSpeed, "Speed");
_materialEditor.ShaderProperty(ScanTiling, "Tiling");
EditorGUIUtility.labelWidth = ofs;
EditorGUI.indentLevel--;
}
19
View Source File : HologramShaderGUI.cs
License : MIT License
Project Creator : andydbc
License : MIT License
Project Creator : andydbc
void DrawGlowSettings()
{
GUILayout.Space(-3);
GUILayout.Label("Glow", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
bool toggle = Array.IndexOf(_material.shaderKeywords, "_GLOW_ON") != -1;
EditorGUI.BeginChangeCheck();
toggle = EditorGUILayout.Toggle("Enable", toggle);
if (EditorGUI.EndChangeCheck())
{
if (toggle)
_material.EnableKeyword("_GLOW_ON");
else
_material.DisableKeyword("_GLOW_ON");
}
var ofs = EditorGUIUtility.labelWidth;
_materialEditor.SetDefaultGUIWidths();
_materialEditor.ShaderProperty(GlowSpeed, "Speed");
_materialEditor.ShaderProperty(GlowTiling, "Tiling");
EditorGUIUtility.labelWidth = ofs;
EditorGUI.indentLevel--;
}
19
View Source File : HologramShaderGUI.cs
License : MIT License
Project Creator : andydbc
License : MIT License
Project Creator : andydbc
void DrawGlitchSettings()
{
GUILayout.Space(-3);
GUILayout.Label("Glitch", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
bool toggle = Array.IndexOf(_material.shaderKeywords, "_GLITCH_ON") != -1;
EditorGUI.BeginChangeCheck();
toggle = EditorGUILayout.Toggle("Enable", toggle);
if (EditorGUI.EndChangeCheck())
{
if (toggle)
_material.EnableKeyword("_GLITCH_ON");
else
_material.DisableKeyword("_GLITCH_ON");
}
var ofs = EditorGUIUtility.labelWidth;
_materialEditor.SetDefaultGUIWidths();
_materialEditor.ShaderProperty(GlitchSpeed, "Speed");
_materialEditor.ShaderProperty(GlitchIntensity, "Intensity");
EditorGUIUtility.labelWidth = ofs;
EditorGUI.indentLevel--;
}
19
View Source File : GeneralHelper.cs
License : MIT License
Project Creator : AnkiTools
License : MIT License
Project Creator : AnkiTools
internal static string ConcatFields(FieldList flds, AnkiItem item, string separator, MediaInfo info)
{
var matchedFields = (from t in flds
where item[t.Name] as string != ""
select item[t.Name]).ToArray();
if (info != null)
{
int indexOfField = Array.IndexOf(matchedFields, item[info.field]);
if (indexOfField != -1)
matchedFields[indexOfField] += String.Format(extensionTag[info.extension], matchedFields[0] + info.extension);
}
return String.Join(separator, matchedFields);
}
19
View Source File : ModelTests.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd
License : Apache License 2.0
Project Creator : AnthonyLloyd
[Fact]
public void Portfolio_Small_Mixed_Example()
{
var portfolio = ModelGen.Portfolio.Example(p =>
p.Positions.Count == 5
&& p.Positions.Any(p => p.Instrument is Bond)
&& p.Positions.Any(p => p.Instrument is Equity)
, "e2v0jI554Uya");
var currencies = portfolio.Positions.Select(p => p.Instrument.Currency).Distinct().ToArray();
var fxRates = ModelGen.Price.Array[currencies.Length].Example(a =>
a.All(p => p > 0.75 && p < 1.5)
, "ftXKwKhS6ec4");
double fxRate(Currency c) => fxRates[Array.IndexOf(currencies, c)];
Check.Hash(h =>
{
h.Add(portfolio.Positions.Select(p => p.Profit));
h.Add(portfolio.Profit(fxRate));
h.Add(portfolio.RiskByPosition(fxRate));
}, 8262409355294024920, decimalPlaces: 2);
}
19
View Source File : CodedToken.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
public bool Encode(uint token, out uint codedToken) {
int index = Array.IndexOf(tableTypes, MDToken.ToTable(token));
if (index < 0) {
codedToken = uint.MaxValue;
return false;
}
// This shift can never overflow a uint since bits < 8 (it's at most 5), and
// ToRid() returns an integer <= 0x00FFFFFF.
codedToken = (MDToken.ToRID(token) << bits) | (uint)index;
return true;
}
19
View Source File : StringsHeap.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
uint AddToCache(UTF8String s) {
if (Array.IndexOf(s.Data, (byte)0) >= 0)
throw new ArgumentException("Strings in the #Strings heap can't contain 00h bytes");
uint offset;
cached.Add(s);
cachedDict[s] = offset = nextOffset;
nextOffset += (uint)s.Data.Length + 1;
return offset;
}
19
View Source File : EditorUtilities.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
public static List<SerializedProperty> GetProperties(this Editor editorInstance, params string[] exlude)
{
var props = new List<SerializedProperty>();
var t = editorInstance.target.GetType();
var bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
if (exlude == null || exlude.Length == 0)
{
bf |= BindingFlags.DeclaredOnly;
}
if (exlude == null)
{
exlude = Empty<string>.array;
}
foreach (var f in t.GetFields(bf))
{
if (((f.IsPrivate || f.IsFamily) && !f.IsDefined<SerializeField>(false)) || f.IsDefined<HideInInspector>(false) || exlude.IndexOf(f.Name) >= 0)
{
continue;
}
props.Add(editorInstance.serializedObject.FindProperty(f.Name));
}
return props;
}
19
View Source File : AttributesUtilityWindow.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
private string GetEntry(int idx, string label, string currentValue)
{
var val = EditorGUILayout.TextField(label, currentValue);
if (EditorUtilities.IsReservedWord(val))
{
var style = new GUIStyle(GUI.skin.label);
style.normal.textColor = Color.red;
EditorGUILayout.LabelField("The above word is a reserved word, please choose another.", style);
_isValid = false;
}
else if (!string.IsNullOrEmpty(val) && Array.IndexOf(_entries, val) != idx)
{
var style = new GUIStyle(GUI.skin.label);
style.normal.textColor = Color.red;
EditorGUILayout.LabelField("The above word already exists in this set, please choose another.", style);
_isValid = false;
}
return val;
}
19
View Source File : SweepingLine.cs
License : GNU General Public License v3.0
Project Creator : Aptacode
License : GNU General Public License v3.0
Project Creator : Aptacode
public static bool CheckCollision(Polygon p, Polygon q)
{
if (p.Vertices.Length < 10 && q.Vertices.Length < 10)
{
return CollisionDetectorMethods.CollidesWith(p, q);
}
List<(Vector2, Vector2)> slSp = new();
List<(Vector2, Vector2)> slSq = new();
FastPriorityQueue<VertexEvent> vertexEventQueue = new(p.Vertices.Length + q.Vertices.Length + 1); //Sorted by X coord of the vertex that is the value of the first item of the tuple in the list.
vertexEventQueue.AddVertexEvents(p);
vertexEventQueue.AddVertexEvents(q);
var pVertices = p.Vertices.Vertices;
var qVertices = q.Vertices.Vertices;
while (vertexEventQueue.Count > 0) //Sweep along the X axis
{
var vertexEvent = vertexEventQueue.Dequeue();
var vertex = vertexEvent.Vertex;
var pIndex = Array.IndexOf(pVertices, vertex); //Returns =1 if it's not in the list. O(N).
var qIndex = Array.IndexOf(qVertices, vertex);
if (pIndex != -1) //only one of these should have values unless the polygons have a shared point.
{
var currentPVertex = pVertices[pIndex];
var nextPVertex = pVertices[(pIndex + 1) % pVertices.Length]; //remainder division to go through array in a cicular way, would mean PolyLines don't work so need to think about it.
var previousPVertex = pVertices[(pIndex - 1 + pVertices.Length) % pVertices.Length];
if (currentPVertex.X <= nextPVertex.X) //Add edge if the current Vertex is the start of the edge (Also includes vertical edges)
{
slSp.Add((currentPVertex, nextPVertex));
}
slSp.Remove((nextPVertex, currentPVertex)); //Remove the edge if this is the end point.
if (currentPVertex.X <= previousPVertex.X)
{
slSp.Add((currentPVertex, previousPVertex));
}
slSp.Remove((previousPVertex, currentPVertex));
}
if (qIndex != -1) //only one of these should have values unless the polygons have a shared point.
{
var currentQVertex = qVertices[qIndex];
var nextQVertex = qVertices[(qIndex + 1) % qVertices.Length];
var previousQVertex = qVertices[(qIndex - 1 + qVertices.Length) % qVertices.Length];
if (currentQVertex.X <= nextQVertex.X) //Add edge if the current Vertex is the start of the edge (Also includes vertical edges)
{
slSq.Add((currentQVertex, nextQVertex));
}
slSq.Remove((nextQVertex, currentQVertex)); //Remove the edge if this is the end point.
if (currentQVertex.X <= previousQVertex.X)
{
slSq.Add((currentQVertex, previousQVertex));
}
slSp.Remove((previousQVertex, currentQVertex));
}
if (slSp.Count == 0 || slSq.Count == 0) //No need to check intersection on empty lists.
{
slSp.RemoveAll(e => Math.Abs(e.Item1.X - e.Item2.X) < Constants.Tolerance); //Now remove the vertical edges.
slSq.RemoveAll(e => Math.Abs(e.Item1.X - e.Item2.X) < Constants.Tolerance);
continue;
}
for (var i = 0; i < slSp.Count; i++) //Now just check the relevant edges
{
var pEdge = slSp[i];
for (var j = 0; j < slSq.Count; j++)
{
var qEdge = slSq[j];
if (pEdge.LineSegmentIntersection(qEdge))
{
return true;
}
}
}
slSp.RemoveAll(e => Math.Abs(e.Item1.X - e.Item2.X) < Constants.Tolerance); //Now remove the vertical edges.
slSq.RemoveAll(e => Math.Abs(e.Item1.X - e.Item2.X) < Constants.Tolerance);
}
return false;
}
19
View Source File : APILegality.cs
License : MIT License
Project Creator : architdate
License : MIT License
Project Creator : architdate
public static void SetEncryptionConstant(PKM pk)
{
if (pk.GenNumber > 5 || pk.VC)
{
int wIndex = Array.IndexOf(Legal.WurmpleEvolutions, pk.Species);
uint EC = wIndex < 0 ? Util.Rand32() : PKX.GetWurmpleEC(wIndex / 2);
if (!(pk.Species == 658 && pk.AltForm == 1)) pk.EncryptionConstant = EC;
}
else pk.EncryptionConstant = pk.PID; // Generations 3 to 5
}
19
View Source File : GhEnergySystem.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
public override bool Write(GH_IWriter writer)
{
if (_viewModel == null)
// CreateViewModel has never been called - no need to write anything, as user has never made any changes
return base.Write(writer);
// collect the data we want to store
var meshes = _viewModel.MeshSurfaces.ToArray();
var formDefinedConversionTech =
_viewModel.ConversionTechnologies.Where(ct => !ct.IsParametricDefined).ToArray();
var formDefinedEmitters = _viewModel.Emitters.Where(e => !e.IsParametricDefined).ToArray();
// write out data - but don't write out the mesh objects themselves... (this is handled by JsonConvert - we use the OptIn
// method for serializing properties and just leave out the mesh objects)
writer.SetString("meshes",
JsonConvert.SerializeObject(meshes, Formatting.Indented, JsonSerializerSettings));
writer.SetString("conversions",
JsonConvert.SerializeObject(formDefinedConversionTech, Formatting.Indented, JsonSerializerSettings));
writer.SetString("emitters",
JsonConvert.SerializeObject(formDefinedEmitters, Formatting.Indented, JsonSerializerSettings));
// write out connection between meshes and conversion tech - needs to be re-replacedembled later in Read()
var meshConnections = new Dictionary<int, int>();
for (var meshIndex = 0; meshIndex < meshes.Length; meshIndex++)
{
var mesh = meshes[meshIndex];
if (mesh.Connection != null)
{
// NOTE: mesh.Connection is guaranteed to be connected to an object in formDefinedConversionTech
var ctIndex = Array.IndexOf(formDefinedConversionTech, mesh.Connection);
meshConnections[meshIndex] = ctIndex;
}
}
writer.SetString("meshConnections",
JsonConvert.SerializeObject(meshConnections, Formatting.Indented, JsonSerializerSettings));
return base.Write(writer);
}
19
View Source File : PointTransferState.cs
License : MIT License
Project Creator : ArcturusZhang
License : MIT License
Project Creator : ArcturusZhang
private bool CheckIfGameEnds()
{
// check if allow zero or negative points
int lowestPoint = CurrentRoundStatus.Points.Min();
switch (CurrentRoundStatus.GameSettings.PointsToGameEnd)
{
case PointsToGameEnd.Zero:
if (lowestPoint <= 0) return true;
break;
case PointsToGameEnd.Negative:
if (lowestPoint < 0) return true;
break;
}
if (CurrentRoundStatus.GameForceEnd) return true;
var isAllLast = CurrentRoundStatus.IsAllLast;
if (!isAllLast) return false;
// is all last
var maxPoint = CurrentRoundStatus.Points.Max();
if (NextRound) // if next round
{
return maxPoint >= CurrentRoundStatus.GameSettings.FirstPlacePoints;
}
else // if not next -- same oya
{
if (maxPoint < CurrentRoundStatus.GameSettings.FirstPlacePoints)
{
return false;
}
int playerIndex = System.Array.IndexOf(CurrentRoundStatus.Points, maxPoint);
if (playerIndex == CurrentRoundStatus.OyaPlayerIndex) // last oya is top
{
return CurrentRoundStatus.GameSettings.GameEndsWhenAllLastTop;
}
return false;
}
}
19
View Source File : StringUtil.cs
License : MIT License
Project Creator : arcusmaximus
License : MIT License
Project Creator : arcusmaximus
private static char MapChar(char c, char[] from, char[] to)
{
int index = from.IndexOf(c);
return index >= 0 ? to[index] : c;
}
19
View Source File : PresetAttributeDrawer.cs
License : MIT License
Project Creator : arimger
License : MIT License
Project Creator : arimger
protected override void OnGUISafe(Rect position, SerializedProperty property, GUIContent label)
{
//NOTE: this implementation does not support multiple different sources
var sourceHandle = Attribute.SourceHandle;
var declaringObject = property.GetDeclaringObject();
//extract (if available) the real preset value
if (!ValueExtractionHelper.TryGetValue(sourceHandle, declaringObject, out var sourceValue))
{
ToolboxEditorLog.MemberNotFoundWarning(attribute, property, sourceHandle);
EditorGUI.PropertyField(position, property, label);
return;
}
if (!(sourceValue is IList presetList))
{
ToolboxEditorLog.AttributeUsageWarning(attribute, property,
string.Format("Preset ({0}) has to be a one-dimensional collection (array or list).", sourceHandle));
EditorGUI.PropertyField(position, property, label);
return;
}
var sourceType = sourceValue.GetType();
var targetType = property.GetProperType(fieldInfo);
//check if types match between property and provided preset
if (targetType != (sourceType.IsGenericType
? sourceType.GetGenericArguments()[0]
: sourceType.GetElementType()))
{
ToolboxEditorLog.AttributeUsageWarning(attribute, property,
"Type mismatch between serialized property and given Preset.");
EditorGUI.PropertyField(position, property, label);
return;
}
var itemsCount = presetList.Count;
var objects = new object[itemsCount];
var options = new string[itemsCount];
for (var i = 0; i < itemsCount; i++)
{
objects[i] = presetList[i];
options[i] = presetList[i]?.ToString();
}
var value = property.GetProperValue(fieldInfo, declaringObject);
var index = Array.IndexOf(objects, value);
//begin the true property
label = EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginChangeCheck();
//get selected preset value
index = EditorGUI.Popup(position, label, index, EditorGUIUtility.TrTempContent(options));
index = Mathf.Clamp(index, 0, itemsCount - 1);
if (EditorGUI.EndChangeCheck())
{
//udpate property value using previously cached FieldInfo and picked value
//there is no cleaner way to do it, since we don't really know what kind of
//serialized property we are updating
property.serializedObject.Update();
property.SetProperValue(fieldInfo, objects[index]);
property.serializedObject.ApplyModifiedProperties();
//handle situation when updating multiple different targets
property.serializedObject.SetIsDifferentCacheDirty();
}
EditorGUI.EndProperty();
}
19
View Source File : Text_element.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
public static Point[] PlotAction(TreeNode tree, Dictionary<string, object> parameterValues, Dictionary<string, Point> coordinates, Graphics graphics)
{
static double distance(Point p1, Point p2)
{
return Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
};
static Point sumPoint(Point p1, Point p2)
{
return new Point(p1.X + p2.X, p1.Y + p2.Y);
}
static Point subtractPoint(Point p1, Point p2)
{
return new Point(p1.X - p2.X, p1.Y - p2.Y);
}
static Point multiplyPoint(Point p1, double scale)
{
return new Point(p1.X * scale, p1.Y * scale);
}
string[] nodeElements = (string[])parameterValues["Node:"];
TreeNode node = tree.GetLastCommonAncestor(nodeElements);
if (node == null)
{
throw new Exception("Could not find the requested node! If you have changed the Name of some nodes, please select the node again!");
}
int anchor = (int)parameterValues["Anchor:"];
int reference = (int)parameterValues["Orientation reference:"];
int branchReference = (int)parameterValues["Branch reference:"];
Point delta = (Point)parameterValues["Position:"];
Point margin = (Point)parameterValues["Margin:"];
Colour backgroundColour = (Colour)parameterValues["Background colour:"];
Colour borderColour = (Colour)parameterValues["Border colour:"];
double borderThickness = (double)parameterValues["Border thickness:"];
LineJoins join = (LineJoins)((int)parameterValues["Line join:"]);
LineDash dash = (LineDash)parameterValues["Border style:"];
int textReference = (int)parameterValues["Reference:"];
double textOrientation = (double)parameterValues["Orientation:"] * Math.PI / 180;
int horizontalAlignment = (int)parameterValues["Horizontal alignment:"];
int verticalAlignment = (int)parameterValues["Vertical alignment:"];
Font font = (Font)parameterValues["Font:"];
Colour colour = (Colour)parameterValues["Text colour:"];
string text = (string)parameterValues["Text:"];
Point rootPoint = coordinates[Modules.RootNodeId];
coordinates.TryGetValue("92aac276-3af7-4506-a263-7220e0df5797", out Point circularCenter);
Point point = coordinates[node.Id];
Point anglePoint = point;
double referenceAngle = 0;
if (reference == 0 && anchor == 0)
{
}
else
{
//Rectangular
if (branchReference == 0)
{
if (node.Parent != null)
{
Point parentPoint = coordinates[node.Parent.Id];
Point pA = coordinates[node.Parent.Children[0].Id];
Point pB = coordinates[node.Parent.Children[^1].Id];
double numerator = pA.Y + pB.Y - 2 * parentPoint.Y;
double denominator = pA.X + pB.X - 2 * parentPoint.X;
Point rectAnglePoint;
if (Math.Abs(numerator) > 1e-5 && Math.Abs(denominator) > 1e-5)
{
double m = numerator / denominator;
double x = (m * (parentPoint.Y - point.Y + m * point.X) + parentPoint.X) / (m * m + 1);
double y = parentPoint.Y - (x - parentPoint.X) / m;
rectAnglePoint = new Point(x, y);
}
else if (Math.Abs(numerator) > 1e-5)
{
rectAnglePoint = new Point(point.X, parentPoint.Y);
}
else if (Math.Abs(denominator) > 1e-5)
{
rectAnglePoint = new Point(parentPoint.X, point.Y);
}
else
{
rectAnglePoint = point;
}
if (reference == 1)
{
referenceAngle = Math.Atan2(point.Y - rectAnglePoint.Y, point.X - rectAnglePoint.X);
}
if (anchor == 1)
{
anglePoint = rectAnglePoint;
}
else if (anchor == 2)
{
double minXChild = double.MaxValue;
double maxXChild = double.MinValue;
double minYChild = double.MaxValue;
double maxYChild = double.MinValue;
foreach (TreeNode leaf in node.GetLeaves())
{
Point pt = coordinates[leaf.Id];
minXChild = Math.Min(minXChild, pt.X);
maxXChild = Math.Max(maxXChild, pt.X);
minYChild = Math.Min(minYChild, pt.Y);
maxYChild = Math.Max(maxYChild, pt.Y);
}
point = new Point((minXChild + maxXChild) * 0.5, (minYChild + maxYChild) * 0.5);
anglePoint = point;
}
else if (anchor == 3)
{
Point branchVector = new Point(Math.Cos(referenceAngle), Math.Sin(referenceAngle));
double d = (rootPoint.X - point.X) * branchVector.X + (rootPoint.Y - point.Y) * branchVector.Y;
Point proj = new Point(point.X + d * branchVector.X, point.Y + d * branchVector.Y);
anglePoint = new Point(-point.X + proj.X * 2, -point.Y + proj.Y * 2);
}
}
else
{
Point parentPoint = coordinates[Modules.RootNodeId];
if (reference == 1)
{
referenceAngle = Math.Atan2(point.Y - parentPoint.Y, point.X - parentPoint.X);
}
if (anchor == 1)
{
anglePoint = parentPoint;
}
else if (anchor == 2)
{
double minXChild = double.MaxValue;
double maxXChild = double.MinValue;
double minYChild = double.MaxValue;
double maxYChild = double.MinValue;
foreach (TreeNode leaf in node.GetLeaves())
{
Point pt = coordinates[leaf.Id];
minXChild = Math.Min(minXChild, pt.X);
maxXChild = Math.Max(maxXChild, pt.X);
minYChild = Math.Min(minYChild, pt.Y);
maxYChild = Math.Max(maxYChild, pt.Y);
}
point = new Point((minXChild + maxXChild) * 0.5, (minYChild + maxYChild) * 0.5);
anglePoint = point;
}
else if (anchor == 3)
{
anglePoint = new Point(-point.X + parentPoint.X * 2, -point.Y + parentPoint.Y * 2);
}
}
}
//Radial
else if (branchReference == 1)
{
Point parentPoint;
if (node.Parent != null)
{
parentPoint = coordinates[node.Parent.Id];
}
else
{
parentPoint = coordinates[Modules.RootNodeId];
}
if (anchor == 1)
{
anglePoint = parentPoint;
}
else if (anchor == 2)
{
double minXChild = double.MaxValue;
double maxXChild = double.MinValue;
double minYChild = double.MaxValue;
double maxYChild = double.MinValue;
foreach (TreeNode leaf in node.GetLeaves())
{
Point pt = coordinates[leaf.Id];
minXChild = Math.Min(minXChild, pt.X);
maxXChild = Math.Max(maxXChild, pt.X);
minYChild = Math.Min(minYChild, pt.Y);
maxYChild = Math.Max(maxYChild, pt.Y);
}
point = new Point((minXChild + maxXChild) * 0.5, (minYChild + maxYChild) * 0.5);
anglePoint = point;
}
else if (anchor == 3)
{
point = coordinates[Modules.RootNodeId];
}
if (reference == 1)
{
referenceAngle = Math.Atan2(point.Y - parentPoint.Y, point.X - parentPoint.X);
}
}
//Circular
else if (branchReference == 2)
{
Point parentPoint;
if (node.Parent != null)
{
parentPoint = coordinates[node.Parent.Id];
}
else
{
parentPoint = coordinates[Modules.RootNodeId];
}
double myRadius = distance(point, circularCenter);
double parentRadius = distance(parentPoint, circularCenter);
Point realElbowPoint = sumPoint(point, multiplyPoint(subtractPoint(circularCenter, point), (myRadius - parentRadius) / myRadius));
if (anchor == 1)
{
anglePoint = realElbowPoint;
}
else if (anchor == 2)
{
double minR = double.MaxValue;
double maxR = double.MinValue;
double minTheta = double.MaxValue;
double maxTheta = double.MinValue;
foreach (TreeNode leaf in node.GetLeaves())
{
Point pt = coordinates[leaf.Id];
double r = pt.Modulus();
double theta = Math.Atan2(pt.Y, pt.X);
minR = Math.Min(minR, r);
maxR = Math.Max(maxR, r);
minTheta = Math.Min(minTheta, theta);
maxTheta = Math.Max(maxTheta, theta);
}
point = new Point((minR + maxR) * 0.5 * Math.Cos((minTheta + maxTheta) * 0.5), (minR + maxR) * 0.5 * Math.Sin((minTheta + maxTheta) * 0.5));
anglePoint = point;
realElbowPoint = circularCenter;
}
else if (anchor == 3)
{
anglePoint = new Point(-point.X + circularCenter.X * 2, -point.Y + circularCenter.Y * 2);
}
if (reference == 1)
{
referenceAngle = Math.Atan2(point.Y - realElbowPoint.Y, point.X - realElbowPoint.X);
}
}
}
if (double.IsNaN(referenceAngle))
{
referenceAngle = 0;
}
point = new Point((point.X + anglePoint.X) * 0.5, (point.Y + anglePoint.Y) * 0.5);
point = new Point(point.X + delta.X * Math.Cos(referenceAngle) - delta.Y * Math.Sin(referenceAngle), point.Y + delta.X * Math.Sin(referenceAngle) + delta.Y * Math.Cos(referenceAngle));
if (textReference == 1)
{
textOrientation += referenceAngle;
}
graphics.Save();
graphics.Translate(point);
graphics.Rotate(textOrientation);
TextBaselines baseline = TextBaselines.Baseline;
switch (verticalAlignment)
{
case 0:
baseline = TextBaselines.Top;
break;
case 1:
baseline = TextBaselines.Middle;
break;
case 2:
baseline = TextBaselines.Baseline;
break;
case 3:
baseline = TextBaselines.Bottom;
break;
}
IEnumerable<FormattedText> formattedText;
if (font.FontFamily.IsStandardFamily)
{
formattedText = FormattedText.Format(text, (FontFamily.StandardFontFamilies)Array.IndexOf(FontFamily.StandardFamilies, font.FontFamily.FileName), font.FontSize, colour);
}
else
{
formattedText = FormattedText.Format(text, font, font, font, font, colour);
}
Font.DetailedFontMetrics metrics = formattedText.Measure();
Point topLeft = point;
Point bottomRight = point;
Point topRight = point;
Point bottomLeft = point;
if (horizontalAlignment == 0)
{
switch (baseline)
{
case TextBaselines.Top:
topLeft = point;
topRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation));
bottomRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) - metrics.Height * Math.Sin(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation) + metrics.Height * Math.Cos(textOrientation));
bottomLeft = new Point(point.X - metrics.Height * Math.Sin(textOrientation), point.Y + metrics.Height * Math.Cos(textOrientation));
break;
case TextBaselines.Middle:
topLeft = new Point(point.X + metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y - metrics.Height * Math.Cos(textOrientation) * 0.5);
topRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) + metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y + metrics.Width * Math.Sin(textOrientation) - metrics.Height * Math.Cos(textOrientation) * 0.5);
bottomRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) - metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y + metrics.Width * Math.Sin(textOrientation) + metrics.Height * Math.Cos(textOrientation) * 0.5);
bottomLeft = new Point(point.X - metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y + metrics.Height * Math.Cos(textOrientation) * 0.5);
break;
case TextBaselines.Baseline:
topLeft = new Point(point.X + metrics.Top * Math.Sin(textOrientation), point.Y - metrics.Top * Math.Cos(textOrientation));
topRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) + metrics.Top * Math.Sin(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation) - metrics.Top * Math.Cos(textOrientation));
bottomRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) + metrics.Bottom * Math.Sin(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation) - metrics.Bottom * Math.Cos(textOrientation));
bottomLeft = new Point(point.X + metrics.Bottom * Math.Sin(textOrientation), point.Y - metrics.Bottom * Math.Cos(textOrientation));
break;
case TextBaselines.Bottom:
topLeft = new Point(point.X + metrics.Height * Math.Sin(textOrientation), point.Y - metrics.Height * Math.Cos(textOrientation));
topRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) + metrics.Height * Math.Sin(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation) - metrics.Height * Math.Cos(textOrientation));
bottomRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation));
bottomLeft = point;
break;
}
}
else if (horizontalAlignment == 1)
{
switch (baseline)
{
case TextBaselines.Top:
topLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) * 0.5, point.Y - metrics.Width * Math.Sin(textOrientation) * 0.5);
topRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) * 0.5, point.Y + metrics.Width * Math.Sin(textOrientation) * 0.5);
bottomRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) * 0.5 - metrics.Height * Math.Sin(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation) * 0.5 + metrics.Height * Math.Cos(textOrientation));
bottomLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) * 0.5 - metrics.Height * Math.Sin(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation) * 0.5 + metrics.Height * Math.Cos(textOrientation));
break;
case TextBaselines.Middle:
topLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) * 0.5 + metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y - metrics.Width * Math.Sin(textOrientation) * 0.5 - metrics.Height * Math.Cos(textOrientation) * 0.5);
topRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) * 0.5 + metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y + metrics.Width * Math.Sin(textOrientation) * 0.5 - metrics.Height * Math.Cos(textOrientation) * 0.5);
bottomRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) * 0.5 - metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y + metrics.Width * Math.Sin(textOrientation) * 0.5 + metrics.Height * Math.Cos(textOrientation) * 0.5);
bottomLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) * 0.5 - metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y - metrics.Width * Math.Sin(textOrientation) * 0.5 + metrics.Height * Math.Cos(textOrientation) * 0.5);
break;
case TextBaselines.Baseline:
topLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) * 0.5 + metrics.Top * Math.Sin(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation) * 0.5 - metrics.Top * Math.Cos(textOrientation));
topRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) * 0.5 + metrics.Top * Math.Sin(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation) * 0.5 - metrics.Top * Math.Cos(textOrientation));
bottomRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) * 0.5 + metrics.Bottom * Math.Sin(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation) * 0.5 - metrics.Bottom * Math.Cos(textOrientation));
bottomLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) * 0.5 + metrics.Bottom * Math.Sin(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation) * 0.5 - metrics.Bottom * Math.Cos(textOrientation));
break;
case TextBaselines.Bottom:
topLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) * 0.5 + metrics.Height * Math.Sin(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation) * 0.5 - metrics.Height * Math.Cos(textOrientation));
topRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) * 0.5 + metrics.Height * Math.Sin(textOrientation), point.Y + metrics.Width * Math.Sin(textOrientation) * 0.5 - metrics.Height * Math.Cos(textOrientation));
bottomRight = new Point(point.X + metrics.Width * Math.Cos(textOrientation) * 0.5, point.Y + metrics.Width * Math.Sin(textOrientation) * 0.5);
bottomLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) * 0.5, point.Y - metrics.Width * Math.Sin(textOrientation) * 0.5);
break;
}
}
else
{
switch (baseline)
{
case TextBaselines.Top:
topLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation));
topRight = new Point(point.X, point.Y);
bottomRight = new Point(point.X - metrics.Height * Math.Sin(textOrientation), point.Y + metrics.Height * Math.Cos(textOrientation));
bottomLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) - metrics.Height * Math.Sin(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation) + metrics.Height * Math.Cos(textOrientation));
break;
case TextBaselines.Middle:
topLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) + metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y - metrics.Width * Math.Sin(textOrientation) - metrics.Height * Math.Cos(textOrientation) * 0.5);
topRight = new Point(point.X + metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y - metrics.Height * Math.Cos(textOrientation) * 0.5);
bottomRight = new Point(point.X - metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y + metrics.Height * Math.Cos(textOrientation) * 0.5);
bottomLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) - metrics.Height * Math.Sin(textOrientation) * 0.5, point.Y - metrics.Width * Math.Sin(textOrientation) + metrics.Height * Math.Cos(textOrientation) * 0.5);
break;
case TextBaselines.Baseline:
topLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) + metrics.Top * Math.Sin(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation) - metrics.Top * Math.Cos(textOrientation));
topRight = new Point(point.X + metrics.Top * Math.Sin(textOrientation), point.Y - metrics.Top * Math.Cos(textOrientation));
bottomRight = new Point(point.X + metrics.Bottom * Math.Sin(textOrientation), point.Y - metrics.Bottom * Math.Cos(textOrientation));
bottomLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) + metrics.Bottom * Math.Sin(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation) - metrics.Bottom * Math.Cos(textOrientation));
break;
case TextBaselines.Bottom:
topLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation) + metrics.Height * Math.Sin(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation) - metrics.Height * Math.Cos(textOrientation));
topRight = new Point(point.X + metrics.Height * Math.Sin(textOrientation), point.Y - metrics.Height * Math.Cos(textOrientation));
bottomRight = new Point(point.X, point.Y);
bottomLeft = new Point(point.X - metrics.Width * Math.Cos(textOrientation), point.Y - metrics.Width * Math.Sin(textOrientation));
break;
}
}
topLeft = new Point(topLeft.X - margin.X * Math.Cos(textOrientation) + margin.Y * Math.Sin(textOrientation), topLeft.Y - margin.X * Math.Sin(textOrientation) - margin.Y * Math.Cos(textOrientation));
topRight = new Point(topRight.X + margin.X * Math.Cos(textOrientation) + margin.Y * Math.Sin(textOrientation), topRight.Y + margin.X * Math.Sin(textOrientation) - margin.Y * Math.Cos(textOrientation));
bottomLeft = new Point(bottomLeft.X - margin.X * Math.Cos(textOrientation) - margin.Y * Math.Sin(textOrientation), bottomLeft.Y - margin.X * Math.Sin(textOrientation) + margin.Y * Math.Cos(textOrientation));
bottomRight = new Point(bottomRight.X + margin.X * Math.Cos(textOrientation) - margin.Y * Math.Sin(textOrientation), bottomRight.Y + margin.X * Math.Sin(textOrientation) + margin.Y * Math.Cos(textOrientation));
double vShift = 0;
switch (baseline)
{
case TextBaselines.Top:
break;
case TextBaselines.Bottom:
vShift = -metrics.Height;
break;
case TextBaselines.Middle:
vShift = -metrics.Height * 0.5;
break;
case TextBaselines.Baseline:
vShift = -metrics.Top;
break;
}
if (horizontalAlignment == 0)
{
if (backgroundColour.A > 0)
{
graphics.FillRectangle(-margin.X, -margin.Y + vShift, metrics.Width + margin.X * 2, metrics.Height + margin.Y * 2, backgroundColour);
}
if (borderColour.A > 0 && borderThickness > 0)
{
graphics.StrokeRectangle(-margin.X, -margin.Y + vShift, metrics.Width + margin.X * 2, metrics.Height + margin.Y * 2, borderColour, borderThickness, lineDash: dash, lineJoin: join);
}
graphics.FillText(0, 0, formattedText, colour, baseline);
}
else if (horizontalAlignment == 1)
{
if (backgroundColour.A > 0)
{
graphics.FillRectangle(-margin.X - metrics.Width * 0.5, -margin.Y + vShift, metrics.Width + margin.X * 2, metrics.Height + margin.Y * 2, backgroundColour);
}
if (borderColour.A > 0 && borderThickness > 0)
{
graphics.StrokeRectangle(-margin.X - metrics.Width * 0.5, -margin.Y + vShift, metrics.Width + margin.X * 2, metrics.Height + margin.Y * 2, borderColour, borderThickness, lineDash: dash, lineJoin: join);
}
graphics.FillText(-metrics.Width * 0.5, 0, formattedText, colour, baseline);
}
else
{
if (backgroundColour.A > 0)
{
graphics.FillRectangle(-margin.X - metrics.Width, -margin.Y + vShift, metrics.Width + margin.X * 2, metrics.Height + margin.Y * 2, backgroundColour);
}
if (borderColour.A > 0 && borderThickness > 0)
{
graphics.StrokeRectangle(-margin.X - metrics.Width, -margin.Y + vShift, metrics.Width + margin.X * 2, metrics.Height + margin.Y * 2, borderColour, borderThickness, lineDash: dash, lineJoin: join);
}
graphics.FillText(-metrics.Width, 0, formattedText, colour, baseline);
}
graphics.Restore();
double minX = Math.Min(Math.Min(topLeft.X, topRight.X), Math.Min(bottomLeft.X, bottomRight.X));
double minY = Math.Min(Math.Min(topLeft.Y, topRight.Y), Math.Min(bottomLeft.Y, bottomRight.Y));
double maxX = Math.Max(Math.Max(topLeft.X, topRight.X), Math.Max(bottomLeft.X, bottomRight.X));
double maxY = Math.Max(Math.Max(topLeft.Y, topRight.Y), Math.Max(bottomLeft.Y, bottomRight.Y));
topLeft = new Point(minX, minY);
bottomRight = new Point(maxX, maxY);
return new Point[] { topLeft, bottomRight };
}
19
View Source File : GapBuffer.cs
License : GNU General Public License v3.0
Project Creator : askeladdk
License : GNU General Public License v3.0
Project Creator : askeladdk
public int IndexOf(T value)
{
var index = Array.IndexOf(this.buffer, value, 0, this.gapLo);
if(index >= 0)
return index;
index = Array.IndexOf(this.buffer, value, this.gapHi,
this.Capacity - this.gapHi);
if(index >= 0)
return index - this.GapSize;
return -1;
}
19
View Source File : BaseErrorHandlingContext.cs
License : MIT License
Project Creator : autostep
License : MIT License
Project Creator : autostep
protected bool ContextStartedWithOneOf(params int[] tokens)
{
var startToken = (Context as ParserRuleContext)?.Start;
if (startToken is null)
{
return false;
}
return Array.IndexOf(tokens, startToken.Type) > -1;
}
19
View Source File : Rope.cs
License : MIT License
Project Creator : AvaloniaUI
License : MIT License
Project Creator : AvaloniaUI
public int IndexOf(T item, int startIndex, int count)
{
VerifyRange(startIndex, count);
while (count > 0)
{
var entry = FindNodeUsingCache(startIndex).PeekOrDefault();
var contents = entry.Node.Contents;
var startWithinNode = startIndex - entry.NodeStartIndex;
var nodeLength = Math.Min(entry.Node.Length, startWithinNode + count);
var r = Array.IndexOf(contents, item, startWithinNode, nodeLength - startWithinNode);
if (r >= 0)
return entry.NodeStartIndex + r;
count -= nodeLength - startWithinNode;
startIndex = entry.NodeStartIndex + nodeLength;
}
return -1;
}
19
View Source File : RegionBootstrap.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public virtual void Refresh()
{
GetSettingResponse getResponse = _coreApi.GetSetting(SettingsKeys.CurrentRegion);
if (!getResponse.Success)
{
RegionIndex = DefaultIndex;
return;
}
RegionIndex = Array.IndexOf(AllRegions, getResponse.Value);
if (RegionIndex < 0)
{
RegionIndex = DefaultIndex;
return;
}
_currentIndex = RegionIndex;
}
19
View Source File : AwsCredentialsCreation.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public virtual void Refresh()
{
_status.IsDisplayed = false;
RegionBootstrap.Refresh();
CurrentProfileName = null;
GetProfilesResponse response = _coreApi.ListCredentialsProfiles();
if (!response.Success)
{
_logger.LogResponseError(response);
return;
}
string[] allProlfileNames = response.Profiles.ToArray();
if (allProlfileNames.Length == 0)
{
return;
}
GetSettingResponse getCurrentResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!getCurrentResponse.Success)
{
return;
}
int currentIndex = Array.IndexOf(allProlfileNames, getCurrentResponse.Value);
if (currentIndex >= 0)
{
CurrentProfileName = allProlfileNames[currentIndex];
}
}
19
View Source File : AwsCredentialsUpdate.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public virtual void Refresh()
{
RegionBootstrap.Refresh();
SelectedProfileIndex = -1;
CurrentProfileName = null;
_currentAccessKeyId = null;
_currentSecretKey = null;
AllProlfileNames = Array.Empty<string>();
GetProfilesResponse response = _coreApi.ListCredentialsProfiles();
if (!response.Success)
{
_logger.LogResponseError(response);
return;
}
AllProlfileNames = response.Profiles.ToArray();
if (AllProlfileNames.Length == 0)
{
return;
}
GetSettingResponse getCurrentResponse = _coreApi.GetSetting(SettingsKeys.CurrentProfileName);
if (!getCurrentResponse.Success)
{
return;
}
int currentIndex = Array.IndexOf(AllProlfileNames, getCurrentResponse.Value);
if (currentIndex >= 0)
{
SelectedProfileIndex = currentIndex;
CurrentProfileIndex = currentIndex;
CurrentProfileName = AllProlfileNames[CurrentProfileIndex];
Load();
}
}
19
View Source File : VoiceChatRecorderEditor.cs
License : GNU General Public License v3.0
Project Creator : AxelSilverdew
License : GNU General Public License v3.0
Project Creator : AxelSilverdew
public override void OnInspectorGUI()
{
VoiceChatRecorder recorder = target as VoiceChatRecorder;
if (Application.isPlaying && Network.isClient)
{
EditorGUILayout.LabelField("Available Devices", EditorStyles.boldLabel);
foreach (string device in recorder.AvailableDevices)
{
EditorGUILayout.LabelField(device);
}
EditorGUILayout.LabelField("Selected Device", EditorStyles.boldLabel);
int index = Mathf.Clamp(Array.IndexOf(recorder.AvailableDevices, recorder.Device), 0, Int32.MaxValue) + 1;
string[] devices = new string[1] { "Default" }.Concat(recorder.AvailableDevices).ToArray();
index = EditorGUILayout.Popup(index, devices);
if (index != 0)
{
recorder.Device = devices[index];
}
else
{
recorder.Device = null;
}
if (recorder.IsRecording)
{
if (GUILayout.Button("Stop Recording"))
{
recorder.StopRecording();
}
}
else
{
if (GUILayout.Button("Start Recording"))
{
recorder.StartRecording();
}
}
}
else
{
DrawDefaultInspector();
}
}
19
View Source File : DefaultPasswordManager.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
protected virtual int DoCalculateStrenghtScore(PreplacedwordFamily family, SecureBuffer preplacedword)
{
var chars = Encoding.UTF8.GetChars(preplacedword.Content);
if (chars.Length == 0) return 0;
try
{
var begin = Array.FindIndex(chars, c => !Char.IsWhiteSpace(c));
if (begin < 0) return 0;
if (chars.Length == begin) return 0;
var end = Array.FindLastIndex(chars, c => !Char.IsWhiteSpace(c)) + 1;
var score = (end - begin) * CREDIT_CHAR_PRESENT;
if (score == 0) return 0;
var wasUpper = false;
var wasLower = false;
var wasDigit = false;
var wreplacedymbol = false;
char pc = (char)0;
for (var i = begin; i < end; i++)
{
var c = chars[i];
if (Char.IsUpper(c)) wasUpper = true;
if (Char.IsLower(c)) wasLower = true;
if (Char.IsDigit(c)) wasDigit = true;
if (isSymbol(c)) wreplacedymbol = true;
if (i > 0 &&
(Char.IsUpper(c) != Char.IsUpper(pc) ||
Char.IsDigit(c) != Char.IsDigit(pc) ||
isSymbol(c) != isSymbol(pc))) score += CREDIT_TYPE_TRANSITION;
if (c == pc) score -= DEBIT_CHAR_REPEAT;
if (Math.Abs(c - pc) == 1) score -= DEBIT_ADJACENT_CHAR;
pc = c;
chars[i] = Char.ToLowerInvariant(c);
}
if (wasUpper && wasLower) score += CREDIT_CASE_MIX;
if (wasDigit && (wasUpper || wasLower || wreplacedymbol)) score += CREDIT_DIGIT_MIX;
if (wreplacedymbol) score += CREDIT_SYMBOL_MIX;
for (var i = 0; i < DEFAULT_COMMON_WORDS.Length; i++)
{
var commonChars = DEFAULT_COMMON_WORDS[i].ToCharArray();
var from = begin;
while((from = Array.IndexOf(chars, commonChars[0], from)) >= 0)
{
var find = true;
var j = 0;
for (; j < commonChars.Length && from + j < chars.Length; j++)
if (chars[from + j] != commonChars[j])
{
find = false;
break;
}
if (find && j == commonChars.Length) score -= DEBIT_COMMON_WORD;
from++;
}
}
return score < 0 ? 0 : score;
}
finally
{
Array.Clear(chars, 0, chars.Length);
}
}
19
View Source File : ArrayExt.cs
License : MIT License
Project Creator : baba-s
License : MIT License
Project Creator : baba-s
public static int IndexOf<T>( this T[] array, T value, int startIndex, int count )
{
return Array.IndexOf( array, value, startIndex, count );
}
19
View Source File : LAMainView.cs
License : Apache License 2.0
Project Creator : Baseflow
License : Apache License 2.0
Project Creator : Baseflow
public override NSDragOperation DraggingEntered(NSDraggingInfo sender)
{
NSPasteboard pboard;
NSDragOperation sourceDragMask;
sourceDragMask = sender.DraggingSourceOperationMask;
pboard = sender.DraggingPasteboard;
if (Array.IndexOf(pboard.Types, NSPasteboard.NSColorType) >= 0 && sourceDragMask.HasFlag(NSDragOperation.Generic))
{
return NSDragOperation.Generic;
}
if (Array.IndexOf(pboard.Types, NSPasteboard.NSFilenamesType) >= 0)
{
if (sourceDragMask.HasFlag(NSDragOperation.Link))
{
return NSDragOperation.Generic;
}
else
{
return NSDragOperation.Copy;
}
}
return NSDragOperation.None;
}
19
View Source File : LAMainView.cs
License : Apache License 2.0
Project Creator : Baseflow
License : Apache License 2.0
Project Creator : Baseflow
public override bool PerformDragOperation(NSDraggingInfo sender)
{
NSPasteboard pboard;
NSDragOperation sourceDragMask;
sourceDragMask = sender.DraggingSourceOperationMask;
pboard = sender.DraggingPasteboard;
if (Array.IndexOf(pboard.Types, NSPasteboard.NSColorType) > -1)
{
}
else if (Array.IndexOf(pboard.Types, NSPasteboard.NSFilenamesType) > -1)
{
var files =
NSArray.StringArrayFromHandle(pboard.GetPropertyListForType(NSPasteboard.NSFilenamesType).Handle);
var jsonFile = files.FirstOrDefault(
(p => Path.GetExtension(p)
.Equals(".JSON", StringComparison.InvariantCultureIgnoreCase))
);
if (jsonFile != null)
{
this.OpenAnimationFile(jsonFile);
}
}
return true;
}
19
View Source File : AnimationLayer.cs
License : MIT License
Project Creator : Baste-RainGames
License : MIT License
Project Creator : Baste-RainGames
private int CompareListIndices(AnimationPlayerState x, AnimationPlayerState y)
{
var xIndex = Array.IndexOf(serializedStateOrder, x.GUID);
var yIndex = Array.IndexOf(serializedStateOrder, y.GUID);
if (xIndex < yIndex)
return -1;
return xIndex > yIndex ? 1 : 0;
}
See More Examples