예제 #1
0
        public static Annotation GetAnnotationDetail(Guid annotationId, SqlDataAccess sda)
        {
            Annotation returnValue = new Annotation();
            try
            {
                #region | SQL QUERY |
                string query = @"SELECT
                                    A.AnnotationId
                                    ,A.MimeType
                                    ,A.FileName
                                    ,A.DocumentBody
                                FROM
                                    Annotation A
                                WHERE
                                    A.AnnotationId = '{0}'";
                #endregion

                DataTable dt = sda.getDataTable(string.Format(query, annotationId));
                if (dt != null && dt.Rows.Count > 0)
                {
                    returnValue.AnnotationId = (Guid)dt.Rows[0]["AnnotationId"];
                    returnValue.MimeType = dt.Rows[0]["MimeType"] != DBNull.Value ? dt.Rows[0]["MimeType"].ToString() : string.Empty;
                    returnValue.FileName = dt.Rows[0]["FileName"] != DBNull.Value ? dt.Rows[0]["FileName"].ToString() : string.Empty;
                    returnValue.File = dt.Rows[0]["DocumentBody"] != DBNull.Value ? dt.Rows[0]["DocumentBody"].ToString() : string.Empty;
                }
            }
            catch (Exception)
            {

            }
            return returnValue;
        }
예제 #2
0
 internal WidgetActions(
     Annotation parent,
     PdfDirectObject baseObject
     )
     : base(parent, baseObject)
 {
 }
        /// <summary>
        /// Executes Sentiment and EntitiesMentioned analysis.
        /// </summary>
        public IOutcome<AnalysisResult> Analyze(StanfordCoreNLP pipeline, string text)
        {
            //Create annotated document
            Annotation doc = new Annotation(text);
            pipeline.annotate(doc);

            //Validate
            var sentences = doc.get(typeof(CoreAnnotations.SentencesAnnotation));

            if (sentences == null)           
                return Outcomes.Outcomes
                               .Failure<AnalysisResult>()
                               .WithMessage("No sentences detected.");

            //Analyze
            var result = new AnalysisResult()
            {
                Sentiment = GetSentiment((ArrayList)sentences),
                MentionedEntities = GetMentions(doc)
            };

            return Outcomes.Outcomes
                           .Success<AnalysisResult>()
                           .WithValue(result);
        }
예제 #4
0
        /// <summary>
        /// Prompts the user to edit an annotation.
        /// </summary>
        public Annotation ShowDialog(Session session, Annotation annotation, string caption)
        {
            if (caption != null)
            {
                this.Text = caption;
            }

            m_session = session;

            if (annotation == null)
            {
                annotation = new Annotation();
                annotation.AnnotationTime = DateTime.UtcNow;
                annotation.UserName = Environment.GetEnvironmentVariable("USERNAME");
                annotation.Message = "<insert your message here>";
            }

            AnnotationTimeDP.Value = annotation.AnnotationTime;
            UserNameTB.Text = annotation.UserName;
            CommentTB.Text = annotation.Message;

            if (ShowDialog() != DialogResult.OK)
            {
                return null;
            }

            annotation = new Annotation();
            annotation.AnnotationTime = AnnotationTimeDP.Value;
            annotation.UserName = UserNameTB.Text;
            annotation.Message = CommentTB.Text;

            return annotation;
        }
예제 #5
0
        private void AddToAnnotationCache(Annotation key)
        {
            if (_annotCache.ContainsKey(key))
                RemoveFromAnnotationCache(key);

            _annotCache.Add(key, AnnotationRendererFactory.Default.Create(key));
        }
예제 #6
0
 /// <summary>
 /// Create an android InnerClass annotation and attach it to the given provider.
 /// </summary>
 public static void AddInnerClassAnnotation(this IAnnotationProvider provider, string simpleName, AccessFlags accessFlags)
 {
     var annotation = new Annotation { Type = new ClassReference("dalvik/annotation/InnerClass"), Visibility = AnnotationVisibility.System };
     annotation.Arguments.Add(new AnnotationArgument("name", simpleName));
     annotation.Arguments.Add(new AnnotationArgument("accessFlags", (int)accessFlags));
     provider.Annotations.Add(annotation);
 }
예제 #7
0
        static void Main()
        {
            // Path to the folder with models extracted from `stanford-corenlp-3.7.0-models.jar`
            var jarRoot = @"..\..\..\..\paket-files\nlp.stanford.edu\stanford-corenlp-full-2016-10-31\models";

            // Text for processing
            var text = "Kosgi Santosh sent an email to Stanford University. He didn't get a reply.";

            // Annotation pipeline configuration
            var props = new Properties();
            props.setProperty("annotators", "tokenize, ssplit, pos, lemma, parse, ner,dcoref");
            props.setProperty("ner.useSUTime", "0");

            // We should change current directory, so StanfordCoreNLP could find all the model files automatically
            var curDir = Environment.CurrentDirectory;
            Directory.SetCurrentDirectory(jarRoot);
            var pipeline = new StanfordCoreNLP(props);
            Directory.SetCurrentDirectory(curDir);

            // Annotation
            var annotation = new Annotation(text);
            pipeline.annotate(annotation);

            // Result - Pretty Print
            using (var stream = new ByteArrayOutputStream())
            {
                pipeline.prettyPrint(annotation, new PrintWriter(stream));
                Console.WriteLine(stream.toString());
                stream.close();
            }
        }
예제 #8
0
 /// <summary>
 /// Creates a <c>Parameter</c> using the provided constructor
 /// and the XML annotation. The parameter produced contains all
 /// information related to the constructor parameter. It knows the
 /// name of the XML entity, as well as the type.
 /// </summary>
 /// <param name="method">
 /// this is the constructor the parameter exists in
 /// </param>
 /// <param name="label">
 /// represents the XML annotation for the contact
 /// </param>
 /// <returns>
 /// returns the parameter instantiated for the field
 /// </returns>
 public Parameter GetInstance(Constructor method, Annotation label, int index) {
    Constructor factory = GetConstructor(label);
    if(!factory.isAccessible()) {
       factory.setAccessible(true);
    }
    return (Parameter)factory.newInstance(method, label, index);
 }
예제 #9
0
 /// <summary>
 /// Create annotations for all included attributes
 /// </summary>
 public static void Create(AssemblyCompiler compiler, ICustomAttributeProvider attributeProvider,
                           IAnnotationProvider annotationProvider, DexTargetPackage targetPackage, bool customAttributesOnly = false)
 {
     if (!attributeProvider.HasCustomAttributes)
         return;
     var annotations = new List<Annotation>();
     foreach (var attr in attributeProvider.CustomAttributes)
     {
         var attributeType = attr.AttributeType.Resolve();
         if (!attributeType.HasIgnoreAttribute())
         {
             Create(compiler, attr, attributeType, annotations, targetPackage);
         }
     }
     if (annotations.Count > 0)
     {
         // Create 1 IAttributes annotation
         var attrsAnnotation = new Annotation { Visibility = AnnotationVisibility.Runtime };
         attrsAnnotation.Type = compiler.GetDot42InternalType("IAttributes").GetClassReference(targetPackage);
         attrsAnnotation.Arguments.Add(new AnnotationArgument("Attributes", annotations.ToArray()));
         annotationProvider.Annotations.Add(attrsAnnotation);
     }
     if (!customAttributesOnly)
     {
         // Add annotations specified using AnnotationAttribute
         foreach (var attr in attributeProvider.CustomAttributes.Where(IsAnnotationAttribute))
         {
             var annotationType = (TypeReference) attr.ConstructorArguments[0].Value;
             var annotationClass = annotationType.GetClassReference(targetPackage, compiler.Module);
             annotationProvider.Annotations.Add(new Annotation(annotationClass, AnnotationVisibility.Runtime));
         }
     }
 }
예제 #10
0
        public void StanfordCoreNlpDemoThatChangeCurrentDirectory()
        {
            const string Text = "Kosgi Santosh sent an email to Stanford University. He didn't get a reply.";

            // Annotation pipeline configuration
            var props = new Properties();
            props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
            props.setProperty("sutime.binders", "0");

            // we should change current directory so StanfordCoreNLP could find all the model files
            var curDir = Environment.CurrentDirectory;
            Directory.SetCurrentDirectory(Config.JarRoot);
            var pipeline = new edu.stanford.nlp.pipeline.StanfordCoreNLP(props);
            Directory.SetCurrentDirectory(curDir);

            // Annotation
            var annotation = new Annotation(Text);
            pipeline.annotate(annotation);
    
            // Result - Pretty Print
            using (var stream = new ByteArrayOutputStream())
            {
                pipeline.prettyPrint(annotation, new PrintWriter(stream));
                Console.WriteLine(stream.toString());
            }

            this.CustomAnnotationPrint(annotation);
        }
예제 #11
0
        /// <summary>
        /// Gets depeendencies from sentence.
        /// </summary>
        /// <param name="annotation"></param>
        /// <returns></returns>
        private NotenizerDependencies GetDepencencies(Annotation annotation)
        {
            Tree tree;
            NotenizerDependency dep;
            GrammaticalStructure gramStruct;
            NotenizerDependencies dependencies;
            NotenizerDependency nsubjComplement;
            TreebankLanguagePack treeBankLangPack;
            java.util.Collection typedDependencies;
            GrammaticalStructureFactory gramStructFact;

            tree = annotation.get(typeof(TreeCoreAnnotations.TreeAnnotation)) as Tree;
            treeBankLangPack = new PennTreebankLanguagePack();
            gramStructFact = treeBankLangPack.grammaticalStructureFactory();
            gramStruct = gramStructFact.newGrammaticalStructure(tree);
            typedDependencies = gramStruct.typedDependenciesCollapsed();
            dependencies = new NotenizerDependencies();

            foreach (TypedDependency typedDependencyLoop in (typedDependencies as java.util.ArrayList))
            {
                dep = new NotenizerDependency(typedDependencyLoop);
                dependencies.Add(dep);

                if (dep.Relation.IsNominalSubject())
                {
                    nsubjComplement = new NotenizerDependency(typedDependencyLoop);
                    nsubjComplement.TokenType = dep.TokenType == TokenType.Dependent ? TokenType.Governor : TokenType.Dependent;
                    dependencies.Add(nsubjComplement);
                }
            }

            return dependencies;
        }
예제 #12
0
        protected internal virtual Annotation VisitAnnotation(Annotation annotation)
        {
            if (annotation == null) return null;

             annotation.Declaration = Visit(annotation.Declaration);
             annotation.Argument = VisitValue(annotation.Argument);
             return annotation;
        }
        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        #region Constructors
        
        /// <summary>
        ///     Creates an instance of AnnotationUpdatedEventArgs with the
        ///     specified action and annotation.
        /// </summary>
        /// <param name="action">the action that was performed on an annotation</param>
        /// <param name="annotation">the annotation that was updated</param>
        public StoreContentChangedEventArgs(StoreContentAction action, Annotation annotation)
        {
            if (annotation == null)
                throw new ArgumentNullException("annotation");

            _action = action;
            _annotation = annotation;
        }
예제 #14
0
 internal TextBlock(int spanStart, int spanEnd, string type, string text, Annotation annotation)
 {
     mSpanStart = spanStart;
     mSpanEnd = spanEnd;
     mType = type;
     mText = text;
     mAnnotation = annotation;
 }
예제 #15
0
 public void AddAnnotation(Annotation annotation)
 {
     if (annotation != null)
     {
         Annotations.Add(annotation);
         if (this.AnnotationAdded != null)
             this.AnnotationAdded(annotation);
     }
 }
예제 #16
0
        public void TestAnnotateAddsToAnnotations()
        {
            var support = new AnnotationSupport();
            var annotation = new Annotation();

            support.Annotate(annotation);

            Assert.AreSame(annotation, support.Annotation<Annotation>());
        }
예제 #17
0
        public override void CreateAnnotations(DexTargetPackage targetPackage)
        {
            base.CreateAnnotations(targetPackage);

            if (Class == null)
                return;

            bool isBaseTypeGeneric = XType.BaseType != null && (XType.BaseType.IsGenericInstance || XType.BaseType.IsGenericParameter);
            bool containsGenericInterfaces = XType.Interfaces.Any(i => i.IsGenericInstance || i.IsGenericParameter);
            bool needsFieldAnnotation = !Class.IsSynthetic && Class.Fields.Count(p => !p.IsSynthetic && !p.IsStatic) > 1;
            
            bool needsAnnotation = Class.GenericInstanceFields.Count > 0 
                                || XType.GenericParameters.Count > 0 
                                || isBaseTypeGeneric 
                                || containsGenericInterfaces 
                                || needsFieldAnnotation;

            if (!needsAnnotation) return;

            var annType = Compiler.GetDot42InternalType(InternalConstants.TypeReflectionInfoAnnotation).GetClassReference(targetPackage);
            var annotation = new Annotation(annType, AnnotationVisibility.Runtime);

            if (Class.GenericInstanceFields.Count > 0)
            {
                    annotation.Arguments.Add(new AnnotationArgument(InternalConstants.TypeReflectionInfoGenericArgumentsFields,
                                             Class.GenericInstanceFields.Select(f=>f.Name).ToArray()));
            }

            if (XType.GenericParameters.Count > 0)
                annotation.Arguments.Add(new AnnotationArgument(InternalConstants.TypeReflectionInfoGenericArgumentCountField, XType.GenericParameters.Count));

            List<Annotation> definitions= new List<Annotation>();

            if (isBaseTypeGeneric)
                definitions.Add(AssemblyCompilerExtensions.GetGenericDefinitionAnnotationForType(
                                XType.BaseType, true, Compiler, targetPackage));

            foreach (var intf in XType.Interfaces)
            {
                if(!intf.IsGenericInstance && !intf.IsGenericParameter)
                    continue;
                definitions.Add(AssemblyCompilerExtensions.GetGenericDefinitionAnnotationForType(
                                                            intf, true, Compiler, targetPackage));
            }

            if(definitions.Count > 0)
                annotation.Arguments.Add(new AnnotationArgument(InternalConstants.TypeReflectionInfoGenericDefinitionsField, definitions.ToArray()));

            if (needsFieldAnnotation)
            {
                annotation.Arguments.Add(new AnnotationArgument(InternalConstants.TypeReflectionInfoFieldsField, 
                                         Class.Fields.Where(p=>!p.IsSynthetic && !p.IsStatic).Select(p=>p.Name).ToArray()));
            }

            Class.Annotations.Add(annotation);
        }
예제 #18
0
파일: NLP.cs 프로젝트: gbolinder/OTAP
 public static JObject ProcessText(string text)
 {
     var annotation = new Annotation(text);
     using (java.io.StringWriter writer = new java.io.StringWriter())
     {
         pipeline.annotate(annotation);
         pipeline.jsonPrint(annotation, writer);
         return JObject.Parse(writer.toString());
     }
 }
        private AnnotationBuilder(AnnotationType type, AnnotationSurfaceSize size, Guid toolId, int currentPage)
        {
            this.surfaceSize = size;
            this.type = type;

            this.annotation = new Annotation()
            {
                Type = type,
                Points = new List<AnnotationPoint>(),
                PageNumber = currentPage,
                ToolId = toolId
            };
        }
예제 #20
0
 /// <summary>
 /// This is used to determine if two annotations are equals based
 /// on the attributes of the annotation. The comparison done can
 /// ignore specific attributes, for instance the name attribute.
 /// </summary>
 /// <param name="left">
 /// this is the left side of the comparison done
 /// </param>
 /// <param name="right">
 /// this is the right side of the comparison done
 /// </param>
 /// <returns>
 /// this returns true if the annotations are equal
 /// </returns>
 public bool Equals(Annotation left, Annotation right) {
    Class type = left.annotationType();
    Method[] list = type.getDeclaredMethods();
    for(Method method : list) {
       if(!IsIgnore(method)) {
          Object value = method.invoke(left);
          Object other = method.invoke(right);
          if(!value.Equals(other)) {
             return false;
          }
       }
    }
    return true;
 }
        public virtual void SendServerSpan(Span span, int duration)
        {
            var annotation = new Annotation()
            {
                Host = zipkinEndpoint.GetEndpoint(serviceName),
                Duration = duration,  //duration is currently not supported by zipkin UI
                Timestamp = GetTimeStamp(),
                Value = zipkinCoreConstants.SERVER_SEND
            };

            span.Annotations.Add(annotation);

            spanCollector.Collect(span);
        }
예제 #22
0
        private string getAnnotation(string input)
        {
            Annotation annotation = new Annotation(input);
            pipeline.annotate(annotation);

            string result = "";
            using (var stream = new ByteArrayOutputStream())
            {
                pipeline.conllPrint(annotation, new PrintWriter(stream));
                result += stream.toString();
                stream.close();
            }
            return result;
        }
예제 #23
0
        // As the declaration may have been a reference, we can now resolve the argument because we know
        // the type from the declaration.
        protected internal override Annotation VisitAnnotation(Annotation annotation)
        {
            if (annotation == null) return null;

             Debug.Assert(!(annotation.Declaration is CapnpReference));

             var decl = annotation.Declaration as CapnpAnnotation;

             var genericDeclaration = annotation.Declaration as CapnpBoundGenericType;
             if (genericDeclaration != null)
             {
            decl = (CapnpAnnotation)genericDeclaration.OpenType;

            //// The annotation is declared within a generic type, so close that type.
            //argType = new CapnpClosedGenericType
            //{
            //   OpenType = genericDeclaration.OpenType,
            //   TypeParameters = genericDeclaration.ParentScope.TypeParameters,
            //   ParentScope = genericDeclaration.ParentScope.ParentScope
            //};
             }

             if (decl != null && annotation.Argument == null)
             {
            // todo: what abotu generics? is this even valid?
            Debug.Assert(decl.ArgumentType == CapnpPrimitive.Void);
            return annotation;
             }

             var v = annotation.Argument as UnresolvedValue;
             if (v == null) return annotation;

             var argType = decl.ArgumentType;
             if (genericDeclaration != null && argType is CapnpGenericParameter)
            argType = genericDeclaration.ResolveGenericParameter((CapnpGenericParameter)argType);

             // Now that we know the argument type, resolve the value.
             var resolvedValue = VisitValue(new UnresolvedValue(argType)
             {
            Position = -1, // todo
            RawData = v == null ? null : v.RawData
             });

             return new Annotation
             {
            Declaration = genericDeclaration == null ? (CapnpType)decl : genericDeclaration,
            Argument = resolvedValue
             };
        }
예제 #24
0
        /// <summary>
        /// Create an annotation for the given attribute
        /// </summary>
        private static void Create(AssemblyCompiler compiler, CustomAttribute attribute, TypeDefinition attributeType,
                                   List<Annotation> annotationList, DexTargetPackage targetPackage)
        {
            // Gets the mapping for the type of attribute
            var mapping = compiler.GetAttributeAnnotationType(attributeType);
            var ctorMap = mapping.CtorMap[attribute.Constructor.Resolve()];

            // Create annotation
            var annotation = new Annotation {Visibility = AnnotationVisibility.Runtime};
            annotation.Type = mapping.AnnotationInterfaceClass;

            // Add ctor arguments
            var argIndex = 0;
            foreach (var arg in attribute.ConstructorArguments)
            {
                var name = ctorMap.ArgumentGetters[argIndex].Name;
                annotation.Arguments.Add(CreateAnnotationArgument(name, arg.Type, arg.Value, targetPackage, compiler.Module));
                argIndex++;
            }

            // Add field values
            foreach (var arg in attribute.Fields)
            {
                var entry = mapping.FieldToGetMethodMap.First(x => x.Key.Name == arg.Name);
                var name = entry.Value.Name;
                annotation.Arguments.Add(CreateAnnotationArgument(name, arg.Argument.Type, arg.Argument.Value, targetPackage, compiler.Module));
            }

            // Add property values
            foreach (var arg in attribute.Properties)
            {
                if (mapping.PropertyToGetMethodMap.Keys.Any(x => x.Name == arg.Name))
                {
                    var entry = mapping.PropertyToGetMethodMap.First(x => x.Key.Name == arg.Name);
                    var name = entry.Value.Name;
                    annotation.Arguments.Add(CreateAnnotationArgument(name, arg.Argument.Type, arg.Argument.Value, targetPackage, compiler.Module));
                }
            }

            // Create attribute annotation
            var attrAnnotation = new Annotation { Visibility = AnnotationVisibility.Runtime };
            attrAnnotation.Type = compiler.GetDot42InternalType("IAttribute").GetClassReference(targetPackage);
            attrAnnotation.Arguments.Add(new AnnotationArgument("AttributeBuilder", ctorMap.Builder));
            attrAnnotation.Arguments.Add(new AnnotationArgument("AttributeType", attributeType.GetReference(targetPackage, compiler.Module)));
            attrAnnotation.Arguments.Add(new AnnotationArgument("Annotation", annotation));

            // Add annotation
            annotationList.Add(attrAnnotation);
        }
예제 #25
0
 protected override void ProcessDocument(Document document)
 {
     TextBlock[] textBlocks = document.GetAnnotatedBlocks(SRC_ANNOT_TYPE);
     foreach (TextBlock textBlock in textBlocks)
     {
         // do tokenization, add annotations to document
         mTokenizer.Text = textBlock.Text;
         for (RegexTokenizer.Enumerator e = (RegexTokenizer.Enumerator)mTokenizer.GetEnumerator(); e.MoveNext(); )
         {
             //Console.WriteLine("{0} {1} {2}", textBlock.SpanStart + e.CurrentTokenIdx, textBlock.SpanStart + e.CurrentTokenIdx + e.Current.Length - 1, e.Current);
             Annotation annot = new Annotation(textBlock.SpanStart + e.CurrentTokenIdx, textBlock.SpanStart + e.CurrentTokenIdx + e.Current.Length - 1, DEST_ANNOT_TYPE);
             document.AddAnnotation(annot);
         }
     }
 }
예제 #26
0
        public static MsCrmResult CreateAnnotation(Annotation note, IOrganizationService service)
        {
            MsCrmResult returnValue = new MsCrmResult();
            try
            {
                Entity ent = new Entity("annotation");

                if (note.AttachmentFile != null)
                {
                    ent["objectid"] = note.AttachmentFile;
                }

                if (!string.IsNullOrEmpty(note.Subject))
                {
                    ent["subject"] = note.Subject;
                }

                if (!string.IsNullOrEmpty(note.File))
                {
                    ent["documentbody"] = note.File;
                }

                if (!string.IsNullOrEmpty(note.FileName))
                {
                    ent["filename"] = note.FileName;
                }

                if (!string.IsNullOrEmpty(note.MimeType))
                {
                    ent["mimetype"] = note.MimeType;
                }

                if (!string.IsNullOrEmpty(note.Text))
                {
                    ent["notetext"] = note.Text;
                }

                returnValue.CrmId = service.Create(ent);
                returnValue.Success = true;
                returnValue.Result = "Dosya Ekleme başarıyla gerçekleşti.";
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Result = ex.Message;
            }
            return returnValue;
        }
예제 #27
0
        public static void CreateAssemblyTypes(AssemblyCompiler compiler, DexTargetPackage targetPackage,
                                               IEnumerable<TypeDefinition> reachableTypes)
        {
            var xAssemblyTypes = compiler.GetDot42InternalType("AssemblyTypes");
            var assemblyTypes = (ClassDefinition)xAssemblyTypes.GetClassReference(targetPackage);
            var entryAssembly = assemblyTypes.Fields.First(f => f.Name == "EntryAssembly");
            var iAssemblyTypes = compiler.GetDot42InternalType("IAssemblyTypes").GetClassReference(targetPackage);
            
            entryAssembly.Value = compiler.Assemblies.First().Name.Name;

            List<object> values = new List<object>();
            string prevAssemblyName = null;

            foreach (var type in reachableTypes.OrderBy(t => t.Module.Assembly.Name.Name)
                                               .ThenBy(t  => t.Namespace)
                                               .ThenBy(t =>  t.Name))
            {
                var assemblyName = type.module.Assembly.Name.Name;
                if (assemblyName == "dot42")
                {
                    // group all android types into virtual "android" assembly,
                    // so that MvvmCross can find all view-types.
                    // -- is this a hack?
                    if (type.Namespace.StartsWith("Android"))
                        assemblyName = "android";
                    else // ignore other types, these will get the "default" assembly.
                        continue;
                }

                if (prevAssemblyName != assemblyName)
                {
                    values.Add("!" + assemblyName); // we need some identification of assemblies.
                    prevAssemblyName = assemblyName;
                }

                // TODO: With compilationmode=all reachable types contains  <Module>
                //       this should be excluded earlier.
                if (type.FullName == "<Module>")
                    continue;

                var tRef = type.GetReference(targetPackage, compiler.Module) as ClassReference;    
                if(tRef != null) values.Add(tRef.Fullname);
            }

            var anno = new Annotation(iAssemblyTypes, AnnotationVisibility.Runtime,
                                      new AnnotationArgument("AssemblyTypeList", values.ToArray()));
            ((IAnnotationProvider)assemblyTypes).Annotations.Add(anno);
        }
예제 #28
0
파일: SspSyllabifier.cs 프로젝트: rmunn/cog
 protected override void SyllabifyUnmarkedAnnotation(Word word, Annotation<ShapeNode> ann, Shape newShape)
 {
     ShapeNode[] annNodes = word.Shape.GetNodes(ann.Span).ToArray();
     ShapeNode syllableStart = null;
     int prevSonority = -1, curSonority = -1;
     FeatureSymbol prevType = null;
     bool useMaximalOnset = false;
     foreach (ShapeNode node in annNodes)
     {
         FeatureSymbol curType = node.Type();
         ShapeNode nextNode = node.Next;
         int nextSonority = ann.Span.Contains(nextNode) ? GetSonority(nextNode) : -1;
         // stress markers indicate a syllable break
         if (syllableStart != null && node.StrRep().IsOneOf("ˈ", "ˌ"))
         {
             if (useMaximalOnset)
                 ProcessSyllableWithMaximalOnset(syllableStart, node.Prev, newShape);
             else
                 ProcessSyllable(syllableStart, node.Prev, newShape);
             useMaximalOnset = false;
             curSonority = -1;
             syllableStart = null;
         }
         else if (curSonority == -1)
         {
             curSonority = GetSonority(node);
         }
         else if ((curSonority < prevSonority && curSonority < nextSonority)
             || ((!_vowelsSameSonorityTautosyllabic || curType != CogFeatureSystem.VowelType || prevType != CogFeatureSystem.VowelType) && curSonority == prevSonority))
         {
             if (useMaximalOnset)
                 ProcessSyllableWithMaximalOnset(syllableStart, node.Prev, newShape);
             else
                 ProcessSyllable(syllableStart, node.Prev, newShape);
             useMaximalOnset = true;
             syllableStart = null;
         }
         if (syllableStart == null)
             syllableStart = node;
         prevType = curType;
         prevSonority = curSonority;
         curSonority = nextSonority;
     }
     if (useMaximalOnset)
         ProcessSyllableWithMaximalOnset(syllableStart, ann.Span.End, newShape);
     else
         ProcessSyllable(syllableStart, ann.Span.End, newShape);
 }
        private Annotation PrepareAnnotation()
        {
            var props = new Properties();
            props.put("pos.model", modelsDir + "pos-tagger/english-left3words/english-left3words-distsim.tagger");
            props.put("ner.model", modelsDir + "ner/english.conll.4class.distsim.crf.ser.gz");
            props.put("parse.model", modelsDir + "lexparser/englishPCFG.ser.gz");
            props.put("sutime.rules", modelsDir + "sutime/defs.sutime.txt, " + modelsDir + "sutime/english.sutime.txt");
            props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse");
            props.setProperty("sutime.binders", "0");
            props.setProperty("ner.useSUTime", "0");

            var pipeline = new StanfordCoreNLP(props);
            var annotatedText = new Annotation(text);
            pipeline.annotate(annotatedText);
            return annotatedText;
        }
예제 #30
0
 public void InsertTestAndGetByPostAndUserTest()
 {
     initializeTest();
     Random rnd = new Random();
     int userid = rnd.Next(10000);
     int postid = rnd.Next(10000);
     Annotation annotation = new Annotation
     {
         UserId = userid,
         PostId = postid,
         Date = DateTime.Parse("2015-11-25 13:58:23"),
         Body = "annotation unit test with userid = " + userid + " and postid =" + postid,
     };
     _annotationRepository.Insert(annotation);
     Annotation annotation_Actual = _annotationRepository.GetByPostAndUser(postid, userid);
     Assert.AreEqual(annotation.UserId, annotation_Actual.UserId);
 }
예제 #31
0
 protected override void AddAnnotation(Annotation annotation)
 {
     _conceptScheme.Annotations.Add(annotation);
 }
예제 #32
0
        public static MsCrmResult SendMailSecondHandToApproval(Product secondHandProduct, Entity _secondHand, UserTypes type, SqlDataAccess sda, IOrganizationService service)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                #region | SEND INFORMATIONS |
                string projectName = secondHandProduct.Project != null ? secondHandProduct.Project.Name : string.Empty;
                string blockName   = secondHandProduct.Block != null ? secondHandProduct.Block.Name : string.Empty;
                string floorNumber = secondHandProduct.FloorNumber != null?secondHandProduct.FloorNumber.ToString() : string.Empty;

                string generalhomeType = secondHandProduct.GeneralHomeType != null ? secondHandProduct.GeneralHomeType.Name : string.Empty;
                string homeType        = secondHandProduct.HomeType != null ? secondHandProduct.HomeType.Name : string.Empty;
                string net             = secondHandProduct.Net != null ? ((decimal)secondHandProduct.Net).ToString("N0", CultureInfo.CurrentCulture) : string.Empty;
                string brut            = secondHandProduct.Brut != null ? ((decimal)secondHandProduct.Brut).ToString("N0", CultureInfo.CurrentCulture) : string.Empty;
                string productAmount   = secondHandProduct.PaymentOfHire.HasValue ? secondHandProduct.PaymentOfHire.Value.ToString("N2") : string.Empty;
                string rentalAmount    = _secondHand.GetAttributeValue <Money>("new_salesfee") != null?_secondHand.GetAttributeValue <Money>("new_salesfee").Value.ToString("N2") : string.Empty;

                string currencyName = _secondHand.GetAttributeValue <EntityReference>("transactioncurrencyid") != null ? (_secondHand.GetAttributeValue <EntityReference>("transactioncurrencyid")).Name : string.Empty;
                #endregion

                #region | GET CURRENCY |
                string            exchangeRate   = string.Empty;
                Guid              currencyId     = (_secondHand.GetAttributeValue <EntityReference>("transactioncurrencyid")).Id;
                MsCrmResultObject currencyResult = CurrencyHelper.GetExchangeRateByCurrency(DateTime.Now, currencyId, sda);
                if (currencyResult.Success)
                {
                    ExchangeRate rate = (ExchangeRate)currencyResult.ReturnObject;
                    exchangeRate = ((decimal)rate.SaleRate).ToString("N0", CultureInfo.CurrentCulture);
                }
                #endregion

                string body = "<table>";
                body += "<tr><td>Proje : </td><td>" + projectName + "</td></tr>";
                body += "<tr><td>Blok : </td><td>" + blockName + "</td></tr>";
                body += "<tr><td>Kat : </td><td>" + floorNumber + "</td></tr>";
                body += "<tr><td>Daire No : </td><td>" + secondHandProduct.HomeNumber + "</td></tr>";
                body += "<tr><td>Tip : </td><td>" + generalhomeType + "</td></tr>";
                body += "<tr><td>Daire Tipi : </td><td>" + homeType + "</td></tr>";
                body += "<tr><td>Konut Satış Fiyatı Fiyatı : </td><td>" + productAmount + "</td></tr>";
                body += "<tr><td>Satılmak İstenen Fiyat : </td><td>" + rentalAmount + "</td></tr>";
                body += "<tr><td>Net m2 : </td><td>" + net + "</td></tr>";
                body += "<tr><td>Brüt m2 : </td><td>" + brut + "</td></tr>";
                body += "<tr><td>Para Birimi : </td><td>" + currencyName + "</td></tr>";
                body += "<tr><td>Güncel Kur : </td><td>" + exchangeRate + "</td></tr>";
                body += "</table>";
                body += "<br/>";
                body += "<br/>";
                body += "<a href='{0}' target='_blank'>Kiralamayı onaylamak/reddetmek için lütfen tıklayınız.</a>";

                string url = "http://fenix.centralproperty.com.tr/index.aspx?page=secondhandconfirm&name=secondhandid&pageid=" + _secondHand.Id;
                body = string.Format(body, url);

                //MsCrmResultObject managerResult = SystemUserHelper.GetSalesManager(sda);
                MsCrmResultObject managerResult = SystemUserHelper.GetUsersByUserTypes(type, sda);

                if (managerResult != null && managerResult.Success)
                {
                    Entity fromParty = new Entity("activityparty");
                    fromParty["partyid"] = _secondHand.GetAttributeValue <EntityReference>("ownerid");
                    Entity[] fromPartyColl = new Entity[] { fromParty };

                    #region | SET TO |

                    List <SystemUser> returnList  = (List <SystemUser>)managerResult.ReturnObject;
                    Entity[]          toPartyColl = new Entity[returnList.Count];
                    for (int i = 0; i < returnList.Count; i++)
                    {
                        Entity toParty = new Entity("activityparty");
                        toParty["partyid"] = new EntityReference("systemuser", returnList[i].SystemUserId);
                        toPartyColl[i]     = toParty;
                    }
                    #endregion
                    Annotation  anno       = null;
                    MsCrmResult mailResult = GeneralHelper.SendMail(_secondHand.Id, "new_resalerecord", fromPartyColl, toPartyColl, "2.El Satış Onayı", body, anno, service);
                    returnValue = mailResult;
                }
                else
                {
                    returnValue.Success = false;
                    returnValue.Result  = managerResult.Result;
                }
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Result  = ex.Message;
            }
            return(returnValue);
        }
 void ITestModelBuilder.AddAnnotation(Annotation annotation)
 {
     throw new NotSupportedException();
 }
예제 #34
0
 protected override bool OnLeaveNotifyEvent(EventCrossing evnt)
 {
     highlightAnnotation = null;
     widget.QueueDraw();
     return(base.OnLeaveNotifyEvent(evnt));
 }
예제 #35
0
 public void setCurrentAnnotation(Annotation pAnnotation)
 {
     annotationCurrent = pAnnotation;
 }
예제 #36
0
            protected override bool OnExposeEvent(Gdk.EventExpose e)
            {
                using (Cairo.Context cr = Gdk.CairoHelper.Create(e.Window)) {
                    cr.LineWidth = Math.Max(1.0, widget.Editor.Options.Zoom);

                    cr.Rectangle(leftSpacer, 0, Allocation.Width, Allocation.Height);
                    cr.SetSourceColor(Styles.BlameView.AnnotationBackgroundColor.ToCairoColor());
                    cr.Fill();

                    int    startLine = widget.Editor.YToLine((int)widget.Editor.VAdjustment.Value);
                    double startY    = widget.Editor.LineToY(startLine);
                    while (startLine > 1 && startLine < annotations.Count && annotations[startLine - 1] != null && annotations[startLine] != null && annotations[startLine - 1].Revision == annotations[startLine].Revision)
                    {
                        startLine--;
                        startY -= widget.Editor.GetLineHeight(widget.Editor.Document.GetLine(startLine));
                    }
                    double curY = startY - widget.Editor.VAdjustment.Value;
                    int    line = startLine;
                    while (curY < Allocation.Bottom && line <= widget.Editor.LineCount)
                    {
                        double curStart = curY;
//						widget.JumpOverFoldings (ref line);
                        int        lineStart = line;
                        int        authorWidth = 0, revisionWidth = 0, dateWidth = 0, h = 16;
                        Annotation ann = line <= annotations.Count ? annotations[line - 1] : null;
                        if (ann != null)
                        {
                            do
                            {
                                widget.JumpOverFoldings(ref line);
                                line++;
                            } while (line <= annotations.Count && annotations[line - 1] != null && annotations[line - 1].Revision == ann.Revision);

                            double nextY = widget.editor.LineToY(line) - widget.editor.VAdjustment.Value;
                            if (highlightAnnotation != null && highlightAnnotation.Revision == ann.Revision && curStart <= highlightPositon && highlightPositon < nextY)
                            {
                                cr.Rectangle(leftSpacer, curStart + cr.LineWidth, Allocation.Width - leftSpacer, nextY - curStart - cr.LineWidth);
                                cr.SetSourceColor(Styles.BlameView.AnnotationHighlightColor.ToCairoColor());
                                cr.Fill();
                            }

                            // use a fixed size revision to get a approx. revision width
                            layout.SetText("88888888");
                            layout.GetPixelSize(out revisionWidth, out h);
                            layout.SetText(TruncRevision(ann.Text));

                            const int dateRevisionSpacing = 16;

                            using (var gc = new Gdk.GC(e.Window)) {
                                gc.RgbFgColor = Styles.BlameView.AnnotationTextColor.ToGdkColor();
                                e.Window.DrawLayout(gc, Allocation.Width - revisionWidth - margin, (int)(curY + (widget.Editor.LineHeight - h) / 2), layout);

                                if (ann.HasDate)
                                {
                                    string dateTime = ann.Date.ToShortDateString();
                                    // use a fixed size date to get a approx. date width
                                    layout.SetText(new DateTime(1999, 10, 10).ToShortDateString());
                                    layout.GetPixelSize(out dateWidth, out h);
                                    layout.SetText(dateTime);

                                    e.Window.DrawLayout(gc, Allocation.Width - revisionWidth - margin - revisionWidth - dateRevisionSpacing, (int)(curY + (widget.Editor.LineHeight - h) / 2), layout);
                                }
                            }

                            using (var authorLayout = MonoDevelop.Components.PangoUtil.CreateLayout(this)) {
                                authorLayout.FontDescription = FontService.SansFont.CopyModified(Ide.Gui.Styles.FontScale11);
                                authorLayout.SetText(ann.Author);
                                authorLayout.GetPixelSize(out authorWidth, out h);

                                var maxWidth = Allocation.Width - revisionWidth - margin - revisionWidth - dateRevisionSpacing;

                                /*				if (authorWidth > maxWidth) {
                                 *                                      int idx = ann.Author.IndexOf ('<');
                                 *                                      if (idx > 0)
                                 *                                              authorLayout.SetText (ann.Author.Substring (0, idx) + Environment.NewLine + ann.Author.Substring (idx));
                                 *                                      authorLayout.GetPixelSize (out authorWidth, out h);
                                 *                              }*/

                                cr.Save();
                                cr.Rectangle(0, 0, maxWidth, Allocation.Height);
                                cr.Clip();
                                cr.Translate(leftSpacer + margin, (int)(curY + (widget.Editor.LineHeight - h) / 2));
                                cr.SetSourceColor(Styles.BlameView.AnnotationTextColor.ToCairoColor());
                                cr.ShowLayout(authorLayout);
                                cr.ResetClip();
                                cr.Restore();
                            }

                            curY = nextY;
                        }
                        else
                        {
                            curY += widget.Editor.GetLineHeight(line);
                            line++;
                            widget.JumpOverFoldings(ref line);
                        }

                        if (ann != null && line - lineStart > 1)
                        {
                            string msg = GetCommitMessage(lineStart, false);
                            if (!string.IsNullOrEmpty(msg))
                            {
                                msg = RevisionHelpers.FormatMessage(msg);

                                layout.SetText(msg);
                                layout.Width = (int)(Allocation.Width * Pango.Scale.PangoScale);
                                using (var gc = new Gdk.GC(e.Window)) {
                                    gc.RgbFgColor    = Styles.BlameView.AnnotationSummaryTextColor.ToGdkColor();
                                    gc.ClipRectangle = new Rectangle(0, (int)curStart, Allocation.Width, (int)(curY - curStart));
                                    e.Window.DrawLayout(gc, (int)(leftSpacer + margin), (int)(curStart + h), layout);
                                }
                            }
                        }

                        cr.Rectangle(0, curStart, leftSpacer, curY - curStart);

                        if (ann != null && !string.IsNullOrEmpty(ann.Author))
                        {
                            double a;

                            if (ann != null && (maxDate - minDate).TotalHours > 0)
                            {
                                a = 1 - (ann.Date - minDate).TotalHours / (maxDate - minDate).TotalHours;
                            }
                            else
                            {
                                a = 1;
                            }
                            var color = Styles.BlameView.AnnotationMarkColor;
                            color.Light      = 0.4 + a / 2;
                            color.Saturation = 1 - a / 2;
                            cr.SetSourceColor(color.ToCairoColor());
                        }
                        else
                        {
                            cr.SetSourceColor((ann != null ? Styles.BlameView.AnnotationMarkModifiedColor : Styles.BlameView.AnnotationBackgroundColor).ToCairoColor());
                        }
                        cr.Fill();

                        if (ann != null)
                        {
                            cr.MoveTo(0, curY + 0.5);
                            cr.LineTo(Allocation.Width, curY + 0.5);
                            cr.SetSourceColor(Styles.BlameView.AnnotationSplitterColor.ToCairoColor());
                            cr.Stroke();
                        }
                    }
                }
                return(true);
            }
예제 #37
0
        public Annotation Apply(InternalEntityTypeBuilder entityTypeBuilder, string name, Annotation annotation, Annotation oldAnnotation)
        {
            if (name == CosmosAnnotationNames.ContainerName)
            {
                Apply(entityTypeBuilder);
            }

            return(annotation);
        }
예제 #38
0
 /// <summary>
 /// Note that the icon used is independent of whether the annotation is resolved/closed or not.
 /// AnnotationEditorView._annotationLogo_Paint paints the check mark over the top if needed.
 /// (This is different from the 16x16 strategy, where we have fine-tuned distinct icons.)
 /// </summary>
 /// <returns></returns>
 public Image GetAnnotationLogoImage()
 {
     return(Annotation.GetImage(32));
 }
예제 #39
0
        protected override void TranslateFunctionDefinition(List <string> output, FunctionDefinition functionDef)
        {
            output.Add(this.CurrentTabIndention);
            output.Add("\nfunction ");
            Annotation returnTypeAnnotation = functionDef.GetAnnotation("type");

            if (returnTypeAnnotation == null)
            {
                throw new ParserException(functionDef.FirstToken, "Need return type.");
            }
            string type = returnTypeAnnotation.GetSingleArgAsString(null);

            if (type == null)
            {
                throw new ParserException(functionDef.FirstToken, "Need return type.");
            }
            output.Add("v_");
            output.Add(functionDef.NameToken.Value);
            output.Add("(");
            for (int i = 0; i < functionDef.ArgNames.Length; ++i)
            {
                if (i > 0)
                {
                    output.Add(", ");
                }
                Annotation annotation = functionDef.ArgAnnotations[i];
                if (annotation == null)
                {
                    throw new ParserException(functionDef.FirstToken, "Arg needs a type.");
                }
                output.Add("$v_" + functionDef.ArgNames[i].Value);
            }
            output.Add(") {\n");
            this.CurrentIndention++;

            HashSet <Variable> variablesUsed = new HashSet <Variable>();

            foreach (Executable line in functionDef.Code)
            {
                line.GetAllVariablesReferenced(variablesUsed);
            }

            foreach (string variable in variablesUsed
                     .Select <Variable, string>(v => v.Name)
                     .Where <string>(s => s.ToUpper() == s)
                     .Distinct <string>()
                     .OrderBy <string, string>(s => s))
            {
                output.Add(this.CurrentTabIndention);
                output.Add("global $v_");
                output.Add(variable);
                output.Add(";\n");
            }

            foreach (Executable line in functionDef.Code)
            {
                this.Translate(output, line);
            }
            this.CurrentIndention--;
            output.Add(this.CurrentTabIndention);
            output.Add("}\n");
        }
        //gets range of tokens that are in the same sentence as the beginning of the quote that precede it, if they exist,
        //or the previous sentence, if it is in the same paragraph.
        //also, ensure that the difference is at least two tokens
        public static Pair <int, int> GetTokenRangePrecedingQuote(Annotation doc, ICoreMap quote)
        {
            IList <ICoreMap> docSentences = doc.Get(typeof(CoreAnnotations.SentencesAnnotation));
            int quoteBeginTokenIndex      = quote.Get(typeof(CoreAnnotations.TokenBeginAnnotation));

            if (quoteBeginTokenIndex <= 2)
            {
                return(null);
            }
            int      quoteBeginSentenceIndex = quote.Get(typeof(CoreAnnotations.SentenceBeginAnnotation));
            ICoreMap beginSentence           = docSentences[quoteBeginSentenceIndex];

            if (beginSentence.Get(typeof(QuoteAttributionUtils.EnhancedSentenceAnnotation)) != null)
            {
                beginSentence = beginSentence.Get(typeof(QuoteAttributionUtils.EnhancedSentenceAnnotation));
            }
            int quoteIndex = quote.Get(typeof(CoreAnnotations.QuotationIndexAnnotation));

            if (beginSentence.Get(typeof(CoreAnnotations.TokenBeginAnnotation)) < quoteBeginTokenIndex - 1)
            {
                //check previous quote to make sure boundary is okay- modify if necessary.
                if (quoteIndex > 0)
                {
                    ICoreMap prevQuote         = doc.Get(typeof(CoreAnnotations.QuotationsAnnotation))[quoteIndex - 1];
                    int      prevQuoteTokenEnd = prevQuote.Get(typeof(CoreAnnotations.TokenEndAnnotation));
                    if (prevQuoteTokenEnd > beginSentence.Get(typeof(CoreAnnotations.TokenBeginAnnotation)))
                    {
                        if (prevQuoteTokenEnd + 1 == quoteBeginTokenIndex)
                        {
                            return(null);
                        }
                        return(new Pair <int, int>(prevQuoteTokenEnd + 1, quoteBeginTokenIndex - 1));
                    }
                }
                return(new Pair <int, int>(beginSentence.Get(typeof(CoreAnnotations.TokenBeginAnnotation)), quoteBeginTokenIndex - 1));
            }
            else
            {
                if (quoteBeginSentenceIndex > 0)
                {
                    //try previous sentence- if it is in the same paragraph.
                    int      currParagraph = beginSentence.Get(typeof(CoreAnnotations.ParagraphIndexAnnotation));
                    ICoreMap prevSentence  = docSentences[quoteBeginSentenceIndex - 1];
                    //check if prevSentence is in same paragraph
                    if (prevSentence.Get(typeof(CoreAnnotations.ParagraphIndexAnnotation)) == currParagraph)
                    {
                        //check previous quote boundary
                        if (quoteIndex > 0)
                        {
                            ICoreMap prevQuote         = doc.Get(typeof(CoreAnnotations.QuotationsAnnotation))[quoteIndex - 1];
                            int      prevQuoteTokenEnd = prevQuote.Get(typeof(CoreAnnotations.TokenEndAnnotation));
                            if (prevQuoteTokenEnd > prevSentence.Get(typeof(CoreAnnotations.TokenBeginAnnotation)))
                            {
                                if (prevQuoteTokenEnd + 1 == quoteBeginTokenIndex)
                                {
                                    return(null);
                                }
                                return(new Pair <int, int>(prevQuoteTokenEnd + 1, quoteBeginTokenIndex - 1));
                            }
                            return(new Pair <int, int>(prevSentence.Get(typeof(CoreAnnotations.TokenBeginAnnotation)), quoteBeginTokenIndex - 1));
                        }
                    }
                }
            }
            return(null);
        }
예제 #41
0
 public override object VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, object data)
 {
     if (objectCreateExpression.Arguments.Count() == 2)
     {
         Expression obj        = objectCreateExpression.Arguments.First();
         Expression func       = objectCreateExpression.Arguments.Last();
         Annotation annotation = func.Annotation <Annotation>();
         if (annotation != null)
         {
             IdentifierExpression methodIdent = (IdentifierExpression)((InvocationExpression)func).Arguments.Single();
             MethodReference      method      = methodIdent.Annotation <MethodReference>();
             if (method != null)
             {
                 if (HandleAnonymousMethod(objectCreateExpression, obj, method))
                 {
                     return(null);
                 }
                 // Perform the transformation to "new Action(obj.func)".
                 obj.Remove();
                 methodIdent.Remove();
                 if (!annotation.IsVirtual && obj is ThisReferenceExpression)
                 {
                     // maybe it's getting the pointer of a base method?
                     if (method.DeclaringType.GetElementType() != context.CurrentType)
                     {
                         obj = new BaseReferenceExpression();
                     }
                 }
                 if (!annotation.IsVirtual && obj is NullReferenceExpression && !method.HasThis)
                 {
                     // We're loading a static method.
                     // However it is possible to load extension methods with an instance, so we compare the number of arguments:
                     bool          isExtensionMethod = false;
                     TypeReference delegateType      = objectCreateExpression.Type.Annotation <TypeReference>();
                     if (delegateType != null)
                     {
                         TypeDefinition delegateTypeDef = delegateType.Resolve();
                         if (delegateTypeDef != null)
                         {
                             MethodDefinition invokeMethod = delegateTypeDef.Methods.FirstOrDefault(m => m.Name == "Invoke");
                             if (invokeMethod != null)
                             {
                                 isExtensionMethod = (invokeMethod.Parameters.Count + 1 == method.Parameters.Count);
                             }
                         }
                     }
                     if (!isExtensionMethod)
                     {
                         obj = new TypeReferenceExpression {
                             Type = AstBuilder.ConvertType(method.DeclaringType)
                         };
                     }
                 }
                 // now transform the identifier into a member reference
                 MemberReferenceExpression mre = new MemberReferenceExpression();
                 mre.Target     = obj;
                 mre.MemberName = methodIdent.Identifier;
                 methodIdent.TypeArguments.MoveTo(mre.TypeArguments);
                 mre.AddAnnotation(method);
                 objectCreateExpression.Arguments.Clear();
                 objectCreateExpression.Arguments.Add(mre);
                 return(null);
             }
         }
     }
     return(base.VisitObjectCreateExpression(objectCreateExpression, data));
 }
예제 #42
0
 public string GetLongLabel()
 {
     return(Annotation.GetLongLabel());
 }
예제 #43
0
 public void AddMessage(string newMessageText)
 {
     Annotation.AddMessage(_user.Name, null, newMessageText);
     UpdateContentNow();
 }
예제 #44
0
        public virtual void OneSpeakerSentence(Annotation doc)
        {
            IList <CoreLabel> toks   = doc.Get(typeof(CoreAnnotations.TokensAnnotation));
            IList <ICoreMap>  quotes = doc.Get(typeof(CoreAnnotations.QuotationsAnnotation));
            IDictionary <int, IList <ICoreMap> > quotesBySentence = new Dictionary <int, IList <ICoreMap> >();

            for (int quoteIndex = 0; quoteIndex < quotes.Count; quoteIndex++)
            {
                ICoreMap quote = quotes[quoteIndex];
                // iterate through each quote in the chapter
                // group quotes by sentence
                int quoteBeginTok   = quote.Get(typeof(CoreAnnotations.TokenBeginAnnotation));
                int sentenceBeginId = toks[quoteBeginTok].SentIndex();
                int quoteEndTok     = quote.Get(typeof(CoreAnnotations.TokenEndAnnotation));
                int sentenceEndId   = toks[quoteEndTok].SentIndex();
                quotesBySentence.PutIfAbsent(sentenceBeginId, new List <ICoreMap>());
                quotesBySentence.PutIfAbsent(sentenceEndId, new List <ICoreMap>());
                quotesBySentence[sentenceBeginId].Add(quote);
                quotesBySentence[sentenceEndId].Add(quote);
            }
            //
            foreach (int k in quotesBySentence.Keys)
            {
                IList <ICoreMap>      quotesInSent     = quotesBySentence[k];
                IList <Sieve.Mention> existantMentions = new List <Sieve.Mention>();
                foreach (ICoreMap quote in quotesInSent)
                {
                    if (quote.Get(typeof(QuoteAttributionAnnotator.MentionAnnotation)) != null)
                    {
                        Sieve.Mention m = new Sieve.Mention(this, quote.Get(typeof(QuoteAttributionAnnotator.MentionBeginAnnotation)), quote.Get(typeof(QuoteAttributionAnnotator.MentionEndAnnotation)), quote.Get(typeof(QuoteAttributionAnnotator.MentionAnnotation)),
                                                            quote.Get(typeof(QuoteAttributionAnnotator.MentionTypeAnnotation)));
                        existantMentions.Add(m);
                    }
                }
                //remove cases in which there is more than one mention in a sentence.
                bool   same = true;
                string text = null;
                foreach (Sieve.Mention m_1 in existantMentions)
                {
                    if (text == null)
                    {
                        text = m_1.text;
                    }
                    if (!Sharpen.Runtime.EqualsIgnoreCase(m_1.text, text))
                    {
                        same = false;
                    }
                }
                if (same && text != null && existantMentions.Count > 0)
                {
                    foreach (ICoreMap quote_1 in quotesInSent)
                    {
                        if (quote_1.Get(typeof(QuoteAttributionAnnotator.MentionAnnotation)) == null)
                        {
                            Sieve.Mention firstM = existantMentions[0];
                            quote_1.Set(typeof(QuoteAttributionAnnotator.MentionAnnotation), firstM.text);
                            quote_1.Set(typeof(QuoteAttributionAnnotator.MentionBeginAnnotation), firstM.begin);
                            quote_1.Set(typeof(QuoteAttributionAnnotator.MentionEndAnnotation), firstM.end);
                            quote_1.Set(typeof(QuoteAttributionAnnotator.MentionSieveAnnotation), "Deterministic one speaker sentence");
                            quote_1.Set(typeof(QuoteAttributionAnnotator.MentionTypeAnnotation), firstM.type);
                        }
                    }
                }
            }
        }
예제 #45
0
 protected override void AddAnnotation(Annotation annotation)
 {
     _series.Annotations.Add(annotation);
 }
 /// <summary>
 /// Constructs a RtfAnnotation based on an Annotation.
 /// </summary>
 /// <param name="doc">The RtfDocument this RtfAnnotation belongs to</param>
 /// <param name="annotation">The Annotation this RtfAnnotation is based off</param>
 public RtfAnnotation(RtfDocument doc, Annotation annotation) : base(doc)
 {
     _title   = annotation.Title;
     _content = annotation.Content;
 }
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual Annotation Apply(
            InternalPropertyBuilder propertyBuilder, string name, Annotation annotation, Annotation oldAnnotation)
        {
            var property = propertyBuilder.Metadata;

            switch (name)
            {
            case RelationalAnnotationNames.DefaultValue:
            case RelationalAnnotationNames.DefaultValueSql:
            case RelationalAnnotationNames.ComputedColumnSql:
                propertyBuilder.ValueGenerated(GetValueGenerated(property), ConfigurationSource.Convention);
                break;
            }

            return(annotation);
        }
        protected override void ConsumeData(IDataProducer sender, object data)
        {
            DocumentCorpus c = (DocumentCorpus)data;

            foreach (Document doc in c.Documents)
            {
                short sentenceNum = 0, blockNum = 0;
                int   tokensPerDocument = 0;
                //string documentId = doc.Features.GetFeatureValue("guid");
                //documentId = documentId.Replace("-", "");
                //doc.Features.SetFeatureValue("fullId", corpusId + "_" + documentId);             //add feature fullId for Achim

                string responseUrl = doc.Features.GetFeatureValue("responseUrl") ?? "";
                string urlKey      = doc.Features.GetFeatureValue("urlKey") ?? "";
                string title       = doc.Features.GetFeatureValue("title") ?? "";
                string domainName  = doc.Features.GetFeatureValue("domainName") ?? "";

                //********************* date = pubdate if |pubDate-timeGet|<3 days
                string   pubDate = doc.Features.GetFeatureValue("pubDate") ?? "";
                DateTime timeGet = DateTime.Parse(doc.Features.GetFeatureValue("time"));
                string   date    = timeGet.ToString("yyyy-MM-dd");
                try
                {
                    DateTime mPubDate = DateTime.Parse(pubDate);
                    if (DateTime.Compare(mPubDate, timeGet) < 0 && timeGet.Subtract(mPubDate).CompareTo(TimeSpan.FromDays(3)) < 0)
                    {
                        date = mPubDate.ToString("yyyy-MM-dd");
                    }
                }
                catch { } // supress errors

                //******************* Document to database
                double pumpDumpIndex = Convert.ToDouble(doc.Features.GetFeatureValue("pumpIndex"));
                bool   isFinancial   = doc.Features.GetFeatureValue("isFinancial") == "True";
                // compute new ID
                Guid             cGuid  = new Guid(c.Features.GetFeatureValue("guid"));
                Guid             dGuid  = new Guid(doc.Features.GetFeatureValue("guid"));
                ArrayList <byte> buffer = new ArrayList <byte>();
                buffer.AddRange(cGuid.ToByteArray());
                buffer.AddRange(dGuid.ToByteArray());
                Guid documentId = new Guid(MD5.Create().ComputeHash(buffer.ToArray()));
                long docId      = ToDb.DocumentToDb(mConnection, title, date, pubDate, timeGet.ToString("yyyy-MM-dd HH:mm"), responseUrl, urlKey, domainName, isFinancial, pumpDumpIndex, documentId);

                //******************* occurrences

                string blockSelector = "TextBlock/Content";
                string rev           = doc.Features.GetFeatureValue("rev");
                if (rev != "1")
                {
                    blockSelector = "TextBlock/Content/Unseen";
                }

                //******************** occurrence to database
                int documentNeg = 0, documentPoz = 0;

                doc.CreateAnnotationIndex();
                foreach (TextBlock tb in doc.GetAnnotatedBlocks(blockSelector)) //"TextBlock/Content" if rev = "1", else "TextBlock/Content/Unseen"
                {
                    int tokensPerBlock = doc.GetAnnotatedBlocks("Token", tb.SpanStart, tb.SpanEnd).Length;
                    tokensPerDocument += tokensPerBlock;
                    int blockNeg = 0, blockPoz = 0;
                    blockNum++;

                    foreach (TextBlock s in doc.GetAnnotatedBlocks("Sentence", tb.SpanStart, tb.SpanEnd)) // *** sentence selector within TextBlock tb
                    {
                        int sentenceNeg = 0;
                        int sentencePoz = 0;
                        sentenceNum++;
                        int tokensPerSentence = doc.GetAnnotatedBlocks("Token", s.SpanStart, s.SpanEnd).Length;
                        // sentiment object
                        foreach (TextBlock so in doc.GetAnnotatedBlocks("SentimentObject", s.SpanStart, s.SpanEnd)) // *** SentimentObject selector within sentence s
                        {
                            Annotation annot = so.Annotation;
                            //     string gazUri = annot.Features.GetFeatureValue("gazetteerUri");
                            string instUri = annot.Features.GetFeatureValue("instanceUri");
                            //     string instClassUri = annot.Features.GetFeatureValue("instanceClassUri");
                            string term = so.Text; // takole pa dobis dejanski tekst...
                            //   Console.WriteLine("\n" + gazUri + " \t" + instUri + " \t" + instClassUri + " \t" + term);
                            long occId = ToDb.OccurrenceToDb(mConnection, date, annot.SpanStart, annot.SpanEnd, sentenceNum, blockNum, docId, instUri);
                            ToDb.TermToDb(mConnection, occId, term);
                        }

                        // sentiment word
                        foreach (TextBlock so in doc.GetAnnotatedBlocks("SentimentWord", s.SpanStart, s.SpanEnd)) // *** SentimentWord selector within sentence s
                        {
                            Annotation annot        = so.Annotation;
                            string     gazUri       = annot.Features.GetFeatureValue("gazetteerUri");
                            string     instUri      = annot.Features.GetFeatureValue("instanceUri");
                            string     instClassUri = annot.Features.GetFeatureValue("instanceClassUri");
                            string     term         = so.Text; // takole pa dobis dejanski tekst...
                            //   Console.WriteLine("\n" + gazUri + " \t" + instUri + " \t" + instClassUri + " \t" + term);
                            if (instClassUri.EndsWith("PositiveWord"))
                            {
                                sentencePoz++;
                                blockPoz++;
                                documentPoz++;
                            }
                            else if (instClassUri.EndsWith("NegativeWord"))
                            {
                                sentenceNeg++;
                                blockNeg++;
                                documentNeg++;
                            }
                            // Insert into SQL table SentimentWordOccurrence
                            ToDb.SentimentWordOccurrenceToDb(mConnection, date, annot.SpanStart, annot.SpanEnd, sentenceNum, blockNum, docId, instUri);
                        }
                    }
                    // Insert into SQL table BlockSentiment
                    if (blockNeg != 0 || blockPoz != 0)
                    {
                        ToDb.BlockSentimentToDb(mConnection, docId, blockNum, blockPoz, blockNeg, tokensPerBlock);
                    }
                }
            }
        }
예제 #49
0
    public void Read(TProtocol iprot)
    {
        TField field;

        iprot.ReadStructBegin();
        while (true)
        {
            field = iprot.ReadFieldBegin();
            if (field.Type == TType.Stop)
            {
                break;
            }
            switch (field.ID)
            {
            case 1:
                if (field.Type == TType.I64)
                {
                    Trace_id = iprot.ReadI64();
                }
                else
                {
                    TProtocolUtil.Skip(iprot, field.Type);
                }
                break;

            case 3:
                if (field.Type == TType.String)
                {
                    Name = iprot.ReadString();
                }
                else
                {
                    TProtocolUtil.Skip(iprot, field.Type);
                }
                break;

            case 4:
                if (field.Type == TType.I64)
                {
                    Id = iprot.ReadI64();
                }
                else
                {
                    TProtocolUtil.Skip(iprot, field.Type);
                }
                break;

            case 5:
                if (field.Type == TType.I64)
                {
                    Parent_id = iprot.ReadI64();
                }
                else
                {
                    TProtocolUtil.Skip(iprot, field.Type);
                }
                break;

            case 6:
                if (field.Type == TType.List)
                {
                    {
                        Annotations = new List <Annotation>();
                        TList _list0 = iprot.ReadListBegin();
                        for (int _i1 = 0; _i1 < _list0.Count; ++_i1)
                        {
                            Annotation _elem2;
                            _elem2 = new Annotation();
                            _elem2.Read(iprot);
                            Annotations.Add(_elem2);
                        }
                        iprot.ReadListEnd();
                    }
                }
                else
                {
                    TProtocolUtil.Skip(iprot, field.Type);
                }
                break;

            case 8:
                if (field.Type == TType.List)
                {
                    {
                        Binary_annotations = new List <BinaryAnnotation>();
                        TList _list3 = iprot.ReadListBegin();
                        for (int _i4 = 0; _i4 < _list3.Count; ++_i4)
                        {
                            BinaryAnnotation _elem5;
                            _elem5 = new BinaryAnnotation();
                            _elem5.Read(iprot);
                            Binary_annotations.Add(_elem5);
                        }
                        iprot.ReadListEnd();
                    }
                }
                else
                {
                    TProtocolUtil.Skip(iprot, field.Type);
                }
                break;

            case 9:
                if (field.Type == TType.Bool)
                {
                    Debug = iprot.ReadBool();
                }
                else
                {
                    TProtocolUtil.Skip(iprot, field.Type);
                }
                break;

            default:
                TProtocolUtil.Skip(iprot, field.Type);
                break;
            }
            iprot.ReadFieldEnd();
        }
        iprot.ReadStructEnd();
    }
예제 #50
0
 public string GetAllInfoForMessageBox()
 {
     return(Annotation.GetDiagnosticDump());
 }
예제 #51
0
        /// <summary>
        /// Handles selecting the nearest peptide to edit the annotation for, and showing the editAnnotation form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void msPlot_DoubleClick(object sender, EventArgs e)
        {
            bool           usingCustomAnnotation = false;
            MouseEventArgs mouseArgs             = (MouseEventArgs)e;
            Graphics       g = msPlot.CreateGraphics();
            GraphPane      closestPane;
            PointPair      closestPoint;
            PointF         mousePt         = new PointF(mouseArgs.X, mouseArgs.Y);
            TextObj        selectedTextObj = null;

            //retrieve the text object that the user may have selected
            if (msPlot.FindClosestPoint(mousePt, out closestPoint, out closestPane))
            {
                foreach (GraphObj textObject in closestPane.GraphObjList)
                {
                    if (textObject.Tag == closestPoint)
                    {
                        //zed graph found the annotation object, use that text object
                        selectedTextObj = textObject as TextObj;
                        break;
                    }
                }
            }
            else
            {
                //couldn't find the annotation from where the user clicked
                return;
            }

            if (selectedTextObj == null)
            {
                return; //no obj, so don't do anything
            }
            //see if we have a custom annotation for this annotation we selected
            LadderInstance currentInstance    = m_manager.GetCurrentInstance();
            Annotation     selectedAnnotation = new Annotation();

            foreach (Annotation annotation in currentInstance.annotations)
            {
                if (annotation.m_point == (PointPair)selectedTextObj.Tag)
                {
                    usingCustomAnnotation = true;
                    selectedAnnotation    = annotation;
                    currentInstance.annotations.Remove(annotation);
                    break;
                }
            }
            if (selectedAnnotation.m_point == null && selectedAnnotation.m_text == null)
            {
                selectedAnnotation.m_showHideAuto = 0;
                selectedAnnotation.m_text         = selectedTextObj.Text;
                selectedAnnotation.m_point        = (PointPair)selectedTextObj.Tag;
            }

            // Open the AnnotationEdit form
            PlotView.AnnotationEdit editForm = new PlotView.AnnotationEdit(selectedAnnotation);
            if (editForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (editForm.m_annotation.m_showHideAuto < 0)
                {
                    selectedTextObj.IsVisible = false;
                }
                else if (editForm.m_annotation.m_showHideAuto > 0)
                {
                    selectedTextObj.IsVisible = true;
                }
                selectedTextObj.Text = editForm.m_annotation.m_text;

                currentInstance.annotations.Add(editForm.m_annotation);
            }
            else if (usingCustomAnnotation)
            {
                //recreate the annotation we thought we were replacing
                currentInstance.annotations.Add(selectedAnnotation);
            }

            msPlot.ReevaluateAnnotations();
            msPlot.Invalidate();
            return;
        }
 public static IDictionary <int, string> SetupCoref(string bammanFile, IDictionary <string, IList <Person> > characterMap, Annotation doc)
 {
     if (bammanFile != null)
     {
         //TODO: integrate coref
         IDictionary <int, IList <CoreLabel> > bammanTokens    = BammanCorefReader.ReadTokenFile(bammanFile, doc);
         IDictionary <int, string>             pronounCorefMap = MapBammanToCharacterMap(bammanTokens, characterMap);
         return(pronounCorefMap);
     }
     else
     {
         IDictionary <int, string> pronounCorefMap = new Dictionary <int, string>();
         foreach (CorefChain cc in doc.Get(typeof(CorefCoreAnnotations.CorefChainAnnotation)).Values)
         {
             string representativeMention = cc.GetRepresentativeMention().mentionSpan;
             foreach (CorefChain.CorefMention cm in cc.GetMentionsInTextualOrder())
             {
                 if (IsPronominal(cm.mentionSpan))
                 {
                     ICoreMap          cmSentence = doc.Get(typeof(CoreAnnotations.SentencesAnnotation))[cm.sentNum - 1];
                     IList <CoreLabel> cmTokens   = cmSentence.Get(typeof(CoreAnnotations.TokensAnnotation));
                     int charBegin = cmTokens[0].Get(typeof(CoreAnnotations.CharacterOffsetBeginAnnotation));
                     pronounCorefMap[charBegin] = representativeMention;
                 }
             }
         }
         return(pronounCorefMap);
     }
 }
        public static int GetQuoteParagraphIndex(Annotation doc, ICoreMap quote)
        {
            IList <ICoreMap> sentences = doc.Get(typeof(CoreAnnotations.SentencesAnnotation));

            return(sentences[quote.Get(typeof(CoreAnnotations.SentenceBeginAnnotation))].Get(typeof(CoreAnnotations.ParagraphIndexAnnotation)));
        }
        public static Pair <int, int> GetTokenRangeFollowingQuote(Annotation doc, ICoreMap quote)
        {
            IList <ICoreMap> sentences = doc.Get(typeof(CoreAnnotations.SentencesAnnotation));
            IList <ICoreMap> quotes    = doc.Get(typeof(CoreAnnotations.QuotationsAnnotation));
            int quoteEndTokenIndex     = quote.Get(typeof(CoreAnnotations.TokenEndAnnotation));

            if (quoteEndTokenIndex >= doc.Get(typeof(CoreAnnotations.TokensAnnotation)).Count - 2)
            {
                return(null);
            }
            int      quoteEndSentenceIndex = quote.Get(typeof(CoreAnnotations.SentenceEndAnnotation));
            ICoreMap endSentence           = sentences[quoteEndSentenceIndex];
            int      quoteIndex            = quote.Get(typeof(CoreAnnotations.QuotationIndexAnnotation));

            if (quoteEndTokenIndex < endSentence.Get(typeof(CoreAnnotations.TokenEndAnnotation)) - 2)
            {
                //quote TokenEndAnnotation is inclusive; sentence TokenEndAnnotation is exclusive
                //check next quote to ensure boundary
                if (quoteIndex < quotes.Count - 1)
                {
                    ICoreMap nextQuote           = quotes[quoteIndex + 1];
                    int      nextQuoteTokenBegin = nextQuote.Get(typeof(CoreAnnotations.TokenBeginAnnotation));
                    if (nextQuoteTokenBegin < endSentence.Get(typeof(CoreAnnotations.TokenEndAnnotation)) - 1)
                    {
                        if (quoteEndTokenIndex + 1 == nextQuoteTokenBegin)
                        {
                            return(null);
                        }
                        return(new Pair <int, int>(quoteEndTokenIndex + 1, nextQuoteTokenBegin - 1));
                    }
                }
                return(new Pair <int, int>(quoteEndTokenIndex + 1, endSentence.Get(typeof(CoreAnnotations.TokenEndAnnotation)) - 1));
            }
            else
            {
                if (quoteEndSentenceIndex < sentences.Count - 1)
                {
                    //check next sentence
                    ICoreMap nextSentence  = sentences[quoteEndSentenceIndex + 1];
                    int      currParagraph = endSentence.Get(typeof(CoreAnnotations.ParagraphIndexAnnotation));
                    if (nextSentence.Get(typeof(CoreAnnotations.ParagraphIndexAnnotation)) == currParagraph)
                    {
                        //check next quote boundary
                        if (quoteIndex < quotes.Count - 1)
                        {
                            ICoreMap nextQuote           = quotes[quoteIndex + 1];
                            int      nextQuoteTokenBegin = nextQuote.Get(typeof(CoreAnnotations.TokenBeginAnnotation));
                            if (nextQuoteTokenBegin < nextSentence.Get(typeof(CoreAnnotations.TokenEndAnnotation)) - 1)
                            {
                                if (quoteEndTokenIndex + 1 == nextQuoteTokenBegin)
                                {
                                    return(null);
                                }
                                return(new Pair <int, int>(quoteEndTokenIndex + 1, nextQuoteTokenBegin - 1));
                            }
                            return(new Pair <int, int>(quoteEndTokenIndex + 1, nextSentence.Get(typeof(CoreAnnotations.TokenEndAnnotation)) - 1));
                        }
                    }
                }
            }
            return(null);
        }
예제 #55
0
 protected virtual void SyllabifyUnmarkedAnnotation(Word word, Annotation <ShapeNode> ann, Shape newShape)
 {
     ProcessSyllable(ann.Range.Start, ann.Range.End, newShape);
 }
        public static void AssignPageRangeManuallyAfterShowingAnnotation()
        {
            KnowledgeItem quotation = Program.ActiveProjectShell.PrimaryMainForm.GetSelectedQuotations().FirstOrDefault();

            if (quotation.EntityLinks.FirstOrDefault() == null)
            {
                return;
            }

            Control quotationSmartRepeater = Program.ActiveProjectShell.PrimaryMainForm.Controls.Find("quotationSmartRepeater", true).FirstOrDefault();

            SwissAcademic.Citavi.Shell.Controls.SmartRepeaters.QuotationSmartRepeater quotationSmartRepeaterAsQuotationSmartRepeater = quotationSmartRepeater as SwissAcademic.Citavi.Shell.Controls.SmartRepeaters.QuotationSmartRepeater;

            Reference reference = quotation.Reference;

            if (reference == null)
            {
                return;
            }

            List <KnowledgeItem> quotations = reference.Quotations.ToList();

            int index = quotations.FindIndex(q => q == quotation);

            Annotation annotation = quotation.EntityLinks.FirstOrDefault().Target as Annotation;

            if (annotation == null)
            {
                return;
            }

            PreviewControl previewControl = Program.ActiveProjectShell.PrimaryMainForm.PreviewControl;

            PdfViewControl pdfViewControl = previewControl.GetPdfViewControl();

            if (pdfViewControl == null)
            {
                return;
            }

            pdfViewControl.GoToAnnotation(annotation);

            KnowledgeItemsForms.NewPageRangeForm("Please enter the new page range:", out string data);

            if (!String.IsNullOrEmpty(data))
            {
                quotation.PageRange = quotation.PageRange.Update(data);
            }

            if (quotations[index - 1] == null)
            {
                return;
            }

            Program.ActiveProjectShell.PrimaryMainForm.ActiveControl = quotationSmartRepeater;
            quotationSmartRepeaterAsQuotationSmartRepeater.SelectAndActivate(quotations[index - 1]);

            annotation = quotations[index - 1].EntityLinks.FirstOrDefault().Target as Annotation;
            if (annotation == null)
            {
                return;
            }

            pdfViewControl.GoToAnnotation(annotation);
        }
예제 #57
0
        public override Dictionary <string, FileOutput> Package(
            BuildContext buildContext,
            string projectId,
            Dictionary <string, ParseTree.Executable[]> finalCode,
            ICollection <ParseTree.StructDefinition> structDefinitions,
            string fileCopySourceRoot,
            ResourceDatabase resourceDatabase,
            SystemLibraryManager libraryManager)
        {
            Dictionary <string, FileOutput> output = new Dictionary <string, FileOutput>();
            string package = projectId.ToLowerInvariant();

            Dictionary <string, string> replacements = new Dictionary <string, string>()
            {
                { "PROJECT_TITLE", projectId },
                { "PROJECT_ID", projectId },
                { "PACKAGE", package },
                { "CURRENT_YEAR", DateTime.Now.Year.ToString() },
                { "COPYRIGHT", "©" },
            };

            bool hasIcon = buildContext.IconFilePath != null;

            if (hasIcon)
            {
                output["resources/icon.png"] = new FileOutput()
                {
                    Type = FileOutputType.Copy,
                    AbsoluteInputPath = buildContext.IconFilePath,
                };
            }

            foreach (string awtFile in new string[] {
                "AwtTranslationHelper",
            })
            {
                output["src/" + package + "/" + awtFile + ".java"] = new FileOutput()
                {
                    Type        = FileOutputType.Text,
                    TextContent = Constants.DoReplacements(
                        Util.ReadResourceFileInternally("game-java-awt/" + awtFile + ".txt"),
                        replacements)
                };
            }

            foreach (string basicFile in new string[] {
                "TranslationHelper",
            })
            {
                output["src/" + package + "/" + basicFile + ".java"] = new FileOutput()
                {
                    Type        = FileOutputType.Text,
                    TextContent = Constants.DoReplacements(
                        Util.ReadResourceFileInternally("java-common/" + basicFile + ".txt"),
                        replacements)
                };
            }

            foreach (string basicFile in new string[] {
                "AwtTranslationHelper",
                "Start",
                "GameWindow",
                "Image",
                "RenderEngine",
            })
            {
                output["src/" + package + "/" + basicFile + ".java"] = new FileOutput()
                {
                    Type        = FileOutputType.Text,
                    TextContent = Constants.DoReplacements(
                        Util.ReadResourceFileInternally("game-java-awt/" + basicFile + ".txt"),
                        replacements)
                };
            }

            string[] items = finalCode.Keys.OrderBy <string, string>(s => s.ToLowerInvariant()).ToArray();

            List <string> crayonWrapper = new List <string>();

            crayonWrapper.Add(string.Join("\n",
                                          "package %%%PACKAGE%%%;",
                                          "",
                                          "import java.util.ArrayList;",
                                          "import java.util.HashMap;",
                                          "import java.util.Stack;",
                                          "",
                                          "public final class CrayonWrapper {",
                                          "    private CrayonWrapper() {}",
                                          ""));

            this.Translator.CurrentIndention++;
            foreach (string finalCodeKey in items)
            {
                this.Translator.Translate(crayonWrapper, finalCode[finalCodeKey]);
            }
            this.Translator.CurrentIndention--;

            crayonWrapper.Add(string.Join("\n",
                                          "}",
                                          ""));

            output["src/" + package + "/CrayonWrapper.java"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = Constants.DoReplacements(string.Join("", crayonWrapper), replacements)
            };

            string nl = this.Translator.NL;

            foreach (StructDefinition structDefinition in structDefinitions)
            {
                string structName = structDefinition.Name.Value;
                string filename   = structName + ".java";

                List <string> codeContents = new List <string>();

                codeContents.Add("public final class " + structName + " {" + nl);
                codeContents.Add("    public " + structName + "(");
                List <string> types = new List <string>();
                for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
                {
                    string     type;
                    Annotation typeAnnotation = structDefinition.Types[i];
                    if (typeAnnotation == null)
                    {
                        throw new Exception("Are there any of these left?");
                    }
                    else
                    {
                        type = this.GetTypeStringFromAnnotation(typeAnnotation.FirstToken, typeAnnotation.GetSingleArgAsString(null), false, false);
                    }
                    types.Add(type);

                    if (i > 0)
                    {
                        codeContents.Add(", ");
                    }
                    codeContents.Add(type);
                    codeContents.Add(" v_" + structDefinition.FieldsByIndex[i]);
                }
                codeContents.Add(") {" + nl);

                for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
                {
                    codeContents.Add("        this." + structDefinition.FieldsByIndex[i] + " = v_" + structDefinition.FieldsByIndex[i] + ";" + nl);
                }

                codeContents.Add("    }" + nl + nl);
                for (int i = 0; i < structDefinition.FieldsByIndex.Length; ++i)
                {
                    codeContents.Add("    public ");
                    codeContents.Add(types[i]);
                    codeContents.Add(" " + structDefinition.FieldsByIndex[i] + ";" + nl);
                }

                codeContents.Add("}" + nl);

                string fileContents = string.Join("", codeContents);
                string header       = "package " + package + ";" + nl + nl;

                bool useList    = fileContents.Contains("ArrayList<");
                bool useHashMap = fileContents.Contains("HashMap<");
                bool useStack   = fileContents.Contains("Stack<");
                if (useList || useHashMap || useStack)
                {
                    if (useList)
                    {
                        header += "import java.util.ArrayList;" + nl;
                    }
                    if (useHashMap)
                    {
                        header += "import java.util.HashMap;" + nl;
                    }
                    if (useStack)
                    {
                        header += "import java.util.Stack;" + nl;
                    }
                    header += nl;
                }
                fileContents = header + fileContents;

                output["src/" + package + "/" + filename] = new FileOutput()
                {
                    Type        = FileOutputType.Text,
                    TextContent = fileContents
                };
            }

            foreach (string tileFile in resourceDatabase.ImageSheetFiles.Keys)
            {
                output["resources/images/" + tileFile] = resourceDatabase.ImageSheetFiles[tileFile];
            }

            foreach (FileOutput image in resourceDatabase.ImageResources)
            {
                if (image.Type != FileOutputType.Ghost)
                {
                    output["resources/images/" + image.CanonicalFileName] = image;
                }
            }

            foreach (FileOutput textFile in resourceDatabase.TextResources)
            {
                output["resources/text/" + textFile.CanonicalFileName] = textFile;
            }

            Dictionary <string, string> libraryResourceFiles = this.LibraryManager.CopiedFiles;

            foreach (string file in libraryResourceFiles.Keys)
            {
                string content = libraryResourceFiles[file];
                output[file.Replace("%PROJECT_ID%", projectId.ToLower())] = new FileOutput()
                {
                    Type        = FileOutputType.Text,
                    TextContent = Constants.DoReplacements(content, replacements)
                };
            }

            output["resources/bytecode.txt"] = resourceDatabase.ByteCodeFile;
            output["resources/manifest.txt"] = resourceDatabase.ResourceManifestFile;
            if (resourceDatabase.ImageSheetManifestFile != null)
            {
                output["resources/imagesheetmanifest.txt"] = resourceDatabase.ImageSheetManifestFile;
            }

            output["build.xml"] = new FileOutput()
            {
                Type        = FileOutputType.Text,
                TextContent = Constants.DoReplacements(
                    Util.ReadResourceFileInternally("game-java-awt/BuildXml.txt"),
                    replacements)
            };

            return(output);
        }
예제 #58
0
 protected override DependencyObject CloneAnnotation(Annotation annotation)
 {
     return(base.CloneAnnotation(new RectangleAnnotation()));
 }
예제 #59
0
 private void SetAnnotationAndFocussedMessage(Annotation annotation, Message message)
 {
     Annotation             = annotation;
     _currentFocusedMessage = message;
     UpdateContentNow();
 }
 /// <summary>Convert a CoreNLP Annotation object to a Document.</summary>
 /// <param name="ann">The CoreNLP Annotation object.</param>
 public GermanDocument(Annotation ann)
     : base(Edu.Stanford.Nlp.Simple.GermanDocument.EmptyProps, ann)
 {
 }