예제 #1
0
        public ActionResult BusTimes(PostcodeSelection selection)
        {
            var apiOutput = ApiClass.MakeApiCalls(selection.Postcode);
            var info      = new BusInfo(selection.Postcode, apiOutput);

            return(PartialView(info));
        }
예제 #2
0
 private void PostProcess_NN_Prop(ApiClass api, Property property)
 {
     if (property.Type == null && property.DefaultValue != null)
     {
         property.Type = InferPropTypeFromDefaultValue(property);
     }
 }
예제 #3
0
 protected void loginBtn_Click(object sender, EventArgs e)
 {
     if (loginName.Text == "" || password.Text == "")
     {
     }
     else
     {
         ApiClass             apiClass = new ApiClass();
         string               url      = "http://api.traffiti.co/api/Author/AuthorLogin";
         string               json     = "{'authorLogin': '******', 'authorPassword': '******'}";
         string               result   = apiClass.PostCallApi(url, json);
         JavaScriptSerializer js       = new JavaScriptSerializer();
         Author               author   = js.Deserialize <Author>(result);
         if (!string.IsNullOrEmpty(author.access_key) && author.author_id > 0)
         {
             HttpCookie myCookie = new HttpCookie("AccessKey");
             //myCookie.Domain = "traffiti.co";
             myCookie.Value = author.access_key;
             //myCookie["accessKey"] = author.access_key;
             myCookie.Expires = DateTime.Now.AddMonths(1);
             Response.Cookies.Add(myCookie);
             Session["author_id"] = author.author_id;
             Response.Redirect("ProfilePage.aspx");
         }
     }
 }
예제 #4
0
        /// <summary>
        /// Gets the data from a returned request to a json api.
        /// </summary>
        /// <param name="cen_feature">The requested stomt feature.</param>
        /// <param name="cen_login">The authentication mode to login in stomt's api.</param>
        /// <param name="cdt_parameters">The json's content parameters.</param>
        /// <returns>The data returned from the request to api.</returns>
        public static async Task <object> uf_atsk_o_GetDataFromRequest(stomt_feature cen_feature, stomt_authentication cen_login, stomt_parameters cdt_parameters)
        {
            // Create the request to send to remote api.
            stomt_api_request cdt_request = ApiClass.uf_cdt_StomtApiMethodRequestUriSuffix(cen_feature, cen_login, cdt_parameters);

            // Request the data from the remote api asyncrhonously.
            HttpResponseMessage httprm_response = await ApiClass.uf_atsk_httprm_RestApiMethodRequest(publ_httpc_client, cdt_request.s_uri_suffix, cdt_request.httpcn_content, cdt_request.cen_method_request);

            // If http response is empty, then return an empty data and stop the process.
            if (httprm_response == null)
            {
                return(null);
            }

            // Get the data from the api's response asyncrhonously.
            string s_response_content = await httprm_response.Content.ReadAsStringAsync();

            // If the retrieved data is a file, then don't do anything else and return the data instead.
            if ((cen_feature == stomt_feature.retrieve_exported_stomts) || (cen_feature == stomt_feature.retrieve_exported_users))
            {
                return(s_response_content);
            }

            // Corrects the multiple backslash in url from uri data send.
            s_response_content = s_response_content.Replace("\\", ""); // url form fixing.

            // Corrects the multiple backslash in the rest of data from uri data send.
            string[] sa_data = Regex.Split(s_response_content, "([][{}])|(\\\":)|(,\\\")|(\\\")").
                               Where(s_value => s_value != string.Empty).ToArray(); // The multiple backslash characters is the result of the escape characters of backslash (\) and double quotes (").

            // Returns the data from the json response, organized in key value pairs of key and value.
            return(JsonClass.uf_kvpsol_GetDataFromJson(sa_data, 0, null, out int i_new_index));
        }
예제 #5
0
        static void Main(string[] args)
        {
            var input  = GetInput();
            var output = ApiClass.MakeApiCalls(input);

            PrintOutput(output.StopAndBusList);
        }
        public ApiClass ConvertToSongleApiRecord(IList <ApiClass> apiClasses, DateTime dateTime)
        {
            var apiClassObj = new ApiClass();

            foreach (var item in apiClasses)
            {
                apiClassObj.ApiNid         = item.ApiNid;
                apiClassObj.ApiName        = item.ApiName;
                apiClassObj.ApiDateOfBirth = item.ApiDateOfBirth;
            }
            if (apiClassObj.ApiDateOfBirth != null)
            {
                CultureInfo provider   = new CultureInfo("en-GB");
                DateTime    formatDate = DateTime.Parse(apiClassObj.ApiDateOfBirth, provider, DateTimeStyles.NoCurrentDateDefault);
                int         result     = DateTime.Compare(formatDate, dateTime);
                if (result == 0)
                {
                    return(apiClassObj);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
예제 #7
0
        public static object Execute(ApiClass apiClass, HttpRequest request)
        {
            var instance = GetInstance(apiClass.Class);

            if (instance == null)
            {
                throw new Exception("class not exist");
            }

            var requestInstance = instance as ApiBase;

            var apiRequest = new ApiRequest(request);

            requestInstance.Request = apiRequest;
            var method = GetMethod(instance, apiClass.Method);

            if (method == null)
            {
                throw new Exception("method not exist");
            }

            var pars = GetParams(method, apiRequest);
            var obj  = method.Invoke(instance, pars);

            return(obj);
        }
예제 #8
0
    public static string AddLike(int wall_id)
    {
        ApiClass apiClass = new ApiClass();
        string   url      = "http://api.traffiti.co/api/Wall/AddLike";
        string   json     = "{'wall_id': " + wall_id + "}";
        string   result   = apiClass.PostCallApi(url, json);

        return(result);
    }
예제 #9
0
        public ActionResult BusInfo(PostcodeSelection selection)
        {
            if (selection.Postcode == null)
            {
                selection.Postcode = "";
            }
            var apiOutput = ApiClass.MakeApiCalls(selection.Postcode);
            var info      = new BusInfo(selection.Postcode, apiOutput);

            return(View(info));
        }
예제 #10
0
        public override void Init(ApiElement apiElement)
        {
            base.Init(apiElement);

            apiClass = ApiElement as ApiClass;
            if (apiClass == null)
            {
                return;
            }

            Extends             = apiClass.Extends;
            ExtendsGenericAware = apiClass.ExtendsGenericAware;
            Obfuscated          = apiClass.Obfuscated;
        }
예제 #11
0
 private void GetCurrentUser()
 {
     if (Request.Cookies["AccessKey"] != null)
     {
         string               value    = Request.Cookies["AccessKey"].Value;
         ApiClass             apiClass = new ApiClass();
         string               url      = "http://api.traffiti.co/api/Author/AuthorLogin";
         string               json     = "{'accessKey': '" + value + "'}";
         string               result   = apiClass.PostCallApi(url, json);
         JavaScriptSerializer js       = new JavaScriptSerializer();
         author = js.Deserialize <Author>(result);
         GetSetting(author);
     }
 }
예제 #12
0
        protected virtual void GenerateDocString(ApiClass decl, CodeWriter s)
        {
            if (string.IsNullOrWhiteSpace(decl.DocString))
            {
                return;
            }
            var docstring = ProcessDocString(decl.DocString);

            s.Out("/// <summary>");
            foreach (var line in Regex.Split(docstring, @"\r?\n"))
            {
                s.Out("///\t" + line);
            }
            s.Out("/// </summary>");
        }
예제 #13
0
 public static bool Check(int index)
 {
     for (int i = startIndex; i <= index; i++)
     {
         int temp = ApiClass.GetTemperatureOnDay(i);
         for (int j = i + 1; j <= index; j++)
         {
             int nexTemp = ApiClass.GetTemperatureOnDay(j);
             if (Math.Abs(temp - nexTemp) > 5)
             {
                 return(false);
             }
         }
     }
     return(true);
 }
예제 #14
0
    public void ShowCurrentTemp()
    {
        ApiClass             apiClass = new ApiClass();
        string               url      = "http://api.traffiti.co/api/Wall/GetTempPhoto";
        string               json     = "{'authorID': " + Session["author_id"] + "}";
        string               result   = apiClass.PostCallApi(url, json);
        JavaScriptSerializer js       = new JavaScriptSerializer();

        tempPhotoList = js.Deserialize <List <TempPhoto> >(result);

        for (int i = 0; i < tempPhotoList.Count; i++)
        {
            tempPhotoList[i].photo_path = ConfigurationSettings.AppSettings["imageDomain"] + tempPhotoList[i].photo_path;
        }

        tempImageRepeater.DataSource = tempPhotoList;
        tempImageRepeater.DataBind();
    }
예제 #15
0
    public void LoadData()
    {
        ApiClass apiClass = new ApiClass();
        string   url      = "http://api.traffiti.co/api/Wall/GetWall";
        string   lang     = "2"; //default lang

        if (Request.Cookies["PresetLang"] != null)
        {
            lang = Request.Cookies["PresetLang"].Value;
        }
        string json                   = "{'pageNum': 1, 'lang_id': " + lang + "}";
        string result                 = apiClass.PostCallApi(url, json);
        JavaScriptSerializer js       = new JavaScriptSerializer();
        List <Wall>          wallList = js.Deserialize <List <Wall> >(result);

        wallRepeater.DataSource = wallList;
        wallRepeater.DataBind();
    }
예제 #16
0
    public void uploadTemp()
    {
        if (imagesUploader.HasFile)
        {
            //client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

            HttpFileCollection uploadedFiles = Request.Files;
            for (int i = 0; i < uploadedFiles.Count; i++)
            {
                HttpPostedFile userPostedFile = uploadedFiles[i];
                try
                {
                    string fileName = userPostedFile.FileName;
                    string fileExt  = fileName.Substring(fileName.LastIndexOf(".") + 1, fileName.Length - (fileName.LastIndexOf(".") + 1));
                    if (userPostedFile.ContentLength > 0 && userPostedFile.ContentLength < 2048000 && (fileExt.ToLower() == "png" || fileExt.ToLower() == "jpeg" || fileExt.ToLower() == "jpg"))
                    {
                        byte[] fileData   = null;
                        Stream fileStream = null;
                        int    length     = 0;

                        length     = userPostedFile.ContentLength;
                        fileData   = new byte[length + 1];
                        fileStream = userPostedFile.InputStream;
                        fileStream.Read(fileData, 0, length);
                        MemoryStream stream = new MemoryStream(fileData);

                        UploadImageS3("client_temp/" + Session["author_id"] + "/" + fileName, stream);

                        ApiClass apiClass = new ApiClass();
                        string   url      = "http://api.traffiti.co/api/Wall/SaveTempPhoto";
                        string   json     = "{'authorID': " + Session["author_id"] + ", 'photoPath': '" + "client_temp/" + Session["author_id"] + "/" + fileName + "'}";
                        string   result   = apiClass.PostCallApi(url, json);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
예제 #17
0
        protected virtual void Process(HierarchyNamespace parent, ApiClass klass)
        {
            var hierarchyClass = CreateHierarchyElementInternal <HierarchyClass> (parent);

            hierarchyClass.Init(klass);

            AddLocationComment(klass, hierarchyClass);
            Helpers.ForEachNotNull(klass.ChildElements, (ApiElement e) => {
                switch (e)
                {
                case ApiField field:
                    Process(hierarchyClass, field);
                    break;

                case ApiConstructor constructor:
                    Process(hierarchyClass, constructor);
                    break;

                case ApiMethod method:
                    Process(hierarchyClass, method);
                    break;

                case ApiImplements implements:
                    Process(hierarchyClass, implements);
                    break;

                case ApiTypeParameter typeParameter:
                    Process(hierarchyClass, typeParameter);
                    break;

                default:
                    Logger.Warning($"Unexpected member type for ApiClass: '{e.GetType ().FullName}'");
                    break;
                }
            });

            parent.AddMember(hierarchyClass);
            TypeIndex.Add(hierarchyClass);
        }
예제 #18
0
    public void LoadData()
    {
        ApiClass             apiClass = new ApiClass();
        string               url      = "http://api.traffiti.co/api/Wall/GetWallDetail";
        string               json     = "{'wall_id': " + Request.QueryString["wall_id"] + ", 'lang_id': 1}";
        string               result   = apiClass.PostCallApi(url, json);
        JavaScriptSerializer js       = new JavaScriptSerializer();

        wallList = js.Deserialize <WallDetail>(result);
        StringBuilder sb = new StringBuilder();

        wallList.photoList.Remove("");

        for (int i = 0; i < wallList.photoList.Count; i++)
        {
            if (i == 0)
            {
                sb.AppendLine("<div class=\"carousel-item active\">");
            }
            else
            {
                sb.AppendLine("<div class=\"carousel-item\">");
            }
            sb.AppendLine("<img class=\"d-block img-fluid\" src=\"" + wallList.photoList[i] + "\" alt=\"" + wallList.photoList[i] + "\">");
            sb.AppendLine("</div>");
        }
        imageList = sb.ToString();

        for (int i = 0; i < wallList.contentList.Count; i++)
        {
            contentList += wallList.contentList[i] + "<br/>";
        }



        //imageRepeater.DataSource = wallList.photoList;
        //imageRepeater.DataBind();
    }
예제 #19
0
 private void CheckAccessKey()
 {
     if (Request.Cookies["AccessKey"] != null)
     {
         string               value    = Request.Cookies["AccessKey"].Value;
         ApiClass             apiClass = new ApiClass();
         string               url      = "http://api.traffiti.co/api/Author/AuthorLogin";
         string               json     = "{'accessKey': '" + value + "'}";
         string               result   = apiClass.PostCallApi(url, json);
         JavaScriptSerializer js       = new JavaScriptSerializer();
         Author               author   = js.Deserialize <Author>(result);
         if (!string.IsNullOrEmpty(author.access_key) && author.author_id > 0)
         {
             HttpCookie myCookie = new HttpCookie("AccessKey");
             //myCookie.Domain = "traffiti.co";
             myCookie.Value = author.access_key;
             //myCookie["accessKey"] = author.access_key;
             myCookie.Expires = DateTime.Now.AddMonths(1);
             Response.Cookies.Add(myCookie);
             Session["author_id"] = author.author_id;
             Response.Redirect("ProfilePage.aspx");
         }
     }
 }
예제 #20
0
    private void GetWall(int authorID, int page, int lang_id)
    {
        ApiClass             apiClass = new ApiClass();
        string               url      = "http://api.traffiti.co/api/Wall/GetProfileWallList";
        string               json     = "{'pageNum': " + page + ", 'lang_id': " + lang_id + ", 'authorID': " + authorID + "}";
        string               result   = apiClass.PostCallApi(url, json);
        JavaScriptSerializer js       = new JavaScriptSerializer();
        List <WallDetail>    wdList   = js.Deserialize <List <WallDetail> >(result);

        for (int i = 0; i < wdList.Count; i++)
        {
            for (int j = 0; j < wdList[i].photoList.Count; j++)
            {
                wdList[i].photos += "<div class=\"col\">";
                wdList[i].photos += "<a href = 'PostDetail.aspx?wall_id=" + wdList[i].wall_id + "'>";
                wdList[i].photos += "<img src=\" " + wdList[i].photoList[j] + "\" class=\"img-fluid\" alt=\"wall_item_cover\">";
                wdList[i].photos += "</a>";
                wdList[i].photos += "</div>";
            }
        }

        wallRepeater.DataSource = wdList;
        wallRepeater.DataBind();
    }
예제 #21
0
    protected void postBtn_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["author_id"] == null)
            {
                content.Text = "Empty session";
            }
            else
            {
                ShowCurrentTemp();
                ApiClass         apiClass = new ApiClass();
                string           url      = "http://api.traffiti.co/api/Wall/CreateWall";
                ComingCreateWall ccw      = new ComingCreateWall();
                ccw.author_id = Convert.ToInt32(Session["author_id"]);
                if (!string.IsNullOrEmpty(hiddenLocation.Value))
                {
                    ccw.location = hiddenLocation.Value;
                }
                else
                {
                    ccw.location = "";
                }
                if (!string.IsNullOrEmpty(lat.Value))
                {
                    ccw.lat = lat.Value;
                }
                else
                {
                    ccw.lat = "";
                }
                if (!string.IsNullOrEmpty(lat.Value))
                {
                    ccw.lon = lon.Value;
                }
                else
                {
                    ccw.lon = "";
                }
                ccw.message   = content.Text;
                ccw.photoList = new List <string>();
                for (int i = 0; i < tempPhotoList.Count; i++)
                {
                    ccw.photoList.Add(tempPhotoList[i].photo_path);
                }
                ccw.publishList = new List <string>();
                JavaScriptSerializer js          = new JavaScriptSerializer();
                string           json            = js.Serialize(ccw);
                string           result          = apiClass.PostCallApi(url, json);
                ComingCreateWall afterCreateWall = js.Deserialize <ComingCreateWall>(result);


                for (int i = 0; i < tempPhotoList.Count; i++)
                {
                    //copy photo
                    WebClient    WC     = new WebClient();
                    MemoryStream stream = new MemoryStream(WC.DownloadData(tempPhotoList[i].photo_path));
                    UploadImageS3("client_upload/" + Session["author_id"] + "/" + afterCreateWall.publishList[i], stream);
                }
            }
            //Response.Redirect("Recently.aspx");
        }
        catch (Exception ex)
        {
            content.Text = ex.Message;
        }

        Response.Redirect("RecentlyList.aspx");
        //if (imagesUploader.HasFile)
        //{
        //    //client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

        //    HttpFileCollection uploadedFiles = Request.Files;
        //    for(int i = 0;i < uploadedFiles.Count;i++)
        //    {
        //        HttpPostedFile userPostedFile = uploadedFiles[i];
        //        try
        //        {
        //            string fileName = userPostedFile.FileName;
        //            string fileExt = fileName.Substring(fileName.LastIndexOf(".") + 1, fileName.Length - (fileName.LastIndexOf(".") + 1));
        //            if (userPostedFile.ContentLength > 0 && userPostedFile.ContentLength < 2048000 && (fileExt.ToLower() == "png" || fileExt.ToLower() == "jpeg" || fileExt.ToLower() == "jpg"))
        //            {
        //                byte[] fileData = null;
        //                Stream fileStream = null;
        //                int length = 0;

        //                length = userPostedFile.ContentLength;
        //                fileData = new byte[length + 1];
        //                fileStream = userPostedFile.InputStream;
        //                fileStream.Read(fileData, 0, length);
        //                MemoryStream stream = new MemoryStream(fileData);

        //                UploadImageS3("client_temp/" + Session["author_id"] + "/" + fileName, stream);
        //            }
        //        }
        //        catch (Exception ex)
        //        {

        //        }
        //    }
        //}
    }
예제 #22
0
파일: Session.cs 프로젝트: r2d2m/NIOS
 public void Init()
 {
     Api = new ApiClass();
     Api.InitializeSession(this);
 }
예제 #23
0
        private IEnumerable <Declaration> InferOverloads_NN(ApiClass api, Declaration f)
        {
            switch (f.Name)
            {
            case "to":
                yield return(new Function()
                {
                    Name = "to", Arguments =
                    {
                        new Argument()
                        {
                            Name = "device", Type = "Device",
                        },
                        new Argument()
                        {
                            Name = "dtype", Type = "Dtype",
                        },
                        new Argument()
                        {
                            Name = "non_blocking", Type = "bool", DefaultValue = "false"
                        },
                    },
                    Returns = { new Argument()
                                {
                                    Type = "Module"
                                } }
                });

                yield return(new Function()
                {
                    Name = "to", Arguments =
                    {
                        new Argument()
                        {
                            Name = "dtype", Type = "Dtype",
                        },
                        new Argument()
                        {
                            Name = "non_blocking", Type = "bool", DefaultValue = "false"
                        },
                    },
                    Returns = { new Argument()
                                {
                                    Type = "Module"
                                } }
                });

                yield return(new Function()
                {
                    Name = "to", Arguments =
                    {
                        new Argument()
                        {
                            Name = "tensor", Type = "Tensor",
                        },
                        new Argument()
                        {
                            Name = "non_blocking", Type = "bool", DefaultValue = "false"
                        },
                    },
                    Returns = { new Argument()
                                {
                                    Type = "Module"
                                } }
                });

                yield break;
            }
            var fullname = $"{api.ClassName.Split(".").Last()}.{f.Name}";

            switch (fullname)
            {
            }
            yield return(f);
        }
예제 #24
0
 public void AddApiClass(ApiClass apiClass)
 {
     _electionUnitOfWork.ApiEntityRepository.Add(apiClass);
     _electionUnitOfWork.Save();
 }
        public void SetupApi()
        {
            ApiClass apiClass = new ApiClass(username, password, host);

            api = apiClass.GetApiService();
        }
예제 #26
0
 public void Get(string URL)
 {
     using (var api = new ApiClass()) { api.Get(URL); }
 }
예제 #27
0
        public void AddToModule()
        {
            StartTime = DateTime.Now;
            string logFile = System.IO.Path.GetDirectoryName(FilePath) + "\\" + System.IO.Path.GetFileNameWithoutExtension(FilePath) + ".log";
            var    log     = new System.IO.StreamWriter(logFile, false);

            log.Log(StartTime, "Beginning import of {0}", FilePath);
            Component        component   = Sprocs.GetOrCreateComponent(ModuleId, File, Version);
            ComponentHistory historyItem = Sprocs.GetOrCreateComponentHistory(component.ComponentId, FullName, Version, VersionNormalized, CodeLines, CommentLines, EmptyLines);

            log.Log(StartTime, "Component is {0}, ID={1}, version={2}", component.ComponentName, component.ComponentId, Version);
            foreach (XmlNode depNode in DocumentElement.SelectSingleNode("dependencies").SelectNodes("dependency"))
            {
                var dep = Sprocs.GetOrCreateDependency(historyItem.ComponentHistoryId, depNode.InnerText, depNode.Attributes["version"].InnerText, depNode.Attributes["versionnorm"].InnerText, depNode.Attributes["name"].InnerText);
            }
            List <int> handledClassIds = new List <int>();

            foreach (XmlNode namespaceNode in DocumentElement.SelectNodes("namespace"))
            {
                ApiNamespace ns = ApiNamespaceRepository.Instance.GetOrCreateNamespace(ModuleId, namespaceNode.Attributes["name"].InnerText);
                log.Log(StartTime, "Namespace {0}", ns.NamespaceName);
                foreach (XmlNode classNode in namespaceNode.SelectNodes("class"))
                {
                    List <int> handledMemberIds   = new List <int>();
                    bool       isDeprecated       = false;
                    string     deprecationMessage = "";
                    if (classNode.SelectSingleNode("deprecation") != null)
                    {
                        isDeprecated       = true;
                        deprecationMessage = classNode.SelectSingleNode("deprecation").InnerText;
                    }
                    try
                    {
                        var      documentation = classNode.SelectSingleNode("documentation").InnerXml.Trim();
                        var      description   = tryGetDescription(documentation);
                        ApiClass cl            = Sprocs.GetOrCreateClass(ns.NamespaceId, component.ComponentId, classNode.Attributes["name"].InnerText.Trim(), classNode.SelectSingleNode("fullName").InnerText.Trim(), classNode.SelectSingleNode("declaration").InnerText.Trim(), documentation, description, Version, isDeprecated, deprecationMessage.Trim(),
                                                                         bool.Parse(classNode.Attributes["IsAbstract"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsAnsiClass"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsArray"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsAutoClass"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsAutoLayout"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsBeforeFieldInit"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsByReference"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsClass"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsDefinition"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsEnum"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsExplicitLayout"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsFunctionPointer"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsGenericInstance"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsGenericParameter"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsImport"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsInterface"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsNested"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsNestedAssembly"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsNestedPrivate"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsNestedPublic"].InnerText),
                                                                         bool.Parse(classNode.Attributes["IsNotPublic"].InnerText));
                        log.Log(StartTime, "Class {0} (ID={1})", cl.ClassName, cl.ClassId);
                        foreach (XmlNode memberNode in classNode.SelectNodes("constructors/constructor"))
                        {
                            handledMemberIds.Add(AddMemberToClass(ModuleId, cl.ClassId, memberNode, MemberType.Constructor, ref log));
                        }
                        foreach (XmlNode memberNode in classNode.SelectNodes("methods/method"))
                        {
                            handledMemberIds.Add(AddMemberToClass(ModuleId, cl.ClassId, memberNode, MemberType.Method, ref log));
                        }
                        foreach (XmlNode memberNode in classNode.SelectNodes("fields/field"))
                        {
                            handledMemberIds.Add(AddMemberToClass(ModuleId, cl.ClassId, memberNode, MemberType.Field, ref log));
                        }
                        foreach (XmlNode memberNode in classNode.SelectNodes("properties/property"))
                        {
                            handledMemberIds.Add(AddMemberToClass(ModuleId, cl.ClassId, memberNode, MemberType.Property, ref log));
                        }
                        foreach (XmlNode memberNode in classNode.SelectNodes("events/event"))
                        {
                            handledMemberIds.Add(AddMemberToClass(ModuleId, cl.ClassId, memberNode, MemberType.Event, ref log));
                        }
                        foreach (var m in MemberRepository.Instance.GetMembersByApiClass(cl.ClassId))
                        {
                            if (!handledMemberIds.Contains(m.MemberId))
                            {
                                Sprocs.MemberDisappeared(m.MemberId, Version);
                            }
                        }
                        handledClassIds.Add(cl.ClassId);
                        log.Log(StartTime, "Finished class {0}", cl.ClassName);
                    }
                    catch (Exception ex)
                    {
                        Exceptions.LogException(ex);
                        log.Log(StartTime, "Exception {0}. Stacktrace: {1}.", ex.Message, ex.StackTrace);
                    }
                }
            }

            foreach (ApiClass c in ApiClassRepository.Instance.GetApiClassesByComponent(component.ComponentId))
            {
                if (!handledClassIds.Contains(c.ClassId))
                {
                    Sprocs.ClassDisappeared(c.ClassId, Version);
                }
            }

            try
            {
                System.IO.File.Delete(this.FilePath);
                log.Log(StartTime, "Deleted {0}", FilePath);
            }
            catch (Exception ex)
            {
                log.Log(StartTime, "Could not delete {0}", FilePath);
            }

            log.Log(StartTime, "Finished component {0}", component.ComponentName);
            log.Flush();
            log.Close();
        }
예제 #28
0
 public static void InitSequence()
 {
     totalNumberDays = ApiClass.GetNumDays();
     LongestStreak(totalNumberDays);
 }
예제 #29
0
        public virtual void GenerateClass(ApiClass api, CodeWriter s)
        {
            GenerateUsings(s);
            s.AppendLine($"namespace {NameSpace}");
            s.Block(() =>
            {
                var names          = new ArraySlice <string>(api.ClassName.Split('.'));
                var static_classes = names.GetSlice(new Slice(0, names.Length - 1));
                var class_name     = names.Last();
                int levels         = names.Length - 1;
                if (levels > 0)
                {
                    foreach (var name in static_classes)
                    {
                        s.Out($"public static partial class {EscapeName(name)} {{");
                        s.Indent();
                    }
                }
                GenerateDocString(api, s);
                s.Out($"public partial class {EscapeName(class_name)} : {EscapeName(api.BaseClass)}");
                s.Block(() =>
                {
                    s.Out($"// auto-generated class");
                    s.Break();
                    s.Out($"public {EscapeName(class_name)}(PyObject pyobj) : base(pyobj) {{ }}");
                    s.Break();
                    s.Out($"public {EscapeName(class_name)}({EscapeName(api.BaseClass)} other) : base(other.PyObject as PyObject) {{ }}");
                    s.Break();

                    // additional constructors
                    foreach (var func in api.Constructors)
                    {
                        try
                        {
                            if (func.ManualOverride || func.Ignore)
                            {
                                continue;
                            }
                            func.Sanitize();
                            func.IsConstructor = true;
                            func.ClassName     = string.Join(".", static_classes);
                            func.Name          = class_name;
                            var arguments      = GenerateArguments(func);
                            //var passed_args = GeneratePassedArgs(func);
                            s.Out($"public {EscapeName(class_name)}({arguments})");
                            s.Block(() =>
                            {
                                GenerateFunctionBody(func, s);
                            });
                        }
                        catch (Exception e)
                        {
                            s.Out("// Error generating constructor");
                            s.Out("// Message: " + e.Message);
                            s.Out("/*");
                            s.Out(e.StackTrace);
                            s.Out("----------------------------");
                            s.Out("Declaration JSON:");
                            s.Out(JObject.FromObject(func).ToString(Formatting.Indented));
                            s.Out("*/");
                        }
                    }
                    // functions
                    s.Break();
                    foreach (var decl in api.Declarations)
                    {
                        try
                        {
                            if (decl.ManualOverride || decl.Ignore)
                            {
                                continue;
                            }
                            GenerateApiFunction(decl, s);
                        }
                        catch (Exception e)
                        {
                            s.Out("// Error generating delaration: " + decl.Name);
                            s.Out("// Message: " + e.Message);
                            s.Out("/*");
                            s.Out(e.StackTrace);
                            s.Out("----------------------------");
                            s.Out("Declaration JSON:");
                            s.Out(JObject.FromObject(decl).ToString(Formatting.Indented));
                            s.Out("*/");
                        }
                    }
                });
                if (levels > 0)
                {
                    foreach (var name in static_classes)
                    {
                        s.Outdent();
                        s.Out("}");
                    }
                }
                //if (decl.CommentOut)
                //    s.Out("*/");
                s.Break();
            });
        }
예제 #30
0
        private void PostProcess_NN_Func(ApiClass api, Function func)
        {
            foreach (var arg in func.Arguments)
            {
                PostProcess(arg);
            }
            var fullname = $"{api.ClassName.Split(".").Last()}.{func.Name}";

            switch (fullname)
            {
            case "Module.apply":
                func["fn"].Type = "Action<Module>";
                break;

            case "Module.forward":
                func.Ignore = true;
                break;

            case "Module.load_state_dict":
                func.Returns[0].Type = "string[]";
                func.Returns.Add(new Argument()
                {
                    Type = "string[]"
                });
                break;

            case "Module.named_buffers":
            case "Module.named_children":
            case "Module.named_modules":
            case "Module.named_parameters":
                func.Returns[0].Type = "IEnumerable<KeyValuePair<string, Tensor>>";
                if (fullname == "Module.named_modules")
                {
                    func["memo"].Type = "HashSet<object>";
                }
                break;

            case "Module.register_backward_hook":
                func["hook"].Type = "Func<Module, Tensor[], Tensor[], Tensor>";
                break;

            case "Module.register_forward_hook":
                func["hook"].Type = "Action<Module, Tensor[], Tensor[]>";
                break;

            case "Module.register_forward_pre_hook":
                func["hook"].Type = "Action<Module, Tensor[]>";
                break;

            case "Module.state_dict":
                func["destination"].Type = "Hashtable";
                break;

            case "MultiheadAttention.forward":
                func.Ignore = true;
                break;
            }
            switch (func.Name)
            {
            case "predict":
                func.Returns[0].Type = "Tensor";
                break;
            }
        }