When we make a query to Translate API
https://translation.googleapis.com/language/translate/v2?key=$API_KEY&q=hello&source=en&target=e
I only get 1 result in :
{
"data": {
"translations": [
{
"translatedText": "....."
}
]
}
}
Is it possible to get all variations (alternatives) of that word, not only 1 translation?
Microsoft Azure supports one. https://learn.microsoft.com/en-us/azure/cognitive-services/translator/reference/v3-0-dictionary-lookup .
For ex. https://api.cognitive.microsofttranslator.com/dictionary/lookup?api-version=3.0&from=en&to=es
[
{"Text":"hello"}
]
gives you a list of translations like this:
[
{
"normalizedSource": "hello",
"displaySource": "hello",
"translations": [
{
"normalizedTarget": "diga",
"displayTarget": "diga",
"posTag": "OTHER",
"confidence": 0.6909,
"prefixWord": "",
"backTranslations": [
{
"normalizedText": "hello",
"displayText": "hello",
"numExamples": 1,
"frequencyCount": 38
}
]
},
{
"normalizedTarget": "dime",
"displayTarget": "dime",
"posTag": "OTHER",
"confidence": 0.3091,
"prefixWord": "",
"backTranslations": [
{
"normalizedText": "tell me",
"displayText": "tell me",
"numExamples": 1,
"frequencyCount": 5847
},
{
"normalizedText": "hello",
"displayText": "hello",
"numExamples": 0,
"frequencyCount": 17
}
]
}
]
}
]
You can see 2 different translations in this case.
The Translation API service doesn't support the retrieval of multiple translations of a word, as mentioned in the FAQ Documentation:
Is it possible to get multiple translations of a word?
No. This feature is only available via the web interface at
translate.google.com
In case this feature doesn't cover your current needs, you can use the Send Feedback button, located at the lower left and upper right corners of the service public documentation, as well as take a look the Issue Tracker tool in order to raise a Translation API feature request and notify to Google about this desired functionality.
Approach mapping Wiktionary using POS tags, related terms and Google-translated word.
TL;DR
The question is titled 'get-multiple-variations-from-google-translate-api', but in short, you (still) currently can't do this by using Google's service alone (as of Sept. 2022). It seems most companies, such as Google, want to continue charging for this service. This answer provides an approach using a (free) service as a pivot to get the term, related terms, and their POS (Parts of Speech) e.g. noun, verb, etc. before translating those terms and then re-querying the service.
This alternative creates a small pipeline that queries Wiktionary before (on the source language), and after (on the translated terms target language) the translation (using Google).
The small pipeline is written in python and bash.
Rationale
We could get word senses, for each POS (Part of Speech) and corresponding synonyms, then translate for each word sense since Google only translates word to word, and then match word senses for the corresponding target language using a tool such as Wiktionary.
Wiktionary
Fortunately, someone has already created a python library to query Wiktionary for multiple languages.
Script to get definitions / synonyms from Wiktionary (using python):
(requires wiktionaryparser )
e.g. python -m pip install wiktionaryparser
import sys;
import json;
from wiktionaryparser import WiktionaryParser;
parser = WiktionaryParser()
# sys.argv[1] is a language e.g. 'english'
parser.set_default_language(sys.argv[1])
print(
json.dumps(
[
[
{
'pos': d.get('partOfSpeech'),
'text':d.get('text'),
'examples':[e for e in d.get('examples')][0] if d.get('examples') else [],
'related': d.get('relatedWords')
} for d in w.get('definitions')
] for w in parser.fetch(sys.argv[2])
],
indent=2
)
)
Google translate + Wiktionary
The bash script below gets Wiktionary definitions, splits on synonym lists and correlates translations based on POS (Part of Speech).
To be honest this script is a bit convoluted, it uses a lot of utils, but it works. It could be refactored into python like the wiktionary part by anyone wanting to make something a bit more robust.
This github post provided some of the below script that call the free Google translate api.
#!/bin/bash
sl=$1
tl=$2
wiki_sl=$3
wiki_tl=$4
string=$5
ua='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
#echo "$string"
result="{\"${sl}\":[],\"${tl}\":[]}"
#set -x
while IFS= read line; do
# line could be better named 'synonym' here
pos="$(echo ${line} | jq -r ".pos")"
sl_result="$(echo $line | jq . -c)"
tl_result=""
opt_single="single?client=gtx&sl=${sl}&tl=${tl}&dt=t&q=${string//[[:blank:]]/+}"
full_url="http://translate.googleapis.com/translate_a/${opt_single}"
response=$(curl -sA "${ua}" "${full_url}")
tl_word="$(echo ${response} | jq -r '.[[0][0]][] | .[0:1][0]')"
echo "${tl_word}" | grep -q " " && continue 1
tl_result_new="$(python ./get_wiki.py "${wiki_tl}" "${tl_word}" | jq -r -c --arg POS "$pos" '.[][] | select(.pos==$POS)'),"
# making json
tl_result="[${tl_result_new}"
# iterate over synonyms
while IFS= read qry; do
opt_single="single?client=gtx&sl=${sl}&tl=${tl}&dt=t&q=${qry//[[:blank:]]/+}"
full_url="http://translate.googleapis.com/translate_a/${opt_single}"
response=$(curl -sA "${ua}" "${full_url}")
tl_word="$(echo ${response} | jq -r '.[[0][0]][] | .[0:1][0]')"
echo "${tl_word}" | grep -q " " && continue 1
tl_result_new="$(python ./get_wiki.py "${wiki_tl}" "${tl_word}" | jq -r -c --arg POS "$pos" '.[][] | select(.pos==$POS)'),"
# adding to json
tl_result="${tl_result},${tl_result_new}"
done< <(echo "${line}" | jq -c -r ' .related[].words[]' | \
sed -e 's/.*://;s/"//g;s/^ *//g;s/ *$//g' | tr ',' '\n')
tl_result="$(echo "${tl_result_new}" | sed 's/,$//g')"
[ -z "${tl_result}" ] && tl_result=null
[ -z "${sl_result}" ] && sl_result=null
result="{\"${sl}\":${sl_result},\"${tl}\":${tl_result}}"
echo "$result" | jq "."
done< <(python ./get_wiki.py "$wiki_sl" "$string" | \
jq -c -r '.[][]|select(.related[].relationshipType=="synonyms")') 2> /dev/null | jq -c '[.]'
How to use:
The first 2 arguments used are for google (source language, and target language in that order which are two-letter codes.
The second 2 arguments used are for Wiktionary (source language, a full word - e.g. 'English', 'French', etc.)
The final (fifth) argument is the single word to be translated.
./translate.sh en pt english portuguese help
In fact, the python 'wiktionaryparser' lib occasionally breaks and can throw an error, due to the fact that it is a webscraping library, which is why I add 2> /dev/null to silence stderr on output.
./translate.sh en pt english portuguese help 2> /dev/null
This script isn't perfect, but it is a starting point and a proof-of-concept to show you this is possible using a free tool such as wiktionary.
English to Portuguese
$ ./translate.sh en pt english portuguese help 2> /dev/null
Output:
[
{
"en": {
"pos": "noun",
"text": [
"help (usually uncountable, plural helps)",
"(uncountable) Action given to provide assistance; aid.",
"(usually uncountable) Something or someone which provides assistance with a task.",
"Documentation provided with computer software, etc. and accessed using the computer.",
"(usually uncountable) One or more people employed to help in the maintenance of a house or the operation of a farm or enterprise.",
"(uncountable) Correction of deficits, as by psychological counseling or medication or social support or remedial training."
],
"examples": "I need some help with my homework.",
"related": [
{
"relationshipType": "synonyms",
"words": [
"(action given to provide assistance): aid, assistance"
]
}
]
},
"pt": {
"pos": "noun",
"text": [
"assistência f (plural assistências)",
"assistance, aid, help",
"protection"
],
"examples": [],
"related": [
{
"relationshipType": "related terms",
"words": [
"assistir"
]
}
]
}
}
]
[
{
"en": {
"pos": "verb",
"text": [
"help (third-person singular simple present helps, present participle helping, simple past helped or (archaic) holp, past participle helped or (archaic) holpen)",
"(transitive) To provide assistance to (someone or something).",
"(transitive) To assist (a person) in getting something, especially food or drink at table; used with to.",
"(transitive) To contribute in some way to.",
"(intransitive) To provide assistance.",
"(transitive) To avoid; to prevent; to refrain from; to restrain (oneself). Usually used in nonassertive contexts with can."
],
"examples": "Risk is everywhere. […] For each one there is a frighteningly precise measurement of just how likely it is to jump from the shadows and get you. “The Norm Chronicles” […] aims to help data-phobes find their way through this blizzard of risks.",
"related": [
{
"relationshipType": "synonyms",
"words": [
"(provide assistance to): aid, assist, come to the aid of, help out; See also Thesaurus:help",
"(contribute in some way to): contribute to",
"(provide assistance): assist; See also Thesaurus:assist"
]
}
]
},
"pt": {
"pos": "verb",
"text": [
"ajudar (first-person singular present indicative ajudo, past participle ajudado)",
"to help, aid; to assist"
],
"examples": "Ajude-me! ― Help me!",
"related": [
{
"relationshipType": "related terms",
"words": [
"ajuda",
"ajudante"
]
}
]
}
}
]
English to Latin
$ ./translate.sh en la english latin body | jq '.'
[
{
"en": {
"pos": "noun",
"text": [
"body (countable and uncountable, plural bodies)",
"Physical frame.",
"Main section.",
"Coherent group.",
"Material entity.",
"(printing) The shank of a type, or the depth of the shank (by which the size is indicated).",
"(geometry) A three-dimensional object, such as a cube or cone."
],
"examples": "I saw them walking from a distance, their bodies strangely angular in the dawn light.",
"related": [
{
"relationshipType": "synonyms",
"words": [
"See also Thesaurus:body",
"See also Thesaurus:corpse"
]
}
]
},
"la": {
"pos": "noun",
"text": [
"cadāver n (genitive cadāveris); third declension",
"A corpse, cadaver, carcass"
],
"examples": [],
"related": []
}
}
]
When it doesn't work
Sometimes there is no output at all.
Shortcomings of this approach, and going further
Despite a lot of words being on Wiktionary, and a lot of synonyms being present, they are not always inside the 'related' field, sometimes synonyms are in the 'text' field, which gives word senses. I suspect that the partial information wiktionaryparser provides is the same on the Wiktionary site.
One could use any dictionary tool, or online thesaurus, such as wordnet, to first get possible POS tags and a word's synsets, or query a fasttext model to get a word's nearest neighbors, then filter only words that are nearest neighbors from the 'text' field in wiktionary.
Sorry for the brief question, but just wondering if there's an API to find out the number of pipelines on a GoCD server.
The Pipeline Groups API will give you what you need after some JSON parsing.
$ curl 'https://ci.example.com/go/api/config/pipeline_groups' \
-u 'username:password'
Returns:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
[
{
"pipelines": [
{
"stages": [
{
"name": "up42_stage"
}
],
"name": "up42",
"materials": [
{
"description": "URL: https://github.com/gocd/gocd, Branch: master",
"fingerprint": "2d05446cd52a998fe3afd840fc2c46b7c7e421051f0209c7f619c95bedc28b88",
"type": "Git"
}
],
"label": "${COUNT}"
}
],
"name": "first"
}
]
You can grab the config.xml file and parse it. from the config repo or via http.
As an alternative, you can just get the cctray file from your server at http://yourgoserver/go/cctray.xml and parse it.
It contains information about all the pipelines (including its stages)
I would recommend using yagocd:
from yagocd import Yagocd
go = Yagocd(server='https://build.gocd.io')
# login as guest
go._session.get('https://build.gocd.io/go/plugin/interact/gocd.guest.user.auth.plugin/index')
print(len(list(go.pipelines)))
Yes, of course. You can get the desired output in different ways. The first easy way to get the number of pipelines and other statistical information from the GoCD support URL (https://example.com/go/api/support) which requires admin privilege.
If the user does not have the admin privilege, we need to go with the GoCD pipeline_groups API. The below command should give you the exact result with jq(JSON processor)
$ curl 'https://example.com/go/api/config/pipeline_groups' -u 'username:password' | jq -r '.[] | .pipelines[].name' | wc -l
NOTE: Still Go Administrator users can get the actual number of pipelines.
I have a project with the following chutzpah.json:
{
"Framework": "jasmine",
"TestHarnessReferenceMode": "AMD",
"TestHarnessLocationMode": "SettingsFileAdjacent",
"EnableTestFileBatching": true,
"References": [
{ "Path": "node_modules/es6-shim/es6-shim.min.js" },
{ "Path": "node_modules/zone.js/dist/zone.min.js" },
{ "Path": "node_modules/reflect-metadata/Reflect.js" },
{ "Path": "node_modules/systemjs/dist/system.js" },
{ "Path": "system-config.js" }
],
"CodeCoverageExcludes": ["node_modules/*"],
"Tests": [
{ "Path": "app", "Includes": [ "*.spec.ts" ] }
]
}
and the following tests files
Test explorer just shows tests stored in the first file
If I try to run the the command of the VSTest I get the same result:
If I call the command setting the name of the file (e.g. "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe" app\InspectionDataView.spec.ts /UseVsixExtensions:true ), the tests in the file run.
Extra point:
I tried to run the test directly with Chutzpah.console.exe, this is what I got:
What am I missing here ?
Note: Using VS 2015 Update 3
Chutzpah does not run TypeScript. It "supports" it, but you have to add this support in the chutzpah.json.
Why the first test suite succeeds? Perhaps it is written in pure ES5 (Without ES6/TS classes, interfaces, etc).
I did set up chutzpah support for typescript from this repo https://github.com/mmanela/chutzpah/tree/master/Samples/Compilation/TypeScript
Basically, in short:
create a compile.bat that transpiles TS to ES5. Normally - tsc.exe with or without tsconfig.json
add "Compile" section as seen in https://github.com/mmanela/chutzpah/blob/master/Samples/Compilation/TypeScript/chutzpah.json
this shall transpile TS to ES5 every time you run chutzpah.console.exe
I build a VirtualBox VM using Packer and I would like to set some VM meta data (e.g. description, version) using the export_opts parameter. The docs say
export_opts (array of strings) - Additional options to pass to the VBoxManage export. This can be useful for passing product information to include in the resulting appliance file.
I am trying to do this in a bash script calling packer:
desc=' ... some ...'
desc+=' ... multiline ...'
desc+=' ... description ...'
# this is actually done using printf, shortened for clarity
export_opts='[ "version", "0.2.0", "description", "${desc}" ]'
# the assembled string looks OK
echo "export_opts: ${export_opts}"
packer build \
... (more options) ...
-var "export_opts=${export_opts}" \
... (more options) ...
<packer configuration file>
I also tried --version instead of version and putting version and the value into the same string, but none of this works; once exported and re-imported, the VM description is empty.
Does anyone have some working sample code or can help me out with what I'm doing wrong ?
Thank you very much.
Update:
Following Anthony Staunton's approach, I figured out that adding
"export_opts": [ "--vsys", "0", "--version", "0.2.0", "--description", "some test description" ],
to the Packer JSON file does work; passing the same string as --var to Packer does not work.
Fixed the problem at long last, updated the packer documentation with the example below, pull requests pending:
Packer JSON configuration file example:
{
"type": "virtualbox-ovf",
"export_opts":
[
"--manifest",
"--vsys", "0",
"--description", "{{user `vm_description`}}",
"--version", "{{user `vm_version`}}"
],
"format": "ova",
}
A VirtualBox VM description may contain arbitrary strings; the GUI interprets HTML formatting. However, the JSON format does not allow arbitrary newlines within a value. Add a multi-line description by preparing the string in the shell before the packer call like this (shell > continuation character snipped for easier copy & paste):
vm_description='some
multiline
description'
vm_version='0.2.0'
packer build \
-var "vm_description=${vm_description}" \
-var "vm_version=${vm_version}" \
"packer_conf.json"
You may have to specify the data as
in your packer json file
"export_opts": [ "--vsys 0 --version \"0.2.0\"", "{{.Name}} --description \"${desc}\" " ],
I'm trying to run the most basic of TypeScript tests using Jasmine and Chutzpah and I just can't get it to work. Here is the source file:
class Simple {
public easyTest() {
return 5;
}
}
Here is the spec:
/// <reference path="../../../scripts/typings/jasmine/jasmine.d.ts" />
/// <reference path="../../../src/typescript/classSimple.ts" />
describe("Simple Calculations", () => {
it("should return true", () => {
var simpl = new Simple();
expect(simpl.easyTest()).toBe(5);
});
});
Here is my chutzpah.json file:
{
"RootReferencePathMode": "SettingsFileDirectory",
"Framework": "jasmine",
"Compile": {
"Mode": "External",
"Extensions": [ ".ts" ],
"ExtensionsWithNoOutput": [ ".d.ts" ]
},
"References": [
{ "Path": "../../../src/typescript/classSimple.ts" }
],
"Tests": [
{ "Path": "simpleSpec.ts" }
],
"EnableTracing": true
}
Here is the folder structure
TestProject.sln
-src
--typescript
---classSimple.ts
-tests
--jasmine
---typescript
----chutzpah.json
----simpleSpec.ts
This VS.NET project is set to compile TypeScript upon save and I'm physically looking at the transpiled JavaScript output: classSimple.js in the exact same directory next to classSimple.ts. Yet when I run the spec using Chutzpah I get the following:
Message:Chutzpah run started in mode Execution with parallelism set to
4 Message:Building test context for
C:\dev\TestProject\tests\jasmine\typescript\simpleSpec.ts
Message:Building test context for
'C:\dev\TestProject\tests\jasmine\typescript\simpleSpec.ts'
Message:Test file
c:\dev\TestProject\tests\jasmine\typescript\simplespec.ts matched test
file path from settings file Message:Investigating reference file path
'../../../src/typescript/classSimple.ts' Message:Added file
'C:\dev\TestProject\src\typescript\classSimple.ts' to referenced
files. Local: True, IncludeInTestHarness: True Message:Processing
referenced file 'C:\dev\TestProject\src\typescript\classSimple.ts' for
expanded references Message:Added framework dependency
'C:\Users\myself\AppData\Local\Microsoft\VisualStudio\14.0\Extensions\mfv4e3ra.luv\TestFiles\jasmine\v2\jasmine_favicon.png' to referenced files Message:Added framework dependency
'C:\Users\myself\AppData\Local\Microsoft\VisualStudio\14.0\Extensions\mfv4e3ra.luv\TestFiles\jasmine\v2\boot.js'
to referenced files Message:Added framework dependency
'C:\Users\myself\AppData\Local\Microsoft\VisualStudio\14.0\Extensions\mfv4e3ra.luv\TestFiles\jasmine\v2\jasmine-html.js'
to referenced files Message:Added framework dependency
'C:\Users\myself\AppData\Local\Microsoft\VisualStudio\14.0\Extensions\mfv4e3ra.luv\TestFiles\jasmine\v2\jasmine.js'
to referenced files Message:Added framework dependency
'C:\Users\myself\AppData\Local\Microsoft\VisualStudio\14.0\Extensions\mfv4e3ra.luv\TestFiles\jasmine\v2\jasmine.css'
to referenced files Message:Added framework dependency
'C:\Users\myself\AppData\Local\Microsoft\VisualStudio\14.0\Extensions\mfv4e3ra.luv\TestFiles\chutzpah_boot.js'
to referenced files Message:Finished building test context for
C:\dev\TestProject\tests\jasmine\typescript\simpleSpec.ts Error: 0 :
Time:22:47:48.6888513; Thread:23; Message:Can't find location for
generated path on C:\dev\TestProject\src\typescript\classSimple.ts
Warning: 0 : Time:22:47:48.6978503; Thread:23; Message:Chutzpah
determined generated .js files are missing but the compile mode is
External so Chutzpah can't compile them. Test results may be wrong.
Information: 0 : Time:22:47:48.7038522; Thread:23; Message:Found
generated path for
C:\dev\TestProject\tests\jasmine\typescript\simpleSpec.ts at
c:\dev\TestProject\tests\jasmine\typescript\simpleSpec.js Error: 0 :
Time:22:47:48.7088508; Thread:23; Message:Couldn't find generated path
for C:\dev\TestProject\src\typescript\classSimple.ts at
And that's it - it just cuts off on the end and nothing happens. The thing is, I see the .js files exactly in the location stated within the trace above, but Chutzpah is claiming Couldn't find generated path for...
This is as simple as it gets for unit testing. I know the tests work independently of the .ts files because if I run just the .js files the tests pass.
What am I doing incorrectly?
Thanks for posting the very detailed repro. You are hitting an issue I have seen a couple times. Since your chutzpah.json is nested in your test folder you need to specify the folder path mapping that chutzpah should use for determining how to map from source to output folder. To do this just change your chutzpah.json to:
{
"RootReferencePathMode": "SettingsFileDirectory",
"Framework": "jasmine",
"Compile": {
"Mode": "External",
"Extensions": [ ".ts" ],
"ExtensionsWithNoOutput": [ ".d.ts" ],
"Paths": [
{ "SourcePath": "../../../", "OutputPath": "../../../"}
]
},
"References": [
{ "Path": "../../../src/typescript/classSimple.ts" }
],
"Tests": [
{ "Path": "simpleSpec.ts" }
],
"EnableTracing": true,
"TraceFilePath": "trace.txt"
}
The other workaround would be to just place the chutzpah.json at the root of your project.
I need to look into making Chutzpah better to avoid this. I think I will look at letting chutzpah in this situation just assume the file is co-located to avoid this common pitfall.
Google led me here for a similar issue:
Some new tests in my Chutzpah project are written in TypeScript and compiled into a single outfile:
tsconfig.json
"compilerOptions": {
"noImplicitAny": true,
"target": "es5",
"module": "none",
"outFile": "./Tests/mytests-ts.js",
"sourceMap": true
}
Chutzpah couldn't find the *.ts files
Chutzpah Error: System.IO.FileNotFoundException: Couldn't find generated path for D:\Code\ChutzpahProject\Scripts\DateServiceMock.ts
until I used the Paths option:
chutzpah.json
"Compile": {
"Extensions": [ ".ts" ],
"ExtensionsWithNoOutput": [ ".d.ts" ],
"Executable": "build-ts.cmd",
"Paths": [
{ "OutputPath": "Tests/mytests-tests-ts.js" }
]
},
This feels like it could have been a comment to #matthew-manela's answer...I think.