-->

Welcome to our Coding with python Page!!! hier you find various code with PHP, Python, AI, Cyber, etc ... Electricity, Energy, Nuclear Power

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Sunday, 3 October 2021

How to get started with the Google Translate API

Even if most of us can’t travel as we once did, the world is a more accessible place, at least online. Business people may not be attending international conferences or flying around the world for meetings so much. But in many respects, businesses are finding that they can access and develop foreign markets by localizing their websites and apps to speak the language of locals and adapt to their standards. Developers can play an integral role in the localization process.

How localization tools are driving innovation in AI-driven APIs

Developers can hop on this trend, increase the value of their software, and expand online on capabilities to their apps. Google has emerged as a leader in translation algorithms in the past decade, leveraging advances in AI-driven neural network tech. This powers Google Translate, well-known to businesses for their companies or clients. They can do so readily by adding auto-translators Google Translate, well-known to businesses and consumers, an app that has made an impact on the translation profession as we know it. We’ll explore here how developers can add Google-powered translations to their apps by leveraging the powers of the company’s Translate API. Localization tools, which drive greater accuracy in translation mechanics, is also necessary for the translator to work more efficiently.

Before diving into the software weeds, it’s worth noting alternatives to the Google Translate API route. Third-party conversion tools like Zapier and IFTTT let you link your software workflow to auto-translation modules via webhooks and web services, with a minimum of coding. Even a tech-savvy non-programmer should be able to implement these solutions. The main drawback, however, is that you are likely to settle for a translation engine inferior to the one offered by Google.

What does Google offer for translation?

Google is a pioneer in both machine language and machine learning—the two L-words representing two sides of the same coin. Language needs to be learned, and that learning is achievable by mastery of a natural language. AI-driven mastery these days is driven by neural machines or NMT in 2016, bringing a “paradigm shift” in translation tech. From that year forward, NMT has been the preferred method of translating.

Back in 2006, Google started training its translation algorithm by digesting tens of millions of words extracted from translated documents of the European Union parliament and the United Nations. Today Google confronts competition from Facebook, which is leveraging the learnings from comments and posts by its 2 billion users to translate more casual conversations, including rendering LOL and WTF in scores of languages. NMT continues to be a way to go.

Happily, the language learning process didn’t stop with bureaucratese and Emoji. Google Translate today supports over 100 languages, several dozen with voice support. You can talk in one language and get the translation vocalized in another, usually with a choice of voice. And, as we will see, machine learning has been productized so that you can effectively translate a domain-specific language of your own.

Getting started with Google Translate API

Google promotes its API as fast and dynamic, adaptable to diverse content needs. The company markets not just to professional coders but to a broader spectrum of users, including those with “limited machine learning expertise” who can quickly “create high-quality, production-ready models.”

For the latter, you can just upload translated language pairs (a structured list of words/phrases with their translations) and AutoML Translation will train a custom translation model. The workflow allows either customized-by-the-client or pre-trained (by Google) inputs. To translate an English product description into French, Korean, and Portuguese, for example, you could customize a Google AutoML model for French and rely on an off-the-shelf pre-trained model for Korean and Portuguese. Then you simply upload your English HTML file to Google Cloud Storage and send a batch request to the Translation API pointing to your AutoML and the pre-trained models. Google’s AutoML Translation will then output your HTML in three separate language files to your Cloud Storage.

Training is key, but the initial model is pre-trained to render 100+ languages. And if you have a domain-specific lexicon (medical or legal terms, for example) these require just a little more training and tweaking of the basic API, if they don’t already exist. A Glossary lets users “wrap” proprietary terminology not to be translated (like brand and product names) to ensure they stay intact during translation. There is also built-in support Media Translation API, which handles real-time, low latency streaming of audio translations. 

The process is essentially three steps: Upload a language pair. Train AutoML. Evaluate.

This translation power is not free but the pricing is fair. Typically, you’ll be using Google’s Translate API and its Media Translation API (if you need voice support). You’ll need the AutoML service only if you need to train more language pairs. 

The fee for the Translate API is $20 per million characters. The Media Translation API will set you back $0.068 to $0.084 per minute. AutoML is a bit pricier, costing $45 per hour for training a language pair, to a max of $300/pair. Pay only for what you use, as you use it. (Google is patient: it wants to get you hooked, so it throws in free processing as you get up to speed, with a full year to practice before needing to pay up.)

Setting up for Your First Translation

The RESTful Translate API is the easiest way to get started. Google offers a basic and advanced setup. You can do this with localization tools, but you can also do it manually. If you’ve set up any Google API service, you’re probably comfortable with the drill and may already have a Cloud Console Account. Assuming this is true, the next things you need to do, if you haven’t already, are: 

  • Create or select your project.
  • Enable the Cloud Translation API.
  • Create a service account.
  • Download your private key in JSON format. Keep the full path to this file for the next step. 

Go to the shell prompt on your Mac OS X, Linux, or Windows (Powershell) system and set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of your JSON service account key using the following commands. This variable only applies to the current shell session. If you open a new session, you’ll need to reset this variable, replacing [PATH] with the path of the JSON file with your key.

If you’re using Linux or macOS:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For Windows, in PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Or, from a command prompt: 

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Then install and initialize Google’s Cloud SDK. Depending on which operating system you’re using, the Cloud SDK may have a dependency on a version of Python that isn’t installed on your system. So be sure to double-check the Cloud SDK documentation to ensure the appropriate version of Python is installed.

Executing Your First Translation

Make a Translation API Request with a REST call using the v2 translate method.

Use curl to make your request to the https://translation.googleapis.com/language/translate/v2 endpoint.

The command includes JSON with (1) the text to be translated (q), (2) the language to translate from (source), and (3) the language to translate to (target).

Source and target languages are identified with ISO-639-1 codes. In this example, the source language is English (en), the target is French (fr). The query format is plain “text”.

The sample curl command uses the gcloud auth application-default print-access-token command to get an authentication token.

curl -s -X POST -H "Content-Type: application/json" \
    -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
    --data "{
  'q': 'The quick brown fox jumps over the lazy dog',
  'source': 'en',
  'target': 'fr',
  'format': 'text'
}" "https://translation.googleapis.com/language/translate/v2"

The response should resemble the following:

{
  "data": {
    "translations": [
      {
        "translatedText": "Le renard brun rapide saute par-dessus le chien paresseux"
      }
    ]
  }
}

Congratulations! You’ve sent your first request to the Cloud Translation API!

Next steps in the translation process

For most apps, you can rely on one of the over 100 language pairs already trained and tested.  (If the pair you require is not available, or you need a custom translation with the AutoML training module.) The full process is as follows:

  1. Create a file containing the desired language pairs, using the CURL example above. Choose source and target languages from the list here (e.g., “en” or “fr”).
  2. Write code that reads the content of your website and makes a REST call to the Cloud Translation API (including a parameter pointing to your model and then producing a translated version of that text). 
  3. Create a new page in your content management system to contain and then display the translated text. Even better, if your CMS is programmable (either directly or by way of API), improve the code by automating this step.
  4. Configure your CMS and website to display the appropriate pages when a specific language is selected by your site’s end users.

Client libraries are currently available for seven popular programming languages – C#, Go, Java, Node.js, PHP, Python, and Ruby. Just install the library of your choice. Go to Translation Client Libraries for installation instructions.


Sunday, 15 November 2020

HP is hiring [ Jobs Updates] - ProgGeek


 

HP is hiring 

Position: IT Developer/ Engineer

Location(s):
Bangalore, Karnataka, India
No additional locations
Category: Information Technology
Job ID: 3065263
Posted: 11/12/2020

Applies basic foundation of a function's principles, theories and concepts to assignments of limited scope. Uses professional concepts and theoretical knowledge acquired through specialized training, education or previous experience. Develops expertise and practical knowledge of applications within business environment. Acts as team member by providing information, analysis and recommendations in support of team efforts. Exercises independent judgment within defined parameters.

Responsibilities:

  • Participates as a member of development team. Performs basic analysis of functional requirements. Completes code stubs prepared by more senior developers. Participates in code review. Prepares and executes Unit tests under supervision. Applies growing technical knowledge to maintain a technology area (e.g. Database Administration).

Education and Experience Required:

  • Typically a technical Bachelor's degree or equivalent experience and a minimum of 0-2 years of related experience.

Knowledge and Skills:

  • 0-2 years experience in writing code (such as, and not limited to, Java, C, C++, C#, VB.Net; databases like SqlServer/ Oracle.
  • Basic Understanding of RDBMS and Database scripting. Basic understanding of testing tools and test scripting.

👉 Apply

👍 All the best.

📤 Share with your friends & colleagues

Thursday, 5 July 2018

c# | yield return | yield (C# Reference)

When you use the yield keyword in a statement, you indicate that the method, operator, or getaccessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator<T> for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.
The following example shows the two forms of the yield statement.
C#
yield return <expression>;  
yield break;  

Remarks

You use a yield return statement to return each element one at a time.
You consume an iterator method by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
You can use a yield break statement to end the iteration.
For more information about iterators, see Iterators.

Iterator Methods and get Accessors

The declaration of an iterator must meet the following requirements:
The yield type of an iterator that returns IEnumerable or IEnumerator is object. If the iterator returns IEnumerable<T> or IEnumerator<T>, there must be an implicit conversion from the type of the expression in the yield return statement to the generic type parameter .
You can't include a yield return or yield break statement in methods that have the following characteristics:
  • Anonymous methods. For more information, see Anonymous Methods.
  • Methods that contain unsafe blocks. For more information, see unsafe.

Exception Handling

A yield return statement can't be located in a try-catch block. A yield return statement can be located in the try block of a try-finally statement.
A yield break statement can be located in a try block or a catch block but not a finally block.
If the foreach body (outside of the iterator method) throws an exception, a finally block in the iterator method is executed.

Technical Implementation

The following code returns an IEnumerable<string> from an iterator method and then iterates through its elements.
C#
IEnumerable<string> elements = MyIteratorMethod();  
foreach (string element in elements)  
{  
   ...  
}  
The call to MyIteratorMethod doesn't execute the body of the method. Instead the call returns an IEnumerable<string> into the elements variable.
On an iteration of the foreach loop, the MoveNext method is called for elements. This call executes the body of MyIteratorMethod until the next yield return statement is reached. The expression returned by the yield return statement determines not only the value of the elementvariable for consumption by the loop body but also the Current property of elements, which is an IEnumerable<string>.
On each subsequent iteration of the foreach loop, the execution of the iterator body continues from where it left off, again stopping when it reaches a yield return statement. The foreach loop completes when the end of the iterator method or a yield break statement is reached.

Example

The following example has a yield return statement that's inside a for loop. Each iteration of the foreach statement body in the Main method creates a call to the Power iterator function. Each call to the iterator function proceeds to the next execution of the yield return statement, which occurs during the next iteration of the for loop.
The return type of the iterator method is IEnumerable, which is an iterator interface type. When the iterator method is called, it returns an enumerable object that contains the powers of a number.
C#
public class PowersOf2
{
    static void Main()
    {
        // Display powers of 2 up to the exponent of 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }

    public static System.Collections.Generic.IEnumerable<int> Power(int number, int exponent)
    {
        int result = 1;

        for (int i = 0; i < exponent; i++)
        {
            result = result * number;
            yield return result;
        }
    }

    // Output: 2 4 8 16 32 64 128 256
}

Example

The following example demonstrates a get accessor that is an iterator. In the example, each yield return statement returns an instance of a user-defined class.
C#
public static class GalaxyClass
{
    public static void ShowGalaxies()
    {
        var theGalaxies = new Galaxies();
        foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)
        {
            Debug.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears.ToString());
        }
    }

    public class Galaxies
    {

        public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy
        {
            get
            {
                yield return new Galaxy { Name = "Tadpole", MegaLightYears = 400 };
                yield return new Galaxy { Name = "Pinwheel", MegaLightYears = 25 };
                yield return new Galaxy { Name = "Milky Way", MegaLightYears = 0 };
                yield return new Galaxy { Name = "Andromeda", MegaLightYears = 3 };
            }
        }

    }

    public class Galaxy
    {
        public String Name { get; set; }
        public int MegaLightYears { get; set; }
    }
}

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

Tuesday, 3 July 2018

C# | Better way of parsing string to boolean

At the moment I am using this to check a boolean property in sharepoint 2007 using C# and .Net Framework 3.5

if (bool.Parse(listItem.Properties["Boolean Property"].ToString()) == false)
is there any better way of doing it ?
Edit
when my code try to convert property into string it gives me exception even when am validating if property is empty or not.
This Worked For me
using method "Contains Key" instead of "Properties.Containsfield"
object abc = "bool property";

foreach (SPListItem item in list.Items)
{
     if (item.Properties.ContainsKey(abc)

Rank

seo