commit c85c238e41b1880ce50120d57dd69773eb431719 Author: poprhythm Date: Sat May 9 03:03:14 2026 +0000 Initial commit — Coursera Big Data coursework diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6628552 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +bin/ +obj/ +packages/ +*.suo +*.v11.suo +*.user +.vs/ diff --git a/hw3/AuthorTerms/App.config b/hw3/AuthorTerms/App.config new file mode 100644 index 0000000..04dad73 --- /dev/null +++ b/hw3/AuthorTerms/App.config @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hw3/AuthorTerms/AuthorTerms.fsproj b/hw3/AuthorTerms/AuthorTerms.fsproj new file mode 100644 index 0000000..f72366d --- /dev/null +++ b/hw3/AuthorTerms/AuthorTerms.fsproj @@ -0,0 +1,69 @@ + + + + + Debug + AnyCPU + 2.0 + 1b4ca350-550f-4533-90f4-eb65ba6a7b8b + Exe + AuthorTerms + AuthorTerms + v4.5 + AuthorTerms + + + true + full + false + false + bin\Debug\ + DEBUG;TRACE + 3 + AnyCPU + bin\Debug\AuthorTerms.XML + true + Dewitt + + + pdbonly + true + true + bin\Release\ + TRACE + 3 + AnyCPU + bin\Release\AuthorTerms.XML + true + Henzinger + + + + + True + + + + + + + + PreserveNewest + + + + + + + + 11 + + + + \ No newline at end of file diff --git a/hw3/AuthorTerms/AuthorTerms.sln b/hw3/AuthorTerms/AuthorTerms.sln new file mode 100644 index 0000000..93f11c0 --- /dev/null +++ b/hw3/AuthorTerms/AuthorTerms.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "AuthorTerms", "AuthorTerms.fsproj", "{1B4CA350-550F-4533-90F4-EB65BA6A7B8B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1B4CA350-550F-4533-90F4-EB65BA6A7B8B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1B4CA350-550F-4533-90F4-EB65BA6A7B8B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1B4CA350-550F-4533-90F4-EB65BA6A7B8B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1B4CA350-550F-4533-90F4-EB65BA6A7B8B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/hw3/AuthorTerms/MapReduce.fs b/hw3/AuthorTerms/MapReduce.fs new file mode 100644 index 0000000..f0b4699 --- /dev/null +++ b/hw3/AuthorTerms/MapReduce.fs @@ -0,0 +1,39 @@ +module MapReduce + +//let map_reduce +// // Map function take pair and create sequence of key/value pairs +// (m:'k1 -> 'v1 -> seq<'k2 * 'v2>) +// // Reduce function takes key and sequence to produce optional value +// (r:'k2 -> seq<'v2> -> 'v3) +// // Takes an input of key/value pairs to produce an output key/value pairs +// : Map<'k1, 'v1> -> Map<'k2, 'v3> = +// +// let map_per_key : Map<'k1, 'v1> -> seq<('k2 * 'v2)> = +// Map.toSeq >> // 1. Map into a sequence +// Seq.map (fun (k, v) -> m k v) >> // 2. Map m over a list of pairs +// Seq.concat // 3. Concat per-key lists +// +// let group_by_key (l:seq<('k2 * 'v2)>) : Map<'k2,seq<'v2>> = +// l +// |> Seq.groupBy fst +// |> Seq.map (fun(k,vs) -> k, Seq.map snd vs) +// |> Map.ofSeq +// +// let reduce_per_key : Map<'k2, seq<'v2>> -> Map<'k2,'v3> = +// let un_some k (Some v) = v // Remove optional type +// let is_some k = function +// | Some _ -> true // Keep entires +// | None -> false // Remove entries +// Map.map r //>> // 1. Apply reduce per key +// //Map.filter is_some >> // 2. Remove None entries +// //Map.map un_some // 3. Transform to remove option +// +// map_per_key >> // 1. Apply map function to each key/value pair +// group_by_key >> // 2. Group intermediate data per key +// reduce_per_key // 3. Apply reduce to each group + +let map_reduce map reduce (inputs:seq<_*_>) = + let intermediates = inputs |> Seq.map map |> Seq.concat + let groupings = intermediates |> Seq.groupBy fst |> Seq.map (fun(x,y) -> x, Seq.map snd y) + let results = groupings |> Seq.map reduce + results \ No newline at end of file diff --git a/hw3/AuthorTerms/Program.fs b/hw3/AuthorTerms/Program.fs new file mode 100644 index 0000000..6f7a97c --- /dev/null +++ b/hw3/AuthorTerms/Program.fs @@ -0,0 +1,47 @@ +// Learn more about F# at http://fsharp.net +// See the 'F# Tutorial' project for more help. + +open data +open MapReduce +open System.Text.RegularExpressions + +[] +let main argv = + let stopwords = getStopwords + + let booksMap = + let bookData = (getData @"..\..\data") + let bookToTuple book = + book.authors |> List.map (fun a -> a, book.title) + let booksToMap books = + books |> Seq.collect bookToTuple + bookData |> booksToMap + let wordsRegex = new Regex("(?\w{2,})", RegexOptions.Compiled) + + let mapfunc (author:string, title) = + let words = + wordsRegex.Matches(title) + |> Seq.cast + |> Seq.map (fun m -> m.Groups.["word"].Value.ToLower()) + |> Seq.filter (fun w -> not (Seq.exists ((=) w) stopwords)) + [ author.ToLower() ,words ] |> Seq.ofList + + let reducefunc (author, words: seq>) = + //let bw = words |> Seq.filter (fun wl -> wl |> Seq.length > 1) |> Array.ofSeq + //printfn "%A" bw + let countedWords = + words + |> Seq.collect (fun s -> s) + |> Seq.groupBy(fun w -> w) + |> Seq.map (fun (w,l) -> w, Seq.length l) + |> Seq.sortBy (fun (_,c) -> -c - 1) + author, countedWords + + let r = map_reduce mapfunc reducefunc booksMap + //printfn "Map Length %A\n" (r |> Map.toSeq |> Seq.length) + //printfn "%A" (r |> Map.toArray) + + //let result = (r |> Seq.filter (fun k v -> v |> Seq.exists (fun (w,c) -> c > 3))) + let result = r |> Seq.filter (fun (k:string,_) -> k.Contains(argv.[0].ToLower())) + printfn "%A\n" result + 0 // return an integer exit code diff --git a/hw3/AuthorTerms/data.fs b/hw3/AuthorTerms/data.fs new file mode 100644 index 0000000..2ae9fac --- /dev/null +++ b/hw3/AuthorTerms/data.fs @@ -0,0 +1,31 @@ +module data +open System.IO +open System.Text.RegularExpressions + +let getStopwords = + let text = File.ReadAllText(@"stopwords.py") + Regex.Matches(text, @"'(?\w*)'") + |> Seq.cast + |> Seq.map (fun m -> m.Groups.["stopword"].Value) + +type Book = { + id : string; + authors : string List; + title : string; +} + +let getData directory = + let parseFile filename = + File.ReadAllLines(filename) + |> Seq.map (fun l -> + Regex.Split(l,":::") + |> fun arr -> + { + id = arr.[0]; + authors = Regex.Split(arr.[1],"::") |> List.ofArray; + title = arr.[2] + } + ) + let files = Directory.GetFiles(directory) + files |> Seq.collect parseFile + diff --git a/hw3/AuthorTerms/data.tar.gz b/hw3/AuthorTerms/data.tar.gz new file mode 100644 index 0000000..6ea05a5 Binary files /dev/null and b/hw3/AuthorTerms/data.tar.gz differ diff --git a/hw3/AuthorTerms/stopwords.py b/hw3/AuthorTerms/stopwords.py new file mode 100644 index 0000000..311ae2d --- /dev/null +++ b/hw3/AuthorTerms/stopwords.py @@ -0,0 +1 @@ +allStopWords={'about':1, 'above':1, 'after':1, 'again':1, 'against':1, 'all':1, 'am':1, 'an':1, 'and':1, 'any':1, 'are':1, 'arent':1, 'as':1, 'at':1, 'be':1, 'because':1, 'been':1, 'before':1, 'being':1, 'below':1, 'between':1, 'both':1, 'but':1, 'by':1, 'cant':1, 'cannot':1, 'could':1, 'couldnt':1, 'did':1, 'didnt':1, 'do':1, 'does':1, 'doesnt':1, 'doing':1, 'dont':1, 'down':1, 'during':1, 'each':1, 'few':1, 'for':1, 'from':1, 'further':1, 'had':1, 'hadnt':1, 'has':1, 'hasnt':1, 'have':1, 'havent':1, 'having':1, 'he':1, 'hed':1, 'hell':1, 'hes':1, 'her':1, 'here':1, 'heres':1, 'hers':1, 'herself':1, 'him':1, 'himself':1, 'his':1, 'how':1, 'hows':1, 'i':1, 'id':1, 'ill':1, 'im':1, 'ive':1, 'if':1, 'in':1, 'into':1, 'is':1, 'isnt':1, 'it':1, 'its':1, 'its':1, 'itself':1, 'lets':1, 'me':1, 'more':1, 'most':1, 'mustnt':1, 'my':1, 'myself':1, 'no':1, 'nor':1, 'not':1, 'of':1, 'off':1, 'on':1, 'once':1, 'only':1, 'or':1, 'other':1, 'ought':1, 'our':1, 'ours ':1, 'ourselves':1, 'out':1, 'over':1, 'own':1, 'same':1, 'shant':1, 'she':1, 'shed':1, 'shell':1, 'shes':1, 'should':1, 'shouldnt':1, 'so':1, 'some':1, 'such':1, 'than':1, 'that':1, 'thats':1, 'the':1, 'their':1, 'theirs':1, 'them':1, 'themselves':1, 'then':1, 'there':1, 'theres':1, 'these':1, 'they':1, 'theyd':1, 'theyll':1, 'theyre':1, 'theyve':1, 'this':1, 'those':1, 'through':1, 'to':1, 'too':1, 'under':1, 'until':1, 'up':1, 'very':1, 'was':1, 'wasnt':1, 'we':1, 'wed':1, 'well':1, 'were':1, 'weve':1, 'were':1, 'werent':1, 'what':1, 'whats':1, 'when':1, 'whens':1, 'where':1, 'wheres':1, 'which':1, 'while':1, 'who':1, 'whos':1, 'whom':1, 'why':1, 'whys':1, 'with':1, 'wont':1, 'would':1, 'wouldnt':1, 'you':1, 'youd':1, 'youll':1, 'youre':1, 'youve':1, 'your':1, 'yours':1, 'yourself':1, 'yourselves':1} diff --git a/hw6/App.config b/hw6/App.config new file mode 100644 index 0000000..04dad73 --- /dev/null +++ b/hw6/App.config @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hw6/Program.fs b/hw6/Program.fs new file mode 100644 index 0000000..4636d69 --- /dev/null +++ b/hw6/Program.fs @@ -0,0 +1,79 @@ +// Learn more about F# at http://fsharp.net +// See the 'F# Tutorial' project for more help. + +type Cond = char * bool + +type P = Cond List * double + +type Variable = + | OneD of Cond * Cond * double + | TwoD of Cond * Cond * Cond * double + | Prior of Cond * double + +let getProbability(p) = + match p with + | OneD(_,_,prob) -> prob + | TwoD(_,_,_,prob) -> prob + | Prior(_,prob) -> prob + +let filterCondition (c, b) v = + match v with + | OneD((pc,pb),_,_) when c = pc && b = pb -> true + | OneD(_,(pc,pb),_) when c = pc && b = pb -> true + | Prior((pc,pb),_) when c = pc && b = pb -> true + | TwoD((pc,pb),_,_,_) when c = pc && b = pb -> true + | TwoD(_,(pc,pb),_,_) when c = pc && b = pb -> true + | TwoD(_,_,(pc,pb),_) when c = pc && b = pb -> true + | _ -> false + +let reciprocal v = + match v with + | Prior((pc,pb),p) -> Prior((pc,not pb),1.0-p) + | OneD((pc,pb),a,p) -> OneD((pc,not pb),a,1.0-p) + | TwoD((pc,pb),a,b,p) -> TwoD((pc,not pb),a,b,1.0-p) + +let matchProb cond variables = cond |> List.fold (fun s c -> List.filter (filterCondition c) s) variables |> List.head |> getProbability + +let completeReciprocalVariable variable = variable |> List.map reciprocal |> List.append variable + +//let addNeg ps = ps concat ps + +//let pa = [Prior(('a', true), 0.01)] +// +//let pta = [OneD(('t', true), ('a', true), 0.5); +// OneD(('t', true), ('a', false), 0.1)] +// +//let ps = [Prior(('s', true), 0.5)] +// +//let pls = [OneD(('l', true), ('s', true), 0.1); +// OneD(('l', true), ('s', false), 0.01)] +// +//let pbs = [OneD(('b', true), ('s', true), 0.6); +// OneD(('b', true), ('s', false), 0.3)] + +let pm = [Prior(('m',true), 0.1)] |> completeReciprocalVariable +let pbm = [OneD(('b',true), ('m',true), 0.9); OneD(('b',true), ('m',false), 0.05)] |> completeReciprocalVariable +let psm = [OneD(('s',true), ('m',true), 0.6); OneD(('s',true), ('m',false), 0.3)] |> completeReciprocalVariable + +let pbym = (pm |> matchProb [('m', true)]) * (pbm |> matchProb [('b',true);('m',true)]) , (pm |> matchProb [('m', false)]) * (pbm |> matchProb [('b',true);('m',false)]) +let pbysym = (pm |> matchProb [('m', true)]) * (pbm |> matchProb [('b',true);('m',true)]) * (psm |> matchProb [('s',true);('m',true)]), + (pm |> matchProb [('m', false)]) * (pbm |> matchProb [('b',true);('m',false)]) * (psm |> matchProb [('s',true);('m',false)]) + + + + +let ps = [Prior(('s',true), 0.3)] |> completeReciprocalVariable +let pr = [Prior(('r',true), 0.2)] |> completeReciprocalVariable +let pwsr = [TwoD(('w',true), ('s',true), ('r',true), 0.9); TwoD(('w',true), ('s',true), ('r',false), 0.7); + TwoD(('w',true), ('s',false), ('r',true), 0.8); TwoD(('w',true), ('s',false), ('r',false), 0.1); ] |> completeReciprocalVariable + +let pwyr = (pr |> matchProb [('r', true)]) * + ((pwsr |> matchProb [('r',true);('w',true);('s',true)]) * (ps |> matchProb [('s',true)]) + + (pwsr |> matchProb [('r',true);('w',true);('s',false)]) * (ps |> matchProb [('s',false)])) + + +[] +let main argv = + + printfn "%A" pwyr + 0 // return an integer exit code diff --git a/hw6/hw6.fsproj b/hw6/hw6.fsproj new file mode 100644 index 0000000..abb7781 --- /dev/null +++ b/hw6/hw6.fsproj @@ -0,0 +1,62 @@ + + + + + Debug + AnyCPU + 2.0 + 09058fa2-2e33-4839-beb2-26e0f0cf261f + Exe + hw6 + hw6 + v4.5 + hw6 + + + true + full + false + false + bin\Debug\ + DEBUG;TRACE + 3 + AnyCPU + bin\Debug\hw6.XML + true + + + pdbonly + true + true + bin\Release\ + TRACE + 3 + AnyCPU + bin\Release\hw6.XML + true + + + + + True + + + + + + + + + + + 11 + + + + \ No newline at end of file diff --git a/hw6/hw6.sln b/hw6/hw6.sln new file mode 100644 index 0000000..c1aae8d --- /dev/null +++ b/hw6/hw6.sln @@ -0,0 +1,26 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "hw6", "hw6.fsproj", "{09058FA2-2E33-4839-BEB2-26E0F0CF261F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "hw6cs", "..\hw6cs\hw6cs.csproj", "{266F814D-56C6-4BF2-8A8B-F6700E6EA920}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {09058FA2-2E33-4839-BEB2-26E0F0CF261F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {09058FA2-2E33-4839-BEB2-26E0F0CF261F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {09058FA2-2E33-4839-BEB2-26E0F0CF261F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {09058FA2-2E33-4839-BEB2-26E0F0CF261F}.Release|Any CPU.Build.0 = Release|Any CPU + {266F814D-56C6-4BF2-8A8B-F6700E6EA920}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {266F814D-56C6-4BF2-8A8B-F6700E6EA920}.Debug|Any CPU.Build.0 = Debug|Any CPU + {266F814D-56C6-4BF2-8A8B-F6700E6EA920}.Release|Any CPU.ActiveCfg = Release|Any CPU + {266F814D-56C6-4BF2-8A8B-F6700E6EA920}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/hw6cs/App.config b/hw6cs/App.config new file mode 100644 index 0000000..54dde17 --- /dev/null +++ b/hw6cs/App.config @@ -0,0 +1,27 @@ + + + + + + + +
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hw6cs/Database1.sdf b/hw6cs/Database1.sdf new file mode 100644 index 0000000..84ebff7 Binary files /dev/null and b/hw6cs/Database1.sdf differ diff --git a/hw6cs/Model1.Context.cs b/hw6cs/Model1.Context.cs new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/hw6cs/Model1.Context.cs @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/hw6cs/Model1.Context.tt b/hw6cs/Model1.Context.tt new file mode 100644 index 0000000..71c7137 --- /dev/null +++ b/hw6cs/Model1.Context.tt @@ -0,0 +1,735 @@ +<#@ template language="C#" debug="false" hostspecific="true"#> +<#@ include file="EF.Utility.CS.ttinclude"#><#@ + output extension=".cs"#><# + +const string inputFile = @"Model1.edmx"; +var textTransform = DynamicTextTransformation.Create(this); +var code = new CodeGenerationTools(this); +var ef = new MetadataTools(this); +var typeMapper = new TypeMapper(code, ef, textTransform.Errors); +var loader = new EdmMetadataLoader(textTransform.Host, textTransform.Errors); +var itemCollection = loader.CreateEdmItemCollection(inputFile); +var modelNamespace = loader.GetModelNamespace(inputFile); +var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); + +var container = itemCollection.OfType().FirstOrDefault(); +if (container == null) +{ + return string.Empty; +} +#> +//------------------------------------------------------------------------------ +// +// <#=GetResourceString("Template_GeneratedCodeCommentLine1")#> +// +// <#=GetResourceString("Template_GeneratedCodeCommentLine2")#> +// <#=GetResourceString("Template_GeneratedCodeCommentLine3")#> +// +//------------------------------------------------------------------------------ + +<# + +var codeNamespace = code.VsNamespaceSuggestion(); +if (!String.IsNullOrEmpty(codeNamespace)) +{ +#> +namespace <#=code.EscapeNamespace(codeNamespace)#> +{ +<# + PushIndent(" "); +} + +#> +using System; +using System.Data.Entity; +using System.Data.Entity.Infrastructure; +<# +if (container.FunctionImports.Any()) +{ +#> +using System.Data.Objects; +using System.Data.Objects.DataClasses; +using System.Linq; +<# +} +#> + +<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext +{ + public <#=code.Escape(container)#>() + : base("name=<#=container.Name#>") + { +<# +if (!loader.IsLazyLoadingEnabled(container)) +{ +#> + this.Configuration.LazyLoadingEnabled = false; +<# +} +#> + } + + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + throw new UnintentionalCodeFirstException(); + } + +<# + foreach (var entitySet in container.BaseEntitySets.OfType()) + { +#> + <#=codeStringGenerator.DbSet(entitySet)#> +<# + } + + foreach (var edmFunction in container.FunctionImports) + { + WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: false); + } +#> +} +<# + +if (!String.IsNullOrEmpty(codeNamespace)) +{ + PopIndent(); +#> +} +<# +} +#> +<#+ + +private void WriteFunctionImport(TypeMapper typeMapper, CodeStringGenerator codeStringGenerator, EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) +{ + if (typeMapper.IsComposable(edmFunction)) + { +#> + + [EdmFunction("<#=edmFunction.NamespaceName#>", "<#=edmFunction.Name#>")] + <#=codeStringGenerator.ComposableFunctionMethod(edmFunction, modelNamespace)#> + { +<#+ + codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter); +#> + <#=codeStringGenerator.ComposableCreateQuery(edmFunction, modelNamespace)#> + } +<#+ + } + else + { +#> + + <#=codeStringGenerator.FunctionMethod(edmFunction, modelNamespace, includeMergeOption)#> + { +<#+ + codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter); +#> + <#=codeStringGenerator.ExecuteFunction(edmFunction, modelNamespace, includeMergeOption)#> + } +<#+ + if (typeMapper.GenerateMergeOptionFunction(edmFunction, includeMergeOption)) + { + WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: true); + } + } +} + +public void WriteFunctionParameter(string name, string isNotNull, string notNullInit, string nullInit) +{ +#> + var <#=name#> = <#=isNotNull#> ? + <#=notNullInit#> : + <#=nullInit#>; + +<#+ +} + +public const string TemplateId = "CSharp_DbContext_Context_EF5"; + +public class CodeStringGenerator +{ + private readonly CodeGenerationTools _code; + private readonly TypeMapper _typeMapper; + private readonly MetadataTools _ef; + + public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(typeMapper, "typeMapper"); + ArgumentNotNull(ef, "ef"); + + _code = code; + _typeMapper = typeMapper; + _ef = ef; + } + + public string Property(EdmProperty edmProperty) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + Accessibility.ForProperty(edmProperty), + _typeMapper.GetTypeName(edmProperty.TypeUsage), + _code.Escape(edmProperty), + _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), + _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); + } + + public string NavigationProperty(NavigationProperty navigationProperty) + { + var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType()); + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)), + navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType, + _code.Escape(navigationProperty), + _code.SpaceAfter(Accessibility.ForGetter(navigationProperty)), + _code.SpaceAfter(Accessibility.ForSetter(navigationProperty))); + } + + public string AccessibilityAndVirtual(string accessibility) + { + return accessibility + (accessibility != "private" ? " virtual" : ""); + } + + public string EntityClassOpening(EntityType entity) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1}partial class {2}{3}", + Accessibility.ForType(entity), + _code.SpaceAfter(_code.AbstractOption(entity)), + _code.Escape(entity), + _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))); + } + + public string EnumOpening(SimpleType enumType) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} enum {1} : {2}", + Accessibility.ForType(enumType), + _code.Escape(enumType), + _code.Escape(_typeMapper.UnderlyingClrType(enumType))); + } + + public void WriteFunctionParameters(EdmFunction edmFunction, Action writeParameter) + { + var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable)) + { + var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"; + var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")"; + var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + parameter.RawClrTypeName + "))"; + writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); + } + } + + public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "{0} IQueryable<{1}> {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + _code.Escape(edmFunction), + string.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray())); + } + + public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});", + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + edmFunction.NamespaceName, + edmFunction.Name, + string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), + _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))); + } + + public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var paramList = String.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray()); + if (includeMergeOption) + { + paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption"; + } + + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + _code.Escape(edmFunction), + paramList); + } + + public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())); + if (includeMergeOption) + { + callParams = ", mergeOption" + callParams; + } + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});", + returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + edmFunction.Name, + callParams); + } + + public string DbSet(EntitySet entitySet) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} DbSet<{1}> {2} {{ get; set; }}", + Accessibility.ForReadOnlyProperty(entitySet), + _typeMapper.GetTypeName(entitySet.ElementType), + _code.Escape(entitySet)); + } + + public string UsingDirectives(bool inHeader, bool includeCollections = true) + { + return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion()) + ? string.Format( + CultureInfo.InvariantCulture, + "{0}using System;{1}" + + "{2}", + inHeader ? Environment.NewLine : "", + includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "", + inHeader ? "" : Environment.NewLine) + : ""; + } +} + +public class TypeMapper +{ + private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"; + + private readonly System.Collections.IList _errors; + private readonly CodeGenerationTools _code; + private readonly MetadataTools _ef; + + public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(ef, "ef"); + ArgumentNotNull(errors, "errors"); + + _code = code; + _ef = ef; + _errors = errors; + } + + public string GetTypeName(TypeUsage typeUsage) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null); + } + + public string GetTypeName(EdmType edmType) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: null); + } + + public string GetTypeName(TypeUsage typeUsage, string modelNamespace) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); + } + + public string GetTypeName(EdmType edmType, string modelNamespace) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace); + } + + public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace) + { + if (edmType == null) + { + return null; + } + + var collectionType = edmType as CollectionType; + if (collectionType != null) + { + return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace)); + } + + var typeName = _code.Escape(edmType.MetadataProperties + .Where(p => p.Name == ExternalTypeNameAttributeName) + .Select(p => (string)p.Value) + .FirstOrDefault()) + ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? + _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : + _code.Escape(edmType)); + + if (edmType is StructuralType) + { + return typeName; + } + + if (edmType is SimpleType) + { + var clrType = UnderlyingClrType(edmType); + if (!IsEnumType(edmType)) + { + typeName = _code.Escape(clrType); + } + + return clrType.IsValueType && isNullable == true ? + String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) : + typeName; + } + + throw new ArgumentException("edmType"); + } + + public Type UnderlyingClrType(EdmType edmType) + { + ArgumentNotNull(edmType, "edmType"); + + var primitiveType = edmType as PrimitiveType; + if (primitiveType != null) + { + return primitiveType.ClrEquivalentType; + } + + if (IsEnumType(edmType)) + { + return GetEnumUnderlyingType(edmType).ClrEquivalentType; + } + + return typeof(object); + } + + public object GetEnumMemberValue(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var valueProperty = enumMember.GetType().GetProperty("Value"); + return valueProperty == null ? null : valueProperty.GetValue(enumMember, null); + } + + public string GetEnumMemberName(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var nameProperty = enumMember.GetType().GetProperty("Name"); + return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null); + } + + public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var membersProperty = enumType.GetType().GetProperty("Members"); + return membersProperty != null + ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null) + : Enumerable.Empty(); + } + + public bool EnumIsFlags(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var isFlagsProperty = enumType.GetType().GetProperty("IsFlags"); + return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null); + } + + public bool IsEnumType(GlobalItem edmType) + { + ArgumentNotNull(edmType, "edmType"); + + return edmType.GetType().Name == "EnumType"; + } + + public PrimitiveType GetEnumUnderlyingType(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null); + } + + public string CreateLiteral(object value) + { + if (value == null || value.GetType() != typeof(TimeSpan)) + { + return _code.CreateLiteral(value); + } + + return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks); + } + + public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable types, string sourceFile) + { + ArgumentNotNull(types, "types"); + ArgumentNotNull(sourceFile, "sourceFile"); + + var hash = new HashSet(StringComparer.InvariantCultureIgnoreCase); + if (types.Any(item => !hash.Add(item))) + { + _errors.Add( + new CompilerError(sourceFile, -1, -1, "6023", + String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict")))); + return false; + } + return true; + } + + public IEnumerable GetEnumItemsToGenerate(IEnumerable itemCollection) + { + return GetItemsToGenerate(itemCollection) + .Where(e => IsEnumType(e)); + } + + public IEnumerable GetItemsToGenerate(IEnumerable itemCollection) where T: EdmType + { + return itemCollection + .OfType() + .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) + .OrderBy(i => i.Name); + } + + public IEnumerable GetAllGlobalItems(IEnumerable itemCollection) + { + return itemCollection + .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) + .Select(g => GetGlobalItemName(g)); + } + + public string GetGlobalItemName(GlobalItem item) + { + if (item is EdmType) + { + return ((EdmType)item).Name; + } + else + { + return ((EntityContainer)item).Name; + } + } + + public IEnumerable GetSimpleProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetSimpleProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetPropertiesWithDefaultValues(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetPropertiesWithDefaultValues(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type); + } + + public IEnumerable GetCollectionNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); + } + + public FunctionParameter GetReturnParameter(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters"); + return returnParamsProperty == null + ? edmFunction.ReturnParameter + : ((IEnumerable)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault(); + } + + public bool IsComposable(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute"); + return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null); + } + + public IEnumerable GetParameters(EdmFunction edmFunction) + { + return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + } + + public TypeUsage GetReturnType(EdmFunction edmFunction) + { + var returnParam = GetReturnParameter(edmFunction); + return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); + } + + public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) + { + var returnType = GetReturnType(edmFunction); + return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; + } +} + +public class EdmMetadataLoader +{ + private readonly IDynamicHost _host; + private readonly System.Collections.IList _errors; + + public EdmMetadataLoader(IDynamicHost host, System.Collections.IList errors) + { + ArgumentNotNull(host, "host"); + ArgumentNotNull(errors, "errors"); + + _host = host; + _errors = errors; + } + + public IEnumerable CreateEdmItemCollection(string sourcePath) + { + ArgumentNotNull(sourcePath, "sourcePath"); + + if (!ValidateInputPath(sourcePath)) + { + return new EdmItemCollection(); + } + + var schemaElement = LoadRootElement(_host.ResolvePath(sourcePath)); + if (schemaElement != null) + { + using (var reader = schemaElement.CreateReader()) + { + IList errors; + var itemCollection = MetadataItemCollectionFactory.CreateEdmItemCollection(new[] { reader }, out errors); + + ProcessErrors(errors, sourcePath); + + return itemCollection; + } + } + return new EdmItemCollection(); + } + + public string GetModelNamespace(string sourcePath) + { + ArgumentNotNull(sourcePath, "sourcePath"); + + if (!ValidateInputPath(sourcePath)) + { + return string.Empty; + } + + var model = LoadRootElement(_host.ResolvePath(sourcePath)); + if (model == null) + { + return string.Empty; + } + + var attribute = model.Attribute("Namespace"); + return attribute != null ? attribute.Value : ""; + } + + private bool ValidateInputPath(string sourcePath) + { + if (sourcePath == "$" + "edmxInputFile" + "$") + { + _errors.Add( + new CompilerError(_host.TemplateFile ?? sourcePath, 0, 0, string.Empty, + GetResourceString("Template_ReplaceVsItemTemplateToken"))); + return false; + } + + return true; + } + + public XElement LoadRootElement(string sourcePath) + { + ArgumentNotNull(sourcePath, "sourcePath"); + + var root = XElement.Load(sourcePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo); + return root.Elements() + .Where(e => e.Name.LocalName == "Runtime") + .Elements() + .Where(e => e.Name.LocalName == "ConceptualModels") + .Elements() + .Where(e => e.Name.LocalName == "Schema") + .FirstOrDefault() + ?? root; + } + + private void ProcessErrors(IEnumerable errors, string sourceFilePath) + { + foreach (var error in errors) + { + _errors.Add( + new CompilerError( + error.SchemaLocation ?? sourceFilePath, + error.Line, + error.Column, + error.ErrorCode.ToString(CultureInfo.InvariantCulture), + error.Message) + { + IsWarning = error.Severity == EdmSchemaErrorSeverity.Warning + }); + } + } + + public bool IsLazyLoadingEnabled(EntityContainer container) + { + string lazyLoadingAttributeValue; + var lazyLoadingAttributeName = MetadataConstants.EDM_ANNOTATION_09_02 + ":LazyLoadingEnabled"; + bool isLazyLoading; + return !MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, out lazyLoadingAttributeValue) + || !bool.TryParse(lazyLoadingAttributeValue, out isLazyLoading) + || isLazyLoading; + } +} + +public static void ArgumentNotNull(T arg, string name) where T : class +{ + if (arg == null) + { + throw new ArgumentNullException(name); + } +} + +private static readonly Lazy ResourceManager = + new Lazy( + () => new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(MetadataItemCollectionFactory).Assembly), isThreadSafe: true); + +public static string GetResourceString(string resourceName) +{ + ArgumentNotNull(resourceName, "resourceName"); + + return ResourceManager.Value.GetString(resourceName, null); +} + +#> \ No newline at end of file diff --git a/hw6cs/Model1.Designer.cs b/hw6cs/Model1.Designer.cs new file mode 100644 index 0000000..49e8c59 --- /dev/null +++ b/hw6cs/Model1.Designer.cs @@ -0,0 +1,4 @@ +// Default code generation is disabled for model 'C:\Users\poprhythm\Documents\code\Coursera_BigData\hw6cs\Model1.edmx'. +// To enable default code generation, change the value of the 'Code Generation Strategy' designer +// property to an alternate value. This property is available in the Properties Window when the model is +// open in the designer. \ No newline at end of file diff --git a/hw6cs/Model1.cs b/hw6cs/Model1.cs new file mode 100644 index 0000000..c370fb0 --- /dev/null +++ b/hw6cs/Model1.cs @@ -0,0 +1,9 @@ +//------------------------------------------------------------------------------ +// +// This code was generated from a template. +// +// Manual changes to this file may cause unexpected behavior in your application. +// Manual changes to this file will be overwritten if the code is regenerated. +// +//------------------------------------------------------------------------------ + diff --git a/hw6cs/Model1.edmx b/hw6cs/Model1.edmx new file mode 100644 index 0000000..713bad2 --- /dev/null +++ b/hw6cs/Model1.edmx @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw6cs/Model1.edmx.diagram b/hw6cs/Model1.edmx.diagram new file mode 100644 index 0000000..b30b04d --- /dev/null +++ b/hw6cs/Model1.edmx.diagram @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/hw6cs/Model1.tt b/hw6cs/Model1.tt new file mode 100644 index 0000000..4e45e93 --- /dev/null +++ b/hw6cs/Model1.tt @@ -0,0 +1,845 @@ +<#@ template language="C#" debug="false" hostspecific="true"#> +<#@ include file="EF.Utility.CS.ttinclude"#><#@ + output extension=".cs"#><# + +const string inputFile = @"Model1.edmx"; +var textTransform = DynamicTextTransformation.Create(this); +var code = new CodeGenerationTools(this); +var ef = new MetadataTools(this); +var typeMapper = new TypeMapper(code, ef, textTransform.Errors); +var fileManager = EntityFrameworkTemplateFileManager.Create(this); +var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); +var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); + +if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile)) +{ + return string.Empty; +} + +WriteHeader(codeStringGenerator, fileManager); + +foreach (var entity in typeMapper.GetItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(entity.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false)#> +<#=codeStringGenerator.EntityClassOpening(entity)#> +{ +<# + var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); + var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); + var complexProperties = typeMapper.GetComplexProperties(entity); + + if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any()) + { +#> + public <#=code.Escape(entity)#>() + { +<# + foreach (var edmProperty in propertiesWithDefaultValues) + { +#> + this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>; +<# + } + + foreach (var navigationProperty in collectionNavigationProperties) + { +#> + this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>(); +<# + } + + foreach (var complexProperty in complexProperties) + { +#> + this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>(); +<# + } +#> + } + +<# + } + + var simpleProperties = typeMapper.GetSimpleProperties(entity); + if (simpleProperties.Any()) + { + foreach (var edmProperty in simpleProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } + + if (complexProperties.Any()) + { +#> + +<# + foreach(var complexProperty in complexProperties) + { +#> + <#=codeStringGenerator.Property(complexProperty)#> +<# + } + } + + var navigationProperties = typeMapper.GetNavigationProperties(entity); + if (navigationProperties.Any()) + { +#> + +<# + foreach (var navigationProperty in navigationProperties) + { +#> + <#=codeStringGenerator.NavigationProperty(navigationProperty)#> +<# + } + } +#> +} +<# + EndNamespace(code); +} + +foreach (var complex in typeMapper.GetItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(complex.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#> +<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#> +{ +<# + var complexProperties = typeMapper.GetComplexProperties(complex); + var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(complex); + + if (propertiesWithDefaultValues.Any() || complexProperties.Any()) + { +#> + public <#=code.Escape(complex)#>() + { +<# + foreach (var edmProperty in propertiesWithDefaultValues) + { +#> + this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>; +<# + } + + foreach (var complexProperty in complexProperties) + { +#> + this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>(); +<# + } +#> + } + +<# + } + + var simpleProperties = typeMapper.GetSimpleProperties(complex); + if (simpleProperties.Any()) + { + foreach(var edmProperty in simpleProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } + + if (complexProperties.Any()) + { +#> + +<# + foreach(var edmProperty in complexProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } +#> +} +<# + EndNamespace(code); +} + +foreach (var enumType in typeMapper.GetEnumItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(enumType.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#> +<# + if (typeMapper.EnumIsFlags(enumType)) + { +#> +[Flags] +<# + } +#> +<#=codeStringGenerator.EnumOpening(enumType)#> +{ +<# + var foundOne = false; + + foreach (MetadataItem member in typeMapper.GetEnumMembers(enumType)) + { + foundOne = true; +#> + <#=code.Escape(typeMapper.GetEnumMemberName(member))#> = <#=typeMapper.GetEnumMemberValue(member)#>, +<# + } + + if (foundOne) + { + this.GenerationEnvironment.Remove(this.GenerationEnvironment.Length - 3, 1); + } +#> +} +<# + EndNamespace(code); +} + +fileManager.Process(); + +#> +<#+ + +public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager) +{ + fileManager.StartHeader(); +#> +//------------------------------------------------------------------------------ +// +// <#=GetResourceString("Template_GeneratedCodeCommentLine1")#> +// +// <#=GetResourceString("Template_GeneratedCodeCommentLine2")#> +// <#=GetResourceString("Template_GeneratedCodeCommentLine3")#> +// +//------------------------------------------------------------------------------ +<#=codeStringGenerator.UsingDirectives(inHeader: true)#> +<#+ + fileManager.EndBlock(); +} + +public void BeginNamespace(CodeGenerationTools code) +{ + var codeNamespace = code.VsNamespaceSuggestion(); + if (!String.IsNullOrEmpty(codeNamespace)) + { +#> +namespace <#=code.EscapeNamespace(codeNamespace)#> +{ +<#+ + PushIndent(" "); + } +} + +public void EndNamespace(CodeGenerationTools code) +{ + if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion())) + { + PopIndent(); +#> +} +<#+ + } +} + +public const string TemplateId = "CSharp_DbContext_Types_EF5"; + +public class CodeStringGenerator +{ + private readonly CodeGenerationTools _code; + private readonly TypeMapper _typeMapper; + private readonly MetadataTools _ef; + + public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(typeMapper, "typeMapper"); + ArgumentNotNull(ef, "ef"); + + _code = code; + _typeMapper = typeMapper; + _ef = ef; + } + + public string Property(EdmProperty edmProperty) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + Accessibility.ForProperty(edmProperty), + _typeMapper.GetTypeName(edmProperty.TypeUsage), + _code.Escape(edmProperty), + _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), + _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); + } + + public string NavigationProperty(NavigationProperty navigationProperty) + { + var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType()); + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)), + navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType, + _code.Escape(navigationProperty), + _code.SpaceAfter(Accessibility.ForGetter(navigationProperty)), + _code.SpaceAfter(Accessibility.ForSetter(navigationProperty))); + } + + public string AccessibilityAndVirtual(string accessibility) + { + return accessibility + (accessibility != "private" ? " virtual" : ""); + } + + public string EntityClassOpening(EntityType entity) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1}partial class {2}{3}", + Accessibility.ForType(entity), + _code.SpaceAfter(_code.AbstractOption(entity)), + _code.Escape(entity), + _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))); + } + + public string EnumOpening(SimpleType enumType) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} enum {1} : {2}", + Accessibility.ForType(enumType), + _code.Escape(enumType), + _code.Escape(_typeMapper.UnderlyingClrType(enumType))); + } + + public void WriteFunctionParameters(EdmFunction edmFunction, Action writeParameter) + { + var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable)) + { + var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"; + var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")"; + var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + parameter.RawClrTypeName + "))"; + writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); + } + } + + public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "{0} IQueryable<{1}> {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + _code.Escape(edmFunction), + string.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray())); + } + + public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});", + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + edmFunction.NamespaceName, + edmFunction.Name, + string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), + _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))); + } + + public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var paramList = String.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray()); + if (includeMergeOption) + { + paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption"; + } + + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + _code.Escape(edmFunction), + paramList); + } + + public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())); + if (includeMergeOption) + { + callParams = ", mergeOption" + callParams; + } + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});", + returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + edmFunction.Name, + callParams); + } + + public string DbSet(EntitySet entitySet) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} DbSet<{1}> {2} {{ get; set; }}", + Accessibility.ForReadOnlyProperty(entitySet), + _typeMapper.GetTypeName(entitySet.ElementType), + _code.Escape(entitySet)); + } + + public string UsingDirectives(bool inHeader, bool includeCollections = true) + { + return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion()) + ? string.Format( + CultureInfo.InvariantCulture, + "{0}using System;{1}" + + "{2}", + inHeader ? Environment.NewLine : "", + includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "", + inHeader ? "" : Environment.NewLine) + : ""; + } +} + +public class TypeMapper +{ + private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"; + + private readonly System.Collections.IList _errors; + private readonly CodeGenerationTools _code; + private readonly MetadataTools _ef; + + public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(ef, "ef"); + ArgumentNotNull(errors, "errors"); + + _code = code; + _ef = ef; + _errors = errors; + } + + public string GetTypeName(TypeUsage typeUsage) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null); + } + + public string GetTypeName(EdmType edmType) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: null); + } + + public string GetTypeName(TypeUsage typeUsage, string modelNamespace) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); + } + + public string GetTypeName(EdmType edmType, string modelNamespace) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace); + } + + public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace) + { + if (edmType == null) + { + return null; + } + + var collectionType = edmType as CollectionType; + if (collectionType != null) + { + return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace)); + } + + var typeName = _code.Escape(edmType.MetadataProperties + .Where(p => p.Name == ExternalTypeNameAttributeName) + .Select(p => (string)p.Value) + .FirstOrDefault()) + ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? + _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : + _code.Escape(edmType)); + + if (edmType is StructuralType) + { + return typeName; + } + + if (edmType is SimpleType) + { + var clrType = UnderlyingClrType(edmType); + if (!IsEnumType(edmType)) + { + typeName = _code.Escape(clrType); + } + + return clrType.IsValueType && isNullable == true ? + String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) : + typeName; + } + + throw new ArgumentException("edmType"); + } + + public Type UnderlyingClrType(EdmType edmType) + { + ArgumentNotNull(edmType, "edmType"); + + var primitiveType = edmType as PrimitiveType; + if (primitiveType != null) + { + return primitiveType.ClrEquivalentType; + } + + if (IsEnumType(edmType)) + { + return GetEnumUnderlyingType(edmType).ClrEquivalentType; + } + + return typeof(object); + } + + public object GetEnumMemberValue(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var valueProperty = enumMember.GetType().GetProperty("Value"); + return valueProperty == null ? null : valueProperty.GetValue(enumMember, null); + } + + public string GetEnumMemberName(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var nameProperty = enumMember.GetType().GetProperty("Name"); + return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null); + } + + public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var membersProperty = enumType.GetType().GetProperty("Members"); + return membersProperty != null + ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null) + : Enumerable.Empty(); + } + + public bool EnumIsFlags(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var isFlagsProperty = enumType.GetType().GetProperty("IsFlags"); + return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null); + } + + public bool IsEnumType(GlobalItem edmType) + { + ArgumentNotNull(edmType, "edmType"); + + return edmType.GetType().Name == "EnumType"; + } + + public PrimitiveType GetEnumUnderlyingType(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null); + } + + public string CreateLiteral(object value) + { + if (value == null || value.GetType() != typeof(TimeSpan)) + { + return _code.CreateLiteral(value); + } + + return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks); + } + + public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable types, string sourceFile) + { + ArgumentNotNull(types, "types"); + ArgumentNotNull(sourceFile, "sourceFile"); + + var hash = new HashSet(StringComparer.InvariantCultureIgnoreCase); + if (types.Any(item => !hash.Add(item))) + { + _errors.Add( + new CompilerError(sourceFile, -1, -1, "6023", + String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict")))); + return false; + } + return true; + } + + public IEnumerable GetEnumItemsToGenerate(IEnumerable itemCollection) + { + return GetItemsToGenerate(itemCollection) + .Where(e => IsEnumType(e)); + } + + public IEnumerable GetItemsToGenerate(IEnumerable itemCollection) where T: EdmType + { + return itemCollection + .OfType() + .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) + .OrderBy(i => i.Name); + } + + public IEnumerable GetAllGlobalItems(IEnumerable itemCollection) + { + return itemCollection + .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) + .Select(g => GetGlobalItemName(g)); + } + + public string GetGlobalItemName(GlobalItem item) + { + if (item is EdmType) + { + return ((EdmType)item).Name; + } + else + { + return ((EntityContainer)item).Name; + } + } + + public IEnumerable GetSimpleProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetSimpleProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetPropertiesWithDefaultValues(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetPropertiesWithDefaultValues(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type); + } + + public IEnumerable GetCollectionNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); + } + + public FunctionParameter GetReturnParameter(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters"); + return returnParamsProperty == null + ? edmFunction.ReturnParameter + : ((IEnumerable)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault(); + } + + public bool IsComposable(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute"); + return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null); + } + + public IEnumerable GetParameters(EdmFunction edmFunction) + { + return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + } + + public TypeUsage GetReturnType(EdmFunction edmFunction) + { + var returnParam = GetReturnParameter(edmFunction); + return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); + } + + public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) + { + var returnType = GetReturnType(edmFunction); + return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; + } +} + +public class EdmMetadataLoader +{ + private readonly IDynamicHost _host; + private readonly System.Collections.IList _errors; + + public EdmMetadataLoader(IDynamicHost host, System.Collections.IList errors) + { + ArgumentNotNull(host, "host"); + ArgumentNotNull(errors, "errors"); + + _host = host; + _errors = errors; + } + + public IEnumerable CreateEdmItemCollection(string sourcePath) + { + ArgumentNotNull(sourcePath, "sourcePath"); + + if (!ValidateInputPath(sourcePath)) + { + return new EdmItemCollection(); + } + + var schemaElement = LoadRootElement(_host.ResolvePath(sourcePath)); + if (schemaElement != null) + { + using (var reader = schemaElement.CreateReader()) + { + IList errors; + var itemCollection = MetadataItemCollectionFactory.CreateEdmItemCollection(new[] { reader }, out errors); + + ProcessErrors(errors, sourcePath); + + return itemCollection; + } + } + return new EdmItemCollection(); + } + + public string GetModelNamespace(string sourcePath) + { + ArgumentNotNull(sourcePath, "sourcePath"); + + if (!ValidateInputPath(sourcePath)) + { + return string.Empty; + } + + var model = LoadRootElement(_host.ResolvePath(sourcePath)); + if (model == null) + { + return string.Empty; + } + + var attribute = model.Attribute("Namespace"); + return attribute != null ? attribute.Value : ""; + } + + private bool ValidateInputPath(string sourcePath) + { + if (sourcePath == "$" + "edmxInputFile" + "$") + { + _errors.Add( + new CompilerError(_host.TemplateFile ?? sourcePath, 0, 0, string.Empty, + GetResourceString("Template_ReplaceVsItemTemplateToken"))); + return false; + } + + return true; + } + + public XElement LoadRootElement(string sourcePath) + { + ArgumentNotNull(sourcePath, "sourcePath"); + + var root = XElement.Load(sourcePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo); + return root.Elements() + .Where(e => e.Name.LocalName == "Runtime") + .Elements() + .Where(e => e.Name.LocalName == "ConceptualModels") + .Elements() + .Where(e => e.Name.LocalName == "Schema") + .FirstOrDefault() + ?? root; + } + + private void ProcessErrors(IEnumerable errors, string sourceFilePath) + { + foreach (var error in errors) + { + _errors.Add( + new CompilerError( + error.SchemaLocation ?? sourceFilePath, + error.Line, + error.Column, + error.ErrorCode.ToString(CultureInfo.InvariantCulture), + error.Message) + { + IsWarning = error.Severity == EdmSchemaErrorSeverity.Warning + }); + } + } + + public bool IsLazyLoadingEnabled(EntityContainer container) + { + string lazyLoadingAttributeValue; + var lazyLoadingAttributeName = MetadataConstants.EDM_ANNOTATION_09_02 + ":LazyLoadingEnabled"; + bool isLazyLoading; + return !MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, out lazyLoadingAttributeValue) + || !bool.TryParse(lazyLoadingAttributeValue, out isLazyLoading) + || isLazyLoading; + } +} + +public static void ArgumentNotNull(T arg, string name) where T : class +{ + if (arg == null) + { + throw new ArgumentNullException(name); + } +} + +private static readonly Lazy ResourceManager = + new Lazy( + () => new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(MetadataItemCollectionFactory).Assembly), isThreadSafe: true); + +public static string GetResourceString(string resourceName) +{ + ArgumentNotNull(resourceName, "resourceName"); + + return ResourceManager.Value.GetString(resourceName, null); +} + +#> \ No newline at end of file diff --git a/hw6cs/Program.cs b/hw6cs/Program.cs new file mode 100644 index 0000000..e68ecab --- /dev/null +++ b/hw6cs/Program.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Linq; + +namespace hw6cs +{ + public class Condition + { + public char Name { get; private set; } + public bool IsTrue { get; private set; } + + public Condition(char name, bool tf) + { + Name = name; + IsTrue = tf; + } + + public Condition Clone() { return new Condition(Name, IsTrue); } + public Condition Negate() { return new Condition(Name, !IsTrue); } + public bool Equals(Condition other) + { + return Name == other.Name && IsTrue == other.IsTrue; + } + } + + public class Variable + { + public double Probability { get; private set; } + public IEnumerable Conditions { get; private set; } + + public Variable(IEnumerable conditions, double probability) + { + Probability = probability; + Conditions = conditions; + } + + public Variable Negate() + { + return new Variable( + Conditions.Take(1).Select(c => c.Negate()) + .Concat(Conditions.Skip(1)), 1.0 - Probability); + } + + //public bool Join(Variable other, char condition) + //{ + + //} + } + + class Program + { + static void Main(string[] args) + { + //var pa = new List { new Variable(new[] { new Condition('a', true) }, .01) }; + //var pta = new List { + // new Variable(new[] { new Condition('t', true), new Condition('a', true) }, .05), + // new Variable(new[] { new Condition('t', true), new Condition('a', false) }, .01) }; + //var ps = new List { new Variable(new[] { new Condition('s', true) }, .50) }; + + //from ac in pa + //join tac in pta on ac.Join(tac, 'a') into ha + } + } + + public + + +} diff --git a/hw6cs/Properties/AssemblyInfo.cs b/hw6cs/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..332fb3d --- /dev/null +++ b/hw6cs/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("hw6cs")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("hw6cs")] +[assembly: AssemblyCopyright("Copyright © 2013")] +[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("2c3220cc-b3e5-4b3d-bacd-43393837a3cc")] + +// 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")] diff --git a/hw6cs/hw6cs.csproj b/hw6cs/hw6cs.csproj new file mode 100644 index 0000000..f572924 --- /dev/null +++ b/hw6cs/hw6cs.csproj @@ -0,0 +1,160 @@ + + + + + Debug + AnyCPU + {266F814D-56C6-4BF2-8A8B-F6700E6EA920} + Exe + Properties + hw6cs + hw6cs + v4.5 + 512 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\hw6\packages\EntityFramework.6.0.1\lib\net45\EntityFramework.dll + + + ..\hw6\packages\EntityFramework.6.0.1\lib\net45\EntityFramework.SqlServer.dll + + + ..\hw6\packages\EntityFramework.SqlServerCompact.6.0.1\lib\net45\EntityFramework.SqlServerCompact.dll + + + + + + + True + ..\hw6\packages\Microsoft.SqlServer.Compact.4.0.8876.1\lib\net40\System.Data.SqlServerCe.dll + + + + + + + + + + + + True + True + Model1.Context.tt + + + True + True + Model1.tt + + + True + True + Model1.edmx + + + + + + + + EntityModelCodeGenerator + Model1.Designer.cs + + + TextTemplatingFileGenerator + Model1.Context.cs + Model1.edmx + + + Model1.edmx + + + TextTemplatingFileGenerator + Model1.cs + Model1.edmx + + + + + + PreserveNewest + + + + + + + + False + Microsoft .NET Framework 4.5 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + SQL Server Compact 4.0 SP1 + true + + + + + + if not exist "$(TargetDir)x86" md "$(TargetDir)x86" + xcopy /s /y "$(SolutionDir)packages\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\x86\*.*" "$(TargetDir)x86" + if not exist "$(TargetDir)amd64" md "$(TargetDir)amd64" + xcopy /s /y "$(SolutionDir)packages\Microsoft.SqlServer.Compact.4.0.8876.1\NativeBinaries\amd64\*.*" "$(TargetDir)amd64" + + + \ No newline at end of file diff --git a/hw6cs/hw6sql.sql b/hw6cs/hw6sql.sql new file mode 100644 index 0000000..86e60da --- /dev/null +++ b/hw6cs/hw6sql.sql @@ -0,0 +1,95 @@ +--select [1] / ([0] + [1]) from +--( +--select ex_pwsr.r as v, sum(ex_pwsr.p * ex_pr.p * ex_ps.p)as p +--from ex_pwsr +-- inner join ex_pr on ex_pwsr.r = ex_pr.r +-- inner join ex_ps on ex_pwsr.s = ex_ps.s +--where +-- w = 1 +-- and ex_pwsr.s = 1 +--group by ex_pwsr.r +--) as s +--pivot (sum(p) for v in ([0],[1])) as pt + +declare @smoking bit; +declare @asia bit; +declare @xray bit; +declare @disponea bit; + +set @asia = 0; +set @smoking = 0; +set @xray = 1; +set @disponea = 0; + +-- tb +select '1.P(Tuber)', [1] / ([0] + [1]) from +( +select pta.t as t, sum(pta.p * pa.p * pelt.p * pxe.p * pls.p * ps.p * pbs.p * pdeb.p) as p +from pa, pta, pelt, pls, pxe, ps, pbs, pdeb +where + pa.a = pta.a and + pta.t = pelt.t and + pelt.e = pxe.e and + pelt.e = pdeb.e and + ps.s = pls.s and + pls.l = pelt.l and + ps.s = pbs.s and + pbs.b = pdeb.b + + --and pta.a = @asia + and ps.s = @smoking + and pxe.x = @xray + --and pdeb.d = @disponea +group by pta.t +) as s +pivot (sum(p) for t in ([0],[1])) as pt + +union + +-- lc +select '2.P(LungCancer)', [1] / ([0] + [1]) from +( +select pls.l as v, sum(pta.p * pa.p * pelt.p * pxe.p * pls.p * ps.p * pbs.p * pdeb.p) as p +from pa, pta, pelt, pls, pxe, ps, pbs, pdeb +where + pa.a = pta.a and + pta.t = pelt.t and + pelt.e = pxe.e and + pelt.e = pdeb.e and + ps.s = pls.s and + pls.l = pelt.l and + ps.s = pbs.s and + pbs.b = pdeb.b + + --and pta.a = @asia + and ps.s = @smoking + and pxe.x = @xray + --and pdeb.d = @disponea +group by pls.l +) as s +pivot (sum(p) for v in ([0],[1])) as pt + +union + +-- lc +select '3.P(Bronchitis)', [1] / ([0] + [1]) from +( +select pbs.b as v, sum(pta.p * pa.p * pelt.p * pxe.p * pls.p * ps.p * pbs.p * pdeb.p) as p +from pa, pta, pelt, pls, pxe, ps, pbs, pdeb +where + pa.a = pta.a and + pta.t = pelt.t and + pelt.e = pxe.e and + pelt.e = pdeb.e and + ps.s = pls.s and + pls.l = pelt.l and + ps.s = pbs.s and + pbs.b = pdeb.b + + --and pta.a = @asia + and ps.s = @smoking + and pxe.x = @xray + --and pdeb.d = @disponea +group by pbs.b +) as s +pivot (sum(p) for v in ([0],[1])) as pt \ No newline at end of file diff --git a/hw6cs/packages.config b/hw6cs/packages.config new file mode 100644 index 0000000..878791a --- /dev/null +++ b/hw6cs/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/hw7/gene.py b/hw7/gene.py new file mode 100644 index 0000000..345b7ba --- /dev/null +++ b/hw7/gene.py @@ -0,0 +1,17 @@ +import Orange + +train = Orange.data.Table("genestrain") #genestrain +blind = Orange.data.Table("genesblind") + +learner = Orange.classification.bayes.NaiveLearner() +classifier = learner(train) +classInt = {'CEU' : 0, 'GIH': 1, 'JPT': 2, 'ASW' : 3, 'YRI' : 4 } + +results = [str(classifier(d)) for d in blind] +intResults = [str(classInt[r]) for r in results] + +print ' '.join(intResults) + +#for d in blind: +# c = classifier(d) +# print "%10s" % (classifier(d)) diff --git a/hw7/genesblind.tab.zip b/hw7/genesblind.tab.zip new file mode 100644 index 0000000..12c6180 Binary files /dev/null and b/hw7/genesblind.tab.zip differ diff --git a/hw7/genestrain.tab.zip b/hw7/genestrain.tab.zip new file mode 100644 index 0000000..958e4d8 Binary files /dev/null and b/hw7/genestrain.tab.zip differ