public rfFolders() { InitializeComponent(); dt = BasicFunctions.GetData("Select Distinct Ordtask.Folderno from ordtask,preptasks,Folders where ordtask.ordno = preptasks.ordno and ordtask.testcode = preptasks.testcode and ordtask.Folderno = Folders.Folderno and preptasks.prepts='Need Prep' and preptasks.dept = 'KELSO' and preptasks.preprunno=-1 and folders.fldsts <> 'Draft' and APPRSTS = 'N/A' and folders.qcfolder = 'N' and ordtask.ts = 'Hold' and (ordtask.sp_Code <> 379 and ordtask.sp_Code <> 378) and preptasks.preptmname is not null and preptasks.sampweight IS NULL Order by Ordtask.Folderno"); rlvFolders.DataSource = dt; rlvFolders.DisplayMember = "FOLDERNO"; }
/// <summary> /// Fill the target and the source registeries or memory that the user can choose /// </summary> /// <param name="function">The function that we want to restrict some registery or memory access</param> /// <param name="editCollection">If true will update the edit collections</param> protected void FillTargetAndSourceRegisteries(BasicFunctions function) { UpdateListOnFunctionChange(ref mTargetRegisteries, ref mSourceRegisteries, ref mCanChooseSource02, function); RaisePropertyChanged(nameof(TargetRegisters)); RaisePropertyChanged(nameof(SourceRegisteries)); RaisePropertyChanged(nameof(CanChooseSource02)); }
/// <summary> /// Initializes a new instance of the <see cref="Config"/> class. /// </summary> public Config() { InitializeComponent(); SetIcons(); IrssLog.Info("Load plugins from " + Application.StartupPath + "..."); try { _transceivers = BasicFunctions.AvailablePlugins(); } catch (Exception ex) { IrssLog.Error(ex); _transceivers = null; } if (_transceivers == null || _transceivers.Length == 0) { MessageBox.Show(this, "No IR Server Plugins found!", "IR Server Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { CreateGrid(); } LoadSettings(); }
/// <summary> /// Retreives a list of detected Blaster plugins. /// </summary> /// <returns>String array of plugin names.</returns> public static string[] DetectBlasters() { IrssLog.Info("Detect Blasters ..."); PluginBase[] plugins = BasicFunctions.AvailablePlugins(); if (plugins == null || plugins.Length == 0) { return(null); } List <string> blasters = new List <string>(); foreach (PluginBase plugin in plugins) { try { if (plugin is ITransmitIR && plugin.Detect() == PluginBase.DetectionResult.DevicePresent) { blasters.Add(plugin.Name); } } catch (Exception ex) { IrssLog.Error(ex); } } if (blasters.Count > 0) { return(blasters.ToArray()); } return(null); }
/// <summary> /// Retreives a list of detected Receiver plugins. /// </summary> /// <returns>String array of plugin names.</returns> public static string[] DetectReceivers() { IrssLog.Info("Detect Receivers ..."); PluginBase[] plugins = BasicFunctions.AvailablePlugins(); if (plugins == null || plugins.Length == 0) { return(null); } List <string> receivers = new List <string>(); foreach (PluginBase plugin in plugins) { try { if ((plugin is IRemoteReceiver || plugin is IKeyboardReceiver || plugin is IMouseReceiver) && plugin.Detect() == PluginBase.DetectionResult.DevicePresent) { receivers.Add(plugin.Name); } } catch (Exception ex) { IrssLog.Error(ex); } } if (receivers.Count > 0) { return(receivers.ToArray()); } return(null); }
private void AddFile() { string filePath = testMode ? Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"../../../File Examples/file_example_1.mp3")) : GetFilePath_OpenDialog("mp3"); if (filePath != null && File.Exists(filePath) && !BasicFunctions.FileInUse(filePath)) { // check if File is already in list bool FileIsInList = false; foreach (MusicFileTag FileInList in MusicFileTags) { if (FileInList.FilePath == filePath) { FileIsInList = true; MessageBox.Show("This file is already in the list"); } } if (!FileIsInList) { MusicFileTag newFile = TaggingLogic.AddFile(filePath); MusicFileTags.Add(newFile); NumberOfFiles++; } } else { if (BasicFunctions.FileInUse(filePath)) { MessageBox.Show("Sorry, this file cannot be opened. " + "Either it is currently in use or this program does not have the necessary rights to read the file."); } } }
public static ServusMessage createServusMessage(Modulename mod, BasicFunctions func) { ServusMessage internalServusMsg = new ServusMessage { Modul = mod, Basicfunc = func }; return(internalServusMsg); }
public IEither <string, TOutput> Parse(IEnumerable <TInput> input) { return ((from parseResult in Out from allDone in ParserState <TInput> .IsEoF() from _ in BasicFunctions.EIf(allDone, () => parseResult, () => "Parser didn't parse all available input").ToStateEither <ParserState <TInput>, string, TOutput>() select _) .Out .Run(new ParserState <TInput>(input.ToArray())) .Item2); }
public float CalculateValue() { if (ValueCalculated) { return(Value); } RawValue = isInput ? inputValue : weights.Sum(weight => weight.Key.CalculateValue() * weight.Value) + bias; Value = isInput ? inputValue : BasicFunctions.Sigmoid(RawValue); desiredValue = Value; ValueCalculated = true; return(Value); }
public void Train(float[][] trainingInputs, float[][] trainingOutputs) { for (var i = 0; i < trainingInputs.Length; i++) { Test(trainingInputs[i]); for (var j = 0; j < desiredValues[desiredValues.Length - 1].Length; j++) { desiredValues[desiredValues.Length - 1][j] = trainingOutputs[i][j]; } for (var j = values.Length - 1; j >= 1; j--) { for (var k = 0; k < values[j].Length; k++) { var biasSmudge = BasicFunctions.SigmoidDerivative(values[j][k]) * (desiredValues[j][k] - values[j][k]); biasesSmudge[j][k] += biasSmudge; for (var l = 0; l < values[j - 1].Length; l++) { var weightSmudge = values[j - 1][l] * biasSmudge; weightsSmudge[j - 1][k][l] += weightSmudge; var valueSmudge = weights[j - 1][k][l] * biasSmudge; desiredValues[j - 1][l] += valueSmudge; } } } } for (var i = values.Length - 1; i >= 1; i--) { for (var j = 0; j < values[i].Length; j++) { biases[i][j] += biasesSmudge[i][j]; biases[i][j] *= 1 - WeightDecay; biasesSmudge[i][j] = 0; for (var k = 0; k < values[i - 1].Length; k++) { weights[i - 1][j][k] += weightsSmudge[i - 1][j][k]; weights[i - 1][j][k] *= 1 - WeightDecay; weightsSmudge[i - 1][j][k] = 0; } desiredValues[i][j] = 0; } } }
/// <summary> /// Конвертация радиальной базисной функции из model в радиальную базисную функцию view. /// </summary> private static VBasicFunctions ConvertBasicFunctionsToVBasicFunctions(BasicFunctions basicFunctions) { switch (basicFunctions) { case BasicFunctions.MultiLog: return(VBasicFunctions.MultiLog); case BasicFunctions.MultiQuadric: return(VBasicFunctions.MultiQuadric); case BasicFunctions.InverseMultiQuadric: return(VBasicFunctions.InverseMultiQuadric); case BasicFunctions.NaturalCubicSpline: return(VBasicFunctions.NaturalCubicSpline); case BasicFunctions.ThinPlateSpline: return(VBasicFunctions.ThinPlateSpline); default: return(VBasicFunctions.MultiLog); } }
public float[] Test(float[] newInput) { for (var i = 0; i < values[0].Length; i++) { values[0][i] = newInput[i]; } for (var i = 1; i < values.Length; i++) { for (var j = 0; j < values[i].Length; j++) { values[i][j] = BasicFunctions.Sigmoid(Sum(values[i - 1], weights[i - 1][j]) + biases[i][j]); desiredValues[i][j] = values[i][j]; } } return(values[values.Length - 1]); }
private void Awake() { if (feedingScript == null) { feedingScript = GetComponentInParent <GirlFeeding>(); } // Setting up trigger events FeedingRoom feedingRoom = GameObject.FindWithTag("MainCamera").GetComponentInChildren <FeedingRoom>(); BasicFunctions basicFunctions = GameObject.FindWithTag("GameController").GetComponent <BasicFunctions>(); onMouthEvent.AddListener(() => { basicFunctions.CancelUIDrag(); feedingRoom.ConsumeItem(); feedingRoom.PlaySFX(); feedingRoom.UpdateFullnessText(); }); }
private void LoadPlaylist() { string playlistPath = testMode ? @"../../../File Examples/My Playlist.m3u" : GetFilePath_OpenDialog("m3u"); if (playlistPath != null && !BasicFunctions.FileInUse(playlistPath)) { MusicFileTags = Logic.LoadPlaylist(playlistPath); } else { if (BasicFunctions.FileInUse(playlistPath)) { MessageBox.Show("Sorry, this file cannot be opened. " + "Either it is currently in use or this program does not have the necessary rights to read the file."); } } NumberOfFiles = MusicFileTags.Count; }
// Function to get an Operation result public async Task <string> GetVideoAnnotateOperation(String op_name) { if (BasicFunctions.isEmpty(APIKey) || BasicFunctions.isEmpty(op_name)) { return(null); } httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // API address to which we will make the HTTP POST query String request_query = "v1/operations/" + $"{op_name}?key={APIKey}"; HttpResponseMessage response = await httpClient.GetAsync(request_query); Stream stream = await response.Content.ReadAsStreamAsync(); StreamReader streamReader = new StreamReader(stream); String response_str = streamReader.ReadToEnd(); return(response_str); }
public void Switch_Gravity(Vector3 new_Gravity, Vector3 hitpoint) { if (networkView.isMine || BasicFunctions.playOffline) { /*if (new_Gravity != Gravity_Direction) { * before_shift = transform.rotation; * Gravity_Direction = new_Gravity; * Vector3 New_Player_Forward_tmp = BasicFunctions.ProjectVectorOnPlane (Gravity_Direction, transform.forward); * after_shift = Quaternion.LookRotation (New_Player_Forward_tmp, Gravity_Direction * -1f); * Gravity_Shift_Counter = Gravity_Shift_Time; * }*/ if (new_Gravity != Gravity_Direction) { before_shift = transform.rotation; before_shift_cam = Main_Camera.rotationY; before_shift_vel = rigidbody.velocity; if (new_Gravity == Gravity_Direction * -1f) { //180 Graden draaien heeft aparte behandeling nodig after_shift = Quaternion.LookRotation(transform.forward, new_Gravity * -1f); after_shift_cam = before_shift_cam * -1f; //Debug.Log("180 graden draai"); } else { //berekenen wat voor extra hoek erij moet. Vector3 player2point = hitpoint - transform.position; //berekenen wat voor extra hoek erij moet. Vector3 extra_tmp = BasicFunctions.ProjectVectorOnPlane(new_Gravity, BasicFunctions.ProjectVectorOnPlane(Gravity_Direction, player2point)); //Debug.Log(extra_tmp); after_shift = Quaternion.LookRotation(Gravity_Direction * -1f + extra_tmp, new_Gravity * -1f); after_shift_cam = 0f; } Gravity_Shift_Counter = Gravity_Shift_Time; Gravity_Direction = new_Gravity; } } }
/// <summary> /// Retreives a plugin instance given the plugin name. /// </summary> /// <param name="pluginName">Name of plugin to instantiate.</param> /// <returns>Plugin instance.</returns> internal static PluginBase GetPlugin(string pluginName) { if (String.IsNullOrEmpty(pluginName)) { throw new ArgumentNullException("pluginName"); } PluginBase[] serverPlugins = BasicFunctions.AvailablePlugins(); if (serverPlugins == null) { throw new FileNotFoundException("No available plugins found"); } foreach (PluginBase plugin in serverPlugins) { if (plugin.Name.Equals(pluginName, StringComparison.OrdinalIgnoreCase)) { return(plugin); } } throw new InvalidOperationException(String.Format("Plugin not found ({0})", pluginName)); }
/// <summary> /// Updates the lists sent to it based on the value of the function that is sent to it /// </summary> /// <param name="targetRegistries"></param> /// <param name="sourceRegistries"></param> /// <param name="canChooseSource02"></param> /// <param name="function"></param> protected void UpdateListOnFunctionChange( ref ObservableCollection <string> targetRegistries, ref ObservableCollection <string> sourceRegistries, ref bool canChooseSource02, BasicFunctions function) { targetRegistries = new ObservableCollection <string>(); sourceRegistries = new ObservableCollection <string>(); //If it is a load opperation if (function == BasicFunctions.LD) { //You can only load to registers targetRegistries = new ObservableCollection <string>(Enum.GetNames(typeof(Registeries))); //And the source is only a registery sourceRegistries = new ObservableCollection <string>(Enum.GetNames(typeof(Memmories))); } //If the operation is a store else if (function == BasicFunctions.SD) { //You can only store in memeory targetRegistries = new ObservableCollection <string>(Enum.GetNames(typeof(Memmories))); //And get the data from the registeries sourceRegistries = new ObservableCollection <string>(Enum.GetNames(typeof(Registeries))); } else { //If anything else the target can be any targetRegistries = new ObservableCollection <string>(Enum.GetNames(typeof(Memmories))); targetRegistries.AddRange(Enum.GetNames(typeof(Registeries))); //But only sorce from the registers sourceRegistries = new ObservableCollection <string>(Enum.GetNames(typeof(Registeries))); } CanChooseSource02 = !(function == BasicFunctions.LD || function == BasicFunctions.SD); }
public ActionResult Create([Bind(Include = "CalculationID,CalculationName,CalculationFormula,PhysicalUnit,DataStatus,DescriptionEN,DescriptionDE,CreatedOn,CreatedBy,ModifiedOn,ModifiedBy,DataFormatID")] Calculation calculation) { try { if (ModelState.IsValid) { if (db.Calculation.Any(x => x.CalculationName.Equals(calculation.CalculationName))) { ModelState.AddModelError("CalculationName", "Calculation Name already exists"); ViewBag.set = db.TcSet.Where(x => x.TcSetID != 0 && x.DataFormat.FormatType.Equals("Number")); ViewBag.DataFormatID = new SelectList(db.DataFormat.OrderBy(x => x.FormatName), "DataFormatID", "FormatName", calculation.DataFormatID); return View(calculation); } var FunctionList = new BasicFunctions(); var delimstringlist = new string[] { "Min", "Max", "Abs" ,"Pow","+","-","*","/","(",")","²","³","Length"," ","\r","\n",",","[","]","Sqrt","Cubrt","^"}; string[] formulaSplit = calculation.CalculationFormula.Split(delimstringlist,StringSplitOptions.RemoveEmptyEntries); double constant = 0; foreach(var s in formulaSplit) { if(!db.TcSet.Any(x=>x.SetName==s && x.DataFormat.FormatType=="Number")&&!double.TryParse(s,out constant)) { ModelState.AddModelError("CalculationFormula", "Formula contains unidentified property names"); ViewBag.set = db.TcSet.Where(x => x.TcSetID != 0 && x.DataFormat.FormatType.Equals("Number")); ViewBag.DataFormatID = new SelectList(db.DataFormat.OrderBy(x => x.FormatName), "DataFormatID", "FormatName", calculation.DataFormatID); return View(calculation); } } calculation.CreatedBy = User.Identity.Name; calculation.CreatedOn = DateTime.Now; calculation.ModifiedBy = User.Identity.Name; calculation.ModifiedOn = DateTime.Now; db.Calculation.Add(calculation); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.set = db.TcSet.Where(x => x.TcSetID != 0); ViewBag.DataFormatID = new SelectList(db.DataFormat.OrderBy(x => x.FormatName), "DataFormatID", "FormatName", calculation.DataFormatID); return View(calculation); } catch (Exception e) { ViewBag.Error = e.Message; return View("Error"); } }
/* * Method: GetPlacesDetail * * Description: This method can be used to query the Places API for details regarding places with a * specific place_id. The place_id is usually obtained from the response of a Place Search function. * * Parameters: * - place_id (String): A String identifier that uniquely identifies a place. This is returned as part * of the response from the Place Search functions. For more details about place_id: * https://developers.google.com/places/web-service/place-id * * - APIKey (String): Implicity required paramter which should be set through the constructor when * creating an object of this class. For more details about the Google API Key please see: * https://developers.google.com/places/web-service/get-api-key * * Return: The method returns a tuple of two items. The first is an object of PlacesDetailResponse * which contains all available details for the place. The second element is a ResponseStatus object * indicating the status of the query along with the appropiate HTTP code. The tuple wrapped in a Task<> * because the method makes Asynchronous HTTP requests to the Places API. */ public async Task <Tuple <PlacesDetailResponse, ResponseStatus> > GetPlaceDetails(String place_id) { if (BasicFunctions.isEmpty(APIKey)) { return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, PlacesStatus.MISSING_API_KEY)); } if (BasicFunctions.isEmpty(place_id)) { return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, PlacesStatus.MISSING_PLACE_ID)); } // Creating the HTTP query url String HTTP_query = $"details/json?placeid={place_id}&key={APIKey}"; // Setting up the request header to indicate that the request body will be in json httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Making an asynchronous HTTP GET request to the Places API and collecting the output HttpResponseMessage response = await httpClient.GetAsync(HTTP_query); Stream stream = await response.Content.ReadAsStreamAsync(); StreamReader streamReader = new StreamReader(stream); String response_str = streamReader.ReadToEnd(); Console.WriteLine(response_str); /* * Here we do a two-step hop again to achieve the appropriate return value: * We use the response string (response_str) from above and attempt to convert it back from json to * NearbySearchResultList, the expected return object for a successful query. This produces one of * two possibilities: * 1. If the response string is not a json of the NearbySearchResultList class, then we either get * a JsonSerializationException or an empty list. In this case we print out the response and * return null (Will improve this to return an appropriate error code). * 2. If the response string is as expected a json of NearbySearchResultList, then things go * smoothly and we return that. */ if (response.IsSuccessStatusCode) { try { PlacesDetailResponse resultList = JsonConvert.DeserializeObject <PlacesDetailResponse>(response_str); if (!resultList.Status.Equals("OK")) { // If the response status from the API is not OK, then we try to return the most appropriate Error ResponseStatus status = PlacesStatus.ProcessErrorMessage(resultList.Status, resultList.Error_message); return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, status)); } else if (resultList.Result == null) { // If the response provides an empty response set, then we return the ZERO_RESULTS (204) error return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, PlacesStatus.ZERO_RESULTS)); } else { return(new Tuple <PlacesDetailResponse, ResponseStatus>(resultList, PlacesStatus.OK)); } } catch (JsonSerializationException e) { // If the deserialization of the response fails, then we return an error Console.WriteLine("Exception: " + e.StackTrace); return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, PlacesStatus.DESERIALIZATION_ERROR)); } } else { // If the response status from the API is not a success, then we return an error using the data returned return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, new ResponseStatus((int)response.StatusCode, response.ReasonPhrase))); } }
/* * Method: GetPlacesDetailWithOptions * * Description: This method can be used to query the Places API for details regarding places with a * specific place_id. The optional parameters can be used to determine the language of the response * as well as what infromation is returned. If no fields are provided, then the query returns all * available fields. * * Parameters: * - place_id (String): A String identifier that uniquely identifies a place. This is returned as part * of the response from the Place Search functions. For more details about place_id: * https://developers.google.com/places/web-service/place-id * * - region_code (String): This is an OPTIONAL parameter, that indicates the region code, specified as a * ccTLD format. This is used to influence the query's results but relevant results outside the * region may also be included. * - fields (List<PlacesDetailFields>): OPTIONAL parameter. This is a list of details you wish to get * about the places that match the query. If the list is empty or null, then the Places API will * return all available details by default. * - language_code (String): OPTIONAL parameter indicating the language in which results will be returned. * By default this is set to English. List of supported languages and their codes: * https://developers.google.com/maps/faq#languagesupport * * - APIKey (String): Implicity required paramter which should be set through the constructor when * creating an object of this class. For more details about the Google API Key please see: * https://developers.google.com/places/web-service/get-api-key * * Return: The method returns a tuple of two items. The first is an object of PlacesDetailResponse * which contains all available details for the place. The second element is a ResponseStatus object * indicating the status of the query along with the appropiate HTTP code. The tuple wrapped in a Task<> * because the method makes Asynchronous HTTP requests to the Places API. */ public async Task <Tuple <PlacesDetailResponse, ResponseStatus> > GetPlaceDetailsWithOptions(String place_id, String region_code = "", String language_code = "", String session_token = "", List <PlacesDetailFields> fields = null) { if (BasicFunctions.isEmpty(APIKey)) { return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, PlacesStatus.MISSING_API_KEY)); } if (BasicFunctions.isEmpty(place_id)) { return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, PlacesStatus.MISSING_PLACE_ID)); } // Creating the HTTP query url String HTTP_query = $"details/json?placeid={place_id}"; // Appending any optional fields that are set if (!BasicFunctions.isEmpty(region_code)) { HTTP_query += $"®ion={region_code}"; } if (!BasicFunctions.isEmpty(language_code)) { HTTP_query += $"&language={language_code}"; } if (!BasicFunctions.isEmpty(session_token)) { HTTP_query += $"&sessiontoken={session_token}"; } if (fields != null && fields.Count != 0) { HTTP_query += $"&fields={BasicFunctions.getPlacesDetailFieldsListString(fields)}"; } HTTP_query += $"&key={APIKey}"; // Setting up the request header to indicate that the request body will be in json httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Making an asynchronous HTTP GET request to the Places API and collecting the output HttpResponseMessage response = await httpClient.GetAsync(HTTP_query); Stream stream = await response.Content.ReadAsStreamAsync(); StreamReader streamReader = new StreamReader(stream); String response_str = streamReader.ReadToEnd(); // Similar two-step hop as in prior functions if (response.IsSuccessStatusCode) { try { PlacesDetailResponse resultList = JsonConvert.DeserializeObject <PlacesDetailResponse>(response_str); if (!resultList.Status.Equals("OK")) { // If the response status from the API is not OK, then we try to return the most appropriate Error ResponseStatus status = PlacesStatus.ProcessErrorMessage(resultList.Status, resultList.Error_message); return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, status)); } else if (resultList.Result == null) { // If the response provides an empty response set, then we return the ZERO_RESULTS (204) error return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, PlacesStatus.ZERO_RESULTS)); } else { return(new Tuple <PlacesDetailResponse, ResponseStatus>(resultList, PlacesStatus.OK)); } } catch (JsonSerializationException e) { // If the deserialization of the response fails, then we return an error Debug.WriteLine("Exception: " + e.StackTrace); return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, PlacesStatus.DESERIALIZATION_ERROR)); } } else { // If the response status from the API is not a success, then we return an error using the data returned return(new Tuple <PlacesDetailResponse, ResponseStatus>(null, new ResponseStatus((int)response.StatusCode, response.ReasonPhrase))); } }
/* * Method: GetPlacesPhotos * * Description: This method can be used to get a photo based on a photo reference returned as part of a * PlacesSearch or PlacesDetail response. If the photo exists, then the method will save the photo at * the desired directory address. * * Parameters: * - photoReference (String): A String identifier that uniquely identifies a photo. This is returned as * part of the response for a PlacesSearch or PlacesDetail queries. * - fileDestination (String): An absolute or relative path address of the desired location where the * photo should be stored. * * One of the following two parameters is required: * - maxHeight (int): This is an OPTIONAL parameter which indicates the maximum height of the image. * - maxWidth (int): This is an OPTIONAL parameter which indicates the maximum width of the image. * * - APIKey (String): Implicity required paramter which should be set through the constructor when * creating an object of this class. For more details about the Google API Key please see: * https://developers.google.com/places/web-service/get-api-key * * Return: The method returns a tuple of two items. The first is a String. If the query is successful * then the string returns the directory location where the photo was stored. If the query fails for any * reason then, the string is returned as null. The second element is a ResponseStatus object indicating * the status of the query along with the appropiate HTTP code. The tuple wrapped in a Task<> because * the method makes Asynchronous HTTP requests to the Places API. */ public async Task <Tuple <String, ResponseStatus> > GetPlacesPhotos(String photoReference, String fileDestination, int maxHeight = 0, int maxWidth = 0) { if (BasicFunctions.isEmpty(APIKey)) { return(new Tuple <String, ResponseStatus>(null, PlacesStatus.MISSING_API_KEY)); } if (BasicFunctions.isEmpty(photoReference)) { return(new Tuple <String, ResponseStatus>(null, PlacesStatus.MISSING_PHOTO_REFERENCE)); } if (maxHeight <= 0 && maxWidth <= 0) { return(new Tuple <string, ResponseStatus>(null, PlacesStatus.MISSING_HEIGHT_WIDTH)); } if (BasicFunctions.isEmpty(fileDestination)) { return(new Tuple <string, ResponseStatus>(null, PlacesStatus.MISSING_FILE_DESTINATION)); } // Creating the HTTP query url String HTTP_query = $"photo?photoreference={photoReference}"; if (maxHeight > 0) { HTTP_query += $"&maxheight={maxHeight}"; } if (maxWidth > 0) { HTTP_query += $"&maxwidth={maxWidth}"; } HTTP_query += $"&key={APIKey}"; // Setting up the request header to indicate that the request body will be in json httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Making an asynchronous HTTP GET request to the Places API and collecting the output HttpResponseMessage response = await httpClient.GetAsync(HTTP_query); Stream stream = await response.Content.ReadAsStreamAsync(); if (response.IsSuccessStatusCode) { // The following block of code is borrowed from https://stackoverflow.com/a/2368180 using (BinaryReader reader = new BinaryReader(stream)) { Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10); try { using (FileStream lxFS = new FileStream(fileDestination, FileMode.Create)) { lxFS.Write(lnByte, 0, lnByte.Length); // End of borrowed code } } catch (ArgumentException e) { // If we get an exception, then the directory path provided is likely invalid and we return that error Debug.WriteLine(e.StackTrace); return(new Tuple <String, ResponseStatus>(null, PlacesStatus.INVALID_FILE_LOCATION)); } catch (IOException e) { Debug.WriteLine(e.StackTrace); if (e.Message.ToLower().Contains("could not find a part of the path")) { return(new Tuple <string, ResponseStatus>(null, PlacesStatus.INVALID_FILE_LOCATION)); } return(new Tuple <String, ResponseStatus>(null, PlacesStatus.INTERNAL_SERVER_ERROR)); } } } else { return(new Tuple <string, ResponseStatus>(null, PlacesStatus.ProcessErrorMessage(response.StatusCode.ToString(), response.ReasonPhrase))); } // If there are no errors, then we return the directory address where the photo was stored return(new Tuple <string, ResponseStatus>(fileDestination, PlacesStatus.OK)); }
public static void TrainNetwork(NeuralNetwork network, List <float[]> inputs, List <float[]> desiredOutputs) { foreach (var desiredOutput in desiredOutputs.Where(desiredOutput => network.Structure[network.Structure.Length - 1] != desiredOutput.Length)) { Debug.Log("Expected " + network.Structure[network.Structure.Length - 1] + " outputs, got " + desiredOutput.Length); return; } var doneTraining = true; for (var i = 0; i < inputs.Count; i++) { var input = inputs[i]; TestNetwork(network, input); for (var j = 0; j < network.Layers[network.Layers.Length - 1].Nodes.Length; j++) { network.Layers[network.Layers.Length - 1].Nodes[j].SetDesiredValue(desiredOutputs[i][j]); } for (var j = network.Layers.Length - 1; j >= 1; j--) { foreach (var node in network.Layers[j].Nodes) { var biasSmudge = BasicFunctions.SigmoidDerivative(node.Value) * network.ClassificationOverPrecision * node.CalculateCostDelta(network.ClassificationOverPrecision, network.MaxError); node.TrainingBiasSmudge += biasSmudge; if (!node.isAcceptableValue) { doneTraining = false; } foreach (var connectedNode in node.GetConnectedNodes()) { var weightSmudge = connectedNode.Value * biasSmudge; node.TrainingWeightsSmudge[connectedNode] += weightSmudge; var valueSmudge = node.GetWeight(connectedNode) * biasSmudge; connectedNode.SmudgeDesiredValue(valueSmudge); } } } } if (doneTraining) { network.Done = true; return; } for (var i = network.Layers.Length - 1; i >= 1; i--) { foreach (var node in network.Layers[i].Nodes) { node.SmudgeBias(node.TrainingBiasSmudge); node.SetBias(node.GetBias() * (1 - network.WeightDecay)); node.TrainingBiasSmudge *= network.Momentum; foreach (var connectedNode in node.GetConnectedNodes()) { node.SmudgeWeight(connectedNode, node.TrainingWeightsSmudge[connectedNode]); node.TrainingWeightsSmudge[connectedNode] *= network.Momentum; node.SetWeight(connectedNode, node.GetWeight(connectedNode) * (1 - network.WeightDecay)); } node.SetDesiredValue(0); } } }
/* * Method: AnnotateImages * * Description: This method can be used to query the Google Cloud Image Intelligence API with a batch of * images and run image detection and annotation on these images. * * Parameters: * - imageRequests (AnnotateImageRequestList): List of all the individual AnnotateImageRequests that will * be sent to the Image Intelligence API. * * - APIKey (String): Implicity required paramter which should be set through the constructor when * creating an object of this class. For more details about the Google API Key please see: * https://developers.google.com/places/web-service/get-api-key * * * Return: If the query is successful, then the method will return a tuple of two items. The first is an * AnnotateImageResponseList object with image identification and annotation corresponding to each image * request from the request list. The second element is a ResponseStatus object indicating the status of * the query along with the appropiate HTTP code. Since the HTTP query and the indentification are both * performed asynchronously, the return object is wrapped in Task<>. */ public async Task <Tuple <AnnotateImageResponseList, ResponseStatus> > AnnotateImages(AnnotateImageRequestList imageRequests, String input = "") { if (BasicFunctions.isEmpty(APIKey)) { return(new Tuple <AnnotateImageResponseList, ResponseStatus>(null, ImageAnnotationStatus.MISSING_API_KEY)); } if (imageRequests == null || imageRequests.Requests.Count == 0) { return(new Tuple <AnnotateImageResponseList, ResponseStatus>(null, ImageAnnotationStatus.MISSING_REQUEST_LIST)); } // Preparing the header to accept the JSON request body httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // The API address to which we will make the HTTP POST query String request_query = "v1/images:annotate?" + $"key={APIKey}"; HttpResponseMessage response = await httpClient.PostAsJsonAsync(request_query, imageRequests); Stream stream = await response.Content.ReadAsStreamAsync(); StreamReader streamReader = new StreamReader(stream); String response_str = streamReader.ReadToEnd(); /* * Similar two-step hop as we have seen before. We try to deserialize the response string, expecting * an object of AnnotateImageResponseList If the response is not an AnnotateImageResponseList object, * then we will encounter a JSONSerialization error and return null. If it is as we expect, then we * just return the AnnotateImageResponseList object. */ if (response.IsSuccessStatusCode) { AnnotateImageResponseList imageResponseList; try { imageResponseList = JsonConvert.DeserializeObject <AnnotateImageResponseList>(response_str); if (imageResponseList == null || imageResponseList.Responses.Count == 0) { return(new Tuple <AnnotateImageResponseList, ResponseStatus>(null, ImageAnnotationStatus.ZERO_RESULTS)); } } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <AnnotateImageResponseList, ResponseStatus>(null, ImageAnnotationStatus.DESERIALIZATION_ERROR)); } return(new Tuple <AnnotateImageResponseList, ResponseStatus>(imageResponseList, ImageAnnotationStatus.OK)); } else { // If the query is not successful, then we try to extract details about the error from the response AnnotateImageResponseList annotateResponse; try { annotateResponse = JsonConvert.DeserializeObject <AnnotateImageResponseList>(response_str); if (annotateResponse == null) { return(new Tuple <AnnotateImageResponseList, ResponseStatus>(null, ImageAnnotationStatus.INTERNAL_SERVER_ERROR)); } if (annotateResponse.Error == null) { return(new Tuple <AnnotateImageResponseList, ResponseStatus>(null, ImageAnnotationStatus.ProcessErrorMessage(response.StatusCode.ToString(), response.ReasonPhrase))); } } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <AnnotateImageResponseList, ResponseStatus>(null, ImageAnnotationStatus.DESERIALIZATION_ERROR)); } ResponseStatus status = ImageAnnotationStatus.ProcessErrorMessage(annotateResponse.Error.Code.ToString(), annotateResponse.Error.Message); return(new Tuple <AnnotateImageResponseList, ResponseStatus>(null, status)); } }
/* * Method: AnalyzeEntities * * Description: This method can be used to find entities in a document or text. If you only wish to run * sentiment analysis on each entity, simultaneously, then please use the AnalyzeEntitySentiment() * method. * * Parameters: * - document (Document): The document/text from which you want Natural Language API to identify and * analyze entities. * - encodingType (EncodingType): The encoding type to help the API determine offsets. Acceptable values * are NONE, UTF8, UTF16, UTF32. If NONE is specified, then encoding-specific information is not set. * * - APIKey (String): Implicity required paramter which should be set through the constructor when * creating an object of this class. For more details about the Google API Key please see: * https://developers.google.com/places/web-service/get-api-key * * Return: The method returns a tuple of two items. If the query is successful, then the first item will * be an object of type AnalyzeEntitiesResponse, which conatins a list of all the entities identified and * the language of the document. If the query is unsuccessful and an error is returned, then the method * returns null. The second element is a ResponseStatus object indicating the status of the query along * with the appropiate HTTP code. Since the HTTP query is performed asynchronously, the return object is * wrapped in Task<>. */ public async Task <Tuple <AnalyzeEntitiesResponse, ResponseStatus> > AnalyzeEntities(Document document, EncodingType encodingType) { if (BasicFunctions.isEmpty(APIKey)) { return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(null, NaturalLanguageStatus.MISSING_API_KEY)); } if (document == null) { return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(null, NaturalLanguageStatus.MISSING_DOCUMENT)); } AnalyzeEntitiesRequest entitiesRequest = new AnalyzeEntitiesRequest(document, encodingType); if (entitiesRequest == null) { return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(null, NaturalLanguageStatus.INTERNAL_SERVER_ERROR)); } // Preparing the header to send a JSON request body httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // API address to which we make the HTTP POST query String request_query = "v1/documents:analyzeEntities?" + $"key={APIKey}"; HttpResponseMessage response = await httpClient.PostAsJsonAsync(request_query, entitiesRequest); Stream stream = await response.Content.ReadAsStreamAsync(); StreamReader streamReader = new StreamReader(stream); String response_str = streamReader.ReadToEnd(); /* * Similar two-step hop as we have seen before. We try to deserialize the response string, expecting * an object of AnalyzeEntitiesResponse. If the response is not an AnalyzeEntitiesResponse object, * then we will encounter a JSONSerialization error and return null. If it is as we expect, then we * just return the AnalyzeEntitiesResponse object, so long as it is not empty or null. */ if (response.IsSuccessStatusCode) { AnalyzeEntitiesResponse entitiesResponse; try { entitiesResponse = JsonConvert.DeserializeObject <AnalyzeEntitiesResponse>(response_str); if (entitiesResponse == null || entitiesResponse.Entities.Count == 0) { return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(null, NaturalLanguageStatus.ZERO_RESULTS)); } } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(null, NaturalLanguageStatus.DESERIALIZATION_ERROR)); } return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(entitiesResponse, NaturalLanguageStatus.OK)); } else { // If the query is not successful, then we try to extract details about the error from the response AnalyzeEntitiesResponse entitiesResponse; try { entitiesResponse = JsonConvert.DeserializeObject <AnalyzeEntitiesResponse>(response_str); } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(null, NaturalLanguageStatus.DESERIALIZATION_ERROR)); } // If no error details are available, then we use the information from the response to determine // the appropriate error code if (entitiesResponse.Error == null) { return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(null, NaturalLanguageStatus.processErrorMessage(response.StatusCode.ToString(), response.ReasonPhrase))); } else { // If we do have an Error object, then we use it to identify the appropriate error code and message return(new Tuple <AnalyzeEntitiesResponse, ResponseStatus>(null, NaturalLanguageStatus.processErrorMessage(entitiesResponse.Error.Code.ToString(), entitiesResponse.Error.Message))); } } }
/* * Method: ClassifyText * * Description: This method can be used to classify the document into categories. Each category is * identified by a name and associated with a confidence number indicating how confident the API is * about the classification. * * Parameters: * - document (Document): The document/text on which you want Natural Language API to perform analysis. * * - APIKey (String): Implicity required paramter which should be set through the constructor when * creating an object of this class. For more details about the Google API Key please see: * https://developers.google.com/places/web-service/get-api-key * * Return: The method returns a tuple of two items. If the query is successful, then the first item will * be an object of type ClassifyTextResponse. If the query is unsuccessful and an error is returned, * then the method returns null. The second element is a ResponseStatus object indicating the status of * the query along with the appropiate HTTP code. Since the HTTP query is performed asynchronously, the * return object is wrapped in Task<>. */ public async Task <Tuple <ClassifyTextResponse, ResponseStatus> > ClassifyText(Document document) { if (BasicFunctions.isEmpty(APIKey)) { return(new Tuple <ClassifyTextResponse, ResponseStatus>(null, NaturalLanguageStatus.MISSING_API_KEY)); } if (document == null) { return(new Tuple <ClassifyTextResponse, ResponseStatus>(null, NaturalLanguageStatus.MISSING_DOCUMENT)); } ClassifyTextRequest classifyTextRequest = new ClassifyTextRequest(document); if (classifyTextRequest == null) { return(new Tuple <ClassifyTextResponse, ResponseStatus>(null, NaturalLanguageStatus.INTERNAL_SERVER_ERROR)); } // Preparing the header to send a JSON request body httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // API address to which we make the HTTP POST query String request_query = "v1/documents:classifyText?" + $"key={APIKey}"; HttpResponseMessage response = await httpClient.PostAsJsonAsync(request_query, classifyTextRequest); Stream stream = await response.Content.ReadAsStreamAsync(); StreamReader streamReader = new StreamReader(stream); String response_str = streamReader.ReadToEnd(); // Similar two-step hop as we have seen in prior methods if (response.IsSuccessStatusCode) { ClassifyTextResponse classifyTextResponse; try { classifyTextResponse = JsonConvert.DeserializeObject <ClassifyTextResponse>(response_str); if (classifyTextResponse == null || classifyTextResponse.Categories.Count == 0) { return(new Tuple <ClassifyTextResponse, ResponseStatus>(null, NaturalLanguageStatus.ZERO_RESULTS)); } } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <ClassifyTextResponse, ResponseStatus>(null, NaturalLanguageStatus.DESERIALIZATION_ERROR)); } return(new Tuple <ClassifyTextResponse, ResponseStatus>(classifyTextResponse, NaturalLanguageStatus.OK)); } else { // If the query is not successful, then we try to extract details about the error from the response ClassifyTextResponse classifyTextResponse; try { classifyTextResponse = JsonConvert.DeserializeObject <ClassifyTextResponse>(response_str); } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <ClassifyTextResponse, ResponseStatus>(null, NaturalLanguageStatus.DESERIALIZATION_ERROR)); } /* * If no error details are available, then we use the information from the response to determine * the appropriate error code. * If we do have an Error object, then we use it to identify the appropriate error code and message */ if (classifyTextResponse.Error == null) { return(new Tuple <ClassifyTextResponse, ResponseStatus>(null, NaturalLanguageStatus.processErrorMessage(response.StatusCode.ToString(), response.ReasonPhrase))); } else { return(new Tuple <ClassifyTextResponse, ResponseStatus>(null, NaturalLanguageStatus.processErrorMessage(classifyTextResponse.Error.Code.ToString(), classifyTextResponse.Error.Message))); } } }
/* * Method: AnnotateVideoWithMultipleDetections * * Description: This method can be used to detect adult content in a video using the Google Cloud * Video Intelligence API. If you wish to run multiple annotations at once, please use the * AnnotateVideoWithMultipleDetections() method. * * Parameters: * Only one of the following two parameters should be provided. If none or both are provided, then an * error will be returned: * - inputUri (String): This string is the URI location of the video. Currently, only Google Cloud * Storage URIs are supported. If this is set, then inputContent should not be set. * - inputContent (String): Bytes format string for the video data. This should be set only if inputUri * is not set. * * At least one of the following three parameters must be set to true: * - labelDetection (Boolean): Set to true if you want to run label detection on the video * - shotChangeDetection (Boolean): Set to true if you want to run shot change detection on the video * - explicitContentDetection (Boolean): Set to true if you want to run explicit content detection on the * video * * - context (VideoContext): Additional context for the video or parameters specific to Label Annotation. * This is an OPTIONAL parameter. * - outputUri (String): OPTIONAL Google Cloud Storage URI where the resulting JSON will be stored. * - cloudRegionId (String): OPTIONAL Google Cloud region id where the video annotation should take place. * If no region is specified then one will be chosen based on the file's location. * * Return: The method returns a tuple of two items. If the query is successful, then the first item will * be an object of type VideoAnnotationResponse. If the query is unsuccessful and an error is returned, * then the method returns null. The second element is a ResponseStatus object indicating the status of * the query along with the appropiate HTTP code. Since the HTTP query is performed asynchronously, the * return object is wrapped in Task<>. */ public async Task <Tuple <VideoAnnotationResponse, ResponseStatus> > AnnotateVideoWithMultipleDetections( String inputUri = null, String inputContent = null, VideoContext context = null, String outputUri = "", String cloudRegionId = "", Boolean labelDetection = false, Boolean shotChangeDetection = false, Boolean explicitContentDetection = false) { // One and only one of inputUri and inputContent can be set if ((BasicFunctions.isEmpty(inputUri) && BasicFunctions.isEmpty(inputContent))) { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.TOO_FEW_PARAMETERS)); } if (!BasicFunctions.isEmpty(inputUri) && !BasicFunctions.isEmpty(inputContent)) { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.TOO_MANY_PARAMETERS)); } if (shotChangeDetection == false && explicitContentDetection == false && labelDetection == false) { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.MISSING_ANNOTATION_FIELD)); } List <String> videoFeatures = new List <String>(); if (labelDetection) { videoFeatures.Add(VideoFeature.LABEL_DETECTION.ToString()); } if (shotChangeDetection) { videoFeatures.Add(VideoFeature.SHOT_CHANGE_DETECTION.ToString()); } if (explicitContentDetection) { videoFeatures.Add(VideoFeature.EXPLICIT_CONTENT_DETECTION.ToString()); } AnnotateVideoRequest annotateVideoRequest = new AnnotateVideoRequest(inputUri, inputContent, videoFeatures, context, outputUri, cloudRegionId); // Setting up the header for the request body httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // API address to which we will make the HTTP POST query String request_query = "v1/videos:annotate?" + $"key={APIKey}"; HttpResponseMessage response = await httpClient.PostAsJsonAsync(request_query, annotateVideoRequest); Stream stream = response.Content.ReadAsStreamAsync().Result; StreamReader streamReader = new StreamReader(stream); String response_str = streamReader.ReadToEnd(); // Similar two-step hop as we have seen in prior functions if (response.IsSuccessStatusCode) { Operation operation; try { operation = JsonConvert.DeserializeObject <Operation>(response_str); } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.DESERIALIZATION_ERROR)); } int ctr = 1; // We get the operation details for the annotation String operation_json = await GetVideoAnnotateOperation(operation.Name); try { VideoAnnotationResponse annotationResponse = JsonConvert.DeserializeObject <VideoAnnotationResponse>(operation_json); // We run a loop that sleeps for 10 seconds and then rechecks to see if the annotation is complete. // For every iteration of the loop, we increase while (!annotationResponse.Done) { System.Threading.Thread.Sleep(10000 * ctr); operation_json = await GetVideoAnnotateOperation(operation.Name); annotationResponse = JsonConvert.DeserializeObject <VideoAnnotationResponse>(operation_json); ctr++; } return(new Tuple <VideoAnnotationResponse, ResponseStatus>(annotationResponse, VideoAnnotationStatus.OK)); } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.DESERIALIZATION_ERROR)); } } else { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, new ResponseStatus((int)response.StatusCode, response.ReasonPhrase))); } }
public void SetItems(BasicFunctions Items) { this.Items = Items; }
/* * Method: AnnotateVideoWithLabelDetection * * Description: This method can be used to annotate the desired video with labels using the Google Cloud * Video Intelligence API. If you wish to run multiple annotations at once, please use the * AnnotateVideoWithMultipleDetections() method. * * Parameters: * Only one of the following two parameters should be provided. If none or both are provided, then an * error will be returned: * - inputUri (String): This string is the URI location of the video. Currently, only Google Cloud * Storage URIs are supported. If this is set, then inputContent should not be set. * - inputContent (String): Bytes format string for the video data. This should be set only if inputUri * is not set. * * - context (VideoContext): Additional context for the video or parameters specific to Label Annotation. * This is an OPTIONAL parameter. * - outputUri (String): OPTIONAL Google Cloud Storage URI where the resulting JSON will be stored. * - cloudRegionId (String): OPTIONAL Google Cloud region id where the video annotation should take place. * If no region is specified then one will be chosen based on the file's location. * * Return: The method returns a tuple of two items. If the query is successful, then the first item will * be an object of type VideoAnnotationResponse. If the query is unsuccessful and an error is returned, * then the method returns null. The second element is a ResponseStatus object indicating the status of * the query along with the appropiate HTTP code. Since the HTTP query is performed asynchronously, the * return object is wrapped in Task<>. */ public async Task <Tuple <VideoAnnotationResponse, ResponseStatus> > AnnotateVideoWithLabelDetection(String inputUri = "", String inputContent = "", VideoContext context = null, String outputUri = "", String cloudRegionId = "") { // One and only one of inputUri and inputContent can be set if ((BasicFunctions.isEmpty(inputUri) && BasicFunctions.isEmpty(inputContent))) { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.TOO_FEW_PARAMETERS)); } if (!BasicFunctions.isEmpty(inputUri) && !BasicFunctions.isEmpty(inputContent)) { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.TOO_MANY_PARAMETERS)); } // Create the features list and the annotation request object List <String> videoFeatures = new List <String> { VideoFeature.LABEL_DETECTION.ToString() }; AnnotateVideoRequest annotateVideoRequest = new AnnotateVideoRequest(inputUri, inputContent, videoFeatures, context, outputUri, cloudRegionId); // Setting up the header for the request body httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // API address to which we will make the HTTP POST query String request_query = "v1/videos:annotate?" + $"key={APIKey}"; HttpResponseMessage response = await httpClient.PostAsJsonAsync(request_query, annotateVideoRequest); Stream stream = response.Content.ReadAsStreamAsync().Result; StreamReader streamReader = new StreamReader(stream); String response_str = streamReader.ReadToEnd(); /* * Similar two-step hop as we have seen before. We try to deserialize the response string, expecting * an object of Operation. If the response is not an Operation object, then we will encounter a * JSONSerialization error and return null. If it is as we expect, then we just return the * Operation object. */ if (response.IsSuccessStatusCode) { Operation operation; try { operation = JsonConvert.DeserializeObject <Operation>(response_str); } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.DESERIALIZATION_ERROR)); } // We get the operation details for the annotation String operation_json = await GetVideoAnnotateOperation(operation.Name); if (BasicFunctions.isEmpty(operation_json)) { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.INTERNAL_SERVER_ERROR)); } try { VideoAnnotationResponse annotationResponse = JsonConvert.DeserializeObject <VideoAnnotationResponse>(operation_json); // We run a loop that sleeps for 10 seconds and then rechecks to see if the annotation is complete while (!annotationResponse.Done) { System.Threading.Thread.Sleep(SLEEP_TIME); operation_json = await GetVideoAnnotateOperation(operation.Name); if (BasicFunctions.isEmpty(operation_json)) { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.INTERNAL_SERVER_ERROR)); } annotationResponse = JsonConvert.DeserializeObject <VideoAnnotationResponse>(operation_json); } return(new Tuple <VideoAnnotationResponse, ResponseStatus>(annotationResponse, VideoAnnotationStatus.OK)); } catch (JsonSerializationException e) { Debug.WriteLine(e.StackTrace); return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, VideoAnnotationStatus.DESERIALIZATION_ERROR)); } } else { return(new Tuple <VideoAnnotationResponse, ResponseStatus>(null, new ResponseStatus((int)response.StatusCode, response.ReasonPhrase))); } }
static int Main(string[] args) { #region SWE Fundamentals 1 #region Program Arguments Directions directionArgument; bool booleanArgument; int integerArgument; if (args.Length == 0) { ArgumentsHelp(); } else { foreach (var arg in args) { if (arg == "/?") { ArgumentsHelp(); return(1); } } var sbArguments = new StringBuilder(); sbArguments.Append("\nThe arguemts passed to the program were: "); bool success = Enum.TryParse(args[0], true, out directionArgument); if (success) { sbArguments.Append($"{directionArgument}, "); success = bool.TryParse(args[1].ToLower(), out booleanArgument); if (success) { sbArguments.Append($"{booleanArgument}, "); success = int.TryParse(args[2], out integerArgument); if (success) { sbArguments.Append($"{integerArgument}, "); } } else { Console.WriteLine("\nCould not properly identify the second passed value"); Console.WriteLine("Expected a True or False (Note: not case sensitive)"); return(1); } } else { Console.WriteLine("\nCould not properly identify the first passed value"); Console.WriteLine("Expected a Direction such as: Up, Down, Left, Right (Note: not case sensitive)"); return(1); } var argString = string.Join(", ", args); Console.WriteLine($"You entered {argString}"); } #endregion #region HelloWorld Console.WriteLine("\nHello World!"); #endregion #region Comments //This is a single line comment /*testing * multin * line * commentes*/ /// <summary> /// This is an XML documentation comment /// </summary> /// <param name="args"></param> #endregion #region Variables bool thisIsABool = false; int thisIsAnInt = 1; double thisIsADouble = 2.0; char thisIsAChar = 'C'; string thisIsAString = "This is a string, how about that!"; var sb = new StringBuilder(); sb.AppendLine("\nExample of C# Variable Types:"); sb.AppendLine($"This is a bool: {thisIsABool}"); sb.AppendLine($"This is an int: {thisIsAnInt}"); sb.AppendLine($"This is an double: {thisIsADouble}"); sb.AppendLine($"This is an char: {thisIsAChar}"); sb.AppendLine($"This is an string: {thisIsAString}"); Console.WriteLine(sb.ToString()); #endregion #region Min / Max Values //maxInt produces an overflow exception error when incrementd by 1 //var maxInt = int.MaxValue + 1; #endregion #region Implicit Types var thisIsAnImplicitBool = false; var thisIsAnImplicitInt = 1; var thisIsAnImplicitDouble = 2.0; var thisIsAnImplicitChar = 'C'; var thisIsAnImplicitString = "This is a string"; #endregion #region Operators #region Assignmnet and Increment/Decrement var x = 1; var y = 5; //x++ will assign the value of x to z1 then will increment x var z1 = x++; //++y will increment y then assign the new value to z2; var z2 = ++y; var sbIncrement = new StringBuilder(); sbIncrement.AppendLine("Incrementing Values"); sbIncrement.AppendLine($"Value of x: {x}"); sbIncrement.AppendLine($"Value of y: {y}"); sbIncrement.AppendLine($"Value of z1: {z1}"); sbIncrement.AppendLine($"Value of z2: {z2}"); Console.WriteLine(sbIncrement.ToString()); #endregion #region Math var z = 10; var a = x + y * z; var b = z / y + x; var c = z - x + y; var isEven = z % 2 == 0 ? true : false; var isDivisibleByThree = y % 3 == 0 ? true : false; var roundToThreeDecimalUsingTruncate = Math.Truncate(x / (double)y); var roundToThreeDecimalUsingStringFormat = (x / (double)y).ToString("#.000"); #endregion #endregion #region Type Conversions int xConversion, yConversion, zConversion; double aConversion, bConversion, cConversion; xConversion = 1; yConversion = 3; zConversion = 6; aConversion = 2.0; bConversion = 6.0; cConversion = 12.0; int placeHolder; var sbTypeConvbersion = new StringBuilder(); sbTypeConvbersion.AppendLine("Type Conversions:"); sbTypeConvbersion.AppendLine($"int x: {xConversion} double a: {aConversion.ToString("#.00")} "); placeHolder = xConversion; xConversion = (int)aConversion; aConversion = (double)placeHolder; sbTypeConvbersion.AppendLine($"conversion = int a: {xConversion} and double x: {aConversion.ToString("#.00")}"); sbTypeConvbersion.AppendLine($"int y: {yConversion} double b: {bConversion.ToString("#.00")} "); placeHolder = yConversion; yConversion = (int)bConversion; bConversion = (double)placeHolder; sbTypeConvbersion.AppendLine($"conversion = int b: {yConversion} and double y: {bConversion.ToString("#.00")}"); sbTypeConvbersion.AppendLine($"int z: {zConversion} double c: {cConversion.ToString("#.00")} "); placeHolder = xConversion; zConversion = (int)cConversion; cConversion = (double)placeHolder; sbTypeConvbersion.AppendLine($"conversion = int c: {zConversion} and double z: {cConversion.ToString("#.00")}"); Console.WriteLine(sbTypeConvbersion.ToString()); #endregion #region Strings #region Escape and literals Console.WriteLine("\nThis is a string with \ttabs and \nnewlines\n"); Console.WriteLine(@"This is a string litteral esacpe sequences like \t (tab) and \n (new line) do not work "); #endregion #region Concatenation var firstString = "\nThis is the first part of my message"; var secondString = "This is the second part of my message"; Console.WriteLine(firstString + " " + secondString); #endregion #region String Legnth var testingStringLength = "\nThis string is how long I wonder?"; Console.WriteLine($"{testingStringLength} Accoring to string.legth property = {testingStringLength.Length}"); #endregion #region Indexing string stringWithOddNumberOfCharacters = "This string has an odd number of characters"; Console.WriteLine(Indexing.findFirstMiddleLastCharacter(stringWithOddNumberOfCharacters)); #endregion #region ChangingCase string toChangeCase = "Get it done!"; ChangingCase.PrintStringUpperAndLowerCase(toChangeCase); #endregion #region GettingPartsOfStrings string getPartsOfThisString = "This will be my test string"; Console.WriteLine("\nGetting parts of strings:"); Console.WriteLine("\"" + getPartsOfThisString + "\""); Console.WriteLine("Using string.Substring property:" + getPartsOfThisString.Substring(1, getPartsOfThisString.Length - 2)); Console.WriteLine("Using string.trim property:" + getPartsOfThisString.Trim(getPartsOfThisString[0]).Trim(getPartsOfThisString[getPartsOfThisString.Length - 1])); #endregion #region Searching string sentenceToSearch = "It was the best of time, it was the worst of times."; char searchCharacter = 'i'; Console.WriteLine("\nSearching:"); Console.WriteLine($"Is \"{searchCharacter}\" in \"{sentenceToSearch}\""); Searching.FindCharInString(sentenceToSearch, searchCharacter); string filePath = @"c:\foo\bar.txt"; Searching.FindFileName(filePath); Searching.FindDriveLetter(filePath); #endregion #region Splitting string testingSplit = "This is a string with spaces"; // splitting the string with .split will create an array of strings var splitString = testingSplit.Split(' '); #endregion #region Formatting Formatting.FormatStrings(); #endregion #region PrintingAndParsing PrintingAndParsing.Parsing(); #endregion #endregion #region Enums var testingEnums = MyEnum.Friday; Console.WriteLine("\nEnums:"); Console.WriteLine($"The Name of the Variable: {testingEnums} and the value: {(int)testingEnums}"); #endregion #region Structs var xStruct = new Car(); var yStruct = new Car(); xStruct.Make = "Hyundai"; xStruct.Owner = "Jonah"; xStruct.Price = 999.99; yStruct.Make = "Tesla"; yStruct.Owner = "Bob"; yStruct.Price = 35000.00; Console.WriteLine("\nStructs:"); Console.WriteLine($"Struct x: " + $"\nOwner: {xStruct.Owner}" + $"\nMake: {xStruct.Make}" + $"\nPrice: {xStruct.Price}"); Console.WriteLine($"\nStruct y: " + $"\nOwner: {yStruct.Owner}" + $"\nMake: {yStruct.Make}" + $"\nPrice: {yStruct.Price}"); xStruct.Make = yStruct.Make; xStruct.Owner = yStruct.Owner; xStruct.Price = yStruct.Price; Console.WriteLine($"\nStruct x after copying values from Struct y: " + $"\nOwner: {xStruct.Owner}" + $"\nMake: {xStruct.Make}" + $"\nPrice: {xStruct.Price}"); #endregion #region Console I/O ConsoleIO.EnterUserName(); #endregion #region Command Line Arguments #endregion #endregion #region SWE Fundamental 2 #region Conditionals Console.WriteLine("\nConditionals: "); #region If / Else Console.WriteLine("\nIf / Else: "); //Console.WriteLine("What value of x would you like to test"); //var valueToCheck = Console.ReadLine(); //int check; //var success = int.TryParse(valueToCheck, out check); //if (success) //{ // Conditionals.Conditions(check); //} IfElse.Conditions(); #endregion #region Switch Console.WriteLine("\nPracticing with switch statements:"); string season = "Winter"; Console.Write($"{season} "); PracticingSwith.choosingThroughSwitch(season); #endregion #region Order Of Operations Console.WriteLine("\nOrder of Operations:"); OrderOfOperations.Order(); #endregion #region Nest Conditionals Console.WriteLine("\nNest Conditionals:"); NestConditionals.NestCondiontionals(); #endregion #endregion #region Loops Console.WriteLine("\nLoop:"); #region While Console.WriteLine("\nWhile Loops:"); WhileLoops.WhileLoopsPractice(); #endregion #region Do While Loops Console.WriteLine("\n\nDo While Loops:"); DoWhileLoops.DoWhileLoopsPractice(); #endregion #region For Loops Console.WriteLine("\n\nFor Loops:"); ForLoops.ForLoopsPractice(); #endregion #region Foreach Loop Console.WriteLine("\n\nForeach Loops:"); ForeachLoops.ForeachLoopsPractice(); #endregion #region Nest Loops Console.WriteLine("\nNested Loops:"); NestedLoops.NestedLoopsPractice(); #endregion #region Loop Flow Contorl Console.WriteLine("\nLoop Flow Control:"); LoopFlowControl.LoopFlowControlPractice(); #endregion #endregion #region Arrays Console.WriteLine("\nArrays:"); #region Single Dimensional Arrays Console.WriteLine("\nSingle Dimensional Arrays:"); SingleDimensionalArrays.SingleDimensionalArraysPractice(); #endregion #region Multi Dimensional Arrays Console.WriteLine("\nMulti Dimensional Arrays:"); MultiDimensionalArrays.MultiDimensionalArraysPractice(); #endregion #endregion #region Functions Console.WriteLine("\nFunctions:"); #region Basic Functions Console.WriteLine("\nBasic Functions:"); var basicString1 = "This will "; var basicString2 = "print when passed "; var basicString3 = "to my basic function"; var arrayToModify = new int[5] { 1, 2, 3, 4, 5 }; var indexToModify = 3; var valueToInsert = 10; var printingEveryOtherWord = "To be or not to be"; BasicFunctions.PrintPassedString(basicString1); BasicFunctions.ConcatenateThreeStrings(basicString1, basicString2, basicString3); BasicFunctions.UpdateArray(arrayToModify, indexToModify, valueToInsert); BasicFunctions.PrintEveryOtherWord(printingEveryOtherWord); Console.WriteLine(); Console.WriteLine(BasicFunctions.CreateSubstring(basicString3, 4)); #endregion #region Reference Type Equality Console.WriteLine("\nReference Type Equality:"); var arrayOne = new int[5] { 1, 2, 3, 4, 5 }; var arrayTwo = new int[5] { 1, 2, 3, 4, 7 }; Console.WriteLine(ReferenceTypeEquality.AreArraysEqual(arrayOne, arrayTwo)); #endregion #region Output Parameters Console.WriteLine("\nOutput Parameters:"); int one = 21; int two = 7; int sum, difference, product, quotient; OutputParameters.mathOutput(one, two, out sum, out difference, out product, out quotient); Console.WriteLine($"The Sum of {one} and {two} = {sum}"); Console.WriteLine($"The Difference of {one} and {two} = {difference}"); Console.WriteLine($"The Product of {one} and {two} = {product}"); Console.WriteLine($"The Quotient of {one} and {two} = {quotient}"); #endregion #region Reference Parameters Console.WriteLine("\nReference Parameters:"); int indexToFind = 3; string stringToSearch = "This is a sting operation, you are under arrest"; Console.WriteLine(stringToSearch); Console.WriteLine($"Function will return the character at index location {indexToFind}"); Console.WriteLine("The charater is: " + ReferenceParameters.ReturnSelectedIndex(stringToSearch, ref indexToFind)); Console.WriteLine($"the value of the index has been changed to: {indexToFind}"); #endregion #endregion #endregion #region File I/O #endregion #region Algorithms Algorithms.AlgorithmPractice(); #endregion Console.ReadLine(); return(1); }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.White; PackageCore packageCore = new PackageCore(); Side(); string AppFolder = "./UAP"; switch (SystemEnvironment.currentSystem) { case SystemType.Windows: AppFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UAP"); break; case SystemType.Linux: AppFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "UAP"); break; case SystemType.MacOS: break; default: break; } BasicFunctions.Init(); Host.ReadLine = Console.ReadLine; Host.WriteLine = Console.WriteLine; Host.Write = Console.Write; Host.ResetColor = Console.ResetColor; Host.SetForeground = (ConsoleColor c) => { Console.ForegroundColor = c; }; for (int i = 0; i < args.Length; i++) { switch (args[i].ToUpper()) { case "INSTALL": i++; try { var package = packageCore.LoadPackage(args[i]); var pkginfo = package.GetInfomation(); Console.WriteLine("Install from:" + args[i]); if (package is ManifestPackage) { Console.Write("Package Type:"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("ManifestPackage"); Console.ForegroundColor = ConsoleColor.White; } double p = 0; //Console.ResetColor(); var result = package.Install(ref p); if (result.Status != UniversalAutomaticPackage.PackageSystem.InstallationStatus.Fail) { DirectoryInfo AppsFolder = new DirectoryInfo(AppFolder); //package var pkg = Path.Combine(AppsFolder.FullName, pkginfo.PackageID.ToString()); Console.WriteLine("Moveing from TemporaryFolder to assigned folder"); BasicFunctions.CopyFolder(result.BinFolder.FullName, pkg); Console.WriteLine("Creating shortcut."); ShortcutCreator.Create(Path.Combine(pkg, package.MainExecutable.fileName), package.MainExecutable.targetDisplayName); Console.WriteLine("Registering Package."); InstalledPackage.RegisterPackage(pkginfo.FriendlyName, pkg); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Completed."); Console.ForegroundColor = ConsoleColor.White; //package.MainExecutable; //Directory.Move(result.BinFolder.FullName, pkg); } else { Console.WriteLine("Failed."); Console.WriteLine("" + result.DetailedMessage); } } catch (Exception e) { Console.WriteLine("Error:" + e.Message); } break; case "REMOVE": { } break; case "VERSION": { Console.Write("UAP,Core:"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(PackageCore.CoreVersion.ToString()); Console.ForegroundColor = ConsoleColor.White; Console.Write("UAP,CLI:"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(CLIVerion.ToString()); Console.ForegroundColor = ConsoleColor.White; } break; case "INIT": if (!Directory.Exists(AppFolder)) { Directory.CreateDirectory(AppFolder); } break; default: break; } } if (args.Length == 0) { ShowHelpContent(); } }