commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
7d0bee686cf5fc5307f5f7d2a88b1f5eaec747d6
|
Update Main class for compatibility Pre-Alpha 5.
|
ParkitectNexus/Carto
|
Main.cs
|
Main.cs
|
using UnityEngine;
namespace Carto
{
public class Main : IMod
{
private GameObject _go;
public void onEnabled()
{
_go = new GameObject("Carto");
_go.AddComponent<Carto>();
}
public void onDisabled()
{
Object.Destroy(_go);
}
public string Name { get { return "Carto"; } }
public string Description { get { return "Gives every guests a map on arrival"; } }
}
}
|
using UnityEngine;
namespace Carto
{
class Main : IMod
{
private GameObject _go;
public void onEnabled()
{
_go = new GameObject("Carto");
_go.AddComponent<Carto>();
}
public void onDisabled()
{
Object.Destroy(_go);
}
public string Name { get { return "Carto"; } }
public string Description { get { return "Gives every guests a map on arrival"; } }
}
}
|
mit
|
C#
|
a912f03167aec9b04f6197b684efc7c3ee5ceb65
|
add UserControl comment
|
AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,MrDaedra/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia
|
src/Avalonia.Controls/UserControl.cs
|
src/Avalonia.Controls/UserControl.cs
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Styling;
namespace Avalonia.Controls
{
/// <summary>
/// Provides the base class for defining a new control that encapsulates related existing controls and provides its own logic.
/// </summary>
public class UserControl : ContentControl, IStyleable, INameScope
{
private readonly NameScope _nameScope = new NameScope();
/// <inheritdoc/>
event EventHandler<NameScopeEventArgs> INameScope.Registered
{
add { _nameScope.Registered += value; }
remove { _nameScope.Registered -= value; }
}
/// <inheritdoc/>
event EventHandler<NameScopeEventArgs> INameScope.Unregistered
{
add { _nameScope.Unregistered += value; }
remove { _nameScope.Unregistered -= value; }
}
/// <inheritdoc/>
Type IStyleable.StyleKey => typeof(ContentControl);
/// <inheritdoc/>
void INameScope.Register(string name, object element)
{
_nameScope.Register(name, element);
}
/// <inheritdoc/>
object INameScope.Find(string name)
{
return _nameScope.Find(name);
}
/// <inheritdoc/>
void INameScope.Unregister(string name)
{
_nameScope.Unregister(name);
}
}
}
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Styling;
namespace Avalonia.Controls
{
public class UserControl : ContentControl, IStyleable, INameScope
{
private readonly NameScope _nameScope = new NameScope();
/// <inheritdoc/>
event EventHandler<NameScopeEventArgs> INameScope.Registered
{
add { _nameScope.Registered += value; }
remove { _nameScope.Registered -= value; }
}
/// <inheritdoc/>
event EventHandler<NameScopeEventArgs> INameScope.Unregistered
{
add { _nameScope.Unregistered += value; }
remove { _nameScope.Unregistered -= value; }
}
Type IStyleable.StyleKey => typeof(ContentControl);
/// <inheritdoc/>
void INameScope.Register(string name, object element)
{
_nameScope.Register(name, element);
}
/// <inheritdoc/>
object INameScope.Find(string name)
{
return _nameScope.Find(name);
}
/// <inheritdoc/>
void INameScope.Unregister(string name)
{
_nameScope.Unregister(name);
}
}
}
|
mit
|
C#
|
d8a96578fd2aa0c54b1119b0a2b8d5a9467e5783
|
Add doc
|
bartlomiejwolk/Annotation
|
Todo.cs
|
Todo.cs
|
using UnityEngine;
using System.Collections;
namespace AnnotationEx {
public sealed class Todo : MonoBehaviour {
#region CONSTANTS
public const string Version = "v0.1.0";
public const string Extension = "Annotation";
#endregion
#region DELEGATES
#endregion
#region EVENTS
#endregion
#region FIELDS
#pragma warning disable 0414
/// <summary>
/// Allows identify component in the scene file when reading it with
/// text editor.
/// </summary>
[SerializeField]
private string componentName = "Todo";
#pragma warning restore0414
#endregion
#region INSPECTOR FIELDS
/// <summary>
/// Description of the task.
/// </summary>
[SerializeField]
private string description = "Description";
#endregion
#region PROPERTIES
/// <summary>
/// Optional text to describe purpose of this instance of the component.
/// </summary>
public string Description {
get { return description; }
set { description = value; }
}
#endregion
#region UNITY MESSAGES
private void Awake() { }
private void FixedUpdate() { }
private void LateUpdate() { }
private void OnEnable() { }
private void Reset() { }
private void Start() { }
private void Update() { }
private void OnValidate() { }
private void OnCollisionEnter(Collision collision) { }
private void OnCollisionStay(Collision collision) { }
private void OnCollisionExit(Collision collision) { }
#endregion
#region EVENT INVOCATORS
#endregion
#region EVENT HANDLERS
#endregion
#region METHODS
#endregion
}
}
|
using UnityEngine;
using System.Collections;
namespace AnnotationEx {
public sealed class Todo : MonoBehaviour {
#region CONSTANTS
public const string Version = "v0.1.0";
public const string Extension = "Annotation";
#endregion
#region DELEGATES
#endregion
#region EVENTS
#endregion
#region FIELDS
#pragma warning disable 0414
/// <summary>
/// Allows identify component in the scene file when reading it with
/// text editor.
/// </summary>
[SerializeField]
private string componentName = "Todo";
#pragma warning restore0414
#endregion
#region INSPECTOR FIELDS
[SerializeField]
private string description = "Description";
#endregion
#region PROPERTIES
/// <summary>
/// Optional text to describe purpose of this instance of the component.
/// </summary>
public string Description {
get { return description; }
set { description = value; }
}
#endregion
#region UNITY MESSAGES
private void Awake() { }
private void FixedUpdate() { }
private void LateUpdate() { }
private void OnEnable() { }
private void Reset() { }
private void Start() { }
private void Update() { }
private void OnValidate() { }
private void OnCollisionEnter(Collision collision) { }
private void OnCollisionStay(Collision collision) { }
private void OnCollisionExit(Collision collision) { }
#endregion
#region EVENT INVOCATORS
#endregion
#region EVENT HANDLERS
#endregion
#region METHODS
#endregion
}
}
|
mit
|
C#
|
eb6a301cb838865b78ed50541f670341cb63d6df
|
Fix xml doc comments
|
RockFramework/Rock.Core
|
Rock.Core/Serialization/SerializationExtensions.cs
|
Rock.Core/Serialization/SerializationExtensions.cs
|
using System;
namespace Rock.Serialization
{
public static class SerializationExtensions
{
/// <summary>
/// Deserializes an XML string into an object of type T.
/// </summary>
/// <typeparam name="T">The type of object represented by this string</typeparam>
/// <param name="str">The XML string to deserialize</param>
/// <returns>An object of type T</returns>
public static T FromXml<T>(this string str)
{
return DefaultXmlSerializer.Current.DeserializeFromString<T>(str);
}
/// <summary>
/// A reflection-friendly method to deserialize an XML string into an object.
/// </summary>
/// <param name="str">The XML string to deserialize</param>
/// <param name="type">The type of object represented by this string</param>
/// <returns>An object</returns>
public static object FromXml(this string str, Type type)
{
return DefaultXmlSerializer.Current.DeserializeFromString(str, type);
}
/// <summary>
/// Deserializes a JSON string into an object of type T.
/// </summary>
/// <typeparam name="T">The type of object represented by this string</typeparam>
/// <param name="str">The JSON string to deserialize</param>
/// <returns>An object of type T</returns>
public static T FromJson<T>(this string str)
{
return DefaultJsonSerializer.Current.DeserializeFromString<T>(str);
}
/// <summary>
/// A reflection-friendly method to deserialize an JSON string into an object.
/// </summary>
/// <param name="str">The JSON string to deserialize</param>
/// <param name="type">The type of object represented by this string</param>
/// <returns>An object</returns>
public static object FromJson(this string str, Type type)
{
return DefaultJsonSerializer.Current.DeserializeFromString(str, type);
}
}
}
|
using System;
namespace Rock.Serialization
{
public static class SerializationExtensions
{
/// <summary>
/// Deserializes an XML string into an object of type T.
/// </summary>
/// <typeparam name="T">The type of object represented by this string</typeparam>
/// <param name="str">The XML string to deserialize</param>
/// <returns>An object of type T</returns>
public static T FromXml<T>(this string str)
{
return DefaultXmlSerializer.Current.DeserializeFromString<T>(str);
}
/// <summary>
/// A reflection-friendly method to deserialize an XML string into an object.
/// </summary>
/// <typeparam name="T">The type of object represented by this string</typeparam>
/// <param name="str">The XML string to deserialize</param>
/// <returns>An object</returns>
public static object FromXml(this string str, System.Type type)
{
return DefaultXmlSerializer.Current.DeserializeFromString(str, type);
}
/// <summary>
/// Deserializes a JSON string into an object of type T.
/// </summary>
/// <typeparam name="T">The type of object represented by this string</typeparam>
/// <param name="str">The JSON string to deserialize</param>
/// <returns>An object of type T</returns>
public static T FromJson<T>(this string str)
{
return DefaultJsonSerializer.Current.DeserializeFromString<T>(str);
}
/// <summary>
/// A reflection-friendly method to deserialize an JSON string into an object.
/// </summary>
/// <typeparam name="T">The type of object represented by this string</typeparam>
/// <param name="str">The JSON string to deserialize</param>
/// <returns>An object</returns>
public static object FromJson(this string str, Type type)
{
return DefaultJsonSerializer.Current.DeserializeFromString(str, type);
}
}
}
|
mit
|
C#
|
62e0cf241b0074f4af073a22f271a4c2ac2beffc
|
Tweak to url builder
|
mcintyre321/Noodles,mcintyre321/Noodles
|
Noodles/PathExtension.cs
|
Noodles/PathExtension.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Walkies;
namespace Noodles
{
public static class PathExtension
{
static ConditionalWeakTable<object, string> urlRoots = new ConditionalWeakTable<object, string>();
public static T SetUrlRoot<T>(this T root, string urlRoot)
{
urlRoots.Remove(root);
urlRoots.GetValue(root, r => urlRoot);
return root;
}
public static string GetUrlRoot<T>(this T root)
{
return urlRoots.GetValue(root, r => null) as string;
}
public static string Path(this object o)
{
return o.WalkedPath("/");
}
public static string Url(this object o)
{
var walked = o.Walked();
var rootPrefix = walked.First().GetUrlRoot() ?? "/";
return rootPrefix + String.Join("/", o.Walked().Skip(1).Select(w => w.GetFragment()));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Walkies;
namespace Noodles
{
public static class PathExtension
{
static ConditionalWeakTable<object, string> urlRoots = new ConditionalWeakTable<object, string>();
public static T SetUrlRoot<T>(this T root, string urlRoot)
{
urlRoots.Remove(root);
urlRoots.GetValue(root, r => urlRoot);
return root;
}
public static string GetUrlRoot<T>(this T root)
{
return urlRoots.GetValue(root, r => null) as string;
}
public static string Path(this object o)
{
return o.WalkedPath("/");
}
public static string Url(this object o)
{
var walked = o.Walked();
var rootPrefix = walked.First().GetUrlRoot() ?? "/";
return rootPrefix + String.Join("/", o.Walked().Select(w => w.GetFragment()));
}
}
}
|
mit
|
C#
|
ce00b7de38f722a9021a1051ea5f69d562dc9616
|
Fix zip file extension handling
|
mstevenson/SeudoBuild
|
UnityBuildServer/Project/Archive/ZipArchiveStep.cs
|
UnityBuildServer/Project/Archive/ZipArchiveStep.cs
|
using System.IO;
using Ionic.Zip;
namespace UnityBuildServer
{
public class ZipArchiveStep : ArchiveStep
{
ZipArchiveConfig config;
public ZipArchiveStep(ZipArchiveConfig config)
{
this.config = config;
}
public override string TypeName
{
get
{
return "Zip File";
}
}
public override ArchiveInfo CreateArchive(BuildInfo buildInfo, Workspace workspace)
{
// Remove file extension in case it was accidentally included in the config data
string filename = Path.GetFileNameWithoutExtension(config.Filename);
// Replace in-line variables
filename = workspace.Replacements.ReplaceVariablesInText(config.Filename);
// Sanitize
filename = filename.Replace(' ', '_');
filename = filename + ".zip";
string filepath = $"{workspace.ArchivesDirectory}/{filename}";
// Remove old file
if (File.Exists(filepath)) {
File.Delete(filepath);
}
// Save zip file
using (var zipFile = new ZipFile())
{
zipFile.AddDirectory(workspace.WorkingDirectory);
zipFile.Save(filepath);
}
var archiveInfo = new ArchiveInfo { ArchiveFileName = filename };
return archiveInfo;
}
}
}
|
using System.IO;
using Ionic.Zip;
namespace UnityBuildServer
{
public class ZipArchiveStep : ArchiveStep
{
ZipArchiveConfig config;
public ZipArchiveStep(ZipArchiveConfig config)
{
this.config = config;
}
public override string TypeName
{
get
{
return "Zip File";
}
}
public override ArchiveInfo CreateArchive(BuildInfo buildInfo, Workspace workspace)
{
// Replace in-line variables
string filename = workspace.Replacements.ReplaceVariablesInText(config.Filename);
// Sanitize
filename = filename.Replace(' ', '_');
string filepath = $"{workspace.ArchivesDirectory}/{filename}.zip";
// Remove old file
if (File.Exists(filepath)) {
File.Delete(filepath);
}
// Save zip file
using (var zipFile = new ZipFile())
{
zipFile.AddDirectory(workspace.WorkingDirectory);
zipFile.Save(filepath);
}
var archiveInfo = new ArchiveInfo { ArchiveFileName = filename };
return archiveInfo;
}
}
}
|
mit
|
C#
|
754cf7d97e6fe83c9f3f5df35c65899a6268231e
|
Remove mismerge.
|
bartdesmet/roslyn,weltkante/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,dotnet/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,weltkante/roslyn
|
src/Workspaces/Core/Portable/Diagnostics/InternalDiagnosticsOptions.cs
|
src/Workspaces/Core/Portable/Diagnostics/InternalDiagnosticsOptions.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class InternalDiagnosticsOptions
{
private const string LocalRegistryPath = @"Roslyn\Internal\Diagnostics\";
public static readonly Option2<bool> PreferLiveErrorsOnOpenedFiles = new(nameof(InternalDiagnosticsOptions), "Live errors will be preferred over errors from build on opened files from same analyzer", defaultValue: true,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "Live errors will be preferred over errors from build on opened files from same analyzer"));
public static readonly Option2<bool> PreferBuildErrorsOverLiveErrors = new(nameof(InternalDiagnosticsOptions), "Errors from build will be preferred over live errors from same analyzer", defaultValue: true,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "Errors from build will be preferred over live errors from same analyzer"));
public static readonly Option2<bool> PutCustomTypeInBingSearch = new(nameof(InternalDiagnosticsOptions), nameof(PutCustomTypeInBingSearch), defaultValue: true,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "PutCustomTypeInBingSearch"));
public static readonly Option2<bool> CrashOnAnalyzerException = new(nameof(InternalDiagnosticsOptions), nameof(CrashOnAnalyzerException), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "CrashOnAnalyzerException"));
public static readonly Option2<bool> ProcessHiddenDiagnostics = new(nameof(InternalDiagnosticsOptions), nameof(ProcessHiddenDiagnostics), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "Process Hidden Diagnostics"));
public static readonly Option2<DiagnosticMode> NormalDiagnosticMode = new(nameof(InternalDiagnosticsOptions), nameof(NormalDiagnosticMode), defaultValue: DiagnosticMode.Default,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "NormalDiagnosticMode"));
public static readonly Option2<bool> EnableFileLoggingForDiagnostics = new(nameof(InternalDiagnosticsOptions), nameof(EnableFileLoggingForDiagnostics), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "EnableFileLoggingForDiagnostics"));
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class InternalDiagnosticsOptions
{
private const string LocalRegistryPath = @"Roslyn\Internal\Diagnostics\";
public static readonly Option2<bool> PreferLiveErrorsOnOpenedFiles = new(nameof(InternalDiagnosticsOptions), "Live errors will be preferred over errors from build on opened files from same analyzer", defaultValue: true,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "Live errors will be preferred over errors from build on opened files from same analyzer"));
public static readonly Option2<bool> PreferBuildErrorsOverLiveErrors = new(nameof(InternalDiagnosticsOptions), "Errors from build will be preferred over live errors from same analyzer", defaultValue: true,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "Errors from build will be preferred over live errors from same analyzer"));
public static readonly Option2<bool> PutCustomTypeInBingSearch = new(nameof(InternalDiagnosticsOptions), nameof(PutCustomTypeInBingSearch), defaultValue: true,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "PutCustomTypeInBingSearch"));
public static readonly Option2<bool> CrashOnAnalyzerException = new(nameof(InternalDiagnosticsOptions), nameof(CrashOnAnalyzerException), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "CrashOnAnalyzerException"));
public static readonly Option2<bool> ProcessHiddenDiagnostics = new(nameof(InternalDiagnosticsOptions), nameof(ProcessHiddenDiagnostics), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "Process Hidden Diagnostics"));
public static readonly Option2<DiagnosticMode> NormalDiagnosticMode = new(nameof(InternalDiagnosticsOptions), nameof(NormalDiagnosticMode), defaultValue: DiagnosticMode.Default,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "NormalDiagnosticMode"));
public static readonly Option2<DiagnosticMode> RazorDiagnosticMode = new(nameof(InternalDiagnosticsOptions), nameof(RazorDiagnosticMode), defaultValue: DiagnosticMode.Pull,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "RazorDiagnosticMode"));
public static readonly Option2<bool> EnableFileLoggingForDiagnostics = new(nameof(InternalDiagnosticsOptions), nameof(EnableFileLoggingForDiagnostics), defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + "EnableFileLoggingForDiagnostics"));
}
}
|
mit
|
C#
|
5dcaa30db92bfea036244a92c933ea227ec445a9
|
Remove main method
|
12joan/hangman
|
table.cs
|
table.cs
|
using System;
namespace Table {
public class Table {
public int Width;
public int Spacing;
public Table(int width, int spacing) {
Width = width;
Spacing = spacing;
}
}
}
|
using System;
namespace Table {
public class Table {
public int Width;
public int Spacing;
public Table(int width, int spacing) {
Width = width;
Spacing = spacing;
}
public static void Main() {
}
}
}
|
unlicense
|
C#
|
c407d0918eb1a3d3e9faf3156bf3ee126bbec7ca
|
fix warnings
|
Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode
|
PulumiDemo/Mocks.cs
|
PulumiDemo/Mocks.cs
|
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Testing;
namespace PulumiDemo
{
internal class Mocks : IMocks
{
public Task<(string id, object state)> NewResourceAsync(string type, string name, ImmutableDictionary<string, object> inputs, string provider, string id)
{
var outputs = ImmutableDictionary.CreateBuilder<string, object>();
// Forward all input parameters as resource outputs, so that we could test them.
outputs.AddRange(inputs);
// Set the name to resource name if it's not set explicitly in inputs.
if (!inputs.ContainsKey("name"))
outputs.Add("name", name);
if (type == "azure:storage/blob:Blob")
{
// Assets can't directly go through the engine.
// We don't need them in the test, so blank out the property for now.
outputs.Remove("source");
}
// For a Storage Account...
if (type == "azure:storage/account:Account")
{
// ... set its web endpoint property.
// Normally this would be calculated by Azure, so we have to mock it.
outputs.Add("primaryWebEndpoint", $"https://{name}.web.core.windows.net");
}
// Default the resource ID to `{name}_id`.
// We could also format it as `/subscription/abc/resourceGroups/xyz/...` if that was important for tests.
id ??= $"{name}_id";
return Task.FromResult((id, (object)outputs));
}
public Task<object> CallAsync(string token, ImmutableDictionary<string, object> inputs, string provider)
{
// We don't use this method in this particular test suite.
// Default to returning whatever we got as input.
return Task.FromResult((object)inputs);
}
}
}
|
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Testing;
namespace PulumiDemo
{
internal class Mocks : IMocks
{
public Task<(string id, object state)> NewResourceAsync(string type, string name, ImmutableDictionary<string, object> inputs, string? provider, string? id)
{
var outputs = ImmutableDictionary.CreateBuilder<string, object>();
// Forward all input parameters as resource outputs, so that we could test them.
outputs.AddRange(inputs);
// Set the name to resource name if it's not set explicitly in inputs.
if (!inputs.ContainsKey("name"))
outputs.Add("name", name);
if (type == "azure:storage/blob:Blob")
{
// Assets can't directly go through the engine.
// We don't need them in the test, so blank out the property for now.
outputs.Remove("source");
}
// For a Storage Account...
if (type == "azure:storage/account:Account")
{
// ... set its web endpoint property.
// Normally this would be calculated by Azure, so we have to mock it.
outputs.Add("primaryWebEndpoint", $"https://{name}.web.core.windows.net");
}
// Default the resource ID to `{name}_id`.
// We could also format it as `/subscription/abc/resourceGroups/xyz/...` if that was important for tests.
id ??= $"{name}_id";
return Task.FromResult((id, (object)outputs));
}
public Task<object> CallAsync(string token, ImmutableDictionary<string, object> inputs, string? provider)
{
// We don't use this method in this particular test suite.
// Default to returning whatever we got as input.
return Task.FromResult((object)inputs);
}
}
}
|
mit
|
C#
|
205148d65e08cb22f2f89e291d3956ee7af5b9cc
|
Fix cross-platform test seperator failure for MultipartTests.can_build_multipart_content()
|
johnmbaughman/Flurl,tmenier/Flurl
|
Test/Flurl.Test/Http/MultipartTests.cs
|
Test/Flurl.Test/Http/MultipartTests.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
using Flurl.Http.Content;
using NUnit.Framework;
namespace Flurl.Test.Http
{
[TestFixture, Parallelizable]
public class MultipartTests
{
[Test]
public void can_build_multipart_content() {
var content = new CapturedMultipartContent()
.AddString("string", "foo")
.AddStringParts(new { part1 = 1, part2 = 2, part3 = (string)null }) // part3 should be excluded
.AddFile("file", Path.Combine("path", "to", "image.jpg"), "image/jpeg")
.AddJson("json", new { foo = "bar" })
.AddUrlEncoded("urlEnc", new { fizz = "buzz" });
Assert.AreEqual(6, content.Parts.Length);
Assert.AreEqual("string", content.Parts[0].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedStringContent>(content.Parts[0]);
Assert.AreEqual("foo", (content.Parts[0] as CapturedStringContent).Content);
Assert.AreEqual("part1", content.Parts[1].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedStringContent>(content.Parts[1]);
Assert.AreEqual("1", (content.Parts[1] as CapturedStringContent).Content);
Assert.AreEqual("part2", content.Parts[2].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedStringContent>(content.Parts[2]);
Assert.AreEqual("2", (content.Parts[2] as CapturedStringContent).Content);
Assert.AreEqual("file", content.Parts[3].Headers.ContentDisposition.Name);
Assert.AreEqual("image.jpg", content.Parts[3].Headers.ContentDisposition.FileName);
Assert.IsInstanceOf<FileContent>(content.Parts[3]);
Assert.AreEqual("json", content.Parts[4].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedJsonContent>(content.Parts[4]);
Assert.AreEqual("{\"foo\":\"bar\"}", (content.Parts[4] as CapturedJsonContent).Content);
Assert.AreEqual("urlEnc", content.Parts[5].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedUrlEncodedContent>(content.Parts[5]);
Assert.AreEqual("fizz=buzz", (content.Parts[5] as CapturedUrlEncodedContent).Content);
}
[Test]
public void must_provide_required_args_to_builder() {
var content = new CapturedMultipartContent();
Assert.Throws<ArgumentNullException>(() => content.AddStringParts(null));
Assert.Throws<ArgumentNullException>(() => content.AddString("other", null));
Assert.Throws<ArgumentException>(() => content.AddString(null, "hello!"));
Assert.Throws<ArgumentException>(() => content.AddFile(" ", "path"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
using Flurl.Http.Content;
using NUnit.Framework;
namespace Flurl.Test.Http
{
[TestFixture, Parallelizable]
public class MultipartTests
{
[Test]
public void can_build_multipart_content() {
var content = new CapturedMultipartContent()
.AddString("string", "foo")
.AddStringParts(new { part1 = 1, part2 = 2, part3 = (string)null }) // part3 should be excluded
.AddFile("file", @"path\to\image.jpg", "image/jpeg")
.AddJson("json", new { foo = "bar" })
.AddUrlEncoded("urlEnc", new { fizz = "buzz" });
Assert.AreEqual(6, content.Parts.Length);
Assert.AreEqual("string", content.Parts[0].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedStringContent>(content.Parts[0]);
Assert.AreEqual("foo", (content.Parts[0] as CapturedStringContent).Content);
Assert.AreEqual("part1", content.Parts[1].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedStringContent>(content.Parts[1]);
Assert.AreEqual("1", (content.Parts[1] as CapturedStringContent).Content);
Assert.AreEqual("part2", content.Parts[2].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedStringContent>(content.Parts[2]);
Assert.AreEqual("2", (content.Parts[2] as CapturedStringContent).Content);
Assert.AreEqual("file", content.Parts[3].Headers.ContentDisposition.Name);
Assert.AreEqual("image.jpg", content.Parts[3].Headers.ContentDisposition.FileName);
Assert.IsInstanceOf<FileContent>(content.Parts[3]);
Assert.AreEqual("json", content.Parts[4].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedJsonContent>(content.Parts[4]);
Assert.AreEqual("{\"foo\":\"bar\"}", (content.Parts[4] as CapturedJsonContent).Content);
Assert.AreEqual("urlEnc", content.Parts[5].Headers.ContentDisposition.Name);
Assert.IsInstanceOf<CapturedUrlEncodedContent>(content.Parts[5]);
Assert.AreEqual("fizz=buzz", (content.Parts[5] as CapturedUrlEncodedContent).Content);
}
[Test]
public void must_provide_required_args_to_builder() {
var content = new CapturedMultipartContent();
Assert.Throws<ArgumentNullException>(() => content.AddStringParts(null));
Assert.Throws<ArgumentNullException>(() => content.AddString("other", null));
Assert.Throws<ArgumentException>(() => content.AddString(null, "hello!"));
Assert.Throws<ArgumentException>(() => content.AddFile(" ", "path"));
}
}
}
|
mit
|
C#
|
f2bbb3613e54a83e87b8173267aaf90343909bd9
|
Update Examples to print out the user's projects list
|
mbrewerton/DotNetPivotalTrackerApi
|
Examples/Program.cs
|
Examples/Program.cs
|
using DotNetPivotalTrackerApi.Enums;
using DotNetPivotalTrackerApi.Models.Project;
using DotNetPivotalTrackerApi.Models.User;
using DotNetPivotalTrackerApi.Services;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examples
{
class Program
{
private static string _apiKey = ConfigurationManager.AppSettings["ApiKey"];
private static int _projectId = 2008069;
private static PivotalTracker _mytracker;
static void Main(string[] args)
{
_mytracker = new PivotalTracker(_apiKey);
//GetUserInfo();
GetProjects();
//CreateNewStory();
Console.ReadKey();
}
private static void GetUserInfo()
{
// This method uses the current API Key for the tracker (_mytracker) to get your user data
PivotalUser user = _mytracker.GetUser();
Console.WriteLine($"User Info: {user.Name} ({user.Initials}) has username {user.Username} and Email {user.Email}");
}
private static void GetProjects()
{
PivotalUser user = _mytracker.GetUser();
// This method uses the current API Key to get the projects the user is assigned to
List<PivotalProject> projects = _mytracker.GetProjects();
Console.WriteLine($"{user.Name} is assigned to the following projects:");
foreach(var project in projects)
{
Console.WriteLine($@" - {project.Name}");
}
}
private static void CreateNewStory()
{
// This will create a new feature, "Please raise me a feature" with no labels
_mytracker.CreateNewStory(_projectId, "Please raise me a feature", StoryType.feature);
Console.WriteLine("Story has been raised, please check the project you used.");
}
}
}
|
using DotNetPivotalTrackerApi.Enums;
using DotNetPivotalTrackerApi.Models.User;
using DotNetPivotalTrackerApi.Services;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examples
{
class Program
{
private static string _apiKey = ConfigurationManager.AppSettings["ApiKey"];
private static int _projectId = 2008069;
private static PivotalTracker _mytracker;
static void Main(string[] args)
{
_mytracker = new PivotalTracker(_apiKey);
//GetUserInfo();
//GetProjects();
CreateNewStory();
Console.ReadKey();
}
private static void GetUserInfo()
{
// This method uses the current API Key for the tracker (_mytracker) to get your user data
PivotalUser user = _mytracker.GetUser();
Console.WriteLine($"User Info: {user.Name} ({user.Initials}) has username {user.Username} and Email {user.Email}");
}
private static void GetProjects()
{
PivotalUser user = _mytracker.GetUser();
// This method uses the current API Key to get the projects the user is assigned to
_mytracker.GetProjects();
}
private static void CreateNewStory()
{
// This will create a new feature, "Please raise me a feature" with no labels
_mytracker.CreateNewStory(_projectId, "Please raise me a feature", StoryType.feature);
Console.WriteLine("Story has been raised, please check the project you used.");
}
}
}
|
mit
|
C#
|
3327669b567300737c575019a53d206c7fc33779
|
Update NumberObjectValue.cs
|
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
|
main/Smartsheet/Api/Models/NumberObjectValue.cs
|
main/Smartsheet/Api/Models/NumberObjectValue.cs
|
// #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2018 SmartsheetClient
// %%
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Smartsheet.Api.Models
{
class NumberObjectValue : IPrimitiveObjectValue<double>
{
private double value;
public NumberObjectValue(double value)
{
this.value = value;
}
public virtual double Value
{
get { return this.value; }
set { this.value = value; }
}
public virtual ObjectValueType ObjectType
{
get { return ObjectValueType.NUMBER; }
}
public virtual void Serialize(JsonWriter writer)
{
writer.WriteValue(value);
}
}
}
|
// #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2018 SmartsheetClient
// %%
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed To in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// %[license]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Smartsheet.Api.Models
{
class NumberObjectValue : IPrimitiveObjectValue<double>
{
private double value;
public NumberObjectValue(double value)
{
this.value = value;
}
public virtual double Value
{
get { return this.value; }
set { this.value = value; }
}
public virtual ObjectValueType ObjectType
{
get { return ObjectValueType.NUMBER; }
}
public virtual void Serialize(JsonWriter writer)
{
writer.WriteValue(value);
}
}
}
|
apache-2.0
|
C#
|
ba11b60f7a80d62ea3604e7c5f605afe4d1993ce
|
Fix exception message in RepositoryBranchState indexer when revisions are not in order.
|
CamTechConsultants/CvsntGitImporter
|
RepositoryBranchState.cs
|
RepositoryBranchState.cs
|
/*
* John Hall <john.hall@camtechconsultants.com>
* Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CTC.CvsntGitImporter
{
/// <summary>
/// Tracks the versions of all files in the repository for a specific branch.
/// </summary>
class RepositoryBranchState
{
private readonly string m_branch;
private readonly Dictionary<string, Revision> m_files = new Dictionary<string, Revision>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets or sets the current revision of a file.
/// </summary>
public Revision this[string filename]
{
get
{
Revision value;
if (m_files.TryGetValue(filename, out value))
return value;
else
return Revision.Empty;
}
set
{
var previousRevision = this[filename];
if (!previousRevision.DirectlyPrecedes(value))
{
throw new RepositoryConsistencyException(String.Format(
"Revision r{0} in {1} did not directly precede r{2}",
value, filename, previousRevision));
}
m_files[filename] = value;
}
}
/// <summary>
/// Gets all currently live files.
/// </summary>
public IEnumerable<string> LiveFiles
{
get { return m_files.Keys; }
}
public RepositoryBranchState(string branch)
{
m_branch = branch;
}
/// <summary>
/// Copy constructor.
/// </summary>
private RepositoryBranchState(string branch, RepositoryBranchState other) : this(branch)
{
foreach (var kvp in other.m_files)
m_files[kvp.Key] = kvp.Value;
}
/// <summary>
/// Apply a commit.
/// </summary>
public void Apply(Commit commit)
{
foreach (var f in commit)
{
if (f.IsDead)
m_files.Remove(f.File.Name);
else
m_files[f.File.Name] = f.Revision;
}
}
/// <summary>
/// Make a copy of this state.
/// </summary>
public RepositoryBranchState Copy(string branch)
{
return new RepositoryBranchState(branch, this);
}
}
}
|
/*
* John Hall <john.hall@camtechconsultants.com>
* Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CTC.CvsntGitImporter
{
/// <summary>
/// Tracks the versions of all files in the repository for a specific branch.
/// </summary>
class RepositoryBranchState
{
private readonly string m_branch;
private readonly Dictionary<string, Revision> m_files = new Dictionary<string, Revision>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets or sets the current revision of a file.
/// </summary>
public Revision this[string filename]
{
get
{
Revision value;
if (m_files.TryGetValue(filename, out value))
return value;
else
return Revision.Empty;
}
set
{
var previousRevision = this[filename];
if (!previousRevision.DirectlyPrecedes(value))
{
throw new RepositoryConsistencyException(String.Format(
"Revision r{0} in {1} did not directly precede r{2}",
value, previousRevision, filename));
}
m_files[filename] = value;
}
}
/// <summary>
/// Gets all currently live files.
/// </summary>
public IEnumerable<string> LiveFiles
{
get { return m_files.Keys; }
}
public RepositoryBranchState(string branch)
{
m_branch = branch;
}
/// <summary>
/// Copy constructor.
/// </summary>
private RepositoryBranchState(string branch, RepositoryBranchState other) : this(branch)
{
foreach (var kvp in other.m_files)
m_files[kvp.Key] = kvp.Value;
}
/// <summary>
/// Apply a commit.
/// </summary>
public void Apply(Commit commit)
{
foreach (var f in commit)
{
if (f.IsDead)
m_files.Remove(f.File.Name);
else
m_files[f.File.Name] = f.Revision;
}
}
/// <summary>
/// Make a copy of this state.
/// </summary>
public RepositoryBranchState Copy(string branch)
{
return new RepositoryBranchState(branch, this);
}
}
}
|
mit
|
C#
|
8c0900d7f72669496c75eeeef5feaa84fcac0b1a
|
Make VimeoApiException public, fixed #66
|
mohibsheth/vimeo-dot-net,mfilippov/vimeo-dot-net
|
src/VimeoDotNet/Exceptions/VimeoApiException.cs
|
src/VimeoDotNet/Exceptions/VimeoApiException.cs
|
using System;
using System.Runtime.Serialization;
namespace VimeoDotNet.Exceptions
{
/// <summary>
/// VimeoApiException
/// </summary>
[Serializable]
public class VimeoApiException : ApplicationException
{
/// <summary>
/// Create new VimeoApiException
/// </summary>
public VimeoApiException()
{
}
/// <summary>
/// Create new VimeoApiException with message
/// </summary>
/// <param name="message">Message</param>
public VimeoApiException(string message)
: base(message)
{
}
/// <summary>
/// Create new VimeoApiException with message and inner exception
/// </summary>
/// <param name="message">Message</param>
/// <param name="innerException"></param>
public VimeoApiException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Create new VimeoApiException
/// </summary>
public VimeoApiException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
|
using System;
using System.Runtime.Serialization;
namespace VimeoDotNet.Exceptions
{
[Serializable]
internal class VimeoApiException : ApplicationException
{
public VimeoApiException()
{
}
public VimeoApiException(string message)
: base(message)
{
}
public VimeoApiException(string message, Exception innerException)
: base(message, innerException)
{
}
public VimeoApiException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
|
mit
|
C#
|
6f2cb94ff01b3a25531fb19a1eb40f064693901e
|
implementa cambios de colores en gradiente de background
|
jopar219/GlobalGameJam2017
|
Assets/Scripts/GradientBackround.cs
|
Assets/Scripts/GradientBackround.cs
|
using UnityEngine;
using System.Collections;
public class GradientBackround : MonoBehaviour {
public Color topColor;
public Color bottomColor;
public Color[] colors = new Color[] {new Color(0.95f, 0.89f, 0.05f), new Color(0.92f, 0.7f, 0.02f), new Color(0.709f, 0.41f, 0.27f), new Color(0.109f, 0.009f, 0.009f), new Color(0.0f, 0.0f, 0.0f)};
public int gradientLayer = 7;
public GameObject ball;
private Mesh mesh;
void Awake() {
gradientLayer = Mathf.Clamp(gradientLayer, 0, 31);
if (!GetComponent<Camera>()) {
Debug.LogError ("Must attach GradientBackground script to the camera");
return;
}
GetComponent<Camera>().clearFlags = CameraClearFlags.Depth;
GetComponent<Camera>().cullingMask = GetComponent<Camera>().cullingMask & ~(1 << gradientLayer);
Camera gradientCam = new GameObject("Gradient Cam", typeof(Camera)).GetComponent<Camera>();
gradientCam.depth = GetComponent<Camera>().depth - 1;
gradientCam.cullingMask = 1 << gradientLayer;
mesh = new Mesh();
mesh.vertices = new Vector3[4]
{new Vector3(-100f, .577f, 1f), new Vector3(100f, .577f, 1f), new Vector3(-100f, -.577f, 1f), new Vector3(100f, -.577f, 1f)};
mesh.triangles = new int[6] {0, 1, 2, 1, 3, 2};
mesh.colors = new Color[4] {topColor, topColor, bottomColor, bottomColor};
Shader shader = Shader.Find("Gradient");
Material mat = new Material(shader);
GameObject gradientPlane = new GameObject("Gradient Plane", typeof(MeshFilter), typeof(MeshRenderer));
((MeshFilter)gradientPlane.GetComponent(typeof(MeshFilter))).mesh = mesh;
gradientPlane.GetComponent<Renderer>().material = mat;
gradientPlane.layer = gradientLayer;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float tilNext = ball.GetComponent<BTBPlayerController>().TimeTilNextBounce;
if(tilNext <= 1.0f) {
bottomColor = colors[0];
topColor = colors[1];
}
else if(tilNext > 1.0f && tilNext <= 2.0f) {
bottomColor = colors[1];
topColor = colors[2];
}
else if(tilNext > 2.0f && tilNext <= 3.0f) {
bottomColor = colors[2];
topColor = colors[3];
}
else {
bottomColor = colors[3];
topColor = colors[4];
}
UpdateGradients();
}
void UpdateGradients() {
mesh.colors = new Color[4] {topColor, topColor, bottomColor, bottomColor};
}
}
|
using UnityEngine;
using System.Collections;
public class GradientBackround : MonoBehaviour {
public Color topColor;
public Color bottomColor;
public int gradientLayer = 7;
void Awake() {
gradientLayer = Mathf.Clamp(gradientLayer, 0, 31);
if (!GetComponent<Camera>()) {
Debug.LogError ("Must attach GradientBackground script to the camera");
return;
}
GetComponent<Camera>().clearFlags = CameraClearFlags.Depth;
GetComponent<Camera>().cullingMask = GetComponent<Camera>().cullingMask & ~(1 << gradientLayer);
Camera gradientCam = new GameObject("Gradient Cam", typeof(Camera)).GetComponent<Camera>();
gradientCam.depth = GetComponent<Camera>().depth - 1;
gradientCam.cullingMask = 1 << gradientLayer;
Mesh mesh = new Mesh();
mesh.vertices = new Vector3[4]
{new Vector3(-100f, .577f, 1f), new Vector3(100f, .577f, 1f), new Vector3(-100f, -.577f, 1f), new Vector3(100f, -.577f, 1f)};
mesh.colors = new Color[4] {topColor, topColor, bottomColor, bottomColor};
mesh.triangles = new int[6] {0, 1, 2, 1, 3, 2};
Shader shader = Shader.Find("Gradient");
Material mat = new Material(shader);
GameObject gradientPlane = new GameObject("Gradient Plane", typeof(MeshFilter), typeof(MeshRenderer));
((MeshFilter)gradientPlane.GetComponent(typeof(MeshFilter))).mesh = mesh;
gradientPlane.GetComponent<Renderer>().material = mat;
gradientPlane.layer = gradientLayer;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
mit
|
C#
|
ee79cfbfd597f4047083bafec7ebe53204dcff30
|
Fix 81 TIiles mod name
|
boformer/BuildingThemes
|
BuildingThemes/BuildingThemesMod.cs
|
BuildingThemes/BuildingThemesMod.cs
|
using ICities;
using BuildingThemes.GUI;
using UnityEngine;
namespace BuildingThemes
{
public class BuildingThemesMod : IUserMod
{
// we'll use this variable to pass the building position to GetRandomBuildingInfo method. It's here to make possible 81 Tiles compatibility
public static Vector3 position;
public static readonly string EIGHTY_ONE_MOD = "81 Tiles (Fixed for C:S 1.2+)";
public string Name => "Building Themes";
public string Description => "Create building themes and apply them to cities and districts.";
public void OnSettingsUI(UIHelperBase helper)
{
UIHelperBase group = helper.AddGroup("Building Themes");
group.AddCheckbox("Unlock Policies Panel From Start", PolicyPanelEnabler.Unlock, delegate (bool c) { PolicyPanelEnabler.Unlock = c; });
group.AddCheckbox("Enable Prefab Cloning (experimental, not stable!)", BuildingVariationManager.Enabled, delegate (bool c) { BuildingVariationManager.Enabled = c; });
group.AddGroup("Warning: When you disable this option, spawned clones will disappear!");
group.AddCheckbox("Warning message when selecting an invalid theme", UIThemePolicyItem.showWarning, delegate (bool c) { UIThemePolicyItem.showWarning = c; });
group.AddCheckbox("Generate Debug Output", Debugger.Enabled, delegate (bool c) { Debugger.Enabled = c; });
}
}
}
|
using ICities;
using BuildingThemes.GUI;
using UnityEngine;
namespace BuildingThemes
{
public class BuildingThemesMod : IUserMod
{
// we'll use this variable to pass the building position to GetRandomBuildingInfo method. It's here to make possible 81 Tiles compatibility
public static Vector3 position;
public static readonly string EIGHTY_ONE_MOD = "81 Tiles(Fixed for C:S 1.2+)";
public string Name => "Building Themes";
public string Description => "Create building themes and apply them to cities and districts.";
public void OnSettingsUI(UIHelperBase helper)
{
UIHelperBase group = helper.AddGroup("Building Themes");
group.AddCheckbox("Unlock Policies Panel From Start", PolicyPanelEnabler.Unlock, delegate (bool c) { PolicyPanelEnabler.Unlock = c; });
group.AddCheckbox("Enable Prefab Cloning (experimental, not stable!)", BuildingVariationManager.Enabled, delegate (bool c) { BuildingVariationManager.Enabled = c; });
group.AddGroup("Warning: When you disable this option, spawned clones will disappear!");
group.AddCheckbox("Warning message when selecting an invalid theme", UIThemePolicyItem.showWarning, delegate (bool c) { UIThemePolicyItem.showWarning = c; });
group.AddCheckbox("Generate Debug Output", Debugger.Enabled, delegate (bool c) { Debugger.Enabled = c; });
}
}
}
|
mit
|
C#
|
291fef0f34866ce3601d1fdf0c807aca93ee1667
|
Update Besiege version
|
yut23/besiege-button-mapper
|
ButtonMapperMod/BesiegeModLoader.cs
|
ButtonMapperMod/BesiegeModLoader.cs
|
using spaar.ModLoader;
using System;
using UnityEngine;
namespace yut23.ButtonMapper
{
public class BesiegeModLoader : Mod
{
public GameObject temp;
public override string Name { get { return "button-mapper-mod"; } }
public override string DisplayName { get { return "Button Mapper Mod"; } }
public override string Author { get { return "Yut23"; } }
public override Version Version { get { return new Version(1, 0); } }
public override string BesiegeVersion { get { return "v0.11"; } }
public override bool CanBeUnloaded { get { return true; } }
public override void OnLoad()
{
GameObject gameObject = new GameObject();
gameObject.AddComponent<ButtonMapperMod>();
GameObject.DontDestroyOnLoad(gameObject);
}
public override void OnUnload() { GameObject.Destroy(temp); }
}
}
|
using spaar.ModLoader;
using System;
using UnityEngine;
namespace yut23.ButtonMapper
{
public class BesiegeModLoader : Mod
{
public GameObject temp;
public override string Name { get { return "button-mapper-mod"; } }
public override string DisplayName { get { return "Button Mapper Mod"; } }
public override string Author { get { return "Yut23"; } }
public override Version Version { get { return new Version(1, 0); } }
public override string BesiegeVersion { get { return "v0.10"; } }
public override bool CanBeUnloaded { get { return true; } }
public override void OnLoad()
{
GameObject gameObject = new GameObject();
gameObject.AddComponent<ButtonMapperMod>();
GameObject.DontDestroyOnLoad(gameObject);
}
public override void OnUnload() { GameObject.Destroy(temp); }
}
}
|
mit
|
C#
|
b1b3087f28afd53cd5a6f971f91a7ca98ec629d6
|
Improve test for DateTime.StartOfWeek
|
DaveSenn/Extend
|
PortableExtensions.Testing/System.DateTime/DateTime.StartOfWeek.Test.cs
|
PortableExtensions.Testing/System.DateTime/DateTime.StartOfWeek.Test.cs
|
#region Using
using System;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class DateTimeExTest
{
[Test]
public void StartOfWeekTestCase()
{
var dateTime = new DateTime(2014, 3, 27);
var expected = new DateTime(2014, 3, 24);
var actual = dateTime.StartOfWeek();
Assert.AreEqual(expected, actual);
expected = new DateTime(2014, 3, 26);
actual = dateTime.StartOfWeek(DayOfWeek.Wednesday);
Assert.AreEqual(expected, actual);
}
[Test]
public void StartOfWeekTestCase1()
{
var dateTime = new DateTime(2014, 3, 27);
var expected = new DateTime(2014, 3, 26);
var actual = dateTime.StartOfWeek(DayOfWeek.Wednesday);
Assert.AreEqual(expected, actual);
}
[Test]
public void StartOfWeekTestCase2()
{
var day = DayOfWeek.Sunday - DayOfWeek.Saturday;
var week = new DateTime(2014, 09, 21);
var expected = new DateTime(2014, 09, 20);
var actual = week.StartOfWeek(DayOfWeek.Saturday);
Assert.AreEqual(expected, actual);
}
}
}
|
#region Using
using System;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class DateTimeExTest
{
[Test]
public void StartOfWeekTestCase()
{
var dateTime = new DateTime( 2014, 3, 27 );
var expected = new DateTime( 2014, 3, 24 );
var actual = dateTime.StartOfWeek();
Assert.AreEqual( expected, actual );
expected = new DateTime( 2014, 3, 26 );
actual = dateTime.StartOfWeek( DayOfWeek.Wednesday );
Assert.AreEqual( expected, actual );
}
}
}
|
mit
|
C#
|
4c0128d40daa5994c567c40f77fc65027b80fbe0
|
Improve performance.
|
mntone/ToastNotificationKit,mntone/ToastNotificationKit
|
Mntone.ToastNotificationServer/Mntone.ToastNotificationServer/Frameworks/ImageHelper.cs
|
Mntone.ToastNotificationServer/Mntone.ToastNotificationServer/Frameworks/ImageHelper.cs
|
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Mntone.ToastNotificationServer.Frameworks
{
public static class ImageHelper
{
public static WriteableBitmap CropAndResize(BitmapSource source, Rect sourceRect, Size expectedSize)
{
return CropAndResize(new WriteableBitmap(source), sourceRect, expectedSize);
}
public static WriteableBitmap CropAndResize(WriteableBitmap source, Rect sourceRect, Size expectedSize)
{
var sourceX = (int)sourceRect.X;
var sourceY = (int)sourceRect.Y;
var sourceWidth = source.PixelWidth;
var sourceStride = 4 * sourceWidth;
var sourceHeight = source.PixelHeight;
if (sourceRect.Right > sourceWidth || sourceRect.Bottom > sourceHeight)
{
throw new ArgumentOutOfRangeException();
}
var resultWidth = (int)expectedSize.Width;
var resultHeight = (int)expectedSize.Height;
var wr = sourceRect.Width / expectedSize.Width;
var hr = sourceRect.Height / expectedSize.Height;
var destination = new WriteableBitmap(resultWidth, resultHeight, 96, 96, PixelFormats.Bgra32, null);
destination.Lock();
unsafe
{
var src = (int*)source.BackBuffer;
var ptr = (int*)destination.BackBuffer;
for (var i = 0; i < resultHeight; ++i)
{
for (var j = 0; j < resultWidth; ++j)
{
var srcPixel = src + sourceWidth * (sourceY + (int)(i * hr)) + (sourceX + (int)(j * wr));
*ptr++ = *srcPixel;
}
}
}
destination.Unlock();
destination.Freeze();
return destination;
}
}
}
|
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Mntone.ToastNotificationServer.Frameworks
{
public static class ImageHelper
{
public static WriteableBitmap CropAndResize(BitmapSource source, Rect sourceRect, Size expectedSize)
{
return CropAndResize(new WriteableBitmap(source), sourceRect, expectedSize);
}
public static WriteableBitmap CropAndResize(WriteableBitmap source, Rect sourceRect, Size expectedSize)
{
var sourceX = (int)sourceRect.X;
var sourceY = (int)sourceRect.Y;
var sourceWidth = source.PixelWidth;
var sourceStride = 4 * sourceWidth;
var sourceHeight = source.PixelHeight;
if (sourceRect.Right > sourceWidth || sourceRect.Bottom > sourceHeight)
{
throw new ArgumentOutOfRangeException();
}
var resultWidth = (int)expectedSize.Width;
var resultHeight = (int)expectedSize.Height;
var wr = sourceRect.Width / expectedSize.Width;
var hr = sourceRect.Height / expectedSize.Height;
var destination = new WriteableBitmap(resultWidth, resultHeight, 96, 96, PixelFormats.Bgra32, null);
destination.Lock();
unsafe
{
byte* src = (byte*)source.BackBuffer;
byte* ptr = (byte*)destination.BackBuffer;
for (var i = 0; i < resultHeight; ++i)
{
for (var j = 0; j < resultWidth; ++j)
{
byte* srcPixel = src + sourceStride * (sourceY + (int)(i * hr)) + 4 * (sourceX + (int)(j * wr));
*ptr++ = srcPixel[0];
*ptr++ = srcPixel[1];
*ptr++ = srcPixel[2];
*ptr++ = srcPixel[3];
}
}
}
destination.Unlock();
destination.Freeze();
return destination;
}
}
}
|
mit
|
C#
|
7b81eeddd4ac839eedc9be7e9daa9f1b47e26463
|
Prepare for Master Merge
|
OfficeDev/PnP-PowerShell,kilasuit/PnP-PowerShell
|
Commands/Properties/AssemblyInfo.cs
|
Commands/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if SP2013
[assembly: AssemblyTitle("SharePointPnP.PowerShell.SP2013.Commands")]
#elif SP2016
[assembly: AssemblyTitle("SharePointPnP.PowerShell.SP2016.Commands")]
#else
[assembly: AssemblyTitle("SharePointPnP.PowerShell.Online.Commands")]
#endif
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
#if SP2013
[assembly: AssemblyProduct("SharePointPnP.PowerShell.SP2013.Commands")]
#elif SP2016
[assembly: AssemblyProduct("SharePointPnP.PowerShell.SP2016.Commands")]
#else
[assembly: AssemblyProduct("SharePointPnP.PowerShell.Online.Commands")]
#endif
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2eebc303-84d4-4dbb-96de-8aaa75248120")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.23.1802.0")]
[assembly: AssemblyFileVersion("2.23.1802.0")]
[assembly: InternalsVisibleTo("SharePointPnP.PowerShell.Tests")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if SP2013
[assembly: AssemblyTitle("SharePointPnP.PowerShell.SP2013.Commands")]
#elif SP2016
[assembly: AssemblyTitle("SharePointPnP.PowerShell.SP2016.Commands")]
#else
[assembly: AssemblyTitle("SharePointPnP.PowerShell.Online.Commands")]
#endif
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
#if SP2013
[assembly: AssemblyProduct("SharePointPnP.PowerShell.SP2013.Commands")]
#elif SP2016
[assembly: AssemblyProduct("SharePointPnP.PowerShell.SP2016.Commands")]
#else
[assembly: AssemblyProduct("SharePointPnP.PowerShell.Online.Commands")]
#endif
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2eebc303-84d4-4dbb-96de-8aaa75248120")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.22.1801.0")]
[assembly: AssemblyFileVersion("2.22.1801.0")]
[assembly: InternalsVisibleTo("SharePointPnP.PowerShell.Tests")]
|
mit
|
C#
|
daa30eaa45515e3d9f3afc7f5965a30742e8f3fa
|
test passing
|
gleroi/selfnet,gleroi/selfnet
|
Selfnet.Tests/Context.cs
|
Selfnet.Tests/Context.cs
|
namespace Selfnet.Tests
{
internal static class Context
{
private static SelfossApi api;
public static ConnectionOptions Options = new ConnectionOptions
{
Host = "host.com",
Base = "selfoss",
Username = "",
Password = ""
};
public static readonly HttpGatewayFake Http = new HttpGatewayFake();
public static SelfossApi Api()
{
if (api == null)
{
api = new SelfossApi(Options, Http);
//api = new SelfossApi(Options);
}
return api;
}
}
}
|
namespace Selfnet.Tests
{
internal static class Context
{
private static SelfossApi api;
public static ConnectionOptions Options = new ConnectionOptions
{
Host = "",
Base = "",
Username = "",
Password = ""
};
public static readonly HttpGatewayFake Http = new HttpGatewayFake();
public static SelfossApi Api()
{
if (api == null)
{
api = new SelfossApi(Options, Http);
//api = new SelfossApi(Options);
}
return api;
}
}
}
|
mit
|
C#
|
f7f5c79e60de7e2a8f32a66e306f847b7814d40e
|
Fix merge
|
jameschch/GeneticTreeAlgorithm
|
GeneticTree/Rule.cs
|
GeneticTree/Rule.cs
|
using GeneticTree.Signal;
using System;
using System.Linq;
using System.Text;
namespace GeneticTree
{
/// <summary>
/// This class wires and evaluates dynamically a set of <see cref="ISignal" /> and a set of logical
/// operators in string format in the form:
/// Indicator1|Operator1|Indicator2|Operator2|...|IndicatorN|OperatorN|
/// </summary>
public class Rule
{
private readonly ISignal _signal;
static Func<bool, bool, bool> and = (a, b) => a && b;
static Func<bool, bool, bool> or = (a, b) => a || b;
static Func<bool, bool, bool> andFirst = (a, b) => (a && b);
static Func<bool, bool, bool> orFirst = (a, b) => (a || b);
public Rule(ISignal signal)
{
_signal = signal;
}
public bool IsReady()
{
return IsReady(_signal);
}
private bool IsReady(ISignal signal)
{
return signal.IsReady && signal.Child == null || IsReady(signal.Child);
}
public bool IsTrue()
{
return IsTrue(_signal);
}
public bool IsTrue(ISignal signal, bool? siblingIsTrue = null)
{
if (signal.Child == null && signal.Sibling == null)
{
return signal.IsTrue();
}
bool isSibling = signal.Sibling != null;
var op = signal.Operator == Operator.AND ? isSibling ? andFirst : and : isSibling ? orFirst : or;
var next = isSibling ? signal.Sibling : signal.Child;
return op(signal.IsTrue(), IsTrue(next));
}
}
}
|
using GeneticTree.Signal;
using System;
using System.Linq;
using System.Text;
namespace GeneticTree
{
/// <summary>
/// This class wires and evaluates dynamically a set of <see cref="ISignal" /> and a set of logical
/// operators in string format in the form:
/// Indicator1|Operator1|Indicator2|Operator2|...|IndicatorN|OperatorN|
/// </summary>
public class Rule
{
private readonly ISignal _signal;
static Func<bool, bool, bool> and = (a, b) => a && b;
static Func<bool, bool, bool> or = (a, b) => a || b;
static Func<bool, bool, bool> andFirst = (a, b) => (a && b);
static Func<bool, bool, bool> orFirst = (a, b) => (a || b);
public Rule(ISignal signal)
{
_signal = signal;
}
public bool IsReady()
{
return IsReady(_signal);
}
private bool IsReady(ISignal signal)
{
return signal.IsReady && signal.Child == null || IsReady(signal.Child);
}
public bool IsTrue()
{
return IsTrue(_signal);
}
public bool IsTrue(ISignal signal, bool? siblingIsTrue = null)
{
if (signal.Child == null && signal.Sibling == null)
{
return signal.IsTrue();
}
bool isSibling = signal.Sibling != null;
var op = signal.Operator == Operator.AND ? isSibling ? andFirst : and : isSibling ? orFirst : or;
var next = isSibling ? signal.Sibling : signal.Child;
return op(signal.IsTrue(), IsTrue(next));
}
}
}
?s
|
apache-2.0
|
C#
|
034b71d40d33386a49b994037c6389d7fa5daf73
|
Update to version 2.3
|
arogozine/EnumUtilities
|
EnumUtil/Properties/AssemblyInfo.cs
|
EnumUtil/Properties/AssemblyInfo.cs
|
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EnumUtil")]
[assembly: AssemblyDescription("Generic Enum Utilities for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EnumUtil")]
[assembly: AssemblyCopyright("Copyright Alexandre Rogozine © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f960fc51-f6c9-4ca8-be59-eb1d5388d9ef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.3.0.0")]
[assembly: AssemblyFileVersion("2.3.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
|
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EnumUtil")]
[assembly: AssemblyDescription("Generic Enum Utilities for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EnumUtil")]
[assembly: AssemblyCopyright("Copyright Alexandre Rogozine © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f960fc51-f6c9-4ca8-be59-eb1d5388d9ef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
|
unlicense
|
C#
|
2bcaebdb8f0dbf876dedb9be39c8074ccee8b70a
|
Fix the size of the file list item does not fit
|
setchi/NotesEditor,setchi/NoteEditor
|
Assets/Scripts/Presenter/MusicSelector/FileListItem.cs
|
Assets/Scripts/Presenter/MusicSelector/FileListItem.cs
|
using NoteEditor.Model;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
using UnityEngine.UI;
namespace NoteEditor.Presenter
{
public class FileListItem : MonoBehaviour
{
[SerializeField]
Color selectedStateBackgroundColor;
[SerializeField]
Color defaultBackgroundColor;
[SerializeField]
Color selectedTextColor;
[SerializeField]
Color defaultTextColor;
[SerializeField]
Image itemTypeIcon;
[SerializeField]
Sprite directoryIcon;
[SerializeField]
Sprite musicFileIcon;
[SerializeField]
Sprite otherFileIcon;
string itemName;
FileItemInfo fileItemInfo;
void Awake()
{
var text = GetComponentInChildren<Text>();
var image = GetComponent<Image>();
this.ObserveEveryValueChanged(_ => itemName == MusicSelector.SelectedFileName.Value)
.Do(selected => image.color = selected ? selectedStateBackgroundColor : defaultBackgroundColor)
.Subscribe(selected => text.color = selected ? selectedTextColor : defaultTextColor)
.AddTo(this);
}
void Start()
{
GetComponent<RectTransform>().localScale = Vector3.one;
}
public void SetInfo(FileItemInfo info)
{
fileItemInfo = info;
itemName = System.IO.Path.GetFileName(info.fullName);
GetComponentInChildren<Text>().text = itemName;
itemTypeIcon.sprite = fileItemInfo.isDirectory
? directoryIcon
: System.IO.Path.GetExtension(itemName) == ".wav"
? musicFileIcon
: otherFileIcon;
}
public void OnMouseDown()
{
if (fileItemInfo.isDirectory && itemName == MusicSelector.SelectedFileName.Value)
{
MusicSelector.DirectoryPath.Value = fileItemInfo.fullName;
// Scroll top
return;
}
MusicSelector.SelectedFileName.Value = itemName;
}
}
}
|
using NoteEditor.Model;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
using UnityEngine.UI;
namespace NoteEditor.Presenter
{
public class FileListItem : MonoBehaviour
{
[SerializeField]
Color selectedStateBackgroundColor;
[SerializeField]
Color defaultBackgroundColor;
[SerializeField]
Color selectedTextColor;
[SerializeField]
Color defaultTextColor;
[SerializeField]
Image itemTypeIcon;
[SerializeField]
Sprite directoryIcon;
[SerializeField]
Sprite musicFileIcon;
[SerializeField]
Sprite otherFileIcon;
string itemName;
FileItemInfo fileItemInfo;
void Awake()
{
GetComponent<RectTransform>().localScale = Vector3.one;
var text = GetComponentInChildren<Text>();
var image = GetComponent<Image>();
this.ObserveEveryValueChanged(_ => itemName == MusicSelector.SelectedFileName.Value)
.Do(selected => image.color = selected ? selectedStateBackgroundColor : defaultBackgroundColor)
.Subscribe(selected => text.color = selected ? selectedTextColor : defaultTextColor)
.AddTo(this);
}
public void SetInfo(FileItemInfo info)
{
fileItemInfo = info;
itemName = System.IO.Path.GetFileName(info.fullName);
GetComponentInChildren<Text>().text = itemName;
itemTypeIcon.sprite = fileItemInfo.isDirectory
? directoryIcon
: System.IO.Path.GetExtension(itemName) == ".wav"
? musicFileIcon
: otherFileIcon;
}
public void OnMouseDown()
{
if (fileItemInfo.isDirectory && itemName == MusicSelector.SelectedFileName.Value)
{
MusicSelector.DirectoryPath.Value = fileItemInfo.fullName;
// Scroll top
return;
}
MusicSelector.SelectedFileName.Value = itemName;
}
}
}
|
mit
|
C#
|
d5a18be21d37569ce4d834812fcc0e869ac1e803
|
bump assembly version
|
timotei/il-repack,gluck/il-repack
|
ILRepack/Properties/AssemblyInfo.cs
|
ILRepack/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ILRepack")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ILRepack")]
[assembly: AssemblyCopyright("Copyright © Francois Valdy 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b140d8b2-68f8-4324-965b-5c047c3745ab")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.15.0")]
[assembly: AssemblyFileVersion("2.0.15.0")]
[assembly: InternalsVisibleTo("ILRepack.Tests")]
[assembly: InternalsVisibleTo("ILRepack.IntegrationTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ILRepack")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ILRepack")]
[assembly: AssemblyCopyright("Copyright © Francois Valdy 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b140d8b2-68f8-4324-965b-5c047c3745ab")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.14.0")]
[assembly: AssemblyFileVersion("2.0.14.0")]
[assembly: InternalsVisibleTo("ILRepack.Tests")]
[assembly: InternalsVisibleTo("ILRepack.IntegrationTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
|
apache-2.0
|
C#
|
3a9a9bcaef10f679235b74a865bbfcf9162f18ca
|
Move a little local variable to smaller scope
|
brnkhy/MapzenGo,brnkhy/MapzenGo
|
Assets/MapzenGo/Models/CachedDynamicTileManager.cs
|
Assets/MapzenGo/Models/CachedDynamicTileManager.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Assets.Helpers;
using Assets.Models.Factories;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
namespace Assets.Models
{
public class CachedDynamicTileManager : DynamicTileManager
{
protected string CacheFolderPath;
public override void Init(List<Factory> factories, World.Settings settings)
{
CacheFolderPath = Path.Combine(Application.dataPath, "MapzenGo/CachedTileData/");
if (!Directory.Exists(CacheFolderPath))
Directory.CreateDirectory(CacheFolderPath);
base.Init(factories, settings);
}
protected override void LoadTile(Vector2 tileTms, Tile tile)
{
var url = string.Format(_mapzenUrl, _mapzenLayers, Zoom, tileTms.x, tileTms.y, _mapzenFormat, _key);
var tilePath = Path.Combine(CacheFolderPath, Zoom + "_" + tileTms.x + "_" + tileTms.y);
if (File.Exists(tilePath))
{
var r = new StreamReader(tilePath, Encoding.Default);
var mapData = r.ReadToEnd();
tile.ConstructTile(mapData);
}
else
{
ObservableWWW.Get(url).Subscribe(
success =>
{
var sr = File.CreateText(tilePath);
sr.Write(success);
sr.Close();
tile.ConstructTile(success);
},
error =>
{
Debug.Log(error);
});
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Assets.Helpers;
using Assets.Models.Factories;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
namespace Assets.Models
{
public class CachedDynamicTileManager : DynamicTileManager
{
protected string CacheFolderPath;
public override void Init(List<Factory> factories, World.Settings settings)
{
CacheFolderPath = Path.Combine(Application.dataPath, "MapzenGo/CachedTileData/");
if (!Directory.Exists(CacheFolderPath))
Directory.CreateDirectory(CacheFolderPath);
base.Init(factories, settings);
}
protected override void LoadTile(Vector2 tileTms, Tile tile)
{
var url = string.Format(_mapzenUrl, _mapzenLayers, Zoom, tileTms.x, tileTms.y, _mapzenFormat, _key);
var tilePath = Path.Combine(CacheFolderPath, Zoom + "_" + tileTms.x + "_" + tileTms.y);
string mapData;
if (File.Exists(tilePath))
{
var r = new StreamReader(tilePath, Encoding.Default);
mapData = r.ReadToEnd();
tile.ConstructTile(mapData);
}
else
{
ObservableWWW.Get(url).Subscribe(
success =>
{
var sr = File.CreateText(tilePath);
sr.Write(success);
sr.Close();
tile.ConstructTile(success);
},
error =>
{
Debug.Log(error);
});
}
}
}
}
|
mit
|
C#
|
4084479dcd35c5aae633f1543accde3f5bd90583
|
Update Exit.cs
|
ghandhikus/Xna-Basic-Input-Detection
|
Code/InputEvents/Exit.cs
|
Code/InputEvents/Exit.cs
|
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion
namespace Game.InputEvents
{
class Exit : InputListener
{
public override void Down(GameTime gameTime) { Console.WriteLine("+Down has fired."); }
public override void Up(GameTime gameTime) { Console.WriteLine("-Up has fired."); }
public override void Click(GameTime gameTime)
{
Console.WriteLine("=Click has fired.");
G.GetInstance().Quit();
}
public override void Hold(GameTime gameTime) { Console.WriteLine("||Hold has fired."); }
public override void Tick(GameTime gameTime) { Console.WriteLine("@Tick has fired."); }
}
}
|
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion
namespace Game.InputEvents
{
class Exit : InputListener
{
public override void Down() { Console.WriteLine("+Down has fired."); }
public override void Up() { Console.WriteLine("-Up has fired."); }
public override void Click()
{
Console.WriteLine("=Click has fired.");
G.GetInstance().Quit();
}
public override void Hold() { Console.WriteLine("||Hold has fired."); }
}
}
|
apache-2.0
|
C#
|
fdcf5b63f5bfc9f1c88ac3164f90f9560e596caf
|
Bump to version 2.3.2.0
|
MeltWS/proshine,bobus15/proshine,Silv3rPRO/proshine
|
PROShine/Properties/AssemblyInfo.cs
|
PROShine/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PROShine")]
[assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Silv3r")]
[assembly: AssemblyProduct("PROShine")]
[assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.3.2.0")]
[assembly: AssemblyFileVersion("2.3.2.0")]
[assembly: NeutralResourcesLanguage("en")]
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PROShine")]
[assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Silv3r")]
[assembly: AssemblyProduct("PROShine")]
[assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.3.1.0")]
[assembly: AssemblyFileVersion("2.3.1.0")]
[assembly: NeutralResourcesLanguage("en")]
|
mit
|
C#
|
ee2c7a23f7f8972a79ba0e5ea809b793e53a39b6
|
make evals safe. less minified but wont break people.
|
mwrock/RequestReduce,mwrock/RequestReduce,mwrock/RequestReduce
|
RequestReduce/Utilities/Minifier.cs
|
RequestReduce/Utilities/Minifier.cs
|
using Microsoft.Ajax.Utilities;
using RequestReduce.Reducer;
using System;
using System.Security.AccessControl;
using RequestReduce.ResourceTypes;
namespace RequestReduce.Utilities
{
public class Minifier : IMinifier
{
private Microsoft.Ajax.Utilities.Minifier minifier = new Microsoft.Ajax.Utilities.Minifier();
private CodeSettings settings = new CodeSettings(){EvalTreatment = EvalTreatment.MakeAllSafe};
public string Minify<T>(string unMinifiedContent) where T : IResourceType
{
if(typeof(T) == typeof(CssResource))
return minifier.MinifyStyleSheet(unMinifiedContent);
if(typeof(T) == typeof(JavaScriptResource))
return minifier.MinifyJavaScript(unMinifiedContent, settings);
throw new ArgumentException("Cannot Minify Resources of unknown type", "resourceType");
}
}
}
|
using Microsoft.Ajax.Utilities;
using RequestReduce.Reducer;
using System;
using System.Security.AccessControl;
using RequestReduce.ResourceTypes;
namespace RequestReduce.Utilities
{
public class Minifier : IMinifier
{
private Microsoft.Ajax.Utilities.Minifier minifier = new Microsoft.Ajax.Utilities.Minifier();
public string Minify<T>(string unMinifiedContent) where T : IResourceType
{
if(typeof(T) == typeof(CssResource))
return minifier.MinifyStyleSheet(unMinifiedContent);
if(typeof(T) == typeof(JavaScriptResource))
return minifier.MinifyJavaScript(unMinifiedContent);
throw new ArgumentException("Cannot Minify Resources of unknown type", "resourceType");
}
}
}
|
apache-2.0
|
C#
|
4d0672e6f4b4687a6ff4ede6ef83a403f5011773
|
fix bug on install/uninstall service
|
orrollo/port-redirector
|
port-redirector/Program.cs
|
port-redirector/Program.cs
|
using System;
using System.Configuration.Install;
using System.Diagnostics;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;
namespace port_redirector
{
class Program : ServiceBase
{
public const string RedirectorServiceName = "port_redirector";
public Program()
{
ServiceName = RedirectorServiceName;
}
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += excHandler;
if (args.Length > 0)
{
foreach (var arg in args)
{
var upper = arg.ToUpper();
if (upper == "-I" || upper == "/I")
{
Install();
return;
}
if (upper == "-U" || upper == "/U")
{
Uninstall();
return;
}
}
Redirector.CommandLine = args;
}
if (System.Environment.UserInteractive)
{
Console.WriteLine("press enter to stop...");
Console.CancelKeyPress += Console_CancelKeyPress;
Redirector.Start();
Console.ReadLine();
DoStop();
}
else
{
Run(new Program());
}
}
protected override void OnStart(string[] args)
{
Redirector.CommandLine = args;
Redirector.Start();
base.OnStart(args);
}
protected override void OnStop()
{
DoStop();
base.OnStop();
}
private static void Uninstall()
{
ManagedInstallerClass.InstallHelper(new[] { "/u", GetLocation() });
}
private static string GetLocation()
{
return Assembly.GetExecutingAssembly().Location;
}
private static void Install()
{
ManagedInstallerClass.InstallHelper(new[] { GetLocation() });
}
private static void excHandler(object sender, UnhandledExceptionEventArgs e)
{
Debug.WriteLine(string.Format("unhandled exception: {0}", e.ExceptionObject));
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
DoStop();
}
private static void DoStop()
{
Redirector.Stop();
Thread.Sleep(1500);
}
}
}
|
using System;
using System.Configuration.Install;
using System.Diagnostics;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;
namespace port_redirector
{
class Program : ServiceBase
{
public const string RedirectorServiceName = "port_redirector";
public Program()
{
ServiceName = RedirectorServiceName;
}
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += excHandler;
if (args.Length > 0)
{
foreach (var arg in args)
{
var upper = arg.ToUpper();
if (upper == "-I" || upper == "/I") Install();
if (upper == "-U" || upper == "/U") Uninstall();
}
Redirector.CommandLine = args;
}
if (System.Environment.UserInteractive)
{
Console.CancelKeyPress += Console_CancelKeyPress;
Redirector.Start();
Console.ReadLine();
DoStop();
}
else
{
Run(new Program());
}
}
protected override void OnStart(string[] args)
{
Redirector.CommandLine = args;
Redirector.Start();
base.OnStart(args);
}
protected override void OnStop()
{
DoStop();
base.OnStop();
}
private static void Uninstall()
{
ManagedInstallerClass.InstallHelper(new[] { "/u", GetLocation() });
}
private static string GetLocation()
{
return Assembly.GetExecutingAssembly().Location;
}
private static void Install()
{
ManagedInstallerClass.InstallHelper(new[] { GetLocation() });
}
private static void excHandler(object sender, UnhandledExceptionEventArgs e)
{
Debug.WriteLine(string.Format("unhandled exception: {0}", e.ExceptionObject));
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
DoStop();
}
private static void DoStop()
{
Redirector.Stop();
Thread.Sleep(1500);
}
}
}
|
mit
|
C#
|
4fd4a4f1d79c424d422a90e92ba1886c2e04aa84
|
Add State and InputStream to the IRecognizer interface
|
cooperra/antlr4,Distrotech/antlr4,parrt/antlr4,sidhart/antlr4,krzkaczor/antlr4,chienjchienj/antlr4,parrt/antlr4,antlr/antlr4,supriyantomaftuh/antlr4,parrt/antlr4,mcanthony/antlr4,wjkohnen/antlr4,lncosie/antlr4,wjkohnen/antlr4,cooperra/antlr4,ericvergnaud/antlr4,Pursuit92/antlr4,chandler14362/antlr4,chandler14362/antlr4,antlr/antlr4,chandler14362/antlr4,krzkaczor/antlr4,worsht/antlr4,krzkaczor/antlr4,cocosli/antlr4,sidhart/antlr4,worsht/antlr4,parrt/antlr4,lncosie/antlr4,ericvergnaud/antlr4,Pursuit92/antlr4,wjkohnen/antlr4,jvanzyl/antlr4,ericvergnaud/antlr4,Distrotech/antlr4,worsht/antlr4,parrt/antlr4,sidhart/antlr4,wjkohnen/antlr4,wjkohnen/antlr4,joshids/antlr4,antlr/antlr4,chienjchienj/antlr4,joshids/antlr4,supriyantomaftuh/antlr4,wjkohnen/antlr4,ericvergnaud/antlr4,chienjchienj/antlr4,cooperra/antlr4,antlr/antlr4,Distrotech/antlr4,hce/antlr4,jvanzyl/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,cooperra/antlr4,mcanthony/antlr4,worsht/antlr4,chandler14362/antlr4,ericvergnaud/antlr4,mcanthony/antlr4,ericvergnaud/antlr4,jvanzyl/antlr4,wjkohnen/antlr4,lncosie/antlr4,chandler14362/antlr4,supriyantomaftuh/antlr4,Distrotech/antlr4,sidhart/antlr4,Pursuit92/antlr4,Pursuit92/antlr4,parrt/antlr4,joshids/antlr4,mcanthony/antlr4,worsht/antlr4,chienjchienj/antlr4,krzkaczor/antlr4,chandler14362/antlr4,krzkaczor/antlr4,hce/antlr4,wjkohnen/antlr4,Pursuit92/antlr4,parrt/antlr4,hce/antlr4,parrt/antlr4,chandler14362/antlr4,antlr/antlr4,supriyantomaftuh/antlr4,cocosli/antlr4,wjkohnen/antlr4,ericvergnaud/antlr4,chandler14362/antlr4,antlr/antlr4,Pursuit92/antlr4,parrt/antlr4,parrt/antlr4,supriyantomaftuh/antlr4,Pursuit92/antlr4,joshids/antlr4,hce/antlr4,cocosli/antlr4,Pursuit92/antlr4,joshids/antlr4,cocosli/antlr4,joshids/antlr4,sidhart/antlr4,lncosie/antlr4,antlr/antlr4,antlr/antlr4,antlr/antlr4,jvanzyl/antlr4,joshids/antlr4,Distrotech/antlr4,lncosie/antlr4,antlr/antlr4,joshids/antlr4,ericvergnaud/antlr4,chandler14362/antlr4,chienjchienj/antlr4,mcanthony/antlr4,Pursuit92/antlr4
|
Antlr4.Runtime/IRecognizer.cs
|
Antlr4.Runtime/IRecognizer.cs
|
namespace Antlr4.Runtime
{
using Antlr4.Runtime.Atn;
public interface IRecognizer
{
string[] TokenNames
{
get;
}
string[] RuleNames
{
get;
}
string GrammarFileName
{
get;
}
ATN Atn
{
get;
}
int State
{
get;
}
IIntStream InputStream
{
get;
}
}
}
|
namespace Antlr4.Runtime
{
using Antlr4.Runtime.Atn;
public interface IRecognizer
{
string[] TokenNames
{
get;
}
string[] RuleNames
{
get;
}
string GrammarFileName
{
get;
}
ATN Atn
{
get;
}
}
}
|
bsd-3-clause
|
C#
|
2d0157f1629cc9d213fa92d0aed07d71e120754b
|
Revert "Fixed Error"
|
luizbranco/close_encounters
|
Assets/Scripts/WordManager.cs
|
Assets/Scripts/WordManager.cs
|
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
public class WordManager : MonoBehaviour {
public GameObject letterPrefab;
public GameObject wordPrefab;
protected FileInfo dictionaryFile = null;
protected StreamReader reader = null;
protected string text = "";
//private string[] tempWords = {};
private struct Word {
public string name;
public GameObject gameObject;
public int counter;
}
List<Word> words = new List<Word>();
List<string> tempWords = new List<string>();
Word target;
private float nextSpawn = 0;
private float width;
private float y;
private float minX;
private float maxX;
private void Awake () {
width = letterPrefab.GetComponent<Renderer>().bounds.size.x;
Vector3 camPos = Camera.main.transform.position;
float camSize = Camera.main.orthographicSize;
y = camPos.y + camSize;
minX = camPos.x - camSize;
maxX = camPos.x + camSize + 1;
dictionaryFile = new FileInfo("Assets/Resources/Text/Dictionary.txt");
reader = dictionaryFile.OpenText();
do {
text = reader.ReadLine();
print (text);
tempWords.Add(text);
} while(text != null);
}
private void Update () {
if (Time.time > nextSpawn) {
CreateRandomWord();
nextSpawn = Time.time + Random.Range(1,3);
}
}
private void CreateRandomWord () {
Vector2 position;
position.y = y;
position.x = Random.Range(minX, maxX);
string name = tempWords[Random.Range(0, tempWords.Count)];
GameObject container = (GameObject)Instantiate(wordPrefab, Vector3.zero, Quaternion.identity);
foreach(char c in name){
GameObject letter = LoadLetter(c);
letter.transform.parent = container.transform;
letter.transform.localPosition = position;
position.x += width;
}
Word word = new Word();
word.name = name;
word.counter = 0;
word.gameObject = container;
words.Add(word);
}
private GameObject LoadLetter (char letter) {
GameObject instance = (GameObject)Instantiate(letterPrefab, Vector2.zero, Quaternion.identity);
string name = "Letters/letter" + letter.ToString().ToUpper();
Sprite sprite = Resources.Load<Sprite>(name);
instance.GetComponent<SpriteRenderer>().sprite = sprite;
return instance;
}
public GameObject DestroyLetter (char letter) {
if (target.gameObject == null) { // target is null
} else {
}
return target.gameObject;
}
}
|
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
public class WordManager : MonoBehaviour {
public GameObject letterPrefab;
public GameObject wordPrefab;
protected FileInfo dictionaryFile = null;
protected StreamReader reader = null;
protected string text = "";
private struct Word {
public string name;
public GameObject gameObject;
public int counter;
}
List<Word> words = new List<Word>();
List<string> tempWords = new List<string>();
Dictionary<int, List<string>> definedWords = new Dictionary<int, List<string>>();
Word target;
private float nextSpawn = 0;
private float width;
private float y;
private float minX;
private float maxX;
private void Awake () {
width = letterPrefab.GetComponent<Renderer>().bounds.size.x;
Vector3 camPos = Camera.main.transform.position;
float camSize = Camera.main.orthographicSize;
y = camPos.y + camSize;
minX = camPos.x - camSize;
maxX = camPos.x + camSize + 1;
dictionaryFile = new FileInfo("Assets/Resources/Text/Dictionary.txt");
reader = dictionaryFile.OpenText();
do {
text = reader.ReadLine();
print (text);
tempWords.Add(text);
// definedWords.Add (text.Length, tempWords);
} while(text != null);
}
private void Update () {
if (Time.time > nextSpawn) {
CreateRandomWord();
nextSpawn = Time.time + Random.Range(1,3);
}
}
private void CreateRandomWord () {
Vector2 position;
position.y = y;
position.x = Random.Range(minX, maxX);
string name = tempWords[Random.Range(0, tempWords.Count)];
GameObject container = (GameObject)Instantiate(wordPrefab, Vector3.zero, Quaternion.identity);
if (name != null) {
foreach(char c in name){
GameObject letter = LoadLetter(c);
letter.transform.parent = container.transform;
letter.transform.localPosition = position;
position.x += width;
}
}
Word word = new Word();
word.name = name;
word.counter = 0;
word.gameObject = container;
words.Add(word);
}
private GameObject LoadLetter (char letter) {
GameObject instance = (GameObject)Instantiate(letterPrefab, Vector2.zero, Quaternion.identity);
string name = "Letters/letter" + letter.ToString().ToUpper();
Sprite sprite = Resources.Load<Sprite>(name);
instance.GetComponent<SpriteRenderer>().sprite = sprite;
return instance;
}
public GameObject DestroyLetter (char letter) {
if (target.gameObject == null) { // target is null
} else {
}
return target.gameObject;
}
}
|
mit
|
C#
|
1c1480948d9477c740d7adc5a16d2b7c85056c5e
|
format code
|
UnstableMutex/DropboxCameraUploadsSorter
|
DropboxSorter/DropboxSorter/Program.cs
|
DropboxSorter/DropboxSorter/Program.cs
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace DropboxSorter
{
class Program
{
static void Main(string[] args)
{
var UserFolder=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string mainFolder = Path.Combine(UserFolder, @"Dropbox\Camera Uploads");
const string mask = @"\d{4}-\d{2}-\d{2} \d{2}\.\d{2}\.\d{2}(-\d)?.jpg";
var re=new Regex(mask);
var directory = new DirectoryInfo(mainFolder);
var files = directory.GetFiles();
var filteredfiles = files.Where(x => re.IsMatch(x.Name));
foreach (var filteredfile in filteredfiles)
{
var date = filteredfile.Name.Substring(0, 10);
const string dateFormat = "yyyy-MM-dd";
var dt =DateTime.ParseExact(date, dateFormat, CultureInfo.CurrentCulture);
var subdir= directory.CreateSubdirectory(dt.ToString(dateFormat));
var newfn = filteredfile.Name.Substring(11);
var fullfn = Path.Combine(subdir.FullName, newfn);
filteredfile.MoveTo(fullfn);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace DropboxSorter
{
class Program
{
static void Main(string[] args)
{
var UserFolder=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string mainFolder = Path.Combine(UserFolder, @"Dropbox\Camera Uploads");
const string mask = @"\d{4}-\d{2}-\d{2} \d{2}\.\d{2}\.\d{2}(-\d)?.jpg";
var re=new Regex(mask);
var directory = new DirectoryInfo(mainFolder);
var files = directory.GetFiles();
var filteredfiles = files.Where(x => re.IsMatch(x.Name));
foreach (var filteredfile in filteredfiles)
{
var date = filteredfile.Name.Substring(0, 10);
const string dateFormat = "yyyy-MM-dd";
var dt =DateTime.ParseExact(date, dateFormat, CultureInfo.CurrentCulture);
var subdir= directory.CreateSubdirectory(dt.ToString(dateFormat));
var newfn = filteredfile.Name.Substring(11);
var fullfn = Path.Combine(subdir.FullName, newfn);
filteredfile.MoveTo(fullfn);
}
}
}
}
|
mit
|
C#
|
9787ea0cfa58762c5b448b8789960c3ff9da3ef6
|
Apply suggestions from code review
|
abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS
|
src/Umbraco.Web.Common/Extensions/UmbracoApplicationBuilder.Identity.cs
|
src/Umbraco.Web.Common/Extensions/UmbracoApplicationBuilder.Identity.cs
|
using System;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Security;
namespace Umbraco.Extensions
{
public static partial class UmbracoApplicationBuilderExtensions
{
public static IUmbracoBuilder SetBackOfficeUserManager<TUserManager>(this IUmbracoBuilder builder)
where TUserManager : UserManager<BackOfficeIdentityUser>, IBackOfficeUserManager
{
Type customType = typeof(TUserManager);
Type userManagerType = typeof(UserManager<BackOfficeIdentityUser>);
builder.Services.Replace(ServiceDescriptor.Scoped(typeof(IBackOfficeUserManager), customType));
builder.Services.AddScoped(customType, services => services.GetRequiredService(userManagerType));
builder.Services.Replace(ServiceDescriptor.Scoped(userManagerType, customType));
return builder;
}
}
}
|
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Security;
namespace Umbraco.Extensions
{
public static partial class UmbracoApplicationBuilderExtensions
{
public static IUmbracoBuilder SetBackOfficeUserManager<TUserManager>(this IUmbracoBuilder builder)
where TUserManager : UserManager<BackOfficeIdentityUser>, IBackOfficeUserManager
{
Type customType = typeof(TUserManager);
Type userManagerType = typeof(UserManager<BackOfficeIdentityUser>);
builder.Services.Replace(ServiceDescriptor.Scoped(typeof(IBackOfficeUserManager), customType));
builder.Services.AddScoped(customType, services => services.GetRequiredService(userManagerType));
builder.Services.Replace(ServiceDescriptor.Scoped(userManagerType, customType));
return builder;
}
}
}
|
mit
|
C#
|
21d88f229255ff645fca01fb7157d87e23ec1c8c
|
fix in IScoreboard CreateScoreboard() metohd
|
TeamLabyrinth4/Labyrinth-4
|
Labyrinth-4/ObjectBuilder/Decorator.cs
|
Labyrinth-4/ObjectBuilder/Decorator.cs
|
namespace Labyrinth.ObjectBuilder
{
using Model;
using Scoreboard;
using Utilities;
/// <summary>
/// A Decorator class which wrap the IGameObjectBuilder interface in order to add new functionality.
/// </summary>
public abstract class Decorator : IGameObjectBuilder
{
/// <summary>
/// Creates instance of the basic Decorator class.
/// </summary>
/// <param name="gameObjectBuilder">Can accepts any type of IGameObjectBuilder object.</param>
protected Decorator(IGameObjectBuilder gameObjectBuilder)
{
this.GameObjectBuilder = gameObjectBuilder;
}
protected IGameObjectBuilder GameObjectBuilder { get; set; }
public Renderer.IRenderer CreteRenderer()
{
return this.GameObjectBuilder.CreteRenderer();
}
public Users.IPlayer CreatePlayer()
{
return this.GameObjectBuilder.CreatePlayer();
}
public IScoreBoardObserver CreteScoreBoardHanler(IScoreboard scoreboard)
{
return this.GameObjectBuilder.CreteScoreBoardHanler(scoreboard);
}
public LabyrinthMatrix CreateLabyrinthMatrix()
{
return this.GameObjectBuilder.CreateLabyrinthMatrix();
}
public string GetUserName()
{
return this.GameObjectBuilder.GetUserName();
}
public IScoreboard CreateScoreboard()
{
return this.GameObjectBuilder.CreateScoreboard();
}
}
}
|
namespace Labyrinth.ObjectBuilder
{
using Model;
using Scoreboard;
using Utilities;
/// <summary>
/// A Decorator class which wrap the IGameObjectBuilder interface in order to add new functionality.
/// </summary>
public abstract class Decorator : IGameObjectBuilder
{
/// <summary>
/// Creates instance of the basic Decorator class.
/// </summary>
/// <param name="gameObjectBuilder">Can accepts any type of IGameObjectBuilder object.</param>
protected Decorator(IGameObjectBuilder gameObjectBuilder)
{
this.GameObjectBuilder = gameObjectBuilder;
}
protected IGameObjectBuilder GameObjectBuilder { get; set; }
public Renderer.IRenderer CreteRenderer()
{
return this.GameObjectBuilder.CreteRenderer();
}
public Users.IPlayer CreatePlayer()
{
return this.GameObjectBuilder.CreatePlayer();
}
public IScoreBoardObserver CreteScoreBoardHanler(IScoreboard scoreboard)
{
return this.GameObjectBuilder.CreteScoreBoardHanler(scoreboard);
}
public LabyrinthMatrix CreateLabyrinthMatrix()
{
return this.GameObjectBuilder.CreateLabyrinthMatrix();
}
public string GetUserName()
{
return this.GameObjectBuilder.GetUserName();
}
public IScoreboard CreateScoreboard()
{
return new LocalScoreBoard();
}
}
}
|
mit
|
C#
|
2b9d69fa8d3ada6505da6e94925987193e2c2c7d
|
Add processed_at_min, processed_at_max and attribution_app_id
|
clement911/ShopifySharp,nozzlegear/ShopifySharp,addsb/ShopifySharp
|
ShopifySharp/Filters/OrderFilter.cs
|
ShopifySharp/Filters/OrderFilter.cs
|
using System;
using Newtonsoft.Json;
using ShopifySharp.Enums;
namespace ShopifySharp.Filters
{
/// <summary>
/// Options for filtering <see cref="OrderService.CountAsync(OrderFilter)"/> and
/// <see cref="OrderService.ListAsync(OrderFilter)"/> results.
/// </summary>
public class OrderFilter : ListFilter
{
/// <summary>
/// The status of orders to retrieve. Known values are "open", "closed", "cancelled" and "any".
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// The financial status of orders to retrieve. Known values are "authorized", "paid", "pending", "partially_paid", "partially_refunded", "refunded" and "voided".
/// </summary>
[JsonProperty("financial_status")]
public string FinancialStatus { get; set; }
/// <summary>
/// The fulfillment status of orders to retrieve. Leave this null to retrieve orders with any fulfillment status.
/// </summary>
[JsonProperty("fulfillment_status")]
public string FulfillmentStatus { get; set; }
/// <summary>
/// Show orders imported after date (format: 2014-04-25T16:15:47-04:00)
/// </summary>
[JsonProperty("processed_at_min")]
public DateTime? ProcessedAtMin { get; set; }
/// <summary>
/// Show orders imported before date (format: 2014-04-25T16:15:47-04:00)
/// </summary>
[JsonProperty("processed_at_max")]
public DateTime? ProcessedAtMax { get; set; }
/// <summary>
/// Show orders attributed to a specific app. Valid values are the app ID to filter on (eg. 123) or a value of "current" to only show orders for the app currently consuming the API.
/// </summary>
[JsonProperty("attribution_app_id")]
public string AttributionAppId { get; set; }
}
}
|
using Newtonsoft.Json;
using ShopifySharp.Enums;
namespace ShopifySharp.Filters
{
/// <summary>
/// Options for filtering <see cref="OrderService.CountAsync(OrderFilter)"/> and
/// <see cref="OrderService.ListAsync(OrderFilter)"/> results.
/// </summary>
public class OrderFilter : ListFilter
{
/// <summary>
/// The status of orders to retrieve. Known values are "open", "closed", "cancelled" and "any".
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// The financial status of orders to retrieve. Known values are "authorized", "paid", "pending", "partially_paid", "partially_refunded", "refunded" and "voided".
/// </summary>
[JsonProperty("financial_status")]
public string FinancialStatus { get; set; }
/// <summary>
/// The fulfillment status of orders to retrieve. Leave this null to retrieve orders with any fulfillment status.
/// </summary>
[JsonProperty("fulfillment_status")]
public string FulfillmentStatus { get; set; }
}
}
|
mit
|
C#
|
bce824af9855da4bd23efbd3bda7e658580367ca
|
fix null reference exception
|
lAnubisl/PostTrack,lAnubisl/PostTrack,lAnubisl/PostTrack
|
Posttrack.BLL/Models/EmailModels/BaseEmailModel.cs
|
Posttrack.BLL/Models/EmailModels/BaseEmailModel.cs
|
using Posttrack.Data.Interfaces.DTO;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Posttrack.BLL.Models.EmailModels
{
internal abstract class BaseEmailModel
{
internal BaseEmailModel(string recipient)
{
Recipient = recipient;
}
internal string Year => DateTime.Now.Year.ToString();
internal string Recipient { get; }
protected static string LoadHistoryTemplate(
ICollection<PackageHistoryItemDTO> oldHistory,
IEnumerable<PackageHistoryItemDTO> newHistory)
{
var itemTemplate = @"<tr><td valign=""top"" style=""width: 140px; {Style}"">{Date}</td><td style = ""{Style}"">{Action} {Place}</td></tr>";
var renderedItems = new Collection<string>();
if (newHistory != null)
{
foreach (var item in newHistory)
{
var greenItem = oldHistory == null || !oldHistory.Contains(item);
renderedItems.Add(itemTemplate
.Replace("{Date}", item.Date.ToString("dd.MM", CultureInfo.CurrentCulture))
.Replace("{Action}", CleanActionRegex.Replace(item.Action, string.Empty))
.Replace("{Place}", item.Place)
.Replace("{Style}", greenItem ? "color:green;font-weight:bold;" : string.Empty));
}
}
return string.Format("<table>{0}</table>", string.Join(string.Empty, renderedItems));
}
private static readonly Regex CleanActionRegex = new Regex("\\d{2}\\. ", RegexOptions.Compiled);
}
}
|
using Posttrack.Data.Interfaces.DTO;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Posttrack.BLL.Models.EmailModels
{
internal abstract class BaseEmailModel
{
internal BaseEmailModel(string recipient)
{
Recipient = recipient;
}
internal string Year => DateTime.Now.Year.ToString();
internal string Recipient { get; }
protected static string LoadHistoryTemplate(
ICollection<PackageHistoryItemDTO> oldHistory,
IEnumerable<PackageHistoryItemDTO> newHistory)
{
var itemTemplate = @"<tr><td valign=""top"" style=""width: 140px; {Style}"">{Date}</td><td style = ""{Style}"">{Action} {Place}</td></tr>";
var renderedItems = new Collection<string>();
foreach (var item in newHistory)
{
var greenItem = oldHistory == null || !oldHistory.Contains(item);
renderedItems.Add(itemTemplate
.Replace("{Date}", item.Date.ToString("dd.MM", CultureInfo.CurrentCulture))
.Replace("{Action}", CleanActionRegex.Replace(item.Action, string.Empty))
.Replace("{Place}", item.Place)
.Replace("{Style}", greenItem ? "color:green;font-weight:bold;" : string.Empty));
}
return string.Format("<table>{0}</table>", string.Join(string.Empty, renderedItems));
}
private static readonly Regex CleanActionRegex = new Regex("\\d{2}\\. ", RegexOptions.Compiled);
}
}
|
apache-2.0
|
C#
|
d657b250d46596f8bd76d7fb4e3c7d1f33a30b4a
|
Implement ISample on Sample
|
smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework
|
osu.Framework/Audio/Sample/Sample.cs
|
osu.Framework/Audio/Sample/Sample.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Audio.Sample
{
public abstract class Sample : AudioCollectionManager<SampleChannel>, ISample
{
public const int DEFAULT_CONCURRENCY = 2;
/// <summary>
/// The length in milliseconds of this <see cref="Sample"/>.
/// </summary>
public double Length { get; protected set; }
public virtual int PlaybackConcurrency { get; set; } = DEFAULT_CONCURRENCY;
public SampleChannel Play()
{
var channel = CreateChannel();
if (channel != null)
AddItem(channel);
return channel;
}
protected abstract SampleChannel CreateChannel();
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Audio.Sample
{
public abstract class Sample : AudioCollectionManager<SampleChannel>
{
public const int DEFAULT_CONCURRENCY = 2;
/// <summary>
/// The length in milliseconds of this <see cref="Sample"/>.
/// </summary>
public double Length { get; protected set; }
public virtual int PlaybackConcurrency { get; set; } = DEFAULT_CONCURRENCY;
public SampleChannel Play()
{
var channel = CreateChannel();
if (channel != null)
AddItem(channel);
return channel;
}
protected abstract SampleChannel CreateChannel();
}
}
|
mit
|
C#
|
502530e57671a1a0b4a41b07b330568e219bc666
|
Bump v1.1.4
|
karronoli/tiny-sato
|
TinySato/Properties/AssemblyInfo.cs
|
TinySato/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TinySato")]
[assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TinySato")]
[assembly: AssemblyCopyright("Copyright 2016 karronoli")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
[assembly: AssemblyVersion("1.1.4.*")]
[assembly: AssemblyFileVersion("1.1.4")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TinySato")]
[assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to be recognized by windows driver.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TinySato")]
[assembly: AssemblyCopyright("Copyright 2016 karronoli")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
[assembly: AssemblyVersion("1.1.3.*")]
[assembly: AssemblyFileVersion("1.1.3")]
|
apache-2.0
|
C#
|
c0f63ff1cea63010813e894779aa3d960164df12
|
Fix spelling
|
SamTheDev/octokit.net,eriawan/octokit.net,thedillonb/octokit.net,editor-tools/octokit.net,SmithAndr/octokit.net,Sarmad93/octokit.net,khellang/octokit.net,shiftkey/octokit.net,ivandrofly/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,rlugojr/octokit.net,devkhan/octokit.net,octokit-net-test-org/octokit.net,M-Zuber/octokit.net,TattsGroup/octokit.net,ivandrofly/octokit.net,eriawan/octokit.net,shana/octokit.net,gdziadkiewicz/octokit.net,adamralph/octokit.net,editor-tools/octokit.net,alfhenrik/octokit.net,dampir/octokit.net,dampir/octokit.net,shiftkey/octokit.net,M-Zuber/octokit.net,shana/octokit.net,chunkychode/octokit.net,khellang/octokit.net,SmithAndr/octokit.net,SamTheDev/octokit.net,thedillonb/octokit.net,TattsGroup/octokit.net,rlugojr/octokit.net,octokit/octokit.net,octokit/octokit.net,shiftkey-tester/octokit.net,alfhenrik/octokit.net,gdziadkiewicz/octokit.net,chunkychode/octokit.net,Sarmad93/octokit.net,octokit-net-test-org/octokit.net,devkhan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shiftkey-tester/octokit.net
|
Octokit/Helpers/ReferenceExtensions.cs
|
Octokit/Helpers/ReferenceExtensions.cs
|
using System.Threading.Tasks;
namespace Octokit.Helpers
{
/// <summary>
/// Represents operations to simplify working with references
/// </summary>
public static class ReferenceExtensions
{
/// <summary>
/// Creates a branch, based off the branch specified.
/// </summary>
/// <param name="referencesClient">The <see cref="IReferencesClient" /> this method extends</param>
/// <param name="owner">The owner of the repository.</param>
/// <param name="name">The name of the repository.</param>
/// <param name="branchName">The new branch name</param>
/// <param name="baseReference">The <see cref="Reference" /> to base the branch from</param>
public static async Task<Reference> CreateBranch(this IReferencesClient referencesClient, string owner, string name, string branchName, Reference baseReference)
{
Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNullOrEmptyString(branchName, "branchName");
Ensure.ArgumentNotNull(baseReference, "baseReference");
return await referencesClient.Create(owner, name, new NewReference("refs/heads/" + branchName, baseReference.Object.Sha));
}
/// <summary>
/// Creates a branch, based off the master branch.
/// </summary>
/// <param name="referencesClient">The <see cref="IReferencesClient" /> this method extends</param>
/// <param name="owner">The owner of the repository.</param>
/// <param name="name">The name of the repository.</param>
/// <param name="branchName">The new branch name</param>
public static async Task<Reference> CreateBranch(this IReferencesClient referencesClient, string owner, string name, string branchName)
{
Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNullOrEmptyString(branchName, "branchName");
var baseBranch = await referencesClient.Get(owner, name, "heads/master");
return await referencesClient.Create(owner, name, new NewReference("refs/heads/" + branchName, baseBranch.Object.Sha));
}
}
}
|
using System.Threading.Tasks;
namespace Octokit.Helpers
{
/// <summary>
/// Represents operations to simplify workink with references
/// </summary>
public static class ReferenceExtensions
{
/// <summary>
/// Creates a branch, based off the branch specified.
/// </summary>
/// <param name="referencesClient">The <see cref="IReferencesClient" /> this method extends</param>
/// <param name="owner">The owner of the repository.</param>
/// <param name="name">The name of the repository.</param>
/// <param name="branchName">The new branch name</param>
/// <param name="baseReference">The <see cref="Reference" /> to base the branch from</param>
public static async Task<Reference> CreateBranch(this IReferencesClient referencesClient, string owner, string name, string branchName, Reference baseReference)
{
Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNullOrEmptyString(branchName, "branchName");
Ensure.ArgumentNotNull(baseReference, "baseReference");
return await referencesClient.Create(owner, name, new NewReference("refs/heads/" + branchName, baseReference.Object.Sha));
}
/// <summary>
/// Creates a branch, based off the master branch.
/// </summary>
/// <param name="referencesClient">The <see cref="IReferencesClient" /> this method extends</param>
/// <param name="owner">The owner of the repository.</param>
/// <param name="name">The name of the repository.</param>
/// <param name="branchName">The new branch name</param>
public static async Task<Reference> CreateBranch(this IReferencesClient referencesClient, string owner, string name, string branchName)
{
Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNullOrEmptyString(branchName, "branchName");
var baseBranch = await referencesClient.Get(owner, name, "heads/master");
return await referencesClient.Create(owner, name, new NewReference("refs/heads/" + branchName, baseBranch.Object.Sha));
}
}
}
|
mit
|
C#
|
1d1ab63b27809d01ba144e079099a1a60f053d87
|
add MultipleWhitespaceCharsToSingleSpace()
|
syl20bnr/omnisharp-server,syl20bnr/omnisharp-server,x335/omnisharp-server,x335/omnisharp-server,corngood/omnisharp-server,svermeulen/omnisharp-server,corngood/omnisharp-server,mispencer/OmniSharpServer,OmniSharp/omnisharp-server
|
OmniSharp/Solution/StringExtensions.cs
|
OmniSharp/Solution/StringExtensions.cs
|
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace OmniSharp.Solution
{
public static class StringExtensions
{
public static string MultipleWhitespaceCharsToSingleSpace
(this string stringToTrim) {
return Regex.Replace(stringToTrim, @"\s+", " ");
}
/// <summary>
/// Changes a path's directory separator from Windows-style to the native
/// separator if necessary and expands it to the full path name.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string FixPath(this string path)
{
if (Path.DirectorySeparatorChar != '\\')
path = path.Replace('\\', Path.DirectorySeparatorChar);
else
// TODO: fix hack - vim sends drive letter as uppercase. usually lower case in project files
return path.Replace(@"C:\", @"c:\").Replace(@"D:\", @"d:\");
return Path.GetFullPath(path);
}
/// <summary>
/// Returns the relative path of a file to another file
/// </summary>
/// <param name="path">Base path to create relative path</param>
/// <param name="pathToMakeRelative">Path of file to make relative against path</param>
/// <returns></returns>
public static string GetRelativePath(this string path, string pathToMakeRelative)
{
return new Uri(path).MakeRelativeUri(new Uri(pathToMakeRelative)).ToString().Replace("/", @"\");
}
}
}
|
using System;
using System.IO;
namespace OmniSharp.Solution
{
public static class StringExtensions
{
/// <summary>
/// Changes a path's directory separator from Windows-style to the native
/// separator if necessary and expands it to the full path name.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string FixPath(this string path)
{
if (Path.DirectorySeparatorChar != '\\')
path = path.Replace('\\', Path.DirectorySeparatorChar);
else
// TODO: fix hack - vim sends drive letter as uppercase. usually lower case in project files
return path.Replace(@"C:\", @"c:\").Replace(@"D:\", @"d:\");
return Path.GetFullPath(path);
}
/// <summary>
/// Returns the relative path of a file to another file
/// </summary>
/// <param name="path">Base path to create relative path</param>
/// <param name="pathToMakeRelative">Path of file to make relative against path</param>
/// <returns></returns>
public static string GetRelativePath(this string path, string pathToMakeRelative)
{
return new Uri(path).MakeRelativeUri(new Uri(pathToMakeRelative)).ToString().Replace("/", @"\");
}
}
}
|
mit
|
C#
|
fecee559c12c325347160a49d1afe3f19077fab3
|
Fix broken build
|
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
|
src/SFA.DAS.ProviderApprenticeshipsService.Web/Models/TransferFundedListItemViewModel.cs
|
src/SFA.DAS.ProviderApprenticeshipsService.Web/Models/TransferFundedListItemViewModel.cs
|
using SFA.DAS.Commitments.Api.Types;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.Models
{
public sealed class TransferFundedListItemViewModel
{
public string HashedCommitmentId { get; set; }
public string ReceivingEmployerName { get; set; }
public TransferApprovalStatus? Status { get; set; }
}
}
|
using SFA.DAS.Commitments.Api.Types;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.Models
{
public sealed class TransferFundedListItemViewModel
{
public string HashedCommitmentId { get; set; }
public string ReceivingEmployerName { get; set; }
public TransferApprovalStatus Status { get; set; }
}
}
|
mit
|
C#
|
322aa3516aedaea7afe702ff1a23c1fa7c659ef5
|
Disable water hitbox
|
kennyvv/Alex,kennyvv/Alex,kennyvv/Alex,kennyvv/Alex
|
src/Alex/Blocks/Minecraft/Water.cs
|
src/Alex/Blocks/Minecraft/Water.cs
|
using Alex.API.Blocks;
using Alex.API.Utils;
using Alex.API.World;
using Alex.Blocks.Properties;
namespace Alex.Blocks.Minecraft
{
public class LiquidBlock : Block
{
protected LiquidBlock()
{
}
}
public class Water : Block
{
public static readonly PropertyInt LEVEL = new PropertyInt("level", 0);
public Water() : base()
{
Solid = false;
Transparent = true;
HasHitbox = false;
//BlockModel = BlockFactory.StationairyWaterModel;
//IsWater = true;
BlockMaterial = Material.Water;
LightOpacity = 3;
}
public override bool ShouldRenderFace(BlockFace face, Block neighbor)
{
var myLevelValue = BlockState.GetTypedValue(LEVEL);
if (neighbor.BlockMaterial.IsLiquid || neighbor.BlockMaterial == Material.WaterPlant || (neighbor.BlockMaterial.IsWatterLoggable && neighbor.IsWaterLogged))
{
var neighborLevel = neighbor.BlockState.GetTypedValue(LEVEL);
if (neighborLevel != myLevelValue)
{
return true;
}
return false;
}
if (neighbor.BlockMaterial.IsLiquid)
return false;
if (neighbor.Solid && (!neighbor.Transparent || neighbor.BlockMaterial.IsOpaque))
return false;
if (neighbor.Solid && neighbor.Transparent && !neighbor.IsFullCube)
return true;
//else if (neighbor.Transparent)
return base.ShouldRenderFace(face, neighbor);
}
/*public override void BlockPlaced(IWorld world, BlockCoordinates position)
{
if (BlockState != null)
{
if (BlockState.GetTypedValue(LEVEL) == 0)
{
IsSourceBlock = true;
}
else
{
IsSourceBlock = false;
}
}
base.BlockPlaced(world, position);
}*/
}
}
|
using Alex.API.Blocks;
using Alex.API.Utils;
using Alex.API.World;
using Alex.Blocks.Properties;
namespace Alex.Blocks.Minecraft
{
public class LiquidBlock : Block
{
protected LiquidBlock()
{
}
}
public class Water : Block
{
public static readonly PropertyInt LEVEL = new PropertyInt("level", 0);
public Water() : base()
{
Solid = false;
Transparent = true;
HasHitbox = true;
//BlockModel = BlockFactory.StationairyWaterModel;
//IsWater = true;
BlockMaterial = Material.Water;
LightOpacity = 3;
}
public override bool ShouldRenderFace(BlockFace face, Block neighbor)
{
var myLevelValue = BlockState.GetTypedValue(LEVEL);
if (neighbor.BlockMaterial.IsLiquid || neighbor.BlockMaterial == Material.WaterPlant || (neighbor.BlockMaterial.IsWatterLoggable && neighbor.IsWaterLogged))
{
var neighborLevel = neighbor.BlockState.GetTypedValue(LEVEL);
if (neighborLevel != myLevelValue)
{
return true;
}
return false;
}
if (neighbor.BlockMaterial.IsLiquid)
return false;
if (neighbor.Solid && (!neighbor.Transparent || neighbor.BlockMaterial.IsOpaque))
return false;
if (neighbor.Solid && neighbor.Transparent && !neighbor.IsFullCube)
return true;
//else if (neighbor.Transparent)
return base.ShouldRenderFace(face, neighbor);
}
/*public override void BlockPlaced(IWorld world, BlockCoordinates position)
{
if (BlockState != null)
{
if (BlockState.GetTypedValue(LEVEL) == 0)
{
IsSourceBlock = true;
}
else
{
IsSourceBlock = false;
}
}
base.BlockPlaced(world, position);
}*/
}
}
|
mpl-2.0
|
C#
|
aa9e3cf5fb05374d0823bb7d1ea0d814fcbe417b
|
Fix options overwrite
|
hoagsie/BetterEntityFramework
|
BetterEntityFramework/DataService.cs
|
BetterEntityFramework/DataService.cs
|
using System;
using BetterEntityFramework.StoreData;
using Microsoft.EntityFrameworkCore;
namespace BetterEntityFramework
{
internal class DataService : IDisposable
{
private EfStoreContext _data;
private DbContextOptions _lastOptions;
/// <summary>
/// Gets an instance of the data service.
/// </summary>
public EfStoreContext Service
{
get
{
if (_data != null)
{
return _data;
}
_lastOptions = _lastOptions ?? new DataOptionsBuilder().Build();
_data = new EfStoreContext(_lastOptions);
return _data;
}
}
public DataService() { }
public DataService(DataOptionsBuilder builder)
{
_lastOptions = builder.Build();
}
public DataOptionsBuilder Configure()
{
return new DataOptionsBuilder();
}
public void UseConfiguration(DataOptionsBuilder builder)
{
_data?.Dispose();
_data = new EfStoreContext(builder.Build());
}
public DataService WithScopedService()
{
var scopedService = new DataService();
scopedService.UseConfiguration(new DataOptionsBuilder(_lastOptions));
return scopedService;
}
public DataService WithScopedService(DataOptionsBuilder builder)
{
var scopedService = new DataService();
scopedService.UseConfiguration(builder);
return scopedService;
}
public void Dispose()
{
_data?.Dispose();
}
}
}
|
using System;
using BetterEntityFramework.StoreData;
using Microsoft.EntityFrameworkCore;
namespace BetterEntityFramework
{
internal class DataService : IDisposable
{
private EfStoreContext _data;
private DbContextOptions _lastOptions;
/// <summary>
/// Gets an instance of the data service.
/// </summary>
public EfStoreContext Service
{
get
{
if (_data != null)
{
return _data;
}
_lastOptions = new DataOptionsBuilder().Build();
_data = new EfStoreContext(_lastOptions);
return _data;
}
}
public DataService() { }
public DataService(DataOptionsBuilder builder)
{
_lastOptions = builder.Build();
}
public DataOptionsBuilder Configure()
{
return new DataOptionsBuilder();
}
public void UseConfiguration(DataOptionsBuilder builder)
{
_data?.Dispose();
_data = new EfStoreContext(builder.Build());
}
public DataService WithScopedService()
{
var scopedService = new DataService();
scopedService.UseConfiguration(new DataOptionsBuilder(_lastOptions));
return scopedService;
}
public DataService WithScopedService(DataOptionsBuilder builder)
{
var scopedService = new DataService();
scopedService.UseConfiguration(builder);
return scopedService;
}
public void Dispose()
{
_data?.Dispose();
}
}
}
|
mit
|
C#
|
d2e9b245181aa817915bd6be27c7d7d4dfba9c1d
|
Add reference for selection sort.
|
scott-fleischman/algorithms-csharp
|
src/Algorithms.Sort/SelectionSort.cs
|
src/Algorithms.Sort/SelectionSort.cs
|
using System;
using System.Collections.Generic;
namespace Algorithms.Sort
{
public class SelectionSort
{
public static void SortInPlace<T>(IList<T> list)
{
SortInPlace(list, Comparer<T>.Default);
}
// Ex 2.2-2, p. 29
public static void SortInPlace<T>(IList<T> list, IComparer<T> comparer)
{
if (list.Count <= 1)
return;
for (int index = 0; index < list.Count - 1; index++)
{
int minIndex = IndexOfMinimum(list, index, comparer);
Swap(list, index, minIndex);
}
}
private static int IndexOfMinimum<T>(IList<T> items, int startIndex, IComparer<T> comparer)
{
if (items.Count - startIndex == 0)
throw new ArgumentException("items must not be empty", "items");
if (items.Count - startIndex == 1)
return startIndex;
int minIndex = startIndex;
for (int index = startIndex + 1; index < items.Count; index++)
{
T item = items[index];
if (comparer.Compare(items[minIndex], item) > 0)
minIndex = index;
}
return minIndex;
}
private static void Swap<T>(IList<T> items, int first, int second)
{
if (first == second)
return;
T temp = items[first];
items[first] = items[second];
items[second] = temp;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Algorithms.Sort
{
public class SelectionSort
{
public static void SortInPlace<T>(IList<T> list)
{
SortInPlace(list, Comparer<T>.Default);
}
public static void SortInPlace<T>(IList<T> list, IComparer<T> comparer)
{
if (list.Count <= 1)
return;
for (int index = 0; index < list.Count - 1; index++)
{
int minIndex = IndexOfMinimum(list, index, comparer);
Swap(list, index, minIndex);
}
}
private static int IndexOfMinimum<T>(IList<T> items, int startIndex, IComparer<T> comparer)
{
if (items.Count - startIndex == 0)
throw new ArgumentException("items must not be empty", "items");
if (items.Count - startIndex == 1)
return startIndex;
int minIndex = startIndex;
for (int index = startIndex + 1; index < items.Count; index++)
{
T item = items[index];
if (comparer.Compare(items[minIndex], item) > 0)
minIndex = index;
}
return minIndex;
}
private static void Swap<T>(IList<T> items, int first, int second)
{
if (first == second)
return;
T temp = items[first];
items[first] = items[second];
items[second] = temp;
}
}
}
|
mit
|
C#
|
fa4597f96a3d30afcfc6cb18ddc5756c064486be
|
Apply Json and Object changes to console test.
|
yojimbo87/ArangoDB-NET,kangkot/ArangoDB-NET
|
src/Arango/Arango.Console/Program.cs
|
src/Arango/Arango.Console/Program.cs
|
using System;
using System.IO;
using Arango.Client;
using System.Dynamic;
namespace Arango.Console
{
class Program
{
static void Main(string[] args)
{
string alias = "test";
string[] connectionString = File.ReadAllText(@"..\..\..\..\..\ConnectionString.txt").Split(';');
ArangoNode node = new ArangoNode(
connectionString[0],
int.Parse(connectionString[1]),
connectionString[2],
connectionString[3],
alias
);
ArangoClient.Nodes.Add(node);
ArangoDatabase database = new ArangoDatabase(alias);
ArangoDocument document = database.GetDocument("10843274/12481674", "x12481674");
System.Console.WriteLine("Handle: {0}, Rev: {1}, Json: {2}", document.Handle, document.Revision, document.Json);
ArangoCollection collection = database.GetCollection(10843274);
System.Console.WriteLine("ID: {0}, Name: {1}, Status: {2}, Type: {3}", collection.ID, collection.Name, collection.Status, collection.Type);
/*ArangoDocument doc = new ArangoDocument();
doc.Json.foo = "abc";
doc.Json.bar = new ExpandoObject();
doc.Json.bar.baz = 123;
System.Console.WriteLine("foo: {0} {1}", doc.Has("foo"), doc.Json.foo);
System.Console.WriteLine("bar: {0} {1}", doc.Has("bar"), doc.Json.bar);
System.Console.WriteLine("bar.baz: {0} {1}", doc.Has("bar.baz"), doc.Json.bar.baz);
System.Console.WriteLine("non: {0}", doc.Has("non"));
System.Console.WriteLine("non.exist: {0}", doc.Has("non.exist"));*/
System.Console.ReadLine();
}
}
}
|
using System;
using System.IO;
using Arango.Client;
using System.Dynamic;
namespace Arango.Console
{
class Program
{
static void Main(string[] args)
{
string alias = "test";
string[] connectionString = File.ReadAllText(@"..\..\..\..\..\ConnectionString.txt").Split(';');
ArangoNode node = new ArangoNode(
connectionString[0],
int.Parse(connectionString[1]),
connectionString[2],
connectionString[3],
alias
);
ArangoClient.Nodes.Add(node);
ArangoDatabase database = new ArangoDatabase(alias);
ArangoDocument document = database.GetDocument("10843274/12481674", "x12481674");
System.Console.WriteLine("Handle: {0}, Rev: {1}, Data: {2}", document.Handle, document.Revision, document.Data);
ArangoCollection collection = database.GetCollection(10843274);
System.Console.WriteLine("ID: {0}, Name: {1}", collection.ID, collection.Name);
ArangoDocument doc = new ArangoDocument();
doc.Json.foo = "abc";
doc.Json.bar = new ExpandoObject();
doc.Json.bar.baz = 123;
System.Console.WriteLine("foo: {0} {1}", doc.Has("foo"), doc.Json.foo);
System.Console.WriteLine("bar: {0} {1}", doc.Has("bar"), doc.Json.bar);
System.Console.WriteLine("bar.baz: {0} {1}", doc.Has("bar.baz"), doc.Json.bar.baz);
System.Console.WriteLine("non: {0}", doc.Has("non"));
System.Console.WriteLine("non.exist: {0}", doc.Has("non.exist"));
System.Console.ReadLine();
}
}
}
|
mit
|
C#
|
c7f0ca7e8e6a6aeb8223df12322aff323b9f4a6c
|
Implement Inkbunny logout
|
libertyernie/WeasylSync
|
CrosspostSharp3/MainForm.Inkbunny.cs
|
CrosspostSharp3/MainForm.Inkbunny.cs
|
using ArtSourceWrapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CrosspostSharp3 {
public partial class MainForm {
private async void inkbunnyToolStripMenuItem_Click(object sender, EventArgs e) {
toolsToolStripMenuItem.Enabled = false;
Settings s = Settings.Load();
using (var acctSelForm = new AccountSelectionForm<Settings.InkbunnySettings>(
s.Inkbunny,
async () => {
using (var f = new UsernamePasswordDialog()) {
f.Text = "Log In - Inkbunny";
if (f.ShowDialog() == DialogResult.OK) {
var client = await InkbunnyLib.InkbunnyClient.CreateAsync(f.Username, f.Password);
return new[] {
new Settings.InkbunnySettings {
sid = client.Sid,
userId = client.UserId,
username = await client.GetUsernameAsync()
}
};
} else {
return Enumerable.Empty<Settings.InkbunnySettings>();
}
}
},
settings => {
new InkbunnyLib.InkbunnyClient(settings.sid, settings.userId).LogoutAsync().ContinueWith(t => {
if (t.Exception != null) MessageBox.Show(t.Exception.Message);
});
}
)) {
acctSelForm.ShowDialog(this);
s.Inkbunny = acctSelForm.CurrentList.ToList();
s.Save();
await ReloadWrapperList();
}
toolsToolStripMenuItem.Enabled = true;
}
}
}
|
using ArtSourceWrapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CrosspostSharp3 {
public partial class MainForm {
private async void inkbunnyToolStripMenuItem_Click(object sender, EventArgs e) {
toolsToolStripMenuItem.Enabled = false;
Settings s = Settings.Load();
using (var acctSelForm = new AccountSelectionForm<Settings.InkbunnySettings>(
s.Inkbunny,
async () => {
using (var f = new UsernamePasswordDialog()) {
f.Text = "Log In - Inkbunny";
if (f.ShowDialog() == DialogResult.OK) {
var client = await InkbunnyLib.InkbunnyClient.CreateAsync(f.Username, f.Password);
return new[] {
new Settings.InkbunnySettings {
sid = client.Sid,
userId = client.UserId,
username = await client.GetUsernameAsync()
}
};
} else {
return Enumerable.Empty<Settings.InkbunnySettings>();
}
}
}
)) {
acctSelForm.ShowDialog(this);
s.Inkbunny = acctSelForm.CurrentList.ToList();
s.Save();
await ReloadWrapperList();
}
toolsToolStripMenuItem.Enabled = true;
}
}
}
|
mit
|
C#
|
a2c0c37bed1b7e50fef958a3bc0dfe64727644b3
|
Remove System.Windows.Forms reference
|
esskar/Canon.Eos.Framework
|
EosCamera.HandeStateEvents.cs
|
EosCamera.HandeStateEvents.cs
|
using System;
using System.Diagnostics;
using EDSDKLib;
namespace Canon.Eos.Framework
{
partial class EosCamera
{
private void OnStateEventShutdown(EventArgs eventArgs)
{
if (this.Shutdown != null)
this.Shutdown(this, eventArgs);
}
private uint HandleStateEvent(uint stateEvent, uint param, IntPtr context)
{
Debug.WriteLine("HandleStateEvent fired: " + stateEvent);
switch (stateEvent)
{
case EDSDK.StateEvent_Shutdown:
this.OnStateEventShutdown(EventArgs.Empty);
break;
}
return EDSDK.EDS_ERR_OK;
}
}
}
|
using System;
using System.Diagnostics;
using System.Windows.Forms;
using EDSDKLib;
namespace Canon.Eos.Framework
{
partial class EosCamera
{
private void OnStateEventShutdown(EventArgs eventArgs)
{
if (this.Shutdown != null)
this.Shutdown(this, eventArgs);
}
private uint HandleStateEvent(uint stateEvent, uint param, IntPtr context)
{
Debug.WriteLine("HandleStateEvent fired: " + stateEvent);
switch (stateEvent)
{
case EDSDK.StateEvent_Shutdown:
this.OnStateEventShutdown(EventArgs.Empty);
break;
}
return EDSDK.EDS_ERR_OK;
}
}
}
|
mit
|
C#
|
1e3c2be295191c9557d29448263c3951cd5c2a43
|
Update project version
|
frabert/SharpPhysFS
|
SharpPhysFS/Properties/AssemblyInfo.cs
|
SharpPhysFS/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SharpPhysFS")]
[assembly: AssemblyDescription("Managed wrapper around PhysFS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Francesco Bertolaccini")]
[assembly: AssemblyProduct("SharpPhysFS")]
[assembly: AssemblyCopyright("Copyright © 2016 Francesco Bertolaccini")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1e8d0656-fbd5-4f97-b634-584943b13af2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.2.1")]
[assembly: AssemblyFileVersion("0.0.2.1")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SharpPhysFS")]
[assembly: AssemblyDescription("Managed wrapper around PhysFS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Francesco Bertolaccini")]
[assembly: AssemblyProduct("SharpPhysFS")]
[assembly: AssemblyCopyright("Copyright © 2016 Francesco Bertolaccini")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1e8d0656-fbd5-4f97-b634-584943b13af2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
|
mit
|
C#
|
2cbcdaff05c861e86185c6dff372eabe8e228413
|
Edit version
|
frabert/SharpPhysFS
|
SharpPhysFS/Properties/AssemblyInfo.cs
|
SharpPhysFS/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SharpPhysFS")]
[assembly: AssemblyDescription("Managed wrapper around PhysFS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Francesco Bertolaccini")]
[assembly: AssemblyProduct("SharpPhysFS")]
[assembly: AssemblyCopyright("Copyright © 2016 Francesco Bertolaccini")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1e8d0656-fbd5-4f97-b634-584943b13af2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SharpPhysFS")]
[assembly: AssemblyDescription("Managed wrapper around PhysFS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Francesco Bertolaccini")]
[assembly: AssemblyProduct("SharpPhysFS")]
[assembly: AssemblyCopyright("Copyright © 2016 Francesco Bertolaccini")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1e8d0656-fbd5-4f97-b634-584943b13af2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.2.0")]
[assembly: AssemblyFileVersion("0.0.2.0")]
|
mit
|
C#
|
5229ef3ffa94dfb80d757bcbf049d484499d2a11
|
Add integration app
|
brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync
|
projects/RetrySample/source/RetrySample.App/Program.cs
|
projects/RetrySample/source/RetrySample.App/Program.cs
|
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace RetrySample
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
internal sealed class Program
{
private static readonly Stopwatch LogStopwatch = Stopwatch.StartNew();
private static void Main(string[] args)
{
RetryLoop loop = new RetryLoop(r => ReadFileAsync(r));
loop.ShouldRetry = r => r.ElapsedTime < TimeSpan.FromMinutes(1.0d);
loop.Succeeded = r => (r.Exception == null) && (r.Get<string>("Text") == "TEST");
loop.BeforeRetry = r => BackoffAsync(r);
loop.ExecuteAsync().Wait();
}
private static void Log(string format, params object[] args)
{
string message = format;
if ((args != null) && (args.Length > 0))
{
message = string.Format(CultureInfo.CurrentCulture, format, args);
}
Console.WriteLine("[{0:000.000}/T={1}] {2}", LogStopwatch.Elapsed.TotalSeconds, Thread.CurrentThread.ManagedThreadId, message);
}
private static async Task ReadFileAsync(RetryContext context)
{
try
{
using (FileStream stream = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 256, true))
{
byte[] buffer = new byte[4];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == buffer.Length)
{
string text = Encoding.ASCII.GetString(buffer);
Log("ReadFileAsync read '{0}'", text);
context.Add("Text", text);
}
else
{
Log("ReadFileAsync read only {0} bytes.", bytesRead);
}
}
}
catch (Exception e)
{
Log("ReadFileAsync error: {0}: {1}", e.GetType().Name, e.Message);
throw;
}
}
private static Task BackoffAsync(RetryContext context)
{
TimeSpan delay = TimeSpan.FromMilliseconds(10 * context.Iteration);
Log("Backing off for {0:0.000} seconds.", delay.TotalSeconds);
return Task.Delay(delay);
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace RetrySample
{
using System;
internal sealed class Program
{
private static void Main(string[] args)
{
}
}
}
|
unlicense
|
C#
|
21954f401b1abc4e05dfedb5fb2ef48386d1fe62
|
Add CheckTimeout
|
imba-tjd/CSharp-Code-Repository
|
单个文件的程序/SNI.cs
|
单个文件的程序/SNI.cs
|
// 检测是否存在SNI RST的程序,接受单个IP、域名或整个URL
using System;
using System.Diagnostics;
class SNI
{
const string TargetIP = "104.131.212.184"; // 用于域前置的IP;community.notepad-plus-plus.org
const string NormalNCNHost = "usa.baidu.com"; // 用于检测TargetIP是否被封,必须用正常的域名
const string NormalCNHost = "www.baidu.com"; // 用于检测是否联网,可换成其它普通国内域名/IP
static int Main(string[] args)
{
#if DEBUG
args = new[] { "www.bbc.com" };
#endif
if (args.Length != 1)
throw new ArgumentException("Expect one and only one url.");
string host = new UriBuilder(args[0]).Host;
return new SNI().Run(host);
}
int Run(string requestedHost) =>
PingFailed(NormalCNHost) ? Log("Check your internet connection.", 3) :
CheckTimeout(NormalNCNHost) ? Log("Cannot connect to target IP.", 2) :
HasSniRst(requestedHost) ? Log("Has SNI RST.", 1) :
Log("No SNI RST.", 0);
string Curl(string host)
{
var psi = new ProcessStartInfo("curl", $"-I -sS --connect-timeout 1 --resolve {host}:443:{TargetIP} https://{host}")
{ UseShellExecute = false, RedirectStandardError = true };
var p = Process.Start(psi);
p.WaitForExit();
return p.StandardError.ReadToEnd();
}
bool HasSniRst(string host) => Curl(host).Contains("failed to receive handshake"); // 充分不必要
bool CheckTimeout(string host) => Curl(host).Contains("Connection timed out"); // 自然超时用的是 port 443: Timed out
bool PingFailed(string host)
{
var p = Process.Start(
new ProcessStartInfo("ping", $"-{GetParam()} 1 {host}")
{ UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true }
);
p.WaitForExit();
return p.ExitCode != 0;
string GetParam() => // Win下是-n,Linux下是-c
Environment.OSVersion.Platform == PlatformID.Win32NT ? "n" : "c";
}
// 为了能在Run用三元表达式
int Log(string message, int returncode)
{
Console.WriteLine(message);
return returncode;
}
// 未来加上命令行选项可以在Debug下用这个记录运行的命令,还要想办法记录输出
string Log(string message)
{
Console.WriteLine(message);
return message;
}
}
|
using System;
using System.Diagnostics;
class SNI
{
const string TargetIP = "104.131.212.184"; // 用于域前置的IP;community.notepad-plus-plus.org
const string NormalNCNHost = "usa.baidu.com"; // 用于检测TargetIP是否被封,必须用正常的域名
const string NormalCNHost = "www.baidu.com"; // 用于检测是否联网,可换成其它普通国内域名/IP
static int Main(string[] args)
{
#if DEBUG
args = new[] { "www.bbc.com" };
#endif
if (args.Length != 1)
throw new ArgumentException("Expect one and only one url.");
string host = new UriBuilder(args[0]).Host;
return new SNI().Run(host);
}
int Run(string requestedHost) =>
PingFailed(NormalCNHost) ? Log("Check your internet connection.", 3) :
HasSniRst(NormalNCNHost) ? Log("Cannot connect to target IP.", 2) :
HasSniRst(requestedHost) ? Log("Has SNI RST.", 1) :
Log("Not SNI RST.", 0);
bool HasSniRst(string host)
{
var psi = new ProcessStartInfo("curl", $"-I -sS --resolve {host}:443:{TargetIP} https://{host}")
{ UseShellExecute = false, RedirectStandardError = true };
var p = Process.Start(psi);
p.WaitForExit();
string result = p.StandardError.ReadToEnd();
return result.Contains("failed to receive handshake"); // 为false时并不意味着就没有SNI RST了
}
bool PingFailed(string host)
{
var p = Process.Start(
new ProcessStartInfo("ping", $"-{GetParam()} 2 {host}")
{ UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true }
);
p.WaitForExit();
return p.ExitCode != 0;
string GetParam() => // Win下是-n,Linux下是-c
Environment.OSVersion.Platform == PlatformID.Win32NT ? "n" : "c";
}
// 为了能在Run用三元表达式
int Log(string message, int returncode)
{
Console.WriteLine(message);
return returncode;
}
}
|
mit
|
C#
|
4c5b0e7226ce5c62ffcff135a92362e3ccf66cb1
|
Update OAuth2AuthorizeAttribute.cs
|
Brightspace/D2L.Security.OAuth2
|
src/D2L.Security.OAuth2.WebApi/Authorization/OAuth2AuthorizeAttribute.cs
|
src/D2L.Security.OAuth2.WebApi/Authorization/OAuth2AuthorizeAttribute.cs
|
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace D2L.Security.OAuth2.Authorization {
public abstract class OAuth2AuthorizeAttribute : AuthorizeAttribute {
private const string AUTH_HAS_RUN = "D2L.Security.OAuth2.Authorization.OAuth2AuthorizeAttribute_Auth_Has_Run";
private const string FAILING_ATTR_PROP = "D2L.Security.OAuth2.Authorization.OAuth2AuthorizeAttribute_Failing_Attribute";
protected override bool IsAuthorized( HttpActionContext actionContext ) {
var props = actionContext.Request.Properties;
if( props.ContainsKey( AUTH_HAS_RUN ) ) {
return true;
}
props[ AUTH_HAS_RUN ] = true;
var actionAttributes = actionContext
.ActionDescriptor
.GetCustomAttributes<OAuth2AuthorizeAttribute>();
var actionAttributeTypes = actionAttributes
.Select( x => x.GetType() );
var controllerAttributes = actionContext
.ActionDescriptor
.ControllerDescriptor
.GetCustomAttributes<OAuth2AuthorizeAttribute>();
var oauth2Attributes = actionAttributes
.Union( controllerAttributes.Where( x => !actionAttributeTypes.Contains( x.GetType() ) ) )
.OrderBy( x => x.Order )
.ToArray();
foreach( var attr in oauth2Attributes ) {
if( !attr.IsAuthorizedInternal( actionContext ) ) {
props[ FAILING_ATTR_PROP ] = attr;
return false;
}
}
return true;
}
protected override void HandleUnauthorizedRequest( HttpActionContext actionContext ) {
var props = actionContext.Request.Properties;
var attr = (OAuth2AuthorizeAttribute)props[ FAILING_ATTR_PROP ];
attr.HandleUnauthorizedRequestInternal( actionContext );
}
protected virtual void HandleUnauthorizedRequestInternal( HttpActionContext actionContext ) {
base.HandleUnauthorizedRequest( actionContext );
}
protected abstract uint Order { get; }
protected abstract bool IsAuthorizedInternal( HttpActionContext actionContext );
}
}
|
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace D2L.Security.OAuth2.Authorization {
public abstract class OAuth2AuthorizeAttribute : AuthorizeAttribute {
private const string AUTH_HAS_RUN = "D2L.Security.OAuth2.Authorization.OAuth2AuthorizeAttribute_Auth_Has_Run";
private const string FAILING_ATTR_PROP = "D2L.Security.OAuth2.Authorization.OAuth2AuthorizeAttribute_Failing_Attribute";
protected override bool IsAuthorized( HttpActionContext actionContext ) {
var props = actionContext.Request.Properties;
if( props.ContainsKey( AUTH_HAS_RUN ) ) {
return true;
}
props[ AUTH_HAS_RUN ] = true;
var actionAttributes = actionContext
.ActionDescriptor
.GetCustomAttributes<OAuth2AuthorizeAttribute>( inherit: false );
var actionAttributeTypes = actionAttributes
.Select( x => x.GetType() );
var controllerAttributes = actionContext
.ActionDescriptor
.ControllerDescriptor
.GetCustomAttributes<OAuth2AuthorizeAttribute>( inherit: false );
var oauth2Attributes = actionAttributes
.Union( controllerAttributes.Where( x => !actionAttributeTypes.Contains( x.GetType() ) ) )
.OrderBy( x => x.Order )
.ToArray();
foreach( var attr in oauth2Attributes ) {
if( !attr.IsAuthorizedInternal( actionContext ) ) {
props[ FAILING_ATTR_PROP ] = attr;
return false;
}
}
return true;
}
protected override void HandleUnauthorizedRequest( HttpActionContext actionContext ) {
var props = actionContext.Request.Properties;
var attr = (OAuth2AuthorizeAttribute)props[ FAILING_ATTR_PROP ];
attr.HandleUnauthorizedRequestInternal( actionContext );
}
protected virtual void HandleUnauthorizedRequestInternal( HttpActionContext actionContext ) {
base.HandleUnauthorizedRequest( actionContext );
}
protected abstract uint Order { get; }
protected abstract bool IsAuthorizedInternal( HttpActionContext actionContext );
}
}
|
apache-2.0
|
C#
|
93748c570669d22af8de5cd0d236808188ce2148
|
Create success-only stubs for user validator
|
meutley/ISTS
|
src/Domain.Test/Users/UserTests.cs
|
src/Domain.Test/Users/UserTests.cs
|
using System;
using Moq;
using Xunit;
using ISTS.Domain.Common;
using ISTS.Domain.Users;
namespace ISTS.Domain.Tests.Users
{
public class UserTests
{
private readonly Mock<IUserValidator> _userValidator;
public UserTests()
{
_userValidator = new Mock<IUserValidator>();
}
[Fact]
public void Create_Returns_New_User()
{
var user = User.Create(_userValidator.Object, "myemail@company.com", "Person", "12345", "password1");
Assert.NotNull(user);
Assert.Equal("myemail@company.com", user.Email);
Assert.Equal("Person", user.DisplayName);
Assert.Equal("12345", user.PostalCode);
Assert.NotNull(user.PasswordHash);
Assert.NotNull(user.PasswordSalt);
}
[Fact]
public void Create_Throws_ArgumentNullException_When_Password_Is_Null()
{
var ex = Assert.Throws<ArgumentNullException>(() => User.Create(_userValidator.Object, "myemail@company.com", "Person", "12345", null));
Assert.NotNull(ex);
}
[Fact]
public void Create_Throws_ArgumentException_When_Password_Is_WhiteSpace()
{
var ex = Assert.Throws<ArgumentException>(() => User.Create(_userValidator.Object, "myemail@company.com", "Person", "12345", " "));
Assert.NotNull(ex);
}
}
}
|
using System;
using Xunit;
using ISTS.Domain.Users;
namespace ISTS.Domain.Tests.Users
{
public class UserTests
{
[Fact]
public void Create_Returns_New_User()
{
var user = User.Create("myemail@company.com", "Person", "12345", "password1");
Assert.NotNull(user);
Assert.Equal("myemail@company.com", user.Email);
Assert.Equal("Person", user.DisplayName);
Assert.Equal("12345", user.PostalCode);
Assert.NotNull(user.PasswordHash);
Assert.NotNull(user.PasswordSalt);
}
[Fact]
public void Create_Throws_ArgumentNullException_When_Password_Is_Null()
{
var ex = Assert.Throws<ArgumentNullException>(() => User.Create("myemail@company.com", "Person", "12345", null));
Assert.NotNull(ex);
}
[Fact]
public void Create_Throws_ArgumentException_When_Password_Is_WhiteSpace()
{
var ex = Assert.Throws<ArgumentException>(() => User.Create("myemail@company.com", "Person", "12345", " "));
Assert.NotNull(ex);
}
}
}
|
mit
|
C#
|
916a91cd3a4e337e325122af507aea32fd56101e
|
Bring across Server Sent Events resource implementation
|
peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype
|
src/Glimpse.Server.Web/Resources/MessageStreamResource.cs
|
src/Glimpse.Server.Web/Resources/MessageStreamResource.cs
|
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http;
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Glimpse.Server.Web
{
public class MessageStreamResource : IResourceStartup
{
private readonly IServerBroker _serverBroker;
private readonly ISubject<string> _senderSubject;
private readonly JsonSerializer _jsonSerializer;
public MessageStreamResource(IServerBroker serverBroker, JsonSerializer jsonSerializer)
{
jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
_jsonSerializer = jsonSerializer;
_serverBroker = serverBroker;
_senderSubject = new Subject<string>();
// TODO: See if we can get Defered working there
// lets subscribe, hope of the thread and then broadcast to all connections
//_serverBroker.OffRecieverThread.ListenAll().Subscribe(message => Observable.Defer(() => Observable.Start(() => ProcessMessage(message), TaskPoolScheduler.Default)));
_serverBroker.OffRecieverThread.ListenAll().Subscribe(message => Observable.Start(() => ProcessMessage(message), TaskPoolScheduler.Default));
}
public void Configure(IResourceBuilder resourceBuilder)
{
resourceBuilder.Run("MessageStream", null, async (context, dictionary) =>
{
var continueTask = new TaskCompletionSource<bool>();
// Disable request compression
var buffering = context.Features.Get<IHttpBufferingFeature>();
if (buffering != null)
{
buffering.DisableRequestBuffering();
}
context.Response.ContentType = "text/event-stream";
await context.Response.WriteAsync("retry: 5000\n\n");
await context.Response.WriteAsync("data: pong\n\n");
await context.Response.Body.FlushAsync();
var unSubscribe = _senderSubject.Subscribe(async t =>
{
await context.Response.WriteAsync($"data: {t}\n\n");
await context.Response.Body.FlushAsync();
});
context.RequestAborted.Register(() =>
{
continueTask.SetResult(true);
unSubscribe.Dispose();
});
await continueTask.Task;
});
}
private void ProcessMessage(IMessage message)
{
var payload = _jsonSerializer.Serialize(message);
_senderSubject.OnNext(payload);
}
}
}
|
namespace Glimpse.Server.Web
{
public class MessageStreamResource : IResourceStartup
{
private readonly IServerBroker _serverBroker;
public MessageStreamResource(IServerBroker serverBroker)
{
_serverBroker = serverBroker;
}
public void Configure(IResourceBuilder resourceBuilder)
{
// TODO: Need to get data to the client
throw new System.NotImplementedException();
}
}
}
|
mit
|
C#
|
d3577b5c56ff02e02e6ad2f095b0aa4a6ce88c38
|
Replace foreach with for
|
davidaramant/buddhabrot,davidaramant/buddhabrot
|
src/Buddhabrot.Core/Utilities/FixedSizeCache.cs
|
src/Buddhabrot.Core/Utilities/FixedSizeCache.cs
|
namespace Buddhabrot.Core.Utilities;
public sealed class FixedSizeCache<TKey, TValue>
where TKey : struct
where TValue : struct
{
private readonly RingBuffer<TKey> _keyCache;
private readonly RingBuffer<TValue> _valueCache;
public int Capacity => _keyCache.Capacity;
public int Count => _keyCache.Count;
public FixedSizeCache(int maxSize)
{
_keyCache = new(maxSize);
_valueCache = new(maxSize);
}
public bool Add(TKey key, TValue value)
{
if (_keyCache.Contains(key))
{
return false;
}
AddUnsafe(key, value);
return true;
}
public void AddUnsafe(TKey key, TValue value)
{
_keyCache.Add(key);
_valueCache.Add(value);
}
public bool TryGetValue(TKey key, out TValue value)
{
// Use a for loop to avoid allocating an enumerator
for (int i = 0; i < _keyCache.Count; i++)
{
if (_keyCache[i].Equals(key))
{
value = _valueCache[i];
return true;
}
}
value = default;
return false;
}
}
|
namespace Buddhabrot.Core.Utilities;
public sealed class FixedSizeCache<TKey, TValue>
where TKey : struct
where TValue : struct
{
private readonly RingBuffer<TKey> _keyCache;
private readonly RingBuffer<TValue> _valueCache;
public int Capacity => _keyCache.Capacity;
public int Count => _keyCache.Count;
public FixedSizeCache(int maxSize)
{
_keyCache = new(maxSize);
_valueCache = new(maxSize);
}
public bool Add(TKey key, TValue value)
{
if (_keyCache.Contains(key))
{
return false;
}
AddUnsafe(key, value);
return true;
}
public void AddUnsafe(TKey key, TValue value)
{
_keyCache.Add(key);
_valueCache.Add(value);
}
public bool TryGetValue(TKey key, out TValue value)
{
int index = 0;
foreach (var savedKey in _keyCache)
{
if (savedKey.Equals(key))
{
value = _valueCache[index];
return true;
}
index++;
}
value = default;
return false;
}
}
|
bsd-2-clause
|
C#
|
3496f1002a527ca037793bc567014f4834fdabfe
|
Allow underscore
|
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
|
Anlab.Core/Domain/TestItem.cs
|
Anlab.Core/Domain/TestItem.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using System.Text.Encodings.Web;
namespace Anlab.Core.Domain
{
public class TestItem
{
[Key]
[StringLength(128)]
[Display(Name = "Code")]
[RegularExpression(@"([A-Z0-9a-z\-#_])+", ErrorMessage = "Codes can only contain alphanumerics, #, _, and dashes.")]
public string Id { get; set; }
[Required]
[StringLength(512)]
public string Analysis { get; set; }
[Required]
[StringLength(64)]
public string Category { get; set; }
[NotMapped]
public string[] Categories {
get => Category != null ? Category.Split('|') : new string[0];
set => Category = string.Join("|", value);
}
[Required]
public string Group { get; set; }
public bool Public { get; set; }
public string AdditionalInfoPrompt { get; set; }
public string Notes { get; set; }
public string NotesEncoded
{
get
{
if (Notes == null)
{
return null;
}
var encoder = HtmlEncoder.Default;
return encoder.Encode(Notes);
}
}
}
public static class TestCategories
{
public static string Soil = "Soil";
public static string Plant = "Plant";
public static string Water = "Water";
public static readonly string[] All = { Soil, Plant, Water };
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using System.Text.Encodings.Web;
namespace Anlab.Core.Domain
{
public class TestItem
{
[Key]
[StringLength(128)]
[Display(Name = "Code")]
[RegularExpression(@"([A-Z0-9a-z\-#])+", ErrorMessage = "Codes can only contain alphanumerics, #, and dashes.")]
public string Id { get; set; }
[Required]
[StringLength(512)]
public string Analysis { get; set; }
[Required]
[StringLength(64)]
public string Category { get; set; }
[NotMapped]
public string[] Categories {
get => Category != null ? Category.Split('|') : new string[0];
set => Category = string.Join("|", value);
}
[Required]
public string Group { get; set; }
public bool Public { get; set; }
public string AdditionalInfoPrompt { get; set; }
public string Notes { get; set; }
public string NotesEncoded
{
get
{
if (Notes == null)
{
return null;
}
var encoder = HtmlEncoder.Default;
return encoder.Encode(Notes);
}
}
}
public static class TestCategories
{
public static string Soil = "Soil";
public static string Plant = "Plant";
public static string Water = "Water";
public static readonly string[] All = { Soil, Plant, Water };
}
}
|
mit
|
C#
|
ac49f092337b7550fda9160b1d757d5593ea51d6
|
Remove Gender, Age in Model.
|
App2Night/App2Night.Xamarin
|
App2Night.Model/Model/User.cs
|
App2Night.Model/Model/User.cs
|
using System.Collections.ObjectModel;
using System.ComponentModel;
using App2Night.Model.Enum;
namespace App2Night.Model.Model
{
public class User
{
public string Name { get; set; }
public string Email { get; set; }
public ObservableCollection<Party> Events { get; set; }
public Location Addresse { get; set; }
public Location LastGpsLocation { get; set; }
}
}
|
using System.Collections.ObjectModel;
using System.ComponentModel;
using App2Night.Model.Enum;
namespace App2Night.Model.Model
{
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; } = Gender.Unkown;
public string Email { get; set; }
public ObservableCollection<Party> Events { get; set; }
public Location Addresse { get; set; }
public Location LastGpsLocation { get; set; }
}
}
|
mit
|
C#
|
81a4f1300773e5e35f03c6077962207c7d7f87cf
|
Update version
|
metaphorce/leaguesharp
|
MetaSmite/Properties/AssemblyInfo.cs
|
MetaSmite/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MetaSmite")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MetaSmite")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef7a8678-e51f-491e-a1f0-a13de0270acb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MetaSmite")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MetaSmite")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef7a8678-e51f-491e-a1f0-a13de0270acb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
b565d1ab762b92683d72d210f3927804a7f61439
|
Update naming
|
Wox-launcher/Wox,qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox
|
Wox.Plugin/SharedCommands/SearchWeb.cs
|
Wox.Plugin/SharedCommands/SearchWeb.cs
|
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Wox.Plugin.SharedCommands
{
public static class SearchWeb
{
/// <summary>
/// Opens search in a new browser. If no browser path is passed in then Chrome is used.
/// Leave browser path blank to use Chrome.
/// </summary>
public static void NewBrowserWindow(this string url, string browserPath)
{
var browserExecutableName = browserPath?
.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.None)
.Last();
var selectedBrowserPath = string.IsNullOrEmpty(browserExecutableName) ? "chrome" : browserPath;
// Internet Explorer will open url in new browser window, and does not take the --new-window parameter
var browserArguements = browserExecutableName == "iexplore.exe" ? "" : "--new-window ";
OpenWebSearch(selectedBrowserPath, browserArguements, url);
}
/// <summary>
/// Opens search as a tab in the default browser chosen in Windows settings.
/// </summary>
public static void NewTabInBrowser(this string url, string browserPath)
{
var browserExecutableName = browserPath?
.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.None)
.Last();
var selectedBrowserPath = string.IsNullOrEmpty(browserExecutableName) ? "" : browserPath;
OpenWebSearch(selectedBrowserPath, "", url);
}
private static void OpenWebSearch(string chosenBrowser, string browserArguements, string url)
{
try
{
Process.Start(chosenBrowser, browserArguements + url);
}
catch (System.ComponentModel.Win32Exception)
{
Process.Start(url);
}
}
}
}
|
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Wox.Plugin.SharedCommands
{
public static class SearchWeb
{
/// <summary>
/// Opens search in a new browser. If no browser path is passed in then Chrome is used.
/// Leave browser path blank to use Chrome.
/// </summary>
public static void NewBrowserWindow(this string url, string browserPath)
{
var browserExecutableName = browserPath?
.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.None)
.Last();
var browser = string.IsNullOrEmpty(browserExecutableName) ? "chrome" : browserPath;
// Internet Explorer will open url in new browser window, and does not take the --new-window parameter
var browserArguements = browserExecutableName == "iexplore.exe" ? "" : "--new-window ";
OpenWebSearch(browser, browserArguements, url);
}
/// <summary>
/// Opens search as a tab in the default browser chosen in Windows settings.
/// </summary>
public static void NewTabInBrowser(this string url, string browserPath)
{
var browserExecutableName = browserPath?
.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.None)
.Last();
var browser = string.IsNullOrEmpty(browserExecutableName) ? "" : browserPath;
OpenWebSearch(browser, "", url);
}
private static void OpenWebSearch(string chosenBrowser, string browserArguements, string url)
{
try
{
Process.Start(chosenBrowser, browserArguements + url);
}
catch (System.ComponentModel.Win32Exception)
{
Process.Start(url);
}
}
}
}
|
mit
|
C#
|
d934ffa9f5a87ffdeecb345344d2b6ba87a2d315
|
add documentation to enumhelpers
|
peopleware/net-ppwcode-util-oddsandends
|
src/II/EnumHelpers/EnumHelpers.cs
|
src/II/EnumHelpers/EnumHelpers.cs
|
// Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using PPWCode.Util.OddsAndEnds.II.Extensions;
namespace PPWCode.Util.OddsAndEnds.II.EnumHelpers
{
/// <summary>
/// Helper class for Enumeration.
/// </summary>
public static class EnumHelpers
{
/// <summary>
/// Returns enumeration as IEnumerable of T.
/// </summary>
/// <typeparam name="T">The type of the enumeration.</typeparam>
/// <returns>IEnumerable of T.</returns>
[Obsolete(@"Use EnumHelpers.AsEnumerable")]
public static IEnumerable<T> EnumEnumerable<T>()
{
return AsEnumerable<T>();
}
/// <summary>
/// Returns enumeration as IEnumerable of T.
/// </summary>
/// <typeparam name="T">The type of the enumeration.</typeparam>
/// <returns>IEnumerable of T.</returns>
public static IEnumerable<T> AsEnumerable<T>()
{
if (!typeof(Enum).IsAssignableFrom(typeof(T)))
{
throw new InvalidCastException("Enum derived type expected.");
}
return Enum.GetValues(typeof(T)).Cast<T>();
}
/// <summary>
/// Gets localized description of value of enumeration.
/// </summary>
/// <param name="enumValue">The type of the enumeration.</param>
/// <returns>The localized description.</returns>
[Obsolete(@"Use EnumExtension.GetLocalizedDescription()")]
public static string GetLocalizedDescription(this Enum enumValue)
{
return EnumExtension.GetLocalizedDescription(enumValue);
}
}
}
|
// Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using PPWCode.Util.OddsAndEnds.II.Extensions;
namespace PPWCode.Util.OddsAndEnds.II.EnumHelpers
{
/// <summary>
/// Helper class for Enumeration.
/// </summary>
public static class EnumHelpers
{
[Obsolete(@"Use EnumHelpers.AsEnumerable")]
public static IEnumerable<T> EnumEnumerable<T>()
{
return AsEnumerable<T>();
}
public static IEnumerable<T> AsEnumerable<T>()
{
if (!typeof(Enum).IsAssignableFrom(typeof(T)))
{
throw new InvalidCastException("Enum derived type expected.");
}
return Enum.GetValues(typeof(T)).Cast<T>();
}
[Obsolete(@"Use EnumExtension.GetLocalizedDescription()")]
public static string GetLocalizedDescription(this Enum enumValue)
{
return EnumExtension.GetLocalizedDescription(enumValue);
}
}
}
|
apache-2.0
|
C#
|
9354d2b0721bc901339ff314692708f0c4a79e84
|
Save after load
|
gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
|
Server/Settings/Base/SettingsBase.cs
|
Server/Settings/Base/SettingsBase.cs
|
using LunaCommon.Xml;
using Server.Context;
using Server.Log;
using Server.System;
using System;
using System.IO;
namespace Server.Settings.Base
{
public abstract class SettingsBase<T>: ISettings
where T : class, new()
{
protected abstract string Filename { get; }
private string SettingsPath => Path.Combine(ServerContext.ConfigDirectory, Filename);
public static T SettingsStore { get; private set; } = new T();
protected SettingsBase()
{
if (!FileHandler.FolderExists(ServerContext.ConfigDirectory))
FileHandler.FolderCreate(ServerContext.ConfigDirectory);
}
public void Load()
{
if (!File.Exists(SettingsPath))
LunaXmlSerializer.WriteToXmlFile(Activator.CreateInstance(typeof(T)), Path.Combine(ServerContext.ConfigDirectory, Filename));
try
{
SettingsStore = LunaXmlSerializer.ReadXmlFromPath(typeof(T), SettingsPath) as T;
Save(); //We call the save to add the new settings into the file
}
catch (Exception)
{
LunaLog.Fatal($"Error while trying to read {SettingsPath}. Default settings will be used. Please remove the file so a new one can be generated");
}
}
public void Save()
{
LunaXmlSerializer.WriteToXmlFile(SettingsStore, SettingsPath);
}
}
}
|
using LunaCommon.Xml;
using Server.Context;
using Server.Log;
using Server.System;
using System;
using System.IO;
namespace Server.Settings.Base
{
public abstract class SettingsBase<T>: ISettings
where T : class, new()
{
protected abstract string Filename { get; }
private string SettingsPath => Path.Combine(ServerContext.ConfigDirectory, Filename);
public static T SettingsStore { get; private set; } = new T();
protected SettingsBase()
{
if (!FileHandler.FolderExists(ServerContext.ConfigDirectory))
FileHandler.FolderCreate(ServerContext.ConfigDirectory);
}
public void Load()
{
if (!File.Exists(SettingsPath))
LunaXmlSerializer.WriteToXmlFile(Activator.CreateInstance(typeof(T)), Path.Combine(ServerContext.ConfigDirectory, Filename));
try
{
SettingsStore = LunaXmlSerializer.ReadXmlFromPath(typeof(T), SettingsPath) as T;
}
catch (Exception)
{
LunaLog.Fatal($"Error while trying to read {SettingsPath}. Default settings will be used. Please remove the file so a new one can be generated");
}
}
public void Save()
{
LunaXmlSerializer.WriteToXmlFile(SettingsStore, SettingsPath);
}
}
}
|
mit
|
C#
|
ca8fefb1be3938e0b18e9325aacf67a2f6b14e15
|
Update Sha256Hasher.cs
|
livarcocc/cli-1,livarcocc/cli-1,johnbeisner/cli,livarcocc/cli-1,johnbeisner/cli,dasMulli/cli,johnbeisner/cli,dasMulli/cli,dasMulli/cli
|
src/dotnet/Telemetry/Sha256Hasher.cs
|
src/dotnet/Telemetry/Sha256Hasher.cs
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Microsoft.DotNet.Cli.Telemetry
{
internal static class Sha256Hasher
{
/// <summary>
/// The hashed mac address needs to be the same hashed value as produced by the other distinct sources given the same input. (e.g. VsCode)
/// </summary>
public static string Hash(string text)
{
var sha256 = SHA256.Create();
return HashInFormat(sha256, text);
}
public static string HashWithNormalizedCasing(string text)
{
return Hash(text.ToUpperInvariant());
}
private static string HashInFormat(SHA256 sha256, string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] hash = sha256.ComputeHash(bytes);
StringBuilder hashString = new StringBuilder();
foreach (byte x in hash)
{
hashString.AppendFormat("{0:x2}", x);
}
return hashString.ToString();
}
}
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Microsoft.DotNet.Cli.Telemetry
{
internal static class Sha256Hasher
{
/// <summary>
/// // The hashed mac address needs to be the same hashed value as produced by the other distinct sources given the same input. (e.g. VsCode)
/// </summary>
public static string Hash(string text)
{
var sha256 = SHA256.Create();
return HashInFormat(sha256, text);
}
public static string HashWithNormalizedCasing(string text)
{
return Hash(text.ToUpperInvariant());
}
private static string HashInFormat(SHA256 sha256, string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] hash = sha256.ComputeHash(bytes);
StringBuilder hashString = new StringBuilder();
foreach (byte x in hash)
{
hashString.AppendFormat("{0:x2}", x);
}
return hashString.ToString();
}
}
}
|
mit
|
C#
|
e8375335acbecb977a66b3098a40609b92450124
|
fix alive endpoint on notifications
|
bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core
|
src/Notifications/Controllers/SendController.cs
|
src/Notifications/Controllers/SendController.cs
|
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace Bit.Notifications
{
[Authorize("Internal")]
public class SendController : Controller
{
private readonly IHubContext<NotificationsHub> _hubContext;
public SendController(IHubContext<NotificationsHub> hubContext)
{
_hubContext = hubContext;
}
[HttpGet("~/alive")]
[HttpGet("~/now")]
[AllowAnonymous]
public DateTime GetAlive()
{
return DateTime.UtcNow;
}
[HttpPost("~/send")]
[SelfHosted(SelfHostedOnly = true)]
public async Task PostSend()
{
using(var reader = new StreamReader(Request.Body, Encoding.UTF8))
{
var notificationJson = await reader.ReadToEndAsync();
if(!string.IsNullOrWhiteSpace(notificationJson))
{
await HubHelpers.SendNotificationToHubAsync(notificationJson, _hubContext);
}
}
}
}
}
|
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace Bit.Notifications
{
[Authorize("Internal")]
[SelfHosted(SelfHostedOnly = true)]
public class SendController : Controller
{
private readonly IHubContext<NotificationsHub> _hubContext;
public SendController(IHubContext<NotificationsHub> hubContext)
{
_hubContext = hubContext;
}
[HttpGet("~/alive")]
[HttpGet("~/now")]
[AllowAnonymous]
[SelfHosted(SelfHostedOnly = false, NotSelfHostedOnly = false)]
public DateTime GetAlive()
{
return DateTime.UtcNow;
}
[HttpPost("~/send")]
public async Task PostSend()
{
using(var reader = new StreamReader(Request.Body, Encoding.UTF8))
{
var notificationJson = await reader.ReadToEndAsync();
if(!string.IsNullOrWhiteSpace(notificationJson))
{
await HubHelpers.SendNotificationToHubAsync(notificationJson, _hubContext);
}
}
}
}
}
|
agpl-3.0
|
C#
|
be2aa88c734254198665fb460c40eca0426e58fb
|
Update ZoomFactor.cs
|
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/CSharp/Worksheets/Display/ZoomFactor.cs
|
Examples/CSharp/Worksheets/Display/ZoomFactor.cs
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Display
{
public class ZoomFactor
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the zoom factor of the worksheet to 75
worksheet.Zoom = 75;
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Display
{
public class ZoomFactor
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the zoom factor of the worksheet to 75
worksheet.Zoom = 75;
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
}
}
}
|
mit
|
C#
|
c305cf7b03d3f8fbf88911c519176d7b80959b0a
|
resolve list
|
HarshPoint/HarshPoint,NaseUkolyCZ/HarshPoint,the-ress/HarshPoint
|
HarshPoint/Provisioning/HarshFieldProvisioner.cs
|
HarshPoint/Provisioning/HarshFieldProvisioner.cs
|
using Microsoft.SharePoint.Client;
using System;
using System.Threading.Tasks;
namespace HarshPoint.Provisioning
{
/// <summary>
/// Base class for provisioners that modify SharePoint fields using the
/// client-side object model.
/// </summary>
public abstract class HarshFieldProvisioner : HarshProvisioner
{
/// <summary>
/// Gets or sets the field identifier.
/// </summary>
/// <value>
/// The field identifier. Must not be an empty <see cref="Guid"/>.
/// </value>
public Guid FieldId
{
get;
set;
}
/// <summary>
/// Gets or sets the list containing the field.
/// </summary>
/// <value>
/// The list. When null, a site column is created or updated.
/// </value>
public IResolveSingle<List> List
{
get;
set;
}
protected override async Task InitializeAsync()
{
if (FieldId == Guid.Empty)
{
throw Error.InvalidOperation(SR.HarshFieldProvisionerBase_FieldIdEmpty);
}
TargetFieldCollection = Web.Fields;
if (List != null)
{
var resolved = await ResolveAsync(List);
TargetFieldCollection = resolved.Fields;
}
Field = TargetFieldCollection.GetById(FieldId);
ClientContext.Load(Field);
await ClientContext.ExecuteQueryAsync();
}
protected Field Field
{
get;
set;
}
protected FieldCollection TargetFieldCollection
{
get;
private set;
}
}
}
|
using Microsoft.SharePoint.Client;
using System;
using System.Threading.Tasks;
namespace HarshPoint.Provisioning
{
/// <summary>
/// Base class for provisioners that modify SharePoint fields using the
/// client-side object model.
/// </summary>
public abstract class HarshFieldProvisioner : HarshProvisioner
{
/// <summary>
/// Gets or sets the field identifier.
/// </summary>
/// <value>
/// The field identifier. Must not be an empty <see cref="Guid"/>.
/// </value>
public Guid FieldId
{
get;
set;
}
/// <summary>
/// Gets or sets the list containing the field.
/// </summary>
/// <value>
/// The list. When null, a site column is created or updated.
/// </value>
public List List
{
get;
set;
}
protected override async Task InitializeAsync()
{
if (FieldId == Guid.Empty)
{
throw Error.InvalidOperation(SR.HarshFieldProvisionerBase_FieldIdEmpty);
}
TargetFieldCollection = Web.Fields;
if (List != null)
{
TargetFieldCollection = List.Fields;
}
Field = TargetFieldCollection.GetById(FieldId);
ClientContext.Load(Field);
await ClientContext.ExecuteQueryAsync();
}
protected Field Field
{
get;
set;
}
protected FieldCollection TargetFieldCollection
{
get;
private set;
}
}
}
|
bsd-2-clause
|
C#
|
2341ba200298257778e72193f18451331a73c516
|
Update assembly version
|
tamasflamich/effort
|
Main/Source/Effort/Properties/AssemblyVersion.cs
|
Main/Source/Effort/Properties/AssemblyVersion.cs
|
// --------------------------------------------------------------------------------------------
// <copyright file="AssemblyVersion.cs" company="Effort Team">
// Copyright (C) Effort Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.3.4")]
[assembly: AssemblyInformationalVersion("1.3.4")]
|
// --------------------------------------------------------------------------------------------
// <copyright file="AssemblyVersion.cs" company="Effort Team">
// Copyright (C) Effort Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------
using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.3.3")]
[assembly: AssemblyInformationalVersion("1.3.3")]
|
mit
|
C#
|
920c3dbb76f34cef1bf789806108b771ccd1addf
|
Remove useless using
|
thennequin/Wox-EasyTotp
|
Wox-EasyTotp/Authenticators/Steam.cs
|
Wox-EasyTotp/Authenticators/Steam.cs
|
using System;
using System.Text;
namespace Wox_EasyTotp.Authenticators
{
[Authenticator("TOTP Steam", "Images/steam.png")]
class Steam : RFC6238
{
static string GetCode(string sSecretKey)
{
if (sSecretKey.Length == 32)
{
try
{
long iInterval = GetInterval(DateTime.Now);
byte[] vHashData = DescryptTime(sSecretKey, (ulong)iInterval);
int iStart = vHashData[19] & 0x0f;
// extract those 4 bytes
byte[] vData = new byte[4];
Array.Copy(vHashData, iStart, vData, 0, 4);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(vData);
}
uint iFullCode = BitConverter.ToUInt32(vData, 0) & 0x7fffffff;
const string sSteamChars = "23456789BCDFGHJKMNPQRTVWXY";
StringBuilder sCodeBuilder = new StringBuilder();
for (var i = 0; i < 5; i++)
{
sCodeBuilder.Append(sSteamChars[(int)(iFullCode % sSteamChars.Length)]);
iFullCode /= (uint)sSteamChars.Length;
}
return sCodeBuilder.ToString();
}
catch { }
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wox_EasyTotp.Authenticators
{
[Authenticator("TOTP Steam", "Images/steam.png")]
class Steam : RFC6238
{
static string GetCode(string sSecretKey)
{
if (sSecretKey.Length == 32)
{
try
{
long iInterval = GetInterval(DateTime.Now);
byte[] vHashData = DescryptTime(sSecretKey, (ulong)iInterval);
int iStart = vHashData[19] & 0x0f;
// extract those 4 bytes
byte[] vData = new byte[4];
Array.Copy(vHashData, iStart, vData, 0, 4);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(vData);
}
uint iFullCode = BitConverter.ToUInt32(vData, 0) & 0x7fffffff;
const string sSteamChars = "23456789BCDFGHJKMNPQRTVWXY";
StringBuilder sCodeBuilder = new StringBuilder();
for (var i = 0; i < 5; i++)
{
sCodeBuilder.Append(sSteamChars[(int)(iFullCode % sSteamChars.Length)]);
iFullCode /= (uint)sSteamChars.Length;
}
return sCodeBuilder.ToString();
}
catch { }
}
return null;
}
}
}
|
mit
|
C#
|
ffc23a002622d2219690dbe0a588dc43ae93a22c
|
refactor TemplateUrlTests to remove dependency on WebApiHelper
|
billboga/Supurlative,ritterim/Supurlative,kendaleiv/Supurlative
|
tests/Core.Tests/TemplateUrlTests.cs
|
tests/Core.Tests/TemplateUrlTests.cs
|
using System.Web.Http;
using Tavis.UriTemplates;
using Xunit;
namespace RimDev.Supurlative.Tests
{
public class TemplateUrlTests
{
const string _baseUrl = "http://localhost:8000/";
[Fact]
public void Can_generate_a_fully_qualified_path()
{
string expected = _baseUrl + "foo/1";
const string routeName = "foo.show";
const string routeTemplate = "foo/{id}";
string template = TestHelper.CreateATemplateGenerator(_baseUrl, routeName, routeTemplate)
.Generate(routeName);
var uriTemplate = new UriTemplate(template);
uriTemplate.AddParameter("id", 1);
string actual = uriTemplate.Resolve();
Assert.Equal(expected, actual);
}
[Fact]
public void Can_generate_a_path_with_anonymous_complex_route_properties()
{
string expected = _baseUrl + "foo/1?bar.abc=abc&bar.def=def";
const string routeName = "foo.show";
const string routeTemplate = "foo/{id}";
string template = TestHelper.CreateATemplateGenerator(_baseUrl, routeName, routeTemplate)
.Generate(routeName, new { Id = 1, Bar = new { Abc = "abc", Def = "def" } });
var uriTemplate = new UriTemplate(template);
uriTemplate.AddParameters(new { id = 1 });
uriTemplate.AddParameter("bar.abc", "abc");
uriTemplate.AddParameter("bar.def", "def");
string actual = uriTemplate.Resolve();
Assert.Equal(expected, actual);
}
[Fact]
public void Can_generate_two_optional_path_items_template()
{
string expected = _baseUrl + "foo/2";
const string routeName = "foo.one.two";
const string routeTemplate = "foo/{one}/{two}";
string template = TestHelper.CreateATemplateGenerator(_baseUrl, routeName, routeTemplate,
routeDefaults: new { one = RouteParameter.Optional, two = RouteParameter.Optional })
.Generate(routeName, new { two = 2 });
var uriTemplate = new UriTemplate(template);
uriTemplate.AddParameter("two", "2");
string actual = uriTemplate.Resolve();
Assert.Equal(expected, actual);
}
}
}
|
using Tavis.UriTemplates;
using Xunit;
namespace RimDev.Supurlative.Tests
{
public class TemplateUrlTests
{
public TemplateGenerator Generator { get; set; }
public TemplateUrlTests()
{
Generator = InitializeGenerator();
}
private static TemplateGenerator InitializeGenerator(SupurlativeOptions options = null)
{
var request = WebApiHelper.GetRequest();
return new TemplateGenerator(request, options ?? SupurlativeOptions.Defaults);
}
[Fact]
public void Can_generate_a_fully_qualified_path()
{
var template = Generator.Generate("foo.show");
var uriTemplate = new UriTemplate(template);
uriTemplate.AddParameter("id", 1);
var generatedUri = uriTemplate.Resolve();
Assert.Equal("http://localhost:8000/foo/1", generatedUri);
}
[Fact]
public void Can_generate_a_path_with_anonymous_complex_route_properties()
{
var template = Generator.Generate("foo.show", new { Id = 1, Bar = new { Abc = "abc", Def = "def" } });
var uriTemplate = new UriTemplate(template);
uriTemplate.AddParameters(new { id = 1 });
uriTemplate.AddParameter("bar.abc", "abc");
uriTemplate.AddParameter("bar.def", "def");
var generatedUri = uriTemplate.Resolve();
Assert.Equal("http://localhost:8000/foo/1?bar.abc=abc&bar.def=def", generatedUri);
}
[Fact]
public void Can_generate_two_optional_path_items_template()
{
var template = Generator.Generate("bar.one.two", new { two = 2});
var uriTemplate = new UriTemplate(template);
uriTemplate.AddParameter("two", "2");
var generatedUri = uriTemplate.Resolve();
Assert.Equal("http://localhost:8000/bar/2", generatedUri);
}
}
}
|
mit
|
C#
|
0ca443426a880586800d85f7186b8fa3bf841fbd
|
add useful ctor
|
you21979/NBitcoin,MetacoSA/NBitcoin,MetacoSA/NBitcoin,HermanSchoenfeld/NBitcoin,dangershony/NStratis,thepunctuatedhorizon/BrickCoinAlpha.0.0.1,bitcoinbrisbane/NBitcoin,stratisproject/NStratis,lontivero/NBitcoin,NicolasDorier/NBitcoin
|
NBitcoin/OpenAsset/AssetId.cs
|
NBitcoin/OpenAsset/AssetId.cs
|
using NBitcoin.DataEncoders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.OpenAsset
{
public class AssetId
{
internal byte[] _Bytes;
public AssetId()
{
_Bytes = new byte[] { 0 };
}
public AssetId(IDestination assetScriptPubKey)
: this(assetScriptPubKey.ScriptPubKey)
{
}
public AssetId(BitcoinAssetId assetId)
{
if(assetId == null)
throw new ArgumentNullException("assetId");
_Bytes = assetId.AssetId._Bytes;
}
public AssetId(Script assetScriptPubKey)
: this(assetScriptPubKey.Hash)
{
}
public AssetId(ScriptId scriptId)
{
_Bytes = scriptId.ToBytes(true);
}
public AssetId(byte[] value)
{
if(value == null)
throw new ArgumentNullException("value");
_Bytes = value;
}
public AssetId(uint160 value)
: this(value.ToBytes())
{
}
public AssetId(string value)
{
_Bytes = Encoders.Hex.DecodeData(value);
_Str = value;
}
public BitcoinAssetId GetWif(Network network)
{
return new BitcoinAssetId(this, network);
}
public byte[] ToBytes()
{
return ToBytes(false);
}
public byte[] ToBytes(bool @unsafe)
{
if(@unsafe)
return _Bytes;
var array = new byte[_Bytes.Length];
Array.Copy(_Bytes, array, _Bytes.Length);
return array;
}
public override bool Equals(object obj)
{
AssetId item = obj as AssetId;
if(item == null)
return false;
return Utils.ArrayEqual(_Bytes, item._Bytes);
}
public static bool operator ==(AssetId a, AssetId b)
{
if(System.Object.ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
return Utils.ArrayEqual(a._Bytes, b._Bytes);
}
public static bool operator !=(AssetId a, AssetId b)
{
return !(a == b);
}
public override int GetHashCode()
{
return Utils.GetHashCode(_Bytes);
}
string _Str;
public override string ToString()
{
if(_Str == null)
_Str = Encoders.Hex.EncodeData(_Bytes);
return _Str;
}
}
}
|
using NBitcoin.DataEncoders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.OpenAsset
{
public class AssetId
{
internal byte[] _Bytes;
public AssetId()
{
_Bytes = new byte[] { 0 };
}
public AssetId(IDestination assetScriptPubKey)
: this(assetScriptPubKey.ScriptPubKey)
{
}
public AssetId(Script assetScriptPubKey)
: this(assetScriptPubKey.Hash)
{
}
public AssetId(ScriptId scriptId)
{
_Bytes = scriptId.ToBytes(true);
}
public AssetId(byte[] value)
{
if(value == null)
throw new ArgumentNullException("value");
_Bytes = value;
}
public AssetId(uint160 value)
: this(value.ToBytes())
{
}
public AssetId(string value)
{
_Bytes = Encoders.Hex.DecodeData(value);
_Str = value;
}
public BitcoinAssetId GetWif(Network network)
{
return new BitcoinAssetId(this, network);
}
public byte[] ToBytes()
{
return ToBytes(false);
}
public byte[] ToBytes(bool @unsafe)
{
if(@unsafe)
return _Bytes;
var array = new byte[_Bytes.Length];
Array.Copy(_Bytes, array, _Bytes.Length);
return array;
}
public override bool Equals(object obj)
{
AssetId item = obj as AssetId;
if(item == null)
return false;
return Utils.ArrayEqual(_Bytes, item._Bytes);
}
public static bool operator ==(AssetId a, AssetId b)
{
if(System.Object.ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
return Utils.ArrayEqual(a._Bytes, b._Bytes);
}
public static bool operator !=(AssetId a, AssetId b)
{
return !(a == b);
}
public override int GetHashCode()
{
return Utils.GetHashCode(_Bytes);
}
string _Str;
public override string ToString()
{
if(_Str == null)
_Str = Encoders.Hex.EncodeData(_Bytes);
return _Str;
}
}
}
|
mit
|
C#
|
e07969dc5a83e512402548ed3b07c9cc0101e54a
|
Add HouseNumber, ApartmentLetter, and ApartmentNumber into AddressData
|
nfleet/.net-sdk
|
NFleetSDK/Data/AddressData.cs
|
NFleetSDK/Data/AddressData.cs
|
namespace NFleet.Data
{
public class AddressData
{
public string Country { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Street { get; set; }
public int HouseNumber { get; set; }
public string ApartmentLetter { get; set; }
public int ApartmentNumber { get; set; }
}
}
|
namespace NFleet.Data
{
public class AddressData
{
public string Country { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Street { get; set; }
}
}
|
mit
|
C#
|
4adcadb6a80120e3c0e827f9d36d1234f79885f0
|
Update ModuleWeaver.cs
|
Fody/Obsolete
|
Obsolete.Fody/ModuleWeaver.cs
|
Obsolete.Fody/ModuleWeaver.cs
|
using System.Collections.Generic;
using Fody;
public partial class ModuleWeaver :
BaseModuleWeaver
{
public SemanticVersion assemblyVersion;
public override void Execute()
{
ReadConfig();
FindEditorBrowsableTypes();
FindObsoleteType();
assemblyVersion = VersionReader.Read(ModuleDefinition.Assembly);
ProcessAssembly();
}
public override IEnumerable<string> GetAssembliesForScanning()
{
yield return "mscorlib";
yield return "System";
yield return "System.Runtime";
yield return "netstandard";
}
public override bool ShouldCleanReference => true;
}
|
using System.Collections.Generic;
using Fody;
public partial class ModuleWeaver:BaseModuleWeaver
{
public SemanticVersion assemblyVersion;
public override void Execute()
{
ReadConfig();
FindEditorBrowsableTypes();
FindObsoleteType();
assemblyVersion = VersionReader.Read(ModuleDefinition.Assembly);
ProcessAssembly();
}
public override IEnumerable<string> GetAssembliesForScanning()
{
yield return "mscorlib";
yield return "System";
yield return "System.Runtime";
yield return "netstandard";
}
public override bool ShouldCleanReference => true;
}
|
mit
|
C#
|
02191eca5d100bc09ec153408037b6bd018b3243
|
add method to compare multiple pixels
|
Gurupitka/pixel-monitor
|
pixel-monitor/ImageComparer.cs
|
pixel-monitor/ImageComparer.cs
|
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Media;
namespace pixel_monitor
{
public class ImageComparer
{
/// <summary>
/// Compares a given color (r,g,b) value to another (r,g,b) value and if the color difference is at least mindelta returns true;
/// </summary>
/// <param name="current"></param>
/// <param name="previous"></param>
/// <param name="MinDelta"></param>
/// <returns></returns>
public static bool PixelChanged(Color current, Color previous, int MinDelta)
{
int totalDelta = Math.Abs((current.R - previous.R) + (current.G - previous.G) + (current.B - previous.B));
return totalDelta >= MinDelta;
}
public static bool PixelsChanged(Color[] current, Color[] previous, int MinPixelDiffToBeConsideredDifferent, int MinDifferentPixels)
{
if(current.Length != previous.Length)
{
throw new Exception("Current and Previous color arrays are of differing lengths; could cause false positives.");
}
int totalPixelsChanged = 0;
for(int i = 0; i < current.Length; i++)
{
if(PixelChanged(current[i], previous[i], MinPixelDiffToBeConsideredDifferent))
{
totalPixelsChanged++;
}
if (totalPixelsChanged >= MinDifferentPixels)
{
return true;
}
}
return false;
}
public static Color GetCurrentRenderedPixelAtLocation(int x, int y)
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
if (x > bounds.Width || y > bounds.Width || x < 0 || y < 0)
{
throw new Exception("Requested pixel is outside bounds of the screen.");
}
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
Color result = bitmap.GetPixel(x, y);
return result;
}
}
}
}
}
|
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Media;
namespace pixel_monitor
{
public class ImageComparer
{
/// <summary>
/// Compares a given color (r,g,b) value to another (r,g,b) value and if the color difference is at least mindelta returns true;
/// </summary>
/// <param name="current"></param>
/// <param name="previous"></param>
/// <param name="MinDelta"></param>
/// <returns></returns>
public bool PixelChanged(Color current, Color previous, int MinDelta)
{
int totalDelta = Math.Abs((current.R - previous.R) + (current.G - previous.G) + (current.B - previous.B));
return totalDelta >= MinDelta;
}
public bool PixelsChanged(Color[] current, Color[] previous, int MinPixelDiffToBeConsideredDifferent, int MinDifferentPixels)
{
if(current.Length != previous.Length)
{
throw new Exception("Current and Previous color arrays are of differing lengths; could cause false positives.");
}
int totalPixelsChanged = 0;
for(int i = 0; i < current.Length; i++)
{
if(PixelChanged(current[i], previous[i], MinPixelDiffToBeConsideredDifferent))
{
totalPixelsChanged++;
}
if (totalPixelsChanged >= MinDifferentPixels)
{
return true;
}
}
return false;
}
}
}
|
mit
|
C#
|
222b72fd9a74db96d33526aff873f3b6006f1a11
|
bump version
|
alecgorge/adzerk-dot-net
|
Adzerk.Api/Properties/AssemblyInfo.cs
|
Adzerk.Api/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Adzerk.Api")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Adzerk.Api")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.8")]
[assembly: AssemblyFileVersion("0.0.0.8")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Adzerk.Api")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Exchange")]
[assembly: AssemblyProduct("Adzerk.Api")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.7")]
[assembly: AssemblyFileVersion("0.0.0.7")]
|
mit
|
C#
|
d2cb9a67c38c55cb47fe0872aa6260dc814a76b9
|
Fix markdownstring required
|
joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
|
Joinrpg/Views/Shared/EditorTemplates/MarkdownString.cshtml
|
Joinrpg/Views/Shared/EditorTemplates/MarkdownString.cshtml
|
@model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<div>
Можно использовать MarkDown (**<b>полужирный</b>**, _<i>курсив</i>_) <br/>
<textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea>
</div>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
}
|
@model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = "";
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = attr.Value.ToString();
}
}
}
<div>
Можно использовать MarkDown (**<b>полужирный</b>**, _<i>курсив</i>_) <br/>
<textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" data-val-required="@requiredMsg" data-val="true" rows="4">@(Model == null ? "" : Model.Contents)</textarea>
</div>
@if (!string.IsNullOrWhiteSpace(requiredMsg))
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
}
|
mit
|
C#
|
b9e79e7c55b8862e10b7f4befeef6fb75065da51
|
Add first implementation of dynamic builder
|
IEVin/PropertyChangedNotificator
|
src/Core/DynamicBuilder.cs
|
src/Core/DynamicBuilder.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Linq;
using System.Reflection.Emit;
namespace NotifyAutoImplementer.Core
{
public static class DynamicBuilder
{
static readonly Lazy<ModuleBuilder> s_builder = new Lazy<ModuleBuilder>(CreateModule);
public static T CreateInstanceProxy<T>()
where T : class, INotifyPropertyChanged, new()
{
var type = CreateProxyType(typeof(T));
return (T)Activator.CreateInstance(type);
}
static Type CreateProxyType(Type type)
{
var tb = s_builder.Value.DefineType(type.Name + "_wrap", type.Attributes, type);
tb.AddInterfaceImplementation(typeof(INotifyPropertyChanged));
var properties = GetPropertyNames(type);
foreach(var q in properties)
{
//var gettet = q.GetGetMethod(true);
var setter = q.GetSetMethod(false);
if(setter == null || !setter.IsVirtual)
continue;
var prop = tb.DefineProperty(q.Name, q.Attributes, q.PropertyType, Type.EmptyTypes);
var newSetter = CreateSetMethod(tb, setter); //, gettet);
tb.DefineMethodOverride(newSetter, setter);
prop.SetSetMethod(newSetter);
}
return tb.CreateType();
}
static MethodBuilder CreateSetMethod(TypeBuilder tb, MethodInfo setMi) //, MethodInfo getMi)
{
var paramTypes = setMi.GetParameters()
.Select(x => x.ParameterType)
.ToArray();
var mb = tb.DefineMethod(setMi.Name, setMi.Attributes, null, paramTypes);
var il = mb.GetILGenerator();
il.EmitWriteLine(setMi.Name);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Call, setMi);
il.Emit(OpCodes.Ret);
return mb;
}
static IEnumerable<PropertyInfo> GetPropertyNames(Type type)
{
// TODO: verify implementation
if(type == null)
return Enumerable.Empty<PropertyInfo>();
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty)
.Concat(GetPropertyNames(type.BaseType));
}
static ModuleBuilder CreateModule()
{
var assemblyName = new AssemblyName(string.Format("DA_{0}", Guid.NewGuid().ToString()));
return AppDomain.CurrentDomain
.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
.DefineDynamicModule(assemblyName.Name);
}
}
}
|
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace NotifyAutoImplementer.Core
{
public static class DynamicBuilder
{
const string AssemblyBuilderName = "DynamicAssembly_871";
static Lazy<AssemblyBuilder> s_assemblyBuilder = new Lazy<AssemblyBuilder>(
() => AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName( AssemblyBuilderName ), AssemblyBuilderAccess.Run ) );
public static T CreateInstanceProxy<T>()
{
return (T)CreateProxy( typeof(T) );
}
static object CreateProxy( Type type )
{
// stub
return Activator.CreateInstance( type );
}
}
}
|
mit
|
C#
|
6da9af7ecbc4254097d28c34ddc22ce8765d06e0
|
Fix for NH-3145
|
gliljas/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core
|
src/NHibernate/Proxy/NHibernateProxyHelper.cs
|
src/NHibernate/Proxy/NHibernateProxyHelper.cs
|
using NHibernate.Cfg;
using NHibernate.Intercept;
namespace NHibernate.Proxy
{
/// <summary>
/// NHibernateProxyHelper provides convenience methods for working with
/// objects that might be instances of Classes or the Proxied version of
/// the Class.
/// </summary>
public static class NHibernateProxyHelper
{
/// <summary>
/// Get the class of an instance or the underlying class of a proxy (without initializing the proxy!).
/// It is almost always better to use the entity name!
/// </summary>
/// <param name="obj">The object to get the type of.</param>
/// <returns>The Underlying Type for the object regardless of if it is a Proxy.</returns>
public static System.Type GetClassWithoutInitializingProxy(object obj)
{
if (obj.IsProxy())
{
var proxy = obj as INHibernateProxy;
return proxy.HibernateLazyInitializer.PersistentClass;
}
return obj.GetType();
}
/// <summary>
/// Get the true, underlying class of a proxied persistent class. This operation
/// will NOT initialize the proxy and thus may return an incorrect result.
/// </summary>
/// <param name="entity">a persistable object or proxy</param>
/// <returns>guessed class of the instance</returns>
/// <remarks>
/// This method is approximate match for Session.bestGuessEntityName in H3.2
/// </remarks>
public static System.Type GuessClass(object entity)
{
if (entity.IsProxy())
{
var proxy = entity as INHibernateProxy;
var li = proxy.HibernateLazyInitializer;
if (li.IsUninitialized)
{
return li.PersistentClass;
}
//NH-3145 : implementation could be a IFieldInterceptorAccessor
entity = li.GetImplementation();
}
var fieldInterceptorAccessor = entity as IFieldInterceptorAccessor;
if (fieldInterceptorAccessor != null)
{
var fieldInterceptor = fieldInterceptorAccessor.FieldInterceptor;
return fieldInterceptor.MappedClass;
}
return entity.GetType();
}
public static bool IsProxy(this object entity)
{
return Environment.BytecodeProvider.ProxyFactoryFactory.IsProxy(entity);
}
}
}
|
using NHibernate.Cfg;
using NHibernate.Intercept;
namespace NHibernate.Proxy
{
/// <summary>
/// NHibernateProxyHelper provides convenience methods for working with
/// objects that might be instances of Classes or the Proxied version of
/// the Class.
/// </summary>
public static class NHibernateProxyHelper
{
/// <summary>
/// Get the class of an instance or the underlying class of a proxy (without initializing the proxy!).
/// It is almost always better to use the entity name!
/// </summary>
/// <param name="obj">The object to get the type of.</param>
/// <returns>The Underlying Type for the object regardless of if it is a Proxy.</returns>
public static System.Type GetClassWithoutInitializingProxy(object obj)
{
if (obj.IsProxy())
{
var proxy = obj as INHibernateProxy;
return proxy.HibernateLazyInitializer.PersistentClass;
}
return obj.GetType();
}
/// <summary>
/// Get the true, underlying class of a proxied persistent class. This operation
/// will NOT initialize the proxy and thus may return an incorrect result.
/// </summary>
/// <param name="entity">a persistable object or proxy</param>
/// <returns>guessed class of the instance</returns>
/// <remarks>
/// This method is approximate match for Session.bestGuessEntityName in H3.2
/// </remarks>
public static System.Type GuessClass(object entity)
{
if (entity.IsProxy())
{
var proxy = entity as INHibernateProxy;
var li = proxy.HibernateLazyInitializer;
if (li.IsUninitialized)
{
return li.PersistentClass;
}
return li.GetImplementation().GetType();
}
var fieldInterceptorAccessor = entity as IFieldInterceptorAccessor;
if (fieldInterceptorAccessor != null)
{
var fieldInterceptor = fieldInterceptorAccessor.FieldInterceptor;
return fieldInterceptor.MappedClass;
}
return entity.GetType();
}
public static bool IsProxy(this object entity)
{
return Environment.BytecodeProvider.ProxyFactoryFactory.IsProxy(entity);
}
}
}
|
lgpl-2.1
|
C#
|
98e72e25ef9d5840160abcd2ce9dbff4ef2e5d0e
|
Add documentation
|
jnoellsch/ektron-fluentapi
|
Src/Ektron.SharedSource.FluentApi/ContentDataExtensions.cs
|
Src/Ektron.SharedSource.FluentApi/ContentDataExtensions.cs
|
using System.Collections.Generic;
using System.Linq;
using Ektron.Cms;
namespace Ektron.SharedSource.FluentApi
{
/// <summary>
/// Represents a set of extensions for <see cref="ContentData"/>.
/// </summary>
public static class ContentDataExtensions
{
/// <summary>
/// Converts a set of ContentData into some content type using Ektron deserialization.
/// </summary>
/// <typeparam name="T">Content Type to convert <see cref="ContentData"/> to.</typeparam>
/// <param name="source">A set of <see cref="ContentData"/> to convert.</param>
/// <returns>A set of content types.</returns>
public static IEnumerable<T> AsContentType<T>(this IEnumerable<ContentData> source)
{
return source.Select(c => c.AsContentType<T>());
}
/// <summary>
/// Converts a ContentData into some Content Type using Ektron deserialization.
/// </summary>
/// <typeparam name="T">Content Type to convert <see cref="ContentData"/> to.</typeparam>
/// <param name="source">The <see cref="ContentData"/> to convert.</param>
/// <returns>A content type.</returns>
public static T AsContentType<T>(this ContentData source)
{
return (T)EkXml.Deserialize(typeof(T), source.Html);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Ektron.Cms;
namespace Ektron.SharedSource.FluentApi
{
public static class ContentDataExtensions
{
public static IEnumerable<T> AsContentType<T>(this IEnumerable<ContentData> source)
{
return source.Select(c => c.AsContentType<T>());
}
public static T AsContentType<T>(this ContentData source)
{
return (T)EkXml.Deserialize(typeof(T), source.Html);
}
}
}
|
mit
|
C#
|
c9ad3645ed4df4dd7fe2311a313c0599a88c60ba
|
Revert "ClickOnce - Load CefSharp.dll from parent directory if not in current directory"
|
Livit/CefSharp,Livit/CefSharp,Livit/CefSharp,Livit/CefSharp
|
CefSharp.BrowserSubprocess/Program.cs
|
CefSharp.BrowserSubprocess/Program.cs
|
// Copyright © 2013 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Diagnostics;
using CefSharp.RenderProcess;
namespace CefSharp.BrowserSubprocess
{
/// <summary>
/// When implementing your own BrowserSubprocess
/// - For Full .Net use <see cref="WcfBrowserSubprocessExecutable"/>
/// - For .Net Core use <see cref="BrowserSubprocessExecutable"/> (No WCF Support)
/// - Include an app.manifest with the dpi/compatability sections, this is required (this project contains the relevant).
/// - If you are targeting x86/Win32 then you should set /LargeAddressAware (https://docs.microsoft.com/en-us/cpp/build/reference/largeaddressaware?view=vs-2017)
/// </summary>
public class Program
{
public static int Main(string[] args)
{
Debug.WriteLine("BrowserSubprocess starting up with command line: " + string.Join("\n", args));
SubProcess.EnableHighDPISupport();
//Add your own custom implementation of IRenderProcessHandler here
IRenderProcessHandler handler = null;
//The WcfBrowserSubprocessExecutable provides BrowserSubProcess functionality
//specific to CefSharp, WCF support (required for Sync JSB) will optionally be
//enabled if the CefSharpArguments.WcfEnabledArgument command line arg is present
//For .Net Core use BrowserSubprocessExecutable as there is no WCF support
var browserProcessExe = new WcfBrowserSubprocessExecutable();
var result = browserProcessExe.Main(args, handler);
Debug.WriteLine("BrowserSubprocess shutting down.");
return result;
}
}
}
|
// Copyright © 2013 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using CefSharp.RenderProcess;
namespace CefSharp.BrowserSubprocess
{
/// <summary>
/// When implementing your own BrowserSubprocess
/// - For Full .Net use <see cref="WcfBrowserSubprocessExecutable"/>
/// - For .Net Core use <see cref="BrowserSubprocessExecutable"/> (No WCF Support)
/// - Include an app.manifest with the dpi/compatability sections, this is required (this project contains the relevant).
/// - If you are targeting x86/Win32 then you should set /LargeAddressAware (https://docs.microsoft.com/en-us/cpp/build/reference/largeaddressaware?view=vs-2017)
/// </summary>
public class Program
{
public static int Main(string[] args)
{
Debug.WriteLine("BrowserSubprocess starting up with command line: " + string.Join("\n", args));
if(!System.IO.File.Exists("CefSharp.dll") && System.IO.File.Exists("..\\CefSharp.dll"))
{
//For publshing ClickOnce AnyCPU CefSharp.dll isn't included in the x64 build
//and the BrowserSubprocess fails to launch as a result.
//As a temp workaround load the file from the parent directory.
System.Reflection.Assembly.LoadFrom("..\\CefSharp.dll");
}
return MainInternal(args);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static int MainInternal(string[] args)
{
SubProcess.EnableHighDPISupport();
//Add your own custom implementation of IRenderProcessHandler here
IRenderProcessHandler handler = null;
//The WcfBrowserSubprocessExecutable provides BrowserSubProcess functionality
//specific to CefSharp, WCF support (required for Sync JSB) will optionally be
//enabled if the CefSharpArguments.WcfEnabledArgument command line arg is present
//For .Net Core use BrowserSubprocessExecutable as there is no WCF support
var browserProcessExe = new WcfBrowserSubprocessExecutable();
var result = browserProcessExe.Main(args, handler);
Debug.WriteLine("BrowserSubprocess shutting down.");
return result;
}
}
}
|
bsd-3-clause
|
C#
|
698c1a781fd149823e4b527efbdc302c4fba5329
|
Set 202 code for removing remark
|
noordwind/Coolector,noordwind/Coolector.Api,noordwind/Collectively.Api,noordwind/Collectively.Api,noordwind/Coolector,noordwind/Coolector.Api
|
Coolector.Api/Modules/RemarkModule.cs
|
Coolector.Api/Modules/RemarkModule.cs
|
using System.Linq;
using Coolector.Api.Commands;
using Coolector.Api.Queries;
using Coolector.Api.Storages;
using Coolector.Api.Validation;
using Coolector.Common.Commands.Remarks;
using Coolector.Dto.Remarks;
namespace Coolector.Api.Modules
{
public class RemarkModule : ModuleBase
{
public RemarkModule(ICommandDispatcher commandDispatcher,
IRemarkStorage remarkStorage,
IValidatorResolver validatorResolver)
: base(commandDispatcher, validatorResolver, modulePath: "remarks")
{
Get("", async args => await FetchCollection<BrowseRemarks, RemarkDto>
(async x => await remarkStorage.BrowseAsync(x))
.MapTo(x => new BasicRemarkDto
{
Id = x.Id,
Author = x.Author.Name,
Category = x.Category.Name,
Location = x.Location,
SmallPhotoUrl = x.Photos.FirstOrDefault(p => p.Size == "small")?.Url,
Description = x.Description,
CreatedAt = x.CreatedAt,
Resolved = x.Resolved
}).HandleAsync());
Get("categories", async args => await FetchCollection<BrowseRemarkCategories, RemarkCategoryDto>
(async x => await remarkStorage.BrowseCategoriesAsync(x)).HandleAsync());
Get("{id}", async args => await Fetch<GetRemark, RemarkDto>
(async x => await remarkStorage.GetAsync(x.Id)).HandleAsync());
Post("", async args => await For<CreateRemark>()
.SetResourceId(x => x.RemarkId)
.OnSuccessAccepted("remarks/{0}")
.DispatchAsync());
Put("{remarkId}/resolve", async args => await For<ResolveRemark>()
.OnSuccessAccepted($"remarks/{args.remarkId}")
.DispatchAsync());
Delete("{remarkId}", async args => await For<DeleteRemark>()
.OnSuccessAccepted(string.Empty)
.DispatchAsync());
}
}
}
|
using System.Linq;
using Coolector.Api.Commands;
using Coolector.Api.Queries;
using Coolector.Api.Storages;
using Coolector.Api.Validation;
using Coolector.Common.Commands.Remarks;
using Coolector.Dto.Remarks;
namespace Coolector.Api.Modules
{
public class RemarkModule : ModuleBase
{
public RemarkModule(ICommandDispatcher commandDispatcher,
IRemarkStorage remarkStorage,
IValidatorResolver validatorResolver)
: base(commandDispatcher, validatorResolver, modulePath: "remarks")
{
Get("", async args => await FetchCollection<BrowseRemarks, RemarkDto>
(async x => await remarkStorage.BrowseAsync(x))
.MapTo(x => new BasicRemarkDto
{
Id = x.Id,
Author = x.Author.Name,
Category = x.Category.Name,
Location = x.Location,
SmallPhotoUrl = x.Photos.FirstOrDefault(p => p.Size == "small")?.Url,
Description = x.Description,
CreatedAt = x.CreatedAt,
Resolved = x.Resolved
}).HandleAsync());
Get("categories", async args => await FetchCollection<BrowseRemarkCategories, RemarkCategoryDto>
(async x => await remarkStorage.BrowseCategoriesAsync(x)).HandleAsync());
Get("{id}", async args => await Fetch<GetRemark, RemarkDto>
(async x => await remarkStorage.GetAsync(x.Id)).HandleAsync());
Post("", async args => await For<CreateRemark>()
.SetResourceId(x => x.RemarkId)
.OnSuccessAccepted("remarks/{0}")
.DispatchAsync());
Put("{remarkId}/resolve", async args => await For<ResolveRemark>()
.OnSuccessAccepted($"remarks/{args.remarkId}")
.DispatchAsync());
Delete("{remarkId}", async args => await For<DeleteRemark>().DispatchAsync());
}
}
}
|
mit
|
C#
|
4f0a239e4e55664f6d566a98d177284940412ef9
|
Fix ComponentManager.Set not returning Option<T>
|
copygirl/EntitySystem
|
src/EntitySystem/ComponentManager.cs
|
src/EntitySystem/ComponentManager.cs
|
using System;
using System.Collections.Generic;
using System.Reflection;
using EntitySystem.Collections;
using EntitySystem.Storage;
using EntitySystem.Utility;
namespace EntitySystem
{
public class ComponentManager
{
readonly TypedCollection<object> _typeHandlers = new TypedCollection<object>();
readonly GenericComponentMap _defaultMap = new GenericComponentMap();
public EntityManager Entities { get; }
public event Action<Entity, IComponent> Added;
public event Action<Entity, IComponent> Removed;
internal ComponentManager(EntityManager entities)
{
Entities = entities;
Entities.Removed += _defaultMap.RemoveAll; // This might be slow..?
}
public ComponentsOfType<T> OfType<T>() where T : IComponent =>
_typeHandlers.GetOrAdd<ComponentsOfType<T>>(() => {
var type = typeof(T).GetTypeInfo();
if (type.IsInterface || type.IsAbstract)
throw new InvalidOperationException(
$"{ typeof(T) } is not a concrete component type");
return new ComponentsOfType<T>(this);
});
public Option<T> Get<T>(Entity entity) where T : IComponent
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
return _defaultMap.Get<T>(entity);
}
public Option<T> Set<T>(Entity entity, Option<T> valueOption) where T : IComponent
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
var previousOption = _defaultMap.Set<T>(entity, valueOption);
T value; var hasValue = valueOption.TryGet(out value);
T previous; var hasPrevious = previousOption.TryGet(out previous);
if (hasValue) {
if (!hasPrevious) {
OfType<T>().RaiseAdded(entity, value);
Added?.Invoke(entity, value);
}
} else if (hasPrevious) {
OfType<T>().RaiseRemoved(entity, previous);
Removed?.Invoke(entity, previous);
}
return previousOption;
}
public IEnumerable<IComponent> GetAll(Entity entity)
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
return _defaultMap.GetAll(entity);
}
public class ComponentsOfType<T> where T : IComponent
{
readonly ComponentManager _manager;
public event Action<Entity, T> Added;
public event Action<Entity, T> Removed;
// Add Changed event? It's possible. Unsure if needed.
// Depends on how large the overhead for it would be.
// Can be overridden by using a custom storage handler in the future.
public IEnumerable<Tuple<Entity, T>> Entries =>
_manager._defaultMap.Entries<T>();
internal ComponentsOfType(ComponentManager manager) { _manager = manager; }
internal void RaiseAdded(Entity entity, T component) => Added?.Invoke(entity, component);
internal void RaiseRemoved(Entity entity, T component) => Removed?.Invoke(entity, component);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using EntitySystem.Collections;
using EntitySystem.Storage;
using EntitySystem.Utility;
namespace EntitySystem
{
public class ComponentManager
{
readonly TypedCollection<object> _typeHandlers = new TypedCollection<object>();
readonly GenericComponentMap _defaultMap = new GenericComponentMap();
public EntityManager Entities { get; }
public event Action<Entity, IComponent> Added;
public event Action<Entity, IComponent> Removed;
internal ComponentManager(EntityManager entities)
{
Entities = entities;
Entities.Removed += _defaultMap.RemoveAll; // This might be slow..?
}
public ComponentsOfType<T> OfType<T>() where T : IComponent =>
_typeHandlers.GetOrAdd<ComponentsOfType<T>>(() => {
var type = typeof(T).GetTypeInfo();
if (type.IsInterface || type.IsAbstract)
throw new InvalidOperationException(
$"{ typeof(T) } is not a concrete component type");
return new ComponentsOfType<T>(this);
});
public Option<T> Get<T>(Entity entity) where T : IComponent
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
return _defaultMap.Get<T>(entity);
}
public Option<T> Set<T>(Entity entity, Option<T> valueOption) where T : IComponent
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
T value;
var hasValue = valueOption.TryGet(out value);
T previous;
var hasPrevious = _defaultMap.Set<T>(entity, valueOption).TryGet(out previous);
if (hasValue) {
if (!hasPrevious) {
OfType<T>().RaiseAdded(entity, value);
Added?.Invoke(entity, value);
}
} else if (hasPrevious) {
OfType<T>().RaiseRemoved(entity, previous);
Removed?.Invoke(entity, previous);
}
return previous;
}
public IEnumerable<IComponent> GetAll(Entity entity)
{
if (!Entities.Has(entity)) throw new EntityNonExistantException(Entities, entity);
return _defaultMap.GetAll(entity);
}
public class ComponentsOfType<T> where T : IComponent
{
readonly ComponentManager _manager;
public event Action<Entity, T> Added;
public event Action<Entity, T> Removed;
// Add Changed event? It's possible. Unsure if needed.
// Depends on how large the overhead for it would be.
// Can be overridden by using a custom storage handler in the future.
public IEnumerable<Tuple<Entity, T>> Entries =>
_manager._defaultMap.Entries<T>();
internal ComponentsOfType(ComponentManager manager) { _manager = manager; }
internal void RaiseAdded(Entity entity, T component) => Added?.Invoke(entity, component);
internal void RaiseRemoved(Entity entity, T component) => Removed?.Invoke(entity, component);
}
}
}
|
mit
|
C#
|
ac186a20c2d69f0d8c1ec69bbfaa6c5a79e4ddac
|
Enable custom layout by default
|
chrisntr/Xamarin-Glass-QR-Scanner,irfanah/Xamarin-Glass-QR-Scanner
|
QRScanExample/MainActivity.cs
|
QRScanExample/MainActivity.cs
|
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Glass.App;
using Android.Media;
using Android.Glass.Media;
using Android.Views.Animations;
namespace QRScanExample
{
[Activity (Label = "Scan Xamarin", Icon = "@drawable/Icon", MainLauncher = true, Enabled = true)]
[IntentFilter (new String[]{ "com.google.android.glass.action.VOICE_TRIGGER" })]
[MetaData ("com.google.android.glass.VoiceTrigger", Resource = "@xml/voicetriggerstart")]
public class MainActivity : Activity
{
// The project requires the Google Glass Component from
// https://components.xamarin.com/view/googleglass
// so make sure you add that in to compile succesfully.
protected override async void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Window.AddFlags (WindowManagerFlags.KeepScreenOn);
var scanner = new ZXing.Mobile.MobileBarcodeScanner(this);
scanner.UseCustomOverlay = true;
scanner.CustomOverlay = LayoutInflater.Inflate(Resource.Layout.QRScan, null);;
var result = await scanner.Scan();
AudioManager audio = (AudioManager) GetSystemService(Context.AudioService);
audio.PlaySoundEffect((SoundEffect)Sounds.Success);
Window.ClearFlags (WindowManagerFlags.KeepScreenOn);
if (result != null) {
Console.WriteLine ("Scanned Barcode: " + result.Text);
var card2 = new Card (this);
card2.SetText (result.Text);
card2.SetFootnote ("Just scanned!");
SetContentView (card2.ToView());
}
}
}
}
|
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Glass.App;
using Android.Media;
using Android.Glass.Media;
using Android.Views.Animations;
namespace QRScanExample
{
[Activity (Label = "Scan Xamarin", Icon = "@drawable/Icon", MainLauncher = true, Enabled = true)]
[IntentFilter (new String[]{ "com.google.android.glass.action.VOICE_TRIGGER" })]
[MetaData ("com.google.android.glass.VoiceTrigger", Resource = "@xml/voicetriggerstart")]
public class MainActivity : Activity
{
// The project requires the Google Glass Component from
// https://components.xamarin.com/view/googleglass
// so make sure you add that in to compile succesfully.
protected override async void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Window.AddFlags (WindowManagerFlags.KeepScreenOn);
var scanner = new ZXing.Mobile.MobileBarcodeScanner(this);
// scanner.UseCustomOverlay = true;
// scanner.CustomOverlay = LayoutInflater.Inflate(Resource.Layout.QRScan, null);;
var result = await scanner.Scan();
AudioManager audio = (AudioManager) GetSystemService(Context.AudioService);
audio.PlaySoundEffect((SoundEffect)Sounds.Success);
Window.ClearFlags (WindowManagerFlags.KeepScreenOn);
if (result != null) {
Console.WriteLine ("Scanned Barcode: " + result.Text);
var card2 = new Card (this);
card2.SetText (result.Text);
card2.SetFootnote ("Just scanned!");
SetContentView (card2.ToView());
}
}
}
}
|
apache-2.0
|
C#
|
370b31f772ab4e10ce5ed44d4206d01e04cc93ba
|
Update Activities/ManagePersonsPermissionCheckerTask.cs
|
Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module
|
Activities/ManagePersonsPermissionCheckerTask.cs
|
Activities/ManagePersonsPermissionCheckerTask.cs
|
using Lombiq.TrainingDemo.Permissions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Localization;
using OrchardCore.Users.Models;
using OrchardCore.Users.Services;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Lombiq.TrainingDemo.Activities;
// A simple workflow task that accepts a username as a TextField input and checks whether the user has ManagePersons Permission or not.
public class ManagePersonsPermissionCheckerTask : TaskActivity
{
private readonly IAuthorizationService _authorizationService;
private readonly IUserService _userService;
private readonly IWorkflowExpressionEvaluator _expressionEvaluator;
private readonly IStringLocalizer S;
public ManagePersonsPermissionCheckerTask(
IAuthorizationService authorizationService,
IUserService userService,
IWorkflowExpressionEvaluator expressionEvaluator,
IStringLocalizer<ManagePersonsPermissionCheckerTask> localizer)
{
_authorizationService = authorizationService;
_userService = userService;
_expressionEvaluator = expressionEvaluator;
S = localizer;
}
// The technical name of the activity. Activities in a workflow definition reference this name.
public override string Name => nameof(ManagePersonsPermissionCheckerTask);
// The displayed name of the activity, so it can use localization.
public override LocalizedString DisplayText => S["Manage Persons Permission Checker Task"];
// The category to which this activity belongs. The activity picker groups activities by this category.
public override LocalizedString Category => S["User"];
// The username to evaluate for ManagePersons permission.
public WorkflowExpression<string> UserName
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
// Returns the possible outcomes of this activity.
public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) =>
Outcomes(S["HasPermission"], S["NoPermission"]);
// This is the heart of the activity and actually performs the work to be done.
public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
var userName = await _expressionEvaluator.EvaluateAsync(UserName, workflowContext, encoder: null);
var user = (User)await _userService.GetUserAsync(userName);
if (user != null)
{
var userClaim = await _userService.CreatePrincipalAsync(user);
if (await _authorizationService.AuthorizeAsync(userClaim, PersonPermissions.ManagePersons))
{
return Outcomes("HasPermission");
}
}
return Outcomes("NoPermission");
}
}
// NEXT STATION: ViewModels/ManagePersonsPermissionCheckerTaskViewModel.cs
|
using Lombiq.TrainingDemo.Permissions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Localization;
using OrchardCore.Users.Models;
using OrchardCore.Users.Services;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Lombiq.TrainingDemo.Activities;
// A simple workflow task that accepts a username as a TextField input and checks whether the user has ManagePersons Permission or not.
public class ManagePersonsPermissionCheckerTask : TaskActivity
{
private readonly IAuthorizationService _authorizationService;
private readonly IUserService _userService;
private readonly IWorkflowExpressionEvaluator _expressionEvaluator;
private readonly IStringLocalizer S;
public ManagePersonsPermissionCheckerTask(
IAuthorizationService authorizationService,
IUserService userService,
IWorkflowExpressionEvaluator expressionEvaluator,
IStringLocalizer<ManagePersonsPermissionCheckerTask> localizer)
{
_authorizationService = authorizationService;
_userService = userService;
_expressionEvaluator = expressionEvaluator;
S = localizer;
}
// The technical name of the activity. Activities on a workflow definition reference this name.
public override string Name => nameof(ManagePersonsPermissionCheckerTask);
// The displayed name of the activity, so it can use localization.
public override LocalizedString DisplayText => S["Manage Persons Permission Checker Task"];
// The category to which this activity belongs. The activity picker groups activities by this category.
public override LocalizedString Category => S["User"];
// The username to evaluate for ManagePersons permission.
public WorkflowExpression<string> UserName
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
// Returns the possible outcomes of this activity.
public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) =>
Outcomes(S["HasPermission"], S["NoPermission"]);
// This is the heart of the activity and actually performs the work to be done.
public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
var userName = await _expressionEvaluator.EvaluateAsync(UserName, workflowContext, encoder: null);
var user = (User)await _userService.GetUserAsync(userName);
if (user != null)
{
var userClaim = await _userService.CreatePrincipalAsync(user);
if (await _authorizationService.AuthorizeAsync(userClaim, PersonPermissions.ManagePersons))
{
return Outcomes("HasPermission");
}
}
return Outcomes("NoPermission");
}
}
// NEXT STATION: ViewModels/ManagePersonsPermissionCheckerTaskViewModel.cs
|
bsd-3-clause
|
C#
|
919a4dd7110c37e160d88b23bec3f731674f916e
|
Add DisplayGraphics
|
MasterOfSomeTrades/CommentEverythingDotNetControlsExtended
|
CEControls/Display/DisplayGraphics.cs
|
CEControls/Display/DisplayGraphics.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CEControls.Display {
public class DisplayGraphics {
private Control _canvas;
private List<DisplayGraphic> _listDisplayGraphic = new List<DisplayGraphic>();
private DisplayGraphics() {
// --- Must call constructor that defines a Control as the canvas
}
public DisplayGraphics(Control canvas) {
_canvas = canvas;
}
public void Add(DisplayGraphic graphic) {
_listDisplayGraphic.Add(graphic);
graphic.Render(_canvas);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CEControls.Display {
public class DisplayGraphics {
/*private Control _canvas;
private DisplayGraphics() {
// --- Must call constructor that defines a Control as the canvas
}
public DisplayGraphics(Control canvas) {
_canvas = canvas;
}
public void Add(DisplayGraphic graphic) {
_canvas.Controls.Add(graphic);
graphic.Render();
}*/
}
}
|
mit
|
C#
|
7b8382c349e022f4fb8c5170b1dbb4237d1de83e
|
remove kestrel
|
smbc-digital/iag-contentapi
|
src/StockportContentApi/Program.cs
|
src/StockportContentApi/Program.cs
|
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace StockportContentApi
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateWebHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls("http://0.0.0.0:5001")
.UseIISIntegration()
.UseStartup<Startup>()
.ConfigureAppConfiguration((hostContext, config) =>
{
config.Sources.Clear();
config.SetBasePath(Directory.GetCurrentDirectory() + "/app-config");
config
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json");
var tempConfig = config.Build();
config.AddJsonFile(
$"{tempConfig["secrets-location"]}/appsettings.{hostContext.HostingEnvironment.EnvironmentName}.secrets.json");
});
});
}
}
|
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace StockportContentApi
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateWebHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls("http://0.0.0.0:5001")
.UseIISIntegration()
.UseStartup<Startup>()
.ConfigureKestrel((context, options) =>
{
// Set properties and call methods on options
})
.ConfigureAppConfiguration((hostContext, config) =>
{
config.Sources.Clear();
config.SetBasePath(Directory.GetCurrentDirectory() + "/app-config");
config
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json");
var tempConfig = config.Build();
config.AddJsonFile(
$"{tempConfig["secrets-location"]}/appsettings.{hostContext.HostingEnvironment.EnvironmentName}.secrets.json");
});
});
}
}
|
mit
|
C#
|
4d28d0ac5f9188ca27321d0c62a2611e31d75d2b
|
increase version
|
tinohager/Nager.Date,tinohager/Nager.Date,brizuelal/Nager.Date,brizuelal/Nager.Date,tinohager/Nager.Date
|
Nager.Date/Properties/AssemblyInfo.cs
|
Nager.Date/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Nager.Date")]
[assembly: AssemblyDescription("Calculate Public Holiday for DE and AT for any Year")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("nager.at")]
[assembly: AssemblyProduct("Nager.Date")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("13bd121f-1af4-429b-a596-1247d3f3f090")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.5")]
[assembly: AssemblyFileVersion("1.0.0.5")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Nager.Date")]
[assembly: AssemblyDescription("Calculate Public Holiday for DE and AT for any Year")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("nager.at")]
[assembly: AssemblyProduct("Nager.Date")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("13bd121f-1af4-429b-a596-1247d3f3f090")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.4")]
[assembly: AssemblyFileVersion("1.0.0.4")]
|
mit
|
C#
|
ba667f2ceb0c823e510bc49d4c4f41252a257771
|
Fix test on build server.
|
mthamil/PlantUMLStudio,mthamil/PlantUMLStudio
|
Tests.Unit/PlantUmlStudio/Configuration/SpecialFolderTokenReplacerTests.cs
|
Tests.Unit/PlantUmlStudio/Configuration/SpecialFolderTokenReplacerTests.cs
|
using System;
using PlantUmlStudio.Configuration;
using Xunit;
namespace Tests.Unit.PlantUmlStudio.Configuration
{
public class SpecialFolderTokenReplacerTests
{
[Theory]
[InlineData(@"<ProgramFilesX86>\test\path", @"C:\Program Files (x86)\test\path")]
[InlineData(@"<Windows>\test\path", @"C:\Windows\test\path")]
public void Test_Parse_With_System_Special_Folders(string input, string expected)
{
// Act.
var actual = _underTest.Parse(input);
// Assert.
Assert.Equal(expected, actual, StringComparer.OrdinalIgnoreCase);
}
[Theory]
[InlineData(@"<MyDocuments>\test\path", Environment.SpecialFolder.MyDocuments)]
[InlineData(@"<UserProfile>\test\path", Environment.SpecialFolder.UserProfile)]
public void Test_Parse_With_User_Special_Folders(string input, Environment.SpecialFolder expectedFolder)
{
// Act.
var actual = _underTest.Parse(input);
// Assert.
Assert.Equal($@"{Environment.GetFolderPath(expectedFolder)}\test\path", actual);
}
[Theory]
[InlineData(@"C:\Program Files\test\path", @"C:\Program Files\test\path")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\<WeirdFolder>\stuff", @"C:\<WeirdFolder>\stuff")]
[InlineData(@"C:\WeirdFolder>\stuff", @"C:\WeirdFolder>\stuff")]
[InlineData(@"C:\<WeirdFolder\stuff", @"C:\<WeirdFolder\stuff")]
[InlineData(@"<>", @"<>")]
[InlineData(@"", @"")]
public void Test_Parse_With_No_Special_Folders(string input, string expected)
{
// Act.
var actual = _underTest.Parse(input);
// Assert.
Assert.Equal(expected, actual);
}
private readonly SpecialFolderTokenReplacer _underTest = new SpecialFolderTokenReplacer();
}
}
|
using System;
using PlantUmlStudio.Configuration;
using Xunit;
namespace Tests.Unit.PlantUmlStudio.Configuration
{
public class SpecialFolderTokenReplacerTests
{
[Theory]
[InlineData(@"<ProgramFilesX86>\test\path", @"C:\Program Files (x86)\test\path")]
[InlineData(@"<Windows>\test\path", @"C:\Windows\test\path")]
public void Test_Parse_With_System_Special_Folders(string input, string expected)
{
// Act.
var actual = _underTest.Parse(input);
// Assert.
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(@"<MyDocuments>\test\path", Environment.SpecialFolder.MyDocuments)]
[InlineData(@"<UserProfile>\test\path", Environment.SpecialFolder.UserProfile)]
public void Test_Parse_With_User_Special_Folders(string input, Environment.SpecialFolder expectedFolder)
{
// Act.
var actual = _underTest.Parse(input);
// Assert.
Assert.Equal($@"{Environment.GetFolderPath(expectedFolder)}\test\path", actual);
}
[Theory]
[InlineData(@"C:\Program Files\test\path", @"C:\Program Files\test\path")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\<WeirdFolder>\stuff", @"C:\<WeirdFolder>\stuff")]
[InlineData(@"C:\WeirdFolder>\stuff", @"C:\WeirdFolder>\stuff")]
[InlineData(@"C:\<WeirdFolder\stuff", @"C:\<WeirdFolder\stuff")]
[InlineData(@"<>", @"<>")]
[InlineData(@"", @"")]
public void Test_Parse_With_No_Special_Folders(string input, string expected)
{
// Act.
var actual = _underTest.Parse(input);
// Assert.
Assert.Equal(expected, actual);
}
private readonly SpecialFolderTokenReplacer _underTest = new SpecialFolderTokenReplacer();
}
}
|
apache-2.0
|
C#
|
ddafbec518002fef82e383ab5555968201719072
|
Attach "Invite" button to "Pending" users
|
JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,Generic-Voting-Application/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,tpkelly/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,stevenhillcox/voting-application
|
VotingApplication/VotingApplication.Web/Views/Routes/ManageInvitees.cshtml
|
VotingApplication/VotingApplication.Web/Views/Routes/ManageInvitees.cshtml
|
<div ng-app="GVA.Creation" ng-controller="ManageInviteesController">
<div class="centered">
<h2>Poll Invitees</h2>
<h4>Email to Invite</h4>
<input id="new-invitee" name="new-invitee" ng-model="inviteString" ng-change="emailUpdated()" ng-trim="false" />
<span class="glyphicon glyphicon-plus" ng-click="addInvitee(inviteString);"></span>
<h4>Pending</h4>
<p ng-if="pendingUsers.length === 0">No pending users</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="invitee in pendingUsers">
<span class="invitee-pill-text">{{invitee.Name || invitee.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitee(invitee)" aria-hidden="true"></span>
</div>
</div>
<div class="manage-section" ng-if="pendingUsers.length > 0">
<button class="manage-btn" ng-click="addInvitee(inviteString); sendInvitations();">Invite</button>
</div>
<h4>Invited</h4>
<p ng-if="invitedUsers.length === 0">You haven't invited anybody yet</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="invitee in invitedUsers">
<span class="invitee-pill-text">{{invitee.Name || invitee.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitee(invitee)" aria-hidden="true"></span>
</div>
</div>
<div class="manage-section">
<button class="manage-btn" ng-click="return()">Done</button>
</div>
</div>
</div>
|
<div ng-app="GVA.Creation" ng-controller="ManageInviteesController">
<div class="centered">
<h2>Poll Invitees</h2>
<h4>Email to Invite</h4>
<input id="new-invitee" name="new-invitee" ng-model="inviteString" ng-change="emailUpdated()" ng-trim="false" />
<span class="glyphicon glyphicon-plus" ng-click="addInvitee(inviteString);"></span>
<h4>Pending</h4>
<p ng-if="pendingUsers.length === 0">No pending users</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="invitee in pendingUsers">
<span class="invitee-pill-text">{{invitee.Name || invitee.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitee(invitee)" aria-hidden="true"></span>
</div>
</div>
<h4>Invited</h4>
<p ng-if="invitedUsers.length === 0">You haven't invited anybody yet</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="invitee in invitedUsers">
<span class="invitee-pill-text">{{invitee.Name || invitee.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitee(invitee)" aria-hidden="true"></span>
</div>
</div>
<div class="manage-section">
<button class="manage-btn" ng-click="addInvitee(inviteString); sendInvitations();">Invite</button>
<button class="manage-btn" ng-click="return()">Done</button>
</div>
</div>
</div>
|
apache-2.0
|
C#
|
c1cb3f85666e20acc4340f524d619dc9ad10e6cf
|
update vehicle dto [#135977713]
|
revaturelabs/revashare-svc-webapi
|
revashare-svc-webapi/revashare-svc-webapi.Logic/Models/VehicleDTO.cs
|
revashare-svc-webapi/revashare-svc-webapi.Logic/Models/VehicleDTO.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace revashare_svc_webapi.Logic.Models {
public class VehicleDTO {
public int Id { get; set; }
public int OwnerId { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string LicensePlate { get; set; }
public string Color { get; set; }
public int Capacity { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace revashare_svc_webapi.Logic.Models {
public class VehicleDTO {
}
}
|
mit
|
C#
|
2404cdc5f03ca3bb6551c5151dbd3daace72bfea
|
Update assembly version.
|
Si13n7/CoD2MPWindowed
|
src/Properties/AssemblyInfo.cs
|
src/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Call of Duty 2 Multiplayer (Windowed)")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Si13n7 Dev. ®")]
[assembly: AssemblyProduct("CoD2MP_w")]
[assembly: AssemblyCopyright("Copyright © Si13n7 Dev. ® 2019")]
[assembly: AssemblyTrademark("Si13n7 Dev. ®")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("79ead147-a020-41f5-9a96-6fc5e3e4f8a3")]
[assembly: AssemblyVersion("1.3.0.2")]
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Call of Duty 2 Multiplayer (Windowed)")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Si13n7 Dev. ®")]
[assembly: AssemblyProduct("CoD2MP_w")]
[assembly: AssemblyCopyright("Copyright © Si13n7 Dev. ® 2019")]
[assembly: AssemblyTrademark("Si13n7 Dev. ®")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("79ead147-a020-41f5-9a96-6fc5e3e4f8a3")]
[assembly: AssemblyVersion("1.3.0.1")]
|
mit
|
C#
|
97db2090b81ad45459334d2c628d06882e4803d5
|
Debug Boards
|
avisuj/myeventurl,avisuj/myeventurl,avisuj/myeventurl
|
MyEventURL/Views/Boards/Delete.cshtml
|
MyEventURL/Views/Boards/Delete.cshtml
|
@model MyEventURL.Board
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Board</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Created)
</dt>
<dd>
@Html.DisplayFor(model => model.Created)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Events)
</dt>
<dd>
@Html.DisplayFor(model => model.Events)
</dd>
<dt>
@Html.DisplayNameFor(model => model.View)
</dt>
<dd>
@Html.DisplayFor(model => model.View)
</dd>
</dl>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Index")
</div>
}
</div>
|
@model MyEventURL.Models.Board
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Board</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Created)
</dt>
<dd>
@Html.DisplayFor(model => model.Created)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Events)
</dt>
<dd>
@Html.DisplayFor(model => model.Events)
</dd>
<dt>
@Html.DisplayNameFor(model => model.View)
</dt>
<dd>
@Html.DisplayFor(model => model.View)
</dd>
</dl>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Index")
</div>
}
</div>
|
mit
|
C#
|
fe6789c8add14781e67f140f463d12a6d0cf30ff
|
Update program.cs
|
UnstableMutex/ANTFECControl
|
program.cs
|
program.cs
|
using ANT_Managed_Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static byte[] networkKey = { 0xB9, 0xA5, 0x21, 0xFB, 0xBD, 0x72, 0xC3, 0x45 };
// static byte[] networkKey = { 0xE8, 0xE4, 0x21, 0x3B, 0x55, 0x7A, 0x67, 0xC1 };
// static byte[] networkKey = { 0xA8, 0xA4, 0x23, 0xB9, 0xF5, 0x5E, 0x63, 0xC1 };
static void Main(string[] args)
{
Console.WriteLine("Connecting to HRM, PRESS ENTER TO TERMINATE PROGRAM");
var device = new ANT_Device();
ANT_Common.enableDebugLogs();
var ressnk = device.setNetworkKey(0, networkKey, 500);
var caps = device.getDeviceCapabilities();
ANT_Channel channel0 = device.getChannel(0);
var acres = channel0.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, 0, 500);
var schres = channel0.setChannelID(0, false, 120, 0, 500);
var schperres = channel0.setChannelPeriod((ushort)8070, 500);
channel0.setChannelSearchTimeout(15);
var scfq = channel0.setChannelFreq(57, 500);
var sps = channel0.setProximitySearch(3, 500); //Is set to limit the search range
channel0.channelResponse += Channel_channelResponse;
var oc = channel0.openChannel(500);
Console.ReadKey();
}
private static void Channel_channelResponse(ANT_Response response)
{
//var rid = response.getMessageID();
//Console.WriteLine(rid);
try
{
var m = response.messageContents;
string s = "";
var d = response.timeReceived;
var hr = response.messageContents[8].ToString();
Console.WriteLine(hr);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("errror");
// throw;
}
}
}
}
|
using ANT_Managed_Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static byte[] networkKey = { 0xB9, 0xA5, 0x21, 0xFB, 0xBD, 0x72, 0xC3, 0x45 };
// static byte[] networkKey = { 0xE8, 0xE4, 0x21, 0x3B, 0x55, 0x7A, 0x67, 0xC1 };
// static byte[] networkKey = { 0xA8, 0xA4, 0x23, 0xB9, 0xF5, 0x5E, 0x63, 0xC1 };
static void Main(string[] args)
{
Console.WriteLine("Connecting to HRM, PRESS ENTER TO TERMINATE PROGRAM");
var device = new ANT_Device();
ANT_Common.enableDebugLogs();
var ressnk = device.setNetworkKey(0, networkKey, 500);
var caps = device.getDeviceCapabilities();
ANT_Channel channel0 = device.getChannel(0);
var acres = channel0.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, 0, 500);
var schres = channel0.setChannelID(0, false, 120, 0, 500);
var schperres = channel0.setChannelPeriod((ushort)8070, 500);
channel0.setChannelSearchTimeout(15);
var scfq = channel0.setChannelFreq(57, 500);
var sps = channel0.setProximitySearch(3, 500); //Is set to limit the search range
channel0.channelResponse += Channel_channelResponse;
var oc = channel0.openChannel(500);
Console.ReadKey();
}
private static void Channel_channelResponse(ANT_Response response)
{
//var rid = response.getMessageID();
//Console.WriteLine(rid);
var m = response.messageContents;
string s = "";
//var ev = response.getChannelEventCode();
//Console.WriteLine(ev);
var d = response.timeReceived;
foreach (var item in m)
{
s += item.ToString() + " ";
}
Console.WriteLine(s);
}
}
}
|
unlicense
|
C#
|
550018dfadcf3b7c47a44b084834e7c560ffaad8
|
add require to field Event
|
dpaluchSii/TODOMigrations,dpaluchSii/TODOMigrations,dpaluchSii/TODOMigrations
|
TODOMigrations/Models/Task.cs
|
TODOMigrations/Models/Task.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TODOMigrations.Models
{
public class Task
{
public int TaskID { get; set; }
[Required(ErrorMessage = "Event is required.")]
public string Event { get; set; }
//public string Eventt { get; set; }
public string Where { get; set; }
public DateTime When { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TODOMigrations.Models
{
public class Task
{
public int TaskID { get; set; }
public string Event { get; set; }
public string Where { get; set; }
public DateTime When { get; set; }
//
}
}
|
apache-2.0
|
C#
|
36891e1c5779491f74013a5e57839a27b104887d
|
Update CrlController.cs
|
nomailme/TestAuthority
|
source/TestAuthority.Host/Controllers/CrlController.cs
|
source/TestAuthority.Host/Controllers/CrlController.cs
|
using System.Net.Mime;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using TestAuthority.Application.CrlBuilders;
using TestAuthority.Domain.CertificateConverters;
using TestAuthority.Domain.Services;
namespace TestAuthority.Host.Controllers;
/// <summary>
/// Provides functionality to work with Crl.
/// </summary>
[Route("api/crl")]
public class CrlController: Controller
{
private readonly IMediator mediator;
private readonly ISignerProvider signerProvider;
private readonly ICertificateConverter converter;
/// <summary>
/// Ctor.
/// </summary>
/// <param name="mediator"><see cref="IMediator"/>.</param>
/// <param name="signerProvider"><see cref="ISignerProvider"/>.</param>
/// <param name="converter"><see cref="ICertificateConverter"/>.</param>
public CrlController(IMediator mediator, ISignerProvider signerProvider, ICertificateConverter converter)
{
this.mediator = mediator;
this.signerProvider = signerProvider;
this.converter = converter;
}
/// <summary>
/// Issue a Certificate Revocation List in PEM.
/// </summary>
[HttpGet]
public async Task<FileContentResult> Get()
{
var signer = signerProvider.GetCertificateSignerInfo();
var crl = await mediator.Send(new CrlBuilderRequest(signer));
var result = converter.ConvertToPem(crl);
return File(result, MediaTypeNames.Application.Octet, "root.crl");
}
/// <summary>
/// Issue a Certificate Revocation List in DER.
/// </summary>
[HttpGet("root.crl")]
public async Task<FileResult> GetCrl()
{
var signer = signerProvider.GetCertificateSignerInfo();
var crlModel = await mediator.Send(new CrlBuilderRequest(signer));
return File(crlModel.Crl.GetEncoded(),"application/pkix-crl" , "root.crl");
}
}
|
using System.Net.Mime;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using TestAuthority.Application.CrlBuilders;
using TestAuthority.Domain.CertificateConverters;
using TestAuthority.Domain.Services;
namespace TestAuthority.Host.Controllers;
/// <summary>
/// Provides functionality to work with Crl.
/// </summary>
[Route("api/crl")]
public class CrlController: Controller
{
private readonly IMediator mediator;
private readonly ISignerProvider signerProvider;
private readonly ICertificateConverter converter;
/// <summary>
/// Ctor.
/// </summary>
/// <param name="mediator"><see cref="IMediator"/>.</param>
/// <param name="signerProvider"><see cref="ISignerProvider"/>.</param>
/// <param name="converter"><see cref="ICertificateConverter"/>.</param>
public CrlController(IMediator mediator, ISignerProvider signerProvider, ICertificateConverter converter)
{
this.mediator = mediator;
this.signerProvider = signerProvider;
this.converter = converter;
}
/// <summary>
/// Issue a Certificate Revocation List.
/// </summary>
[HttpGet]
public async Task<FileContentResult> Get()
{
var signer = signerProvider.GetCertificateSignerInfo();
var crl = await mediator.Send(new CrlBuilderRequest(signer));
return File(crl.Crl.GetEncoded(), "application/pkix-crl", "root.crl");
}
}
|
mit
|
C#
|
559c827dbf597b5ea6cf4d914b051b729d580f7d
|
Include original WebException when throwing new ApplicationException
|
jcvandan/XeroAPI.Net,TDaphneB/XeroAPI.Net,XeroAPI/XeroAPI.Net,MatthewSteeples/XeroAPI.Net
|
source/XeroApi/OAuth/Consumer/ConsumerRequestRunner.cs
|
source/XeroApi/OAuth/Consumer/ConsumerRequestRunner.cs
|
using System;
using System.Net;
namespace DevDefined.OAuth.Consumer
{
public interface IConsumerRequestRunner
{
IConsumerResponse Run(IConsumerRequest consumerRequest);
}
public class DefaultConsumerRequestRunner : IConsumerRequestRunner
{
public IConsumerResponse Run(IConsumerRequest consumerRequest)
{
HttpWebRequest webRequest = consumerRequest.ToWebRequest();
IConsumerResponse consumerResponse = null;
try
{
consumerResponse = new ConsumerResponse(webRequest.GetResponse() as HttpWebResponse);
}
catch (WebException webEx)
{
// I *think* it's safe to assume that the response will always be a HttpWebResponse...
HttpWebResponse httpWebResponse = (HttpWebResponse)(webEx.Response);
if (httpWebResponse == null)
{
throw new ApplicationException("An HttpWebResponse could not be obtained from the WebException. Status was " + webEx.Status, webEx);
}
consumerResponse = new ConsumerResponse(httpWebResponse, webEx);
}
return consumerResponse;
}
}
}
|
using System;
using System.Net;
namespace DevDefined.OAuth.Consumer
{
public interface IConsumerRequestRunner
{
IConsumerResponse Run(IConsumerRequest consumerRequest);
}
public class DefaultConsumerRequestRunner : IConsumerRequestRunner
{
public IConsumerResponse Run(IConsumerRequest consumerRequest)
{
HttpWebRequest webRequest = consumerRequest.ToWebRequest();
IConsumerResponse consumerResponse = null;
try
{
consumerResponse = new ConsumerResponse(webRequest.GetResponse() as HttpWebResponse);
}
catch (WebException webEx)
{
// I *think* it's safe to assume that the response will always be a HttpWebResponse...
HttpWebResponse httpWebResponse = (HttpWebResponse)(webEx.Response);
if (httpWebResponse == null)
{
throw new ApplicationException("An HttpWebResponse could not be obtained from the WebException. Status was " + webEx.Status.ToString());
}
consumerResponse = new ConsumerResponse(httpWebResponse, webEx);
}
return consumerResponse;
}
}
}
|
mit
|
C#
|
a894d10872e709edbcbd3c7e8a330f1e9bebb4bd
|
Add proper po formatting
|
pdfforge/translatable
|
TranslationExport/Exporter.cs
|
TranslationExport/Exporter.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Translation;
using TranslationTest;
namespace TranslationExport
{
class Exporter
{
// TODO Hack to actually load assembly
private MainWindowTranslation x = new MainWindowTranslation();
public void DoExport(string outputDirectory)
{
if (!Directory.Exists(outputDirectory))
Directory.CreateDirectory(outputDirectory);
var translatableType = typeof(ITranslatable);
var translatables = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(t => translatableType.IsAssignableFrom(t) && !t.IsAbstract).ToList();
foreach (var translatable in translatables)
{
Export(outputDirectory, translatable);
}
}
private void Export(string outputDirectory, Type translatable)
{
StringBuilder sb = new StringBuilder();
var properties = translatable.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var obj = Activator.CreateInstance(translatable);
foreach (var property in properties)
{
var comment = GetTranslatorcomment(property, obj);
if (!string.IsNullOrEmpty(comment))
sb.AppendLine("#. " + EscpaeString(comment));
var escapedMessage = EscpaeString(property.GetValue(obj).ToString());
sb.AppendLine($"msgid \"{escapedMessage}\"");
sb.AppendLine("msgstr \"\"");
sb.AppendLine();
}
var file = Path.Combine(outputDirectory, translatable.FullName + ".pot");
File.WriteAllText(file, sb.ToString());
}
private string EscpaeString(string str)
{
return str.Replace("\r", "\\r").Replace("\n", "\\n");
}
private string GetTranslatorcomment(PropertyInfo pi, object o)
{
var attributes = pi.GetCustomAttributes(typeof(TranslatorCommentAttribute), false) as TranslatorCommentAttribute[];
if (attributes != null && attributes.Length > 0)
return attributes[0].Value;
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Translation;
using TranslationTest;
namespace TranslationExport
{
class Exporter
{
// TODO Hack to actually load assembly
private MainWindowTranslation x = new MainWindowTranslation();
public void DoExport(string outputDirectory)
{
if (!Directory.Exists(outputDirectory))
Directory.CreateDirectory(outputDirectory);
var translatableType = typeof(ITranslatable);
var translatables = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(t => translatableType.IsAssignableFrom(t) && !t.IsAbstract).ToList();
foreach (var translatable in translatables)
{
Export(outputDirectory, translatable);
}
}
private void Export(string outputDirectory, Type translatable)
{
StringBuilder sb = new StringBuilder();
var properties = translatable.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var obj = Activator.CreateInstance(translatable);
foreach (var property in properties)
{
var comment = GetTranslatorcomment(property, obj);
if (!string.IsNullOrEmpty(comment))
sb.AppendLine("//" + comment);
sb.AppendLine($"{property.GetValue(obj)}");
}
var file = Path.Combine(outputDirectory, translatable.FullName + ".pot");
File.WriteAllText(file, sb.ToString());
}
private string GetTranslatorcomment(PropertyInfo pi, object o)
{
var attributes = pi.GetCustomAttributes(typeof(TranslatorCommentAttribute), false) as TranslatorCommentAttribute[];
if (attributes != null && attributes.Length > 0)
return attributes[0].Value;
return null;
}
}
}
|
mit
|
C#
|
a3fe7d9e377bd01313406c70c33ef39e22bb2226
|
change DelegateValidationRule .ctor()
|
tibel/Caliburn.Light
|
src/Caliburn.Core/Validation/DelegateValidationRule.cs
|
src/Caliburn.Core/Validation/DelegateValidationRule.cs
|
using System;
using System.Globalization;
namespace Caliburn.Light
{
/// <summary>
/// Determines whether or not an object of type <typeparamref name="T"/> satisfies a rule and
/// provides an error if it does not.
/// </summary>
/// <typeparam name="T">The type of the object the rule applies to.</typeparam>
public sealed class DelegateValidationRule<T> : ValidationRule<T>
{
private readonly Func<T, bool> _rule;
/// <summary>
/// Initializes a new instance of the <see cref="DelegateValidationRule<T>"/> class.
/// </summary>
/// <param name="propertyName">The name of the property this instance applies to.</param>
/// <param name="rule">The rule to execute.</param>
/// <param name="errorMessage">The error message if the rules fails.</param>
public DelegateValidationRule(string propertyName, Func<T, bool> rule, string errorMessage)
: base(propertyName, errorMessage)
{
if (rule == null)
throw new ArgumentNullException(nameof(rule));
_rule = rule;
}
/// <summary>
/// Applies the rule to the specified object.
/// </summary>
/// <param name="obj">The object to apply the rule to.</param>
/// <param name="cultureInfo">The culture to use in this rule.</param>
/// <returns>
/// A <see cref="ValidationResult" /> object.
/// </returns>
public override ValidationResult Apply(T obj, CultureInfo cultureInfo)
{
var valid = _rule(obj);
if (valid)
return ValidationResult.Success();
else
return ValidationResult.Failure(ErrorMessage);
}
}
}
|
using System;
using System.Globalization;
namespace Caliburn.Light
{
/// <summary>
/// Determines whether or not an object of type <typeparamref name="T"/> satisfies a rule and
/// provides an error if it does not.
/// </summary>
/// <typeparam name="T">The type of the object the rule applies to.</typeparam>
public sealed class DelegateValidationRule<T> : ValidationRule<T>
{
private readonly Func<T, bool> _rule;
/// <summary>
/// Initializes a new instance of the <see cref="DelegateValidationRule<T>"/> class.
/// </summary>
/// <param name="propertyName">The name of the property this instance applies to.</param>
/// <param name="errorMessage">The error message if the rules fails.</param>
/// <param name="rule">The rule to execute.</param>
public DelegateValidationRule(string propertyName, string errorMessage, Func<T, bool> rule)
: base(propertyName, errorMessage)
{
if (rule == null)
throw new ArgumentNullException(nameof(rule));
_rule = rule;
}
/// <summary>
/// Applies the rule to the specified object.
/// </summary>
/// <param name="obj">The object to apply the rule to.</param>
/// <param name="cultureInfo">The culture to use in this rule.</param>
/// <returns>
/// A <see cref="ValidationResult" /> object.
/// </returns>
public override ValidationResult Apply(T obj, CultureInfo cultureInfo)
{
var valid = _rule(obj);
if (valid)
return ValidationResult.Success();
else
return ValidationResult.Failure(ErrorMessage);
}
}
}
|
mit
|
C#
|
4c74897bfe91f494a325e2a55918d4424bfcdeae
|
Add Curry methods
|
sakapon/KLibrary-Labs
|
CoreLab/Core/Pipeline/FuncHelper.cs
|
CoreLab/Core/Pipeline/FuncHelper.cs
|
using System;
namespace KLibrary.Labs.Pipeline
{
public static class FuncHelper
{
public static Func<T1, T3> Compose<T1, T2, T3>(this Func<T1, T2> f1, Func<T2, T3> f2)
{
return p1 => f2(f1(p1));
}
// カリー化
public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)
{
return p1 => p2 => func(p1, p2);
}
public static Func<T1, Func<T2, T3, TResult>> Curry<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> func)
{
return p1 => (p2, p3) => func(p1, p2, p3);
}
// 非カリー化
public static Func<T1, T2, TResult> Uncurry<T1, T2, TResult>(this Func<T1, Func<T2, TResult>> func)
{
return (p1, p2) => func(p1)(p2);
}
public static Func<T1, T2, T3, TResult> Uncurry<T1, T2, T3, TResult>(this Func<T1, Func<T2, T3, TResult>> func)
{
return (p1, p2, p3) => func(p1)(p2, p3);
}
// 部分適用
public static Func<T2, TResult> Partial<T1, T2, TResult>(this Func<T1, T2, TResult> func, T1 arg1)
{
return func.Curry()(arg1);
}
public static Func<T2, T3, TResult> Partial<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> func, T1 arg1)
{
return func.Curry()(arg1);
}
}
}
|
using System;
namespace KLibrary.Labs.Pipeline
{
public static class FuncHelper
{
public static Func<T1, T3> Compose<T1, T2, T3>(this Func<T1, T2> f1, Func<T2, T3> f2)
{
return x => f2(f1(x));
}
}
}
|
mit
|
C#
|
b29361f7e9e243dd1c09e9851f89223dd9ec5e41
|
Update version number.
|
ronnymgm/csla-light,JasonBock/csla,ronnymgm/csla-light,rockfordlhotka/csla,BrettJaner/csla,MarimerLLC/csla,BrettJaner/csla,jonnybee/csla,BrettJaner/csla,ronnymgm/csla-light,JasonBock/csla,MarimerLLC/csla,MarimerLLC/csla,jonnybee/csla,rockfordlhotka/csla,JasonBock/csla,rockfordlhotka/csla,jonnybee/csla
|
cslacs/Csla/Properties/AssemblyInfo.cs
|
cslacs/Csla/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CSLA .NET")]
[assembly: AssemblyDescription("CSLA .NET Framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rockford Lhotka")]
[assembly: AssemblyProduct("CSLA .NET")]
[assembly: AssemblyCopyright("Copyright © 2007 Rockford Lhotka")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Mark the assembly as CLS compliant
[assembly: System.CLSCompliant(true)]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("43110d9d-9176-498d-95e0-2be52fcd11d2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CSLA .NET")]
[assembly: AssemblyDescription("CSLA .NET Framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rockford Lhotka")]
[assembly: AssemblyProduct("CSLA .NET")]
[assembly: AssemblyCopyright("Copyright © 2007 Rockford Lhotka")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Mark the assembly as CLS compliant
[assembly: System.CLSCompliant(true)]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("43110d9d-9176-498d-95e0-2be52fcd11d2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.1.4.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
b92d65747051e69f5f238046d21065d8013725cc
|
Fix RxCounter example
|
tnakamura/ReduxSharp
|
examples/RxCounter/MainViewModel.cs
|
examples/RxCounter/MainViewModel.cs
|
using System;
using System.ComponentModel;
using System.Reactive.Linq;
namespace RxCounter
{
public class MainViewModel : INotifyPropertyChanged
{
readonly IDisposable _subscription;
public MainViewModel()
{
_subscription = App.Store
.Select(s => s.Counter)
.Subscribe(s =>
{
Count = s.Count;
});
}
int count = 0;
public int Count
{
get { return count; }
set
{
if (count != value)
{
count = value;
OnPropertyChanged(nameof(Count));
}
}
}
public void CountUp()
{
App.Store.Dispatch(CountUpAction.Instance);
}
public void CountDown()
{
App.Store.Dispatch(CountDownAction.Instance);
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
using System;
using System.ComponentModel;
namespace RxCounter
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
App.Store.Subscribe(state =>
{
Count = state.Counter.Count;
});
}
int count = 0;
public int Count
{
get { return count; }
set
{
if (count != value)
{
count = value;
OnPropertyChanged(nameof(Count));
}
}
}
public void CountUp()
{
App.Store.Dispatch(CountUpAction.Instance);
}
public void CountDown()
{
App.Store.Dispatch(CountDownAction.Instance);
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.