Only get single translation from Google Translate API - php

So I'm using the Google Translate API in PHP as explained in the documentation...
require 'vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=src/i18n-php/credential.json');
use Google\Cloud\Translate\TranslateClient;
$g_tr = new TranslateClient([ 'projectId' => 'my-project' ]);
$source_language = "en";
$target_language = "de";
$text_to_translate = "Last name";
$result = $g_tr->translate($text_to_translate, [
'source' => $source_language,
'target' => $target_language,
]);
echo $result['text'];
This works just as expected until there are several translation possibilities, like in the above code example, where the German translation can either be "Familienname" or "Nachname" - The Google Translate API outputs both into the $result['text'] seperated by comma: Familienname, Nachname.
I've been searching my fingers sore looking for a way to only get a single (preferably the most popular) translation. What do I have to do so that I only get one single translation possibility back from Google?

Related

API pagination, how to implement page token paging method?

I am working on implementing an API interface for my project.
As i know, there are different forms to make pagination through the results, like the following:
https://example.com/api/purchaseorders?page=2&pagesize=25
But, i see many APIs like google use a different approach, in which they use a "pageToken" to let the user move between the pages of results, for example:
https://example.com/api/purchaseorders?pagesize=25&pageToken=ClkKHgoRc291cmNlX2NyZWF0ZWRfYXQSCQjA67Si5sr
So instead of page=2 they used pageToken=[token].
It is not clear for me the idea of pageToken and how to implement it.
It will be helpful if you guide me to any resources so i can get more knowledge.
Thank you.
Here's a very simple standalone example using the filesystem as a keyvalue store (since a filesystem will always be available).
$requestParameters = [];
if (($token = filter_input(INPUT_GET,"pageToken")) && is_readable("/tmp/$token")) {
$requestParameters = file_get_contents("/tmp/$token");
} else {
$requestParameters = [
"q" => filter_input(INPUT_GET,"q"),
"pageSize" => filter_input(INPUT_GET,"pageSize",FILTER_VALIDATE_INT),
"page" => filter_input(INPUT_GET,"page",FILTER_VALIDATE_INT)
];
}
$nextPageRequestParameters = $requestParameters;
$nextPageRequestParameters["page"]++;
$nextPageToken = md5(serialize($nextPageRequestParameters)); //This is not ideal but at least people can't guess it easily.
file_put_contents("/tmp/$nextPageToken", serialize($nextPageRequestParameters));
//Do request using $requestParameters
$result = [ "nextPageToken" => $nextPageToken, "data" => $resultData ];
echo json_encode($result);

Codeigniter how to set API keys and Resource urls for easy access in applications

I am trying to clean up my site by putting all of my configurations in one place for easy access.
I have many different configuration dependencies for example, PayPal and Stripe public/private and sandbox/live keys as well as a number of links e.g. google recaptcha links.
I don't want to be spreading these keys around my app and then need to go hunting for them if I want to go from sandbox to live for example.
I am trying to define my API keys and most used links in the CodeIgniter config.php file like this...
$config['stripe_live'] = [
'secret' => 'secret_key_xyz',
'private' => 'private_key_xyz',
]
$config['stripe_sandbox'] = [
'secret' => 'secret_key_xyz',
'private' => 'private_key_xyz',
]
$config['paypal'] = [
'secret' => 'secret_key_xyz',
'private' => 'private_key_xyz',
]
$config['recaptcha'] = [
'site_key' => 'xyz_one_two_three',
'secret_key' => 'xyz_one_two_three',
];
$config['jquery'] = [
['jquery_link'] => base_url() . 'Public/js/jquery.js',
]
$config['bootstrap'] = [
['bootstrap_link'] => base_url() . 'Public/js/jquery.js',
]
$config['fontawesome'] = [
]
$config['google_fonts'] = [
];
$config['groupworld'] = [
'groupworld_api' => 'api_key_xyz';
];
Question one:
If I wanted to access my Stripe live private key I would have to write...
$stripe_live = $this->config->item('stripe_live');
$stripe_live['public_key'];
This is almost as much work as just copying the key to where I need it (one or two places). So is there a simpler way?
Question two:
Is is okay to put my urls in the config file like in my example above? Or would it be better to define my URLs as constants (in the constants file) and then simply access them as constants instead of writing out $this->config->item('bootstrap_link')
Thanks.
After looking at the CodeIgniter Config documentation I have come up with the following solution at least for my API configuration settings, in the example below I am using the google recaptcha API.
1 - Make a new file inside of the application/config folder and call it whatever you want... e.g. api_config.php
Inside this file put your API keys like this:
// stripe api
$config["stripe_live_public_key"] = "public_key_xyz";
$config["stripe_live_private_key"] = "public_key_xyz";
$config["stripe_sandbox_public_key"] = "public_key_xyz";
$config["stripe_sandbox_private_key"] = "public_key_xyz";
// paypal api
$config["paypal_live_public_key"] = "public_key_xyz";
$config["paypal_live_private_key"] = "public_key_xyz";
$config["paypal_sandbox_public_key"] = "public_key_xyz";
$config["paypal_sandbox_private_key"] = "public_key_xyz";
// recaptcha api
$config["recaptcha_api_url"] = 'https://www.google.com/recaptcha/api.js';
$config["recaptcha_verification_url"] = "https://www.google.com/recaptcha/api/siteverify";
$config["recaptcha_public_key"] = "lfgksl;dfg;kkkkdsjfhskjfhkjsdhfjshjksjdh";
$config["recaptcha_private_key"] = "sfkljslfjsjfahjjjjjjhjhsdfjskhajkakkajdj";
// groupworld api
// phpmailer api
2 - In the controller file load your config file and mass the data to the view like this...
$this->config->load('api_config');
$data['recaptcha_api_url'] = $this->config->item('recaptcha_api_url');
$data['recaptcha_public_key'] = $this->config->item('recaptcha_public_key');
3 - In the view file simply display your data...
<script src="<?php echo $recaptcha_api_url; ?>"></script>
<div class="g-recaptcha" data-sitekey="<?php echo $recaptcha_public_key; ?>"></div>
Now to change your config data in multiple places simply go to the api_config.php file and paste in your new keys.
As I'm a newbie can't comment :/ .
I will start with question 2. Its ok to keep like this. But stripe,paypal are payment gateways it will be good to store it in db as Yogesh said and retrieve to use it.It will also comes in handy if you want to provide user to edit it.
For js,css links you can put them in a view like 'includefiles.php' and load it in all pages as we load views.
for easy retrieval of your data, you can use helper functions.
<?php
//paymentdetail_helper
function getpaymentdetailhelper(someid or gateway name as arg eg.$id){
$ins=& get_instance();
$ins->load->database();
//your queries $ins->db->query();
return $data;
}
?>
Save this in application/helpers as paymentdetail_helper.php and load it as usual. more info about helpers in questionInfo about helper
Its my idea. :) You're welcome with suggestions

Plivo Rent a number Api not Working for me

require 'vendor/autoload.php';
use Plivo\RestAPI;
$auth_id = "My AUTH_ID";
$auth_token = "My AUTH_TOKEN";
$p = new RestAPI($auth_id, $auth_token);
$params = array(
'number' => '12512077502' # Phone number to buy
);
$response = $p->get_number($params);
print_r ($response);
It Will Give me Error Message
Array (
[status] => 404
[response] => Array (
[api_id] => 0b6214ee-aec4-11e5-ae4f-22000ac69a0d
[error] => not found
) )
See here https://www.plivo.com/docs/getting-started/phone-number-api/#rent-a-number
You seem to be using the wrong function (get_number) from the python helper library. The correct one is "buy_phone_number" function which uses PhoneNumber API.
Reference - https://github.com/plivo/plivo-python/blob/master/plivo.py#L175
I was using the Python plivo module and had the same problem.
From Plivo Support: "Use the new API: https://www.plivo.com/docs/api/number/phonenumber/#buy-number "
What I found that the the plivo module uses the wrong URL when renting a phone number. My work around is to make the call without the helper library. The following is Python code but it might help give you an idea what to do.
import requests
params = {
'number' : phone_number # Phone number to buy
}
host = 'https://api.plivo.com/v1/Account/%s/PhoneNumber/%s/' % \
(account_sid, phone_number)
r = requests.post(host, timeout=5, json=params, auth=(account_sid, auth_token))
assert r.status_code == 201, 'r.status_code=%s' % `r.status_code`
Update: The above might not be necessary after all. I just got an update from Plivo support. The new method name is buy_phone_number() instead of get_number(). That solved the problem for me. I assume the same is true for the PHP library.

Yii2 translating data stored in database

I'm working with Yii2 Framework, and already configured i18n component using this guide:
http://thecodeninja.net/2014/12/i18n-with-yii-2-advanced-template/
So, I can now translate strings within my php files using Yii::t() function. Translatable strings are extracted using $ ./yii message/extract console command, which generates proper translation files.
I now need to display translations for strings stored in the database.
I could use Yii:t() with a variable instead of a string as an argument like this
echo Yii:t('app', $some_string_from_db );
and make a new php file with some code like this
<?php
function dbStringsToTranslate() {
$o = Yii::t('app','db english string 1');
$o.= Yii::t('app','db english string 2');
$o.= Yii::t('app','db english string 3');
return $o;
}
This way $ ./yii message/extract command will find the needed translations.
This is working Ok, but of course $ ./yii message/extract is throwing some warnings anywhere I use Yii:t() with variables.
Skipping line 39. Make sure both category and message are static strings.
I think this is not a big deal, but well, here is my question:
Is this a right way to translate strings stored in a database?
Is there a better way to accomplish this?
You can check out this extension. https://github.com/creocoder/yii2-translateable it allows for attaching behaviors to models to support multiple languages.
I am using it now in a projects and it is easy to use.
I was having the same problem, and I found the solution with this module. In the module configuration you have the 'tables' array, in which you can specify which field(s) of which table(s) should be translated.
Then, the module has its own 'scan' action (equivalent to message/extract) with which it adds all the translatable strings to database (using DbMessageSource): all Yii::t, the specified database fields, and many more (even javascript, check the docs). It also has a nice user interface to do the translations, it's awesome!
For example, with the following configuration the field name from table nationality will be scanned and added for its translation (i.e country names):
'modules' => [
'translatemanager' => [
'class' => 'lajax\translatemanager\Module',
...
'tables' => [ // Properties of individual tables
[
'connection' => 'db', // connection identifier
'table' => 'nationality', // table name
'columns' => ['name'], // names of multilingual fields
'category' => 'database-table-name',// the category is the database table name
'categoryPrefix' => 'lx-' //
]
]
],
],
You can generate php file with some fake Yii:t() calls.
For example:
$filename = Yii::getAlias('#frontend/runtime/fake-category-translations.php');
$str = '<?php' . PHP_EOL;
foreach (Category::find()->all() as $category) {
$str .= "Yii::t('category', '{$category->name}');" . PHP_EOL;
}
file_put_contents($filename, $str);
In output this file will be something like this:
<?php
Yii::t('category', 'Art & Design');
Yii::t('category', 'Creativity');
Yii::t('category', 'Educational');
Yii::t('category', 'Education');
Yii::t('category', 'Lifestyle');
Yii::t('category', 'Casual');
So, now you can just call console method for searching untranslated strings:
php yii message/extract #frontend/messages/config.php
I know this is old but I faced same thing with rest API, and here is how I went about resolving it. Note that When saving I used
$post->comment = Yii::t('app', 'My Nice Comment here');
$post->save();
class Post extends ActiveRecord
{
public function fields()
{
$fields = parent::fields();
$fields['comment'] = function ($model) {
return Yii::t('app', $model->comment);
};
return $fields;
}
}

LyricAPI - how to get full lyrics?

I want to use LyricAPI hosted on Wikia to get lyrics of songs. But in response I get only part of lyrics:
Await the coming storm, behold the sign in the sun
Chaos upon us spawn! The arrows of time pinpoints us all
Oh, well the maddening laughter growing louder with the memories
Atoms like incense rising, like a thousand candles al[...]
How can I get entire lyrics?
Here is my code:
$client = new SoapClient("http://lyrics.wikia.com/server.php?wsdl", array(
'username' => LYRIC_LOGIN,
'password' => LYRIC_PASS
));
$auth = array(
'username' => LYRIC_LOGIN,
'password' => LYRIC_PASS
);
$header = new SoapHeader('NAMESPACE','Auth',$auth,false);
$client->__setSoapHeaders($header);
$song = $client->getSOTD();
http://api.wikia.com/wiki/Documentation
For legal reasons, the API is not allowed to provide full-lyrics at
the moment. It currently provides a fair-use sample (to verify that
the match is correct) and a link to the page where the full lyrics can
be viewed.

Categories