Here are the examples of the csharp api System.IO.TextWriter.WriteLine() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1281 Examples
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static int Main(string[] args)
{
var isCurrentOffline = false;
var current = replacedembly.GetEntryreplacedembly().GetName().Version;
var versions = new List<Version>();
versions.AddRange(Updater.Versions);
Version selected = default(Version);
if (!versions.Contains(current))
{
versions.Add(current);
isCurrentOffline = true;
}
versions.Sort();
versions.Reverse();
switch (args.Length)
{
case 0:
_PrintUsage();
Console.WriteLine("Current version: Pck v{0}", current);
Console.WriteLine();
Console.WriteLine("Available versions:");
for (int ic = versions.Count, i = 0; i < ic; ++i)
{
var v = versions[i];
Console.Write("\tPck v");
Console.Write(v);
if (isCurrentOffline && v == current)
Console.Write(" (offline only)");
Console.WriteLine();
}
break;
case 1:
if("/updated"==args[0])
{
Updater.DeleteUpdaterFiles();
Console.Error.Write("Successfully changed version to Pck v");
Console.Error.WriteLine(replacedembly.GetEntryreplacedembly().GetName().Version);
return 0;
}
selected = Updater.LatestVersion;
goto case 2;
case 2:
if("/update"!=args[0])
{
Console.Error.WriteLine("Invalid switch: " + args[0]);
Console.Error.WriteLine();
_PrintUsage();
return 1;
}
if(default(Version)==selected)
{
if(!Version.TryParse(args[1],out selected))
{
Console.Error.WriteLine("Invalid version format: " + args[1]);
Console.Error.WriteLine();
_PrintUsage();
return 1;
}
}
if(!versions.Contains(selected))
{
Console.Error.WriteLine("The specified version was not found: " + args[1]);
Console.Error.WriteLine();
Console.Error.WriteLine("Available versions:");
for (int ic = versions.Count, i = 0; i < ic; ++i)
{
var v = versions[i];
Console.Error.Write("\tPck v");
Console.Error.Write(v);
if (isCurrentOffline && v == current)
Console.Error.Write(" (offline only)");
Console.Error.WriteLine();
}
return 1;
}
if(selected == current)
{
Console.Error.WriteLine("The version is already selected. There is nothing to do.");
return 0;
}
_DoUpdate(current,selected);
break;
}
return 0;
}
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static void _PrintUsagereplaceden()
{
Console.Error.Write(string.Concat(_name, " "));
Console.Error.WriteLine("replaceden [<specfile> [<outputfile>]] [/clreplaced <clreplacedname>] [/namespace <namespace>] [/language <language>]");
Console.Error.WriteLine();
Console.Error.WriteLine(" <specfile>\tThe pck specification file to use (or stdin)");
Console.Error.WriteLine(" <outputfile>\tThe file to write (or stdout)");
Console.Error.WriteLine(" <clreplacedname>\tThe name of the clreplaced to generate (or taken from the filename or from the start symbol of the grammar)");
Console.Error.WriteLine(" <namespace>\tThe namespace to generate the code under (or none)");
Console.Error.WriteLine(" <language>\tThe .NET language to generate the code for (or draw from filename or C#)");
Console.Error.WriteLine();
Console.Error.WriteLine(" Generates an FA tokenizer/lexer in the specified .NET language.");
Console.Error.WriteLine();
Console.Error.WriteLine();
}
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static void _PrintUsageLL1Tree()
{
Console.Error.Write(string.Concat(_name, " "));
Console.Error.WriteLine("ll1tree <specfile> [<inputfile>]");
Console.Error.WriteLine();
Console.Error.WriteLine(" <specfile>\tThe pck specification file to use");
Console.Error.WriteLine(" <inputfile>\tThe file to parse (or stdin)");
Console.Error.WriteLine();
Console.Error.WriteLine(" Prints a tree from the specified input file using the specified pck specification file.");
Console.Error.WriteLine();
}
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static void _PrintUsageXlt()
{
Console.Error.Write(string.Concat(_name, " "));
Console.Error.WriteLine("xlt [<inputfile> [<outputfile>]] [/transform <transform>] [/replacedembly <replacedembly>]");
Console.Error.WriteLine();
Console.Error.WriteLine(" <inputfile>\tThe input file to use (or stdin)");
Console.Error.WriteLine(" <outputfile>\tThe file to write (or stdout)");
Console.Error.WriteLine(" <transform>\tThe name of the transform to use (or taken from the input and/or output filenames)");
Console.Error.WriteLine(" <replacedembly>\tThe replacedembly to reference");
Console.Error.WriteLine();
Console.Error.WriteLine(" Translates an input format to an output format.");
Console.Error.WriteLine();
Console.Error.WriteLine(" Available transforms include: ");
Console.Error.WriteLine();
foreach(var xfrm in _byName)
Console.Error.WriteLine(
string.Concat(
" ",
xfrm.Key,
string.Concat(
"\t",
xfrm.Value.Key.Description)));
Console.Error.WriteLine();
}
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static void _PrintUsage()
{
Console.Error.WriteLine(string.Concat("Usage: ",_name," <command> [<arguments>]"));
Console.Error.WriteLine();
Console.Error.WriteLine("Commands:");
Console.Error.WriteLine();
_PrintUsagereplaceden();
_PrintUsageLL1Gen();
_PrintUsageLL1Factor();
_PrintUsageLL1Tree();
_PrintUsageLalr1Gen();
_PrintUsageLalr1Tree();
_PrintUsageXlt();
Console.Error.WriteLine();
}
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static void _PrintUsageLalr1Gen()
{
Console.Error.Write(string.Concat(_name, " "));
Console.Error.WriteLine("lalr1gen [<specfile> [<outputfile>]] [/clreplaced <clreplacedname>] [/namespace <namespace>] [/language <language>]");
Console.Error.WriteLine();
Console.Error.WriteLine(" <specfile>\tThe pck specification file to use (or stdin)");
Console.Error.WriteLine(" <outputfile>\tThe file to write (or stdout)");
Console.Error.WriteLine(" <clreplacedname>\tThe name of the clreplaced to generate (or taken from the filename or from the start symbol of the grammar)");
Console.Error.WriteLine(" <namespace>\tThe namespace to generate the code under (or none)");
Console.Error.WriteLine(" <language>\tThe .NET language to generate the code for (or draw from filename or C#)");
Console.Error.WriteLine();
Console.Error.WriteLine(" Generates an LALR(1) parser in the specified .NET language.");
Console.Error.WriteLine();
}
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static void _PrintUsageLalr1Tree()
{
Console.Error.Write(string.Concat(_name, " "));
Console.Error.WriteLine("lalr1tree <specfile> [<inputfile>]");
Console.Error.WriteLine();
Console.Error.WriteLine(" <specfile>\tThe pck specification file to use");
Console.Error.WriteLine(" <inputfile>\tThe file to parse (or stdin)");
Console.Error.WriteLine();
Console.Error.WriteLine(" Prints a tree from the specified input file using the specified pck specification file.");
Console.Error.WriteLine();
}
19
Source : Program.fagen.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static int _replaceden(string[] args)
{
string specFile = null;
string outFile = null;
string @namespace = null;
string @clreplaced = null;
string language = null;// "c#";
var optIndex = -1;
for (var i = 0; i < args.Length; ++i)
{
if ("--help" == args[i] || "/?" == args[i] || "/help" == args[i])
{
Console.Error.Write("Usage: ");
_PrintUsagereplaceden();
return 0;
}
if (args[i].StartsWith("/"))
{
optIndex = i;
if (i == args.Length - 1)
{
Console.Error.Write("Usage: ");
_PrintUsagereplaceden();
return 1;
}
switch (args[i])
{
case "/language":
++i;
language = args[i];
break;
case "/namespace":
++i;
@namespace = args[i];
break;
case "/clreplaced":
++i;
@clreplaced = args[i];
break;
default:
_PrintUsagereplaceden();
return 1;
}
}
else
{
if (-1 != optIndex)
{
Console.Error.Write("Usage: ");
_PrintUsagereplaceden();
return 1;
}
if (0 == i)
specFile = args[i];
else if (1 == i)
outFile = args[i];
else
{
Console.Error.Write("Usage: ");
_PrintUsagereplaceden();
return 1;
}
}
}
TextReader inp = null;
TextWriter outp = null;
try
{
if (null == specFile)
inp = Console.In;
else
inp = new StreamReader(specFile);
if (null == outFile)
outp = Console.Out;
else
outp = new StreamWriter(outFile);
var buf = inp.ReadToEnd();
var lex = LexDoreplacedent.Parse(buf);
var cfg = CfgDoreplacedent.Parse(buf);
var syms = cfg.FillSymbols();
if (string.IsNullOrEmpty(@clreplaced))
{
if (null != outFile)
@clreplaced = Path.GetFileNameWithoutExtension(outFile);
else if (0 < syms.Count)
{
foreach (var attrs in lex.AttributeSets)
{
var i = attrs.Value.IndexOf("start");
if (-1 < i && attrs.Value[i].Value is bool && (bool)attrs.Value[i].Value)
{
@clreplaced = string.Concat(attrs.Key, "Tokenizer");
break;
}
}
if (null == @clreplaced)
@clreplaced = string.Concat(syms[0], "Tokenizer");
}
}
TokenizerCodeGenerator.WriteClreplacedTo(lex, syms, @clreplaced,@namespace, language, new _TokenizerConsoleProgress(),outp);
Console.Error.WriteLine();
outp.Flush();
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
finally
{
inp.Close();
outp.Close();
}
}
19
Source : Program.Lalr1Tree.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static int _Lalr1Tree(string[] args)
{
if (1 > args.Length || args.Length > 2)
{
_PrintUsageLalr1Tree();
return 1;
}
var pckspec = args[0];
string pck;
using (var sr = File.OpenText(pckspec))
pck = sr.ReadToEnd();
var cfg = CfgDoreplacedent.Parse(pck);
var lex = LexDoreplacedent.Parse(pck);
var tokenizer = lex.ToTokenizer(
(1 < args.Length) ? (TextReaderEnumerable)new FileReaderEnumerable(args[1]) :
new ConsoleReaderEnumerable(),
cfg.EnumSymbols(),new _TokenizerConsoleProgress());
var parser = cfg.ToLalr1Parser(tokenizer,new _Lalr1ConsoleProgress());
Console.Error.WriteLine();
parser.ShowHidden = true;
while (LRNodeType.EndDoreplacedent != parser.NodeType)
Console.WriteLine(parser.ParseReductions());
return 1;
}
19
Source : Program.LL1Tree.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static int _LL1Tree(string[] args)
{
if (1> args.Length || args.Length>2)
{
_PrintUsageLL1Tree();
return 1;
}
var pckspec = args[0];
string pck;
using (var sr = File.OpenText(pckspec))
pck = sr.ReadToEnd();
var cfg = CfgDoreplacedent.Parse(pck);
var lex = LexDoreplacedent.Parse(pck);
var tokenizer = lex.ToTokenizer(
(1<args.Length)?(TextReaderEnumerable)new FileReaderEnumerable(args[1]):
new ConsoleReaderEnumerable(),
cfg.EnumSymbols(),new _TokenizerConsoleProgress());
Console.Error.WriteLine();
var parser = cfg.ToLL1Parser(tokenizer);
parser.ShowHidden = true;
while (LLNodeType.EndDoreplacedent != parser.NodeType)
Console.WriteLine(parser.ParseSubtree());
return 1;
}
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static void _PrintUsageLL1Gen()
{
Console.Error.Write(string.Concat(_name, " "));
Console.Error.WriteLine("ll1gen [<specfile> [<outputfile>]] [/clreplaced <clreplacedname>] [/namespace <namespace>] [/language <language>]");
Console.Error.WriteLine();
Console.Error.WriteLine(" <specfile>\tThe pck specification file to use (or stdin)");
Console.Error.WriteLine(" <outputfile>\tThe file to write (or stdout)");
Console.Error.WriteLine(" <clreplacedname>\tThe name of the clreplaced to generate (or taken from the filename or from the start symbol of the grammar)");
Console.Error.WriteLine(" <namespace>\tThe namespace to generate the code under (or none)");
Console.Error.WriteLine(" <language>\tThe .NET language to generate the code for (or draw from filename or C#)");
Console.Error.WriteLine();
Console.Error.WriteLine(" Generates an LL(1) parser in the specified .NET language.");
Console.Error.WriteLine();
}
19
Source : Program.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
static void _PrintUsageLL1Factor()
{
Console.Error.Write(string.Concat(_name, " "));
Console.Error.WriteLine("ll1factor [<specfile> [<outputfile>]]");
Console.Error.WriteLine();
Console.Error.WriteLine(" <specfile>\tThe pck specification file to use (or stdin)");
Console.Error.WriteLine(" <outputfile>\tThe file to write (or stdout)");
Console.Error.WriteLine();
Console.Error.WriteLine(" Factors a pck grammar spec so that it can be used with an LL(1) parser.");
Console.Error.WriteLine();
}
19
Source : XbnfToPckTransform.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
public static void Transform(XbnfDoreplacedent doreplacedent, TextWriter writer)
{
var syms = new HashSet<string>();
// gather the attributes and production names
for (int ic = doreplacedent.Productions.Count, i = 0; i < ic; ++i)
{
var p = doreplacedent.Productions[i];
syms.Add(p.Name);
if (0 < p.Attributes.Count)
{
writer.Write(string.Concat(p.Name, ": "));
var delim = "";
for (int jc = p.Attributes.Count, j = 0; j < jc; ++j)
{
writer.Write(string.Concat(delim, p.Attributes[j].ToString()));
delim = ", ";
}
writer.WriteLine();
}
}
writer.WriteLine();
// use a list dictionary to keep these in order
var tmap = new ListDictionary<XbnfExpression, string>();
var attrSets = new Dictionary<string, XbnfAttributeList>();
var rules = new List<KeyValuePair<string, IList<string>>>();
// below are scratch
var working = new HashSet<XbnfExpression>();
var done = new HashSet<XbnfExpression>();
// now get the terminals and their ids, declaring if necessary
for (int ic = doreplacedent.Productions.Count, i = 0; i < ic; ++i)
{
var p = doreplacedent.Productions[i];
if (p.IsTerminal)
{
tmap.Add(p.Expression, p.Name);
done.Add(p.Expression);
}
else
_VisitFetchTerminals(p.Expression, working);
}
foreach (var term in working)
{
if (!done.Contains(term))
{
var newId = _GetImplicitTermId(syms);
tmap.Add(term, newId);
}
}
var ntd = new Dictionary<string, IList<IList<string>>>();
// now we can use tmap and syms to help solve the rest of our productions
for (int ic = doreplacedent.Productions.Count, i = 0; i < ic; ++i)
{
var p = doreplacedent.Productions[i];
if (!p.IsTerminal)
{
var dys = _GetDysjunctions(doreplacedent, syms, tmap, attrSets, rules, p, p.Expression);
ntd.Add(p.Name, dys);
}
}
// now that we've done that, write the rest of our attributes
foreach (var attrs in attrSets)
{
writer.Write(string.Concat(attrs.Key, ":"));
var delim = "";
for (int jc = attrs.Value.Count, j = 0; j < jc; ++j)
{
writer.Write(string.Concat(delim, attrs.Value[j].ToString()));
delim = ", ";
}
writer.WriteLine();
}
// now write our main rules
foreach (var nt in ntd)
{
foreach (var l in nt.Value)
{
writer.Write(string.Concat(nt.Key, "->"));
foreach (var s in l)
writer.Write(string.Concat(" ", s));
writer.WriteLine();
}
}
// write our secondary rules
foreach (var rule in rules)
{
writer.Write(string.Concat(rule.Key, "->"));
foreach (var s in rule.Value)
writer.Write(string.Concat(" ", s));
writer.WriteLine();
}
writer.WriteLine();
// write our terminals
for (int ic = tmap.Count, i = 0; i < ic; ++i)
{
var te = tmap[i];
writer.WriteLine(string.Concat(te.Value, "= \'", _ToRegex(doreplacedent, te.Key), "\'"));
}
writer.Flush();
return;
}
19
Source : ConvertService.cs
with MIT License
from CodySchrank
with MIT License
from CodySchrank
private void Convert()
{
log("Converting..");
foreach (var file in Models)
{
var directoryPath = Path.Combine(LocalConvertDir, file.Structure);
var relativePath = PathStyle == PathStyle.Kebab
? ToKebabCasePath(file.Structure)
: file.Structure;
DirectoryInfo di = Directory.CreateDirectory(Path.Combine(LocalConvertDir, relativePath));
di.Create();
string fileName = (PathStyle == PathStyle.Kebab ? ToKebabCase(file.Name) : ToCamelCase(file.Name)) + ".ts";
log("Creating file {0}", fileName);
string saveDir = Path.Combine(directoryPath, fileName);
using (var stream = GetStream(saveDir, 0))
using (StreamWriter f =
new StreamWriter(stream, System.Text.Encoding.UTF8, 1024, false))
{
var importing = false; //only used for formatting
var imports = new List<string>(); //used for duplication
if (AutoGeneratedTag)
{
f.WriteLine("/* Auto Generated */");
f.WriteLine();
}
if (file.IsEnum)
{
f.WriteLine(
"export enum "
+ file.Name
// + (String.IsNullOrEmpty(file.Inherits) ? "" : (" : " + file.Inherits)) //typescript doesn't extend enums like c#
+ " {"
);
foreach (var obj in file.EnumObjects)
{
if (!String.IsNullOrEmpty(obj.Name))
{ //not an empty obj
string tsName;
switch (PropertyStyle)
{
case PropertyStyle.CamelCase:
tsName = ToCamelCase(obj.Name);
break;
case PropertyStyle.PascalCase:
tsName = ToPascalCase(obj.Name);
break;
default:
throw new ArgumentOutOfRangeException();
}
var str = tsName;
if (EnumValues == EnumValues.Strings)
{
str += " = '" + tsName + "'";
}
else if (!obj.IsImplicit)
{
str += " = " + obj.Value;
}
str += ",";
f.WriteLine(" " + str);
}
}
f.WriteLine("}");
}
else
{
foreach (var obj in file.Objects)
{
if (!String.IsNullOrEmpty(file.Inherits))
{
importing = true;
var import = "import { " + file.Inherits + " } from \""
+ (PathStyle == PathStyle.Kebab ? ToKebabCasePath(file.InheritenceStructure) : file.InheritenceStructure) + "\";";
if (!imports.Contains(import))
{
f.WriteLine(import);
imports.Add(import);
}
}
if (obj.UserDefined)
{
importing = true;
var import = "import { " + obj.Type + " } from \""
+ (PathStyle == PathStyle.Kebab ? ToKebabCasePath(obj.UserDefinedImport) : obj.UserDefinedImport) + "\";";
if (!imports.Contains(import))
{
f.WriteLine(import);
imports.Add(import);
}
}
if (obj.IsContainer)
{
foreach (LineObject innerObj in obj.Container)
{
if (innerObj.UserDefined)
{
importing = true;
var import = "import { " + innerObj.Type + " } from \""
+ (PathStyle == PathStyle.Kebab ? ToKebabCasePath(innerObj.UserDefinedImport) : innerObj.UserDefinedImport) + "\";";
if (!imports.Contains(import))
{
f.WriteLine(import);
imports.Add(import);
}
}
}
}
}
if (importing)
{
f.WriteLine("");
}
f.WriteLine(
"export interface "
+ file.Name
+ (String.IsNullOrEmpty(file.Inherits) ? "" : (" extends " + file.Inherits)) //if clreplaced has inheritance
+ " {"
);
foreach (var obj in file.Objects)
{
string propertyName;
switch (PropertyStyle)
{
case PropertyStyle.CamelCase:
propertyName = ToCamelCase(obj.VariableName);
break;
case PropertyStyle.PascalCase:
propertyName = ToPascalCase(obj.VariableName);
break;
default:
throw new ArgumentOutOfRangeException();
}
if(obj.IsContainer)
{
LineObject[] objects = obj.Container;
var str =
propertyName
+ (obj.IsOptional ? "?" : String.Empty)
+ ": "
+ $"Partial<{obj.Type}<{objects[0].Type}{(objects[0].IsArray ? "[]" : "")}, {objects[1].Type}{(objects[1].IsArray ? "[]" : "")}>>;";
f.WriteLine(" " + str);
}
else if (!String.IsNullOrEmpty(obj.VariableName))
{ //not an empty obj
var str =
propertyName
+ (obj.IsOptional ? "?" : String.Empty)
+ ": "
+ obj.Type
+ (obj.IsArray ? "[]" : String.Empty)
+ ";";
f.WriteLine(" " + str);
}
}
f.WriteLine("}");
}
}
}
}
19
Source : PostgresDataSetAdapter.cs
with MIT License
from CoFlows
with MIT License
from CoFlows
public StreamReader ExecuteStreamReader(string command)
{
// lock (objLock)
{
if (string.IsNullOrWhiteSpace(command))
return null;
NpgsqlConnection _connection_internal = new NpgsqlConnection(ConnectString);
_connection_internal.Open();
NpgsqlCommand com = new NpgsqlCommand(command);
com.CommandTimeout = 0 * 60 * 15;
com.Connection = _connection_internal;
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
var dataReader = com.ExecuteReader();
for (int i = 0; i < dataReader.FieldCount; i++)
{
var name = dataReader.GetName(i);
if (string.IsNullOrEmpty(name))
name = "result";
sw.Write(name + (i == dataReader.FieldCount - 1 ? "" : ","));
}
sw.WriteLine();
for (int i = 0; i < dataReader.FieldCount; i++)
sw.Write(dataReader.GetFieldType(i) + (i == dataReader.FieldCount - 1 ? "" : ","));
sw.WriteLine();
var stream = new MemoryStream();
var t0 = DateTime.Now;
int counter = 0;
while (dataReader.Read())
{
counter++;
for (int i = 0; i < dataReader.FieldCount; i++)
{
var value = dataReader.GetValue(i);
var value_str = "";
if (value.GetType() == typeof(DateTime))
value_str = ((DateTime)value).ToString("yyyy-MM-ddTHH:mm:ss.fff");
else if (value.GetType() == typeof(string))
value_str = value.ToString().Replace(',', (char)30);
else
value_str = value.ToString();
sw.Write(value_str + (i == dataReader.FieldCount - 1 ? "" : ","));
}
sw.WriteLine();
}
dataReader.Close();
((NpgsqlDataReader)dataReader).Close();
_connection_internal.Close();
ms.Position = 0;
var sr = new StreamReader(ms);
return sr;
}
}
19
Source : SQLiteDataSetAdapter.cs
with MIT License
from CoFlows
with MIT License
from CoFlows
public StreamReader ExecuteStreamReader(string command)
{
lock (objLock)
{
if (string.IsNullOrWhiteSpace(command))
return null;
SQLiteConnection _connection_internal = new SQLiteConnection(ConnectString);
_connection_internal.Open();
SQLiteCommand com = new SQLiteCommand(command);
com.CommandTimeout = 0 * 60 * 15;
com.Connection = _connection_internal;
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
var dataReader = com.ExecuteReader();
for (int i = 0; i < dataReader.FieldCount; i++)
{
var name = dataReader.GetName(i);
if (string.IsNullOrEmpty(name))
name = "result";
sw.Write(name + (i == dataReader.FieldCount - 1 ? "" : ","));
}
sw.WriteLine();
for (int i = 0; i < dataReader.FieldCount; i++)
sw.Write(dataReader.GetFieldType(i) + (i == dataReader.FieldCount - 1 ? "" : ","));
sw.WriteLine();
var stream = new MemoryStream();
var t0 = DateTime.Now;
int counter = 0;
while (dataReader.Read())
{
counter++;
for (int i = 0; i < dataReader.FieldCount; i++)
{
var value = dataReader.GetValue(i);
var value_str = "";
if (value.GetType() == typeof(DateTime))
value_str = ((DateTime)value).ToString("yyyy-MM-ddTHH:mm:ss.fff");
else if (value.GetType() == typeof(string))
value_str = value.ToString().Replace(',', (char)30);
else
value_str = value.ToString();
sw.Write(value_str + (i == dataReader.FieldCount - 1 ? "" : ","));
}
sw.WriteLine();
}
dataReader.Close();
((SQLiteDataReader)dataReader).Close();
_connection_internal.Close();
ms.Position = 0;
var sr = new StreamReader(ms);
return sr;
}
}
19
Source : MSSQLDataSetAdapter.cs
with MIT License
from CoFlows
with MIT License
from CoFlows
public StreamReader ExecuteStreamReader(string command)
{
// lock (objLock)
{
if (string.IsNullOrWhiteSpace(command))
return null;
SqlConnection _connection_internal = new SqlConnection(ConnectString);
_connection_internal.Open();
SqlCommand com = new SqlCommand(command);
com.CommandTimeout = 0 * 60 * 15;
com.Connection = _connection_internal;
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
var dataReader = com.ExecuteReader();
/////////////////////////
for (int i = 0; i < dataReader.FieldCount; i++)
{
var name = dataReader.GetName(i);
if (string.IsNullOrEmpty(name))
name = "result";
sw.Write(name + (i == dataReader.FieldCount - 1 ? "" : ","));
}
sw.WriteLine();
for (int i = 0; i < dataReader.FieldCount; i++)
sw.Write(dataReader.GetFieldType(i) + (i == dataReader.FieldCount - 1 ? "" : ","));
sw.WriteLine();
var stream = new MemoryStream();
var t0 = DateTime.Now;
int counter = 0;
while (dataReader.Read())
{
counter++;
for (int i = 0; i < dataReader.FieldCount; i++)
{
var value = dataReader.GetValue(i);
var value_str = "";
if (value.GetType() == typeof(DateTime))
value_str = ((DateTime)value).ToString("yyyy-MM-ddTHH:mm:ss.fff");
else if (value.GetType() == typeof(string))
value_str = value.ToString().Replace(',', (char)30);
else
value_str = value.ToString();
sw.Write(value_str + (i == dataReader.FieldCount - 1 ? "" : ","));
}
sw.WriteLine();
}
dataReader.Close();
((System.Data.SqlClient.SqlDataReader)dataReader).Close();
_connection_internal.Close();
ms.Position = 0;
var sr = new StreamReader(ms);
return sr;
}
}
19
Source : NeatGenomeSaver.cs
with MIT License
from colgreen
with MIT License
from colgreen
public static void Save(NeatGenome<T> genome, StreamWriter sw)
{
// Write input and output node counts.
sw.WriteLine("# Input and output node counts.");
sw.WriteLine($"{genome.MetaNeatGenome.InputNodeCount}\t{genome.MetaNeatGenome.OutputNodeCount}");
sw.WriteLine();
// Write connections.
WriteConnections(genome.ConnectionGenes, sw);
// Write activation function.
WriteActivationFunction(genome.MetaNeatGenome.ActivationFn.GetType().Name, sw);
}
19
Source : NeatGenomeSaver.cs
with MIT License
from colgreen
with MIT License
from colgreen
private static void WriteConnections(ConnectionGenes<T> connGenes, StreamWriter sw)
{
sw.WriteLine("# Connections (source target weight).");
DirectedConnection[] connArr = connGenes._connArr;
T[] weightArr = connGenes._weightArr;
for(int i=0; i < connArr.Length; i++)
{
var conn = connArr[i];
// Use runtime binding to access ToString(string) on the weight type,
// which will be either double or float. This is slow but this is not performance
// critical code.
dynamic weight = weightArr[i];
string weightStr = weight.ToString("R", CultureInfo.InvariantCulture);
sw.WriteLine($"{conn.SourceId}\t{conn.TargetId}\t{weightStr}");
}
sw.WriteLine();
}
19
Source : NeatGenomeSaver.cs
with MIT License
from colgreen
with MIT License
from colgreen
private static void WriteActivationFunction(string name, StreamWriter sw)
{
sw.WriteLine("# Activation functions (functionId functionCode).");
sw.WriteLine($"0\t{name}");
sw.WriteLine();
}
19
Source : HtmlClassFormatter.cs
with Microsoft Public License
from CommunityToolkit
with Microsoft Public License
from CommunityToolkit
private void WriteFooter(ILanguage language)
{
Guard.ArgNotNull(language, "language");
Writer.WriteLine();
WriteHeaderPreEnd();
WriteHeaderDivEnd();
}
19
Source : HtmlClassFormatter.cs
with Microsoft Public License
from CommunityToolkit
with Microsoft Public License
from CommunityToolkit
private void WriteHeader(ILanguage language)
{
Guard.ArgNotNull(language, "language");
WriteHeaderDivStart(language);
WriteHeaderPreStart();
Writer.WriteLine();
}
19
Source : HtmlFormatter.cs
with Microsoft Public License
from CommunityToolkit
with Microsoft Public License
from CommunityToolkit
private void WriteFooter(ILanguage language)
{
Writer.WriteLine();
WriteHeaderPreEnd();
WriteHeaderDivEnd();
}
19
Source : HtmlFormatter.cs
with Microsoft Public License
from CommunityToolkit
with Microsoft Public License
from CommunityToolkit
private void WriteHeader(ILanguage language)
{
WriteHeaderDivStart();
WriteHeaderPreStart();
Writer.WriteLine();
}
19
Source : Assembler.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
public virtual void FlushText(TextWriter aOutput)
{
BeforeFlush();
BeforeFlushText(aOutput);
// Write out data declarations
aOutput.WriteLine();
foreach (DataMember xMember in mDataMembers)
{
if (mAddWhitespaceWhileFlushing)
{
aOutput.Write("\t");
}
if (xMember.IsComment)
{
aOutput.Write(xMember.Name);
}
else
{
xMember.WriteText(this, aOutput);
}
aOutput.WriteLine();
}
aOutput.WriteLine();
// Write out code
for (int i = 0; i < mInstructions.Count; i++)
{
var xOp = mInstructions[i];
string prefix = null;
if (mAddWhitespaceWhileFlushing)
{
prefix = "\t\t\t";
}
if (xOp is Label)
{
var xLabel = (Label) xOp;
aOutput.WriteLine();
if (mAddWhitespaceWhileFlushing)
{
prefix = "\t\t";
}
aOutput.Write(prefix);
xLabel.WriteText(this, aOutput);
aOutput.WriteLine();
}
else
{
aOutput.Write(prefix);
xOp.WriteText(this, aOutput);
aOutput.WriteLine();
}
}
OnFlushTextAfterEmitEverything(aOutput);
aOutput.Flush();
}
19
Source : VMwareHost.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
private void CreateVmx()
{
//var xNvramFile = Path.ChangeExtension(mLaunchSettings.ConfigurationFile, ".nvram");
//if (!File.Exists(xNvramFile))
//{
// using (var xStream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(typeof(VMware), "VMware.nvram"))
// {
// using (var xFile = File.Create(xNvramFile))
// {
// xStream.CopyTo(xFile);
// }
// }
//}
var xConfiguration = GetDefaultConfiguration();
var xVariables = new Dictionary<string, string>()
{
{ "$NVRAM_PATH$", Path.ChangeExtension(Path.GetFileName(mLaunchSettings.ConfigurationFile), ".nvram") },
{ "$ISO_PATH$", mLaunchSettings.IsoFile },
{ "$HARD_DISK_PATH$", mLaunchSettings.HardDiskFile },
{ "$PIPE_SERVER_NAME$", mLaunchSettings.PipeServerName }
};
xConfiguration = ReplaceConfigurationVariables(xConfiguration, xVariables);
if (mLaunchSettings.UseGDB)
{
xConfiguration += Environment.NewLine;
xConfiguration += "debugStub.hideBreakpoints = \"TRUE\"" + Environment.NewLine;
xConfiguration += "debugStub.listen.guest32 = \"TRUE\"" + Environment.NewLine;
xConfiguration += "debugStub.listen.guest32.remote = \"TRUE\"" + Environment.NewLine;
xConfiguration += "monitor.debugOnStartGuest32 = \"TRUE\"" + Environment.NewLine;
}
var xConfigurationFile = mLaunchSettings.ConfigurationFile;
using (var xSrc = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(typeof(VMwareHost), "VMware.vmx")))
{
using (var xDest = new StreamWriter(File.Open(xConfigurationFile, FileMode.Create)))
{
string xLine;
while ((xLine = xSrc.ReadLine()) != null)
{
var xParts = xLine.Split('=');
if (xParts.Length == 2)
{
string xName = xParts[0].Trim();
string xValue = xParts[1].Trim();
if (String.Equals(xName, "uuid.location", StringComparison.Ordinal)
|| String.Equals(xName, "uuid.bios", StringComparison.Ordinal))
{
// We delete uuid entries so VMware doesnt ask the user "Did you move or copy" the file
xValue = null;
}
else if (String.Equals(xName, "ide1:0.fileName", StringComparison.Ordinal))
{
// Set the ISO file for booting
xValue = "\"" + mLaunchSettings.IsoFile + "\"";
}
else if (String.Equals(xName, "ide0:0.fileName", StringComparison.Ordinal))
{
xValue = "\"" + mLaunchSettings.HardDiskFile + "\"";
}
else if (String.Equals(xName, "nvram", StringComparison.Ordinal))
{
// Point it to an initially non-existent nvram.
// This has the effect of disabling PXE so the boot is faster.
xValue = "\"" + Path.ChangeExtension(xConfigurationFile, ".nvram") + "\"";
}
if (xValue != null)
{
xDest.WriteLine(xName + " = " + xValue);
}
}
}
if (mLaunchSettings.UseGDB)
{
xDest.WriteLine();
xDest.WriteLine("debugStub.listen.guest32 = \"TRUE\"");
xDest.WriteLine("debugStub.hideBreakpoints = \"TRUE\"");
xDest.WriteLine("monitor.debugOnStartGuest32 = \"TRUE\"");
xDest.WriteLine("debugStub.listen.guest32.remote = \"TRUE\"");
}
}
}
}
19
Source : NASM.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
protected void Add(OpCode aOpCode, string aOutput = null, params Type[] aParamTypes)
{
Action<object[]> xAction;
if (aOutput == null)
{
xAction = (object[] aValues) =>
{
Out.WriteLine();
};
}
else
{
xAction = (object[] aValues) =>
{
// Can be done with a single call to .WriteLine but makes
// debugging far more difficult.
string xOut = String.Format(aOutput, aValues);
Out.WriteLine(xOut);
};
}
Map.Add(xAction, aOpCode, aParamTypes);
}
19
Source : Clogger.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
public virtual void WriteBlankLine() {
if (CopyToStdOut) {
Console.WriteLine();
}
Out.WriteLine();
}
19
Source : StringUtils.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
private static void ActionTextReaderLine(TextReader textReader, TextWriter textWriter, ActionLine lineAction)
{
string line;
bool firstLine = true;
while ((line = textReader.ReadLine()) != null)
{
if (!firstLine)
textWriter.WriteLine();
else
firstLine = false;
lineAction(textWriter, line);
}
}
19
Source : Program.cs
with GNU Lesser General Public License v2.1
from crozone
with GNU Lesser General Public License v2.1
from crozone
private static void WriteFromSpan(Span<byte> span, Stream stream, bool textMode)
{
if (textMode)
{
StreamWriter streamWriter = new StreamWriter(stream);
for (int i = 0; i < span.Length; i++)
{
if (i > 0 && i % 16 == 0)
{
streamWriter.WriteLine();
}
streamWriter.Write("{0:X2}", span[i]);
}
streamWriter.WriteLine();
streamWriter.Flush();
}
else
{
stream.Write(span);
stream.Flush();
}
}
19
Source : JsonWriter.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
private void WriteNewLine()
{
if (this.Pretty)
{
_writer.WriteLine();
}
}
19
Source : TextReportRenderer.cs
with MIT License
from csf-dev
with MIT License
from csf-dev
void WriteScenarioHeader(IProvidesScenarioMetadata scenario)
{
writer.WriteLine();
var featureText = $"Feature: {scenario.GetPrintableFeatureName()}";
if(featureText != null)
writer.WriteLine(featureText);
writer.WriteLine($"Scenario: {scenario.GetPrintableScenarioName()}");
WriteScenarioOutcome(scenario);
}
19
Source : TextReportRenderer.cs
with MIT License
from csf-dev
with MIT License
from csf-dev
void WriteGainAbility(IReportable reportable, int currentIndentLevel)
{
WriteIndent(currentIndentLevel);
WritePerformanceType(reportable, currentIndentLevel);
writer.Write(reportable.Report);
writer.WriteLine();
}
19
Source : TextReportRenderer.cs
with MIT License
from csf-dev
with MIT License
from csf-dev
void WritePerformance(IReportable reportable, int currentIndentLevel)
{
WriteIndent(currentIndentLevel);
WritePerformanceType(reportable, currentIndentLevel);
writer.Write(reportable.Report);
writer.WriteLine();
if(reportable.Type == ReportableType.SuccessWithResult)
WriteResult(reportable, currentIndentLevel);
else if(reportable.Type == ReportableType.Failure)
WriteFailure(reportable, currentIndentLevel);
else if(reportable.Type == ReportableType.FailureWithError && !reportable.Reportables.Any())
WriteFailure(reportable, currentIndentLevel);
foreach(var child in reportable.Reportables)
{
WriteReportable(child, currentIndentLevel + 1);
}
}
19
Source : DumpText.cs
with MIT License
from csinkers
with MIT License
from csinkers
static void DumpMapEvents(StreamWriter sw, IreplacedetManager replacedets, MapId mapId, IMapData map)
{
var formatter = new EventFormatter(replacedets.LoadString, mapId.ToMapText());
sw.WriteLine();
sw.WriteLine($"Map {mapId.Id} {mapId}:");
foreach (var e in map.Events)
{
var chainId = map.Chains.Select((x, i) => x == e.Id ? i : (int?)null).FirstOrDefault(x => x != null);
PrintEvent(sw, formatter, e, chainId);
}
/*
var rootNodes = new HashSet<(bool, TriggerType, int)>();
foreach (var zone in map.Zones)
rootNodes.Add((zone.Global, zone.Trigger, zone.EventNumber));
var sorted =
rootNodes
.OrderByDescending(x => x.Item1)
.ThenBy(x => x.Item2)
.ThenBy(x => x.Item3)
;
foreach (var (global, trigger, number) in sorted)
{
var e = map.Events[number];
sw.WriteLine($"{(global ? "Global" : "Local")} {trigger}:");
PrintChain(sw, formatter, e, 1);
}*/
}
19
Source : IniFile.cs
with GNU General Public License v3.0
from cumulusmx
with GNU General Public License v3.0
from cumulusmx
internal void Flush()
{
lock (m_Lock)
{
// *** If local cache was not modified, exit ***
if (!m_CacheModified) return;
var success = false;
var retries = replacedulus.LogFileRetries;
do
{
try
{
// *** Open the file ***
using (StreamWriter sw = new StreamWriter(m_FileName))
{
// *** Cycle on all sections ***
bool First = false;
foreach (KeyValuePair<string, Dictionary<string, string>> SectionPair in m_Sections)
{
Dictionary<string, string> Section = SectionPair.Value;
if (First) sw.WriteLine();
First = true;
// *** Write the section name ***
sw.Write('[');
sw.Write(SectionPair.Key);
sw.WriteLine(']');
// *** Cycle on all key+value pairs in the section ***
foreach (KeyValuePair<string, string> ValuePair in Section)
{
// *** Write the key+value pair ***
sw.Write(ValuePair.Key);
sw.Write('=');
sw.WriteLine(ValuePair.Value);
}
}
}
success = true;
m_CacheModified = false;
}
catch (IOException ex)
{
if (ex.HResult == -2147024864) // 0x80070020
{
retries--;
System.Threading.Thread.Sleep(250);
}
else
{
throw;
}
}
catch
{
throw;
}
} while (!success && retries >= 0);
}
}
19
Source : JsonRpcStreamsTests.cs
with Apache License 2.0
from CXuesong
with Apache License 2.0
from CXuesong
[Fact]
public async Task ServerHandlerTest()
{
var request = new RequestMessage(123, "add", JToken.FromObject(new {x = 20, y = 35}));
(var ss, var cs) = FullDuplexStream.CreatePair();
using (var clientReader = new StreamReader(cs))
using (var clientWriter = new StreamWriter(cs))
using (var serverReader = new ByLineTextMessageReader(ss))
using (var serverWriter = new ByLineTextMessageWriter(ss))
{
async Task<ResponseMessage> WaitForResponse()
{
var sw = Stopwatch.StartNew();
var content = await clientReader.ReadLineAsync();
Output.WriteLine($"Received response in {sw.Elapsed}.");
return (ResponseMessage) Message.LoadJson(content);
}
async Task<ResponseMessage> SendRequest(MessageId messageId)
{
request.Id = messageId;
request.WriteJson(clientWriter);
clientWriter.WriteLine();
await clientWriter.FlushAsync();
var response = await WaitForResponse();
replacedert.Equal(messageId, response.Id);
replacedert.Null(response.Error);
replacedert.Equal(55, (int) response.Result);
return response;
}
using (var server = new ServerTestHelper(this, serverReader, serverWriter,
StreamRpcServerHandlerOptions.None))
{
await SendRequest(123);
await SendRequest("abc");
}
}
}
19
Source : MainWindowViewModel.cs
with MIT License
from cyberark
with MIT License
from cyberark
void writeResultsToFile()
{
Dictionary<string, int> recurrences = new Dictionary<string, int>();
foreach (string g in greenRoute)
{
// don't write if have a recurrence of results
if (recurrences.ContainsKey(g))
return;
recurrences.Add(g, 1);
} // end foreach
for (int ai = 0; ai < greenRoute.Count; ai++)
{
if (enreplacedies.ContainsKey(greenRoute[ai]))
enreplacedies[greenRoute[ai]]++;
else
enreplacedies.Add(greenRoute[ai], 1);
} // endfor found
StreamWriter wr = new StreamWriter("out.txt", true);
for (int ai = 0; ai < greenRoute.Count; ai++)
wr.Write(greenRoute[ai] + " > ");
wr.WriteLine();
wr.Close();
//
// also, update enreplacediesToEdges dictionary
for (int a = 0; a < greenRoute.Count - 1; a++)
{
string name = greenRoute[a];
string nameTo = greenRoute[a + 1];
if (enreplacediesToEdges.ContainsKey(name))
{
List<objectDesignators> edges = enreplacediesToEdges[name];
bool foundedge = false;
for (int inx = 0; inx < edges.Count; inx++)
{
if (edges[inx].objectName == nameTo)
{
edges[inx].privileges |= greenRoutePrivileges[a + 1];
foundedge = true;
break;
}
} // endfor scan all existing edges
if (!foundedge)
{
objectDesignators obj = new objectDesignators();
obj.objectName = nameTo;
obj.privileges = greenRoutePrivileges[a + 1];
obj.beenHere = false;
edges.Add(obj);
}
} // endfor all winning routes
else
{
// enreplacediesToEdges does not contain the name found
objectDesignators obj = new objectDesignators();
obj.objectName = nameTo;
obj.privileges = greenRoutePrivileges[a + 1];
obj.beenHere = false;
List<objectDesignators> edges = new List<objectDesignators>();
edges.Add(obj);
enreplacediesToEdges.Add(name, edges);
}
} // end for
}
19
Source : DebugUtil.cs
with MIT License
from CymaticLabs
with MIT License
from CymaticLabs
public static void Dump(byte[] bytes, TextWriter writer) {
int rowlen = 16;
for (int count = 0; count < bytes.Length; count += rowlen) {
int thisRow = Math.Min(bytes.Length - count, rowlen);
writer.Write(String.Format("{0:X8}: ", count));
for (int i = 0; i < thisRow; i++) {
writer.Write(String.Format("{0:X2}", bytes[count + i]));
}
for (int i = 0; i < (rowlen - thisRow); i++) {
writer.Write(" ");
}
writer.Write(" ");
for (int i = 0; i < thisRow; i++) {
if (bytes[count + i] >= 32 &&
bytes[count + i] < 128)
{
writer.Write((char) bytes[count + i]);
} else {
writer.Write('.');
}
}
writer.WriteLine();
}
if (bytes.Length % 16 != 0) {
writer.WriteLine(String.Format("{0:X8}: ", bytes.Length));
}
}
19
Source : Http.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public static byte[] CreateResponse(HttpCode httpCode, string content, bool closeConnection = false)
{
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
sw.WriteLine($"HTTP/1.1 {(int)httpCode} {httpCode}");
//sw.WriteLine($"Date: {DateTime.Now.ToUniversalTime():r}");
//sw.WriteLine("Server: Arctium-Emulation");
//sw.WriteLine("Retry-After: 600");
sw.WriteLine($"Content-Length: {content.Length}");
//sw.WriteLine("Vary: Accept-Encoding");
if (closeConnection)
sw.WriteLine("Connection: close");
sw.WriteLine("Content-Type: application/json;charset=UTF-8");
sw.WriteLine();
sw.WriteLine(content);
}
return Encoding.UTF8.GetBytes(sb.ToString());
}
19
Source : SysFileCsv.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public override int Output(IEnumerable<BsonDoreplacedent> source, BsonValue options)
{
var filename = GetOption(options, "filename")?.replacedtring ?? throw new LiteException(0, "Collection $file_json requires string as 'filename' or a doreplacedent field 'filename'");
var overwritten = GetOption(options, "overwritten", false).AsBoolean;
var encoding = GetOption(options, "encoding", "utf-8").replacedtring;
var delimiter = GetOption(options, "delimiter", ",").replacedtring[0];
var header = GetOption(options, "header", true).AsBoolean;
var index = 0;
IList<string> headerFields = null;
FileStream fs = null;
StreamWriter writer = null;
try
{
foreach (var doc in source)
{
if (index++ == 0)
{
fs = new FileStream(filename, overwritten ? FileMode.OpenOrCreate : FileMode.CreateNew);
writer = new StreamWriter(fs, Encoding.GetEncoding(encoding));
headerFields = doc.Keys.ToList();
// print file header
if (header)
{
var idxHeader = 0;
foreach (var elem in doc)
{
if (idxHeader++ > 0) writer.Write(delimiter);
writer.Write(elem.Key);
}
writer.WriteLine();
}
}
else
{
writer.WriteLine();
}
var idxValue = 0;
foreach(var field in headerFields)
{
var value = doc[field];
if (idxValue++ > 0) writer.Write(delimiter);
this.WriteValue(value, writer);
}
}
if (index > 0)
{
writer.Flush();
}
}
finally
{
if (writer != null) writer.Dispose();
if (fs != null) fs.Dispose();
}
return index;
}
19
Source : SysFileJson.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public override int Output(IEnumerable<BsonDoreplacedent> source, BsonValue options)
{
var filename = GetOption(options, "filename")?.replacedtring ?? throw new LiteException(0, "Collection $file_json requires string as filename or a doreplacedent field 'filename'");
var pretty = GetOption(options, "pretty", false).AsBoolean;
var indent = GetOption(options, "indent", 4).AsInt32;
var encoding = GetOption(options, "encoding", "utf-8").replacedtring;
var overwritten = GetOption(options, "overwritten", false).AsBoolean;
var index = 0;
FileStream fs = null;
StreamWriter writer = null;
JsonWriter json = null;
try
{
foreach (var doc in source)
{
if (index++ == 0)
{
fs = new FileStream(filename, overwritten ? FileMode.OpenOrCreate : FileMode.CreateNew);
writer = new StreamWriter(fs, Encoding.GetEncoding(encoding));
json = new JsonWriter(writer)
{
Pretty = pretty,
Indent = indent
};
writer.WriteLine("[");
}
else
{
writer.WriteLine(",");
}
json.Serialize(doc);
}
if (index > 0)
{
writer.WriteLine();
writer.Write("]");
writer.Flush();
}
}
finally
{
if (writer != null) writer.Dispose();
if (fs != null) fs.Dispose();
}
return index;
}
19
Source : MatrixUtil.cs
with GNU Lesser General Public License v3.0
from czsgeo
with GNU Lesser General Public License v3.0
from czsgeo
public static void SaveToText(double[][] matrix, string path, bool printZero = false, char spliter = ',')
{
using (StreamWriter bw = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write)))
{
int row = matrix.Length;
int col = matrix[0].Length;
bw.WriteLine(row.ToString() + spliter.ToString() + col.ToString());
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (!printZero && matrix[i][j] == 0) bw.Write(" " + spliter);
else bw.Write(matrix[i][j].ToString() + spliter);
}
bw.WriteLine();
}
bw.Close();
}
}
19
Source : MatrixUtil.cs
with GNU Lesser General Public License v3.0
from czsgeo
with GNU Lesser General Public License v3.0
from czsgeo
public static void Print(Stream outStream, double[][] matrix, char spliter = ',')
{
int width = 15;
using (StreamWriter writer = new StreamWriter(outStream, Encoding.UTF8))
{
writer.WriteLine(matrix.Length + "" + spliter + "" + matrix[0].Length);
foreach (var array in matrix)
{
foreach (var item in array)
{
if (item == 0) writer.Write(StringUtil.FillSpace(item.ToString(), width) + spliter.ToString());
else writer.Write(StringUtil.FillSpace(DoubleUtil.ScientificFomate(item, "E14.10"), width) + spliter.ToString());
}
writer.WriteLine();
}
}
}
19
Source : FFEncoder.cs
with GNU General Public License v3.0
from DaGooseYT
with GNU General Public License v3.0
from DaGooseYT
internal static void TryStartProcess(StreamWriter log, Process process, StringBuilder sb, FFLoaderBase ffloader)
{
try
{
FFHelper.FFMpegPathNullOrMissing(ffloader.FFMpegPath);
FFHelper.InputFileNullOrMissing(ffloader.InputVideoPath);
FFHelper.OutputPathNullOrMissing(ffloader.OutputVideoPath);
if (!string.IsNullOrEmpty(ffloader.AvisynthScriptPath))
{
FFHelper.AvsScriptFileNullOrMissing(ffloader.AvisynthScriptPath);
}
process.Start();
Timer.Restart();
string line = new string('=', 100);
//Create and write log file.
log.WriteLine(line);
log.WriteLine($"FFMpeg logs generated by FFLoader on {DateTime.Now}");
log.WriteLine($"FFMpeg Command: ffmpeg.exe {ffloader.FFMpegCommand}");
log.WriteLine(line + Environment.NewLine);
process.BeginErrorReadLine();
process.WaitForExit();
Timer.Stop();
FileInfo file = new FileInfo(ffloader.OutputVideoPath);
if (!string.IsNullOrEmpty(sb.ToString()))
{
ffloader.CatchAvsError(sb.ToString(), out AviSynthErrorHandler handler);
ffloader.UpdateAvsError(handler);
ProcessWorker.Cancelled = true;
}
else if (FFHelper.OutputFileNotCreated(ffloader.OutputVideoPath) || file.Length < 10000)
{
ffloader.CatchFFMpegError("An unknown error occured with FFMpeg.", out FFMpegErrorHandler handler);
ffloader.UpdateFFMpegError(handler);
ProcessWorker.Cancelled = true;
}
log.WriteLine();
log.WriteLine(line);
log.WriteLine("End of logs.");
log.WriteLine(line);
log.Close();
line = null;
}
catch (FFLoaderException e)
{
ffloader.CatchException(e.Source + ": " + e.Message, out FFExceptionHandler handler);
ffloader.UpdateException(handler);
}
finally
{
try
{
log = null;
ffloader.CloseProcess();
}
catch (FFLoaderException e)
{
ffloader.CatchException(e.Source + ": " + e.Message, out FFExceptionHandler handler);
ffloader.UpdateException(handler);
}
}
}
19
Source : GraphicsExtension.cs
with MIT License
from dahall
with MIT License
from dahall
public override string ToString()
{
var sb = new StringBuilder();
using (var tw = new StringWriter(sb))
{
for (var i = 0; i < Length / bmp.Width; i++)
{
for (var j = 0; j < bmp.Width; j++)
tw.Write($"0x{this[i, j].ToArgb():X}\t");
tw.WriteLine();
}
tw.Close();
}
return sb.ToString();
}
19
Source : Converter.cs
with MIT License
from DaisukeAtaraxiA
with MIT License
from DaisukeAtaraxiA
public override bool Convert(EnvDTE.DTE dte)
{
var solutionInfoList = VerifySolution(dte);
if (solutionInfoList == null)
{
return false;
}
logger.Info("Converting the projects");
var cmProjects = new List<CMProject>();
foreach (var solutionInfo in solutionInfoList)
{
var cmProject = new CMProject(solutionInfo.project);
cmProject.setLogger(logger);
cmProject.Platform = Platform;
cmProject.BuildConfigurations =
solutionInfo.cfgs.Select(x => x.prjCfgName).ToArray();
foreach (var cfg in solutionInfo.cfgs)
{
cmProject.SetSolutionConfigurationName(cfg.prjCfgName,
cfg.slnCfgName);
}
if (!cmProject.Prepare())
{
return false;
}
cmProjects.Add(cmProject);
}
var solutionDir = Path.GetDirectoryName(dte.Solution.FullName);
foreach (var cmProject in cmProjects)
{
if (!cmProject.Convert(solutionDir, cmProjects))
{
return false;
}
}
logger.Info("Converting the projects - done");
// Output CMakeLists.txt for the solution file.
logger.Info("Converting the solution");
logger.Info($"--- Converting {dte.Solution.FullName} ---");
var cmakeListsPath = Path.Combine(solutionDir, "CMakeLists.txt");
var sw = new StreamWriter(cmakeListsPath);
sw.WriteLine($"cmake_minimum_required(VERSION {Constants.CMAKE_REQUIRED_VERSION})");
sw.WriteLine();
sw.WriteLine("project({0})",
Path.GetFileNameWithoutExtension(
dte.Solution.FileName));
sw.WriteLine();
foreach (var cmProject in cmProjects)
{
var projectDir = Path.GetDirectoryName(
cmProject.Project.FileName);
var relativePath =
Utility.ToRelativePath(projectDir, solutionDir);
sw.WriteLine($"add_subdirectory({relativePath})");
}
sw.Close();
logger.Info($" {Path.GetFileNameWithoutExtension(dte.Solution.FullName)} -> {cmakeListsPath}");
logger.Info("Converting the solution - done");
return true;
}
19
Source : fp.cs
with MIT License
from danielmansson
with MIT License
from danielmansson
internal static void GenerateTanLut()
{
using (var writer = new StreamWriter("Fix64TanLut.cs"))
{
writer.Write(
@"namespace Unity.Mathematics.FixedPoint
{
partial struct Fix64
{
public static readonly long[] TanLut = new[]
{");
int lineCounter = 0;
for (int i = 0; i < LUT_SIZE; ++i)
{
var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1);
if (lineCounter++ % 8 == 0)
{
writer.WriteLine();
writer.Write(" ");
}
var tan = Math.Tan(angle);
if (tan > (double)max_value || tan < 0.0)
{
tan = (double)max_value;
}
var rawValue = (((decimal)tan > (decimal)max_value || tan < 0.0) ? max_value : (fp)tan).m_rawValue;
writer.Write(string.Format("0x{0:X}L, ", rawValue));
}
writer.Write(
@"
};
}
}");
}
}
19
Source : PowerfulAsyncEnumerableExtensions.cs
with Apache License 2.0
from danielmarbach
with Apache License 2.0
from danielmarbach
public static void PrintStatistics(
this PowerfulAsyncEnumerable runnable,
List<PackageMetadata> packagesWithNetFxAsms,
int totalCount)
{
Console.Out.WriteLine();
Console.Out.WriteLine($"Packages with dotnet replacedemblies: {packagesWithNetFxAsms.Count} ({totalCount})");
Console.Out.WriteLine($"Total download size(MB): {packagesWithNetFxAsms.Sum(p => p.Size) / 1000000.0}");
}
19
Source : fp.cs
with MIT License
from danielmansson
with MIT License
from danielmansson
internal static void GenerateSinLut()
{
using (var writer = new StreamWriter("Fix64SinLut.cs"))
{
writer.Write(
@"namespace Unity.Mathematics.FixedPoint
{
partial struct Fix64
{
public static readonly long[] SinLut = new[]
{");
int lineCounter = 0;
for (int i = 0; i < LUT_SIZE; ++i)
{
var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1);
if (lineCounter++ % 8 == 0)
{
writer.WriteLine();
writer.Write(" ");
}
var sin = Math.Sin(angle);
var rawValue = ((fp)sin).m_rawValue;
writer.Write(string.Format("0x{0:X}L, ", rawValue));
}
writer.Write(
@"
};
}
}");
}
}
See More Examples