I am using Google Translate API with Java and whenever I send an English text with double quotes to be translated, I get this weird formatting:
Source text (en):
"Fresh Air"
Google's response (pt):
"Ar Fresco"
Google's response (es):
"Aire Fresco"
Desired result:
"Ar Fresco" (for Portuguese) and "Aire Fresco" (for Spanish)
Java code used to retrieve translations:
String google_key = "SOME_GOOGLE_API_KEY";
List<String> result = new ArrayList<String>();
try {
Translate t = new Translate.Builder(
com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.newTrustedTransport(),
com.google.api.client.json.gson.GsonFactory.getDefaultInstance(), null)
.setApplicationName("myApp").build();
List<String> totranslate = new ArrayList<String>();
totranslate.add(sourceText);
Translate.Translations.List list = t.new Translations().list(
totranslate,
targetLanguage.getCode());
list.setKey(google_key);
TranslationsListResponse response = list.execute();
for (TranslationsResource tr : response.getTranslations()) {
result.add(tr.getTranslatedText());
}
System.out.println("Google translation: ["+sourceText+"]("+targetLanguage+"): "+result.get(0));
return result.get(0);
} catch (Exception e) {
e.printStackTrace();
return null;
}
What am I missing? Is there a way to avoid this kind of result and get the double quotes as in the original source text?
google api translation is considering the input by default as HTML, you can change the format to "text" or "text/plain"
https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/translate/Translate.TranslateOption.html#format-java.lang.String-
Related
I need to retrieve data (two words - Mega building) from Firebase correctly. However,
"Mega building" is retrieved as "Megabuilding". As seen, it happens without space between two words. Is there any solution for this to draw data like "Mega building"? or Can it be done without space, is there an alternative solution when retrieving JSON object data?
Firebase node:
My node;
Pro_:
Basket:
ID_1:
cat: “ Titan Tech”
info:”Mega Building”
orderid:”Ref_1”
ID_2:
cat: “Tech”
info:”Android”
orderid:”Ref_2”
name:”Mike”
My function:
Intent intent=this.getIntent();
Bundle bundle=intent.getExtras();
Map<String, Object> map1 = (Map)bundle.getSerializable(“basket”);
//First output
System.out.println(“My_basket:”+map1.values());
for (Object value : map1.values()) {
JSONObject json = null;
try {
json = new JSONObject(String.valueOf(value).replaceAll(" ",""));
String cat_ = json.getString(“cat”);
String info_ = json.getString(“info”);
String orderid_ = json.getString(“orderid”);
//Second output
System.out.println(“Info_:”+info_);
} catch (JSONException e) {
//Third output
e.printStackTrace();
}
}
First output:
My_basket:[{cat=Titan Tech, info=Mega Building, orderid=Ref_1,}, {cat=Tech, info=Android, orderid=Ref_2,}]
Second output (ı want to retrieve like “Mega Building”. Problem line is here)
Info_: MegaBuilding
Third output
org.json.JSONException: Unterminated object at character 23 of etc
First of all, you need to mark the spaces where there are spaces.
json = new JSONObject(String.valueOf(value).replaceAll(" ","-"));
Output : Mega-Building
Then just replace the marker you created with spaces again. That's it.
info_ = info_.replace("-"," ");
Output : Mega Building
I am new to shapefile processing. Kindly guide me on how to achieve my below query.
I am using this shapefile tl_2018_us_aiannh.shp from census.gov : TIGER-LINE. I am to obtain the census block group entities like Block, Tract, County subdivision and County details from the shapefile based on the latitude and longitude provided by the user.
My requirement is to achieve this by shapefile alone and not through any API's.
Can someone help on which framework I can achieve this?
What I've tried/using so far:
I have used GeoTools to read the shapefile . Can I continue using the same? Will my requirement be achievable by this tool?
I have gone through a documentation from census.gov which states:
The Census Bureau assigns a code and these appear in fields such as
“TRACTCE”, where “CE” stands for Census. Finally, state-submitted
codes end in “ST”, such as “SLDLST”, and local education agency codes
end in “LEA”, as in “ELSDLEA”.
Which I tried in my code by:
File file = new File("D:\\tl_2018_us_aiannh.shp");
try {
Map<String, String> connect = new HashMap();
connect.put("url", file.toURI().toString());
DataStore dataStore = DataStoreFinder.getDataStore(connect);
String[] typeNames = dataStore.getTypeNames();
String typeName = typeNames[0];
System.out.println("Reading content " + typeName);
SimpleFeatureSource featureSource = dataStore
.getFeatureSource(typeName);
SimpleFeatureCollection collection = featureSource.getFeatures();
SimpleFeatureIterator iterator = collection.features();
try {
while (iterator.hasNext()) {
SimpleFeature feature = iterator.next();
GeometryAttribute sourceGeometry = feature
.getDefaultGeometryProperty();
String name = (String) (feature).getAttribute("TRACTCE");
Property property = feature.getProperty("TRACTCE");
System.out.println(property);
}
} finally {
iterator.close();
}
} catch (Throwable e) {
e.getMessage();
}
But I am receiving null as the value.
Any help would be much helpful.
I have found the solution to this. Hope this would be helpful to someone in need.
SimpleFeature is the type that has the attributes of shape files that you can check when you try to debug or print a line on runtime. You can use the SimpleFeature to get the property. The attributes can be achieved by:
try {
while (iterator.hasNext()) {
SimpleFeature feature = iterator.next();
Property intptlat = feature.getProperty("TRACTCE");
}
}
Make sure you are choosing the Block Groups as the layer type for download in Tiger-Line or which ever site is concerned, where you download the shape file.
I'm using the Java API for ElasticSearch. I'm attempting to highlight my fields but it's not working. The correct results that match the search term are being returned, so there is content to highlight, but it simply won't do it. I set my SearchResponse and HighlightBuilder like this:
QueryBuilder matchQuery = simpleQueryStringQuery(searchTerm);
...
HighlightBuilder highlightBuilder = new HighlightBuilder()
.postTags("<highlight>")
.preTags("</highlight>")
.field("description");
SearchResponse response = client.prepareSearch("mediaitems")
.setTypes("mediaitem")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(matchQuery) // Query
.setFrom(from)
.setSize(pageSize)
.setExplain(true)
.highlighter(highlightBuilder)
.get();
and in my JSON->POJO code, I check to see which fields have been highlighted, but the returned Map is empty.
Arrays.stream(hits).forEach((SearchHit hit) -> {
String source = hit.getSourceAsString();
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
try {
MediaItem mediaItem = objectMapper.readValue(source, MediaItem.class);
mediaItemList.add(mediaItem);
} catch (IOException e) {
e.printStackTrace();
}
});
Why on earth is my highlighting request being ignored?
Any help is greatly appreciated.
You have to set the highlighted field in HighlightBuilder.
For example:
HighlightBuilder.Field field = new HighlightBuilder.Field(fieldName);
highlightBuilder.field(field);
I saw you are using simple query string query, so you can do the following:
Your query string: fieldname: searched text
So for example your query string is the following:
price: >2000 && city: Manchaster
With this query string you specified the fields in the query too.
Now highlighter should work.
I have this question for your.
I've a simple file xml and I have to convert it to file Json. So far that's all right but, the output that gives me back isn't well formatted.
Here is the code:
modalities.xml
<cons>
<modalities type="mod">
<modality id="001">
<name>CC</name>
</modality>
<modality id="002">
<name>RS</name>
</modality>
<modality id="003">
<name>TC</name>
</modality>
<modality id="004">
<name>US</name>
</modality>
</modalities>
And ListModalities.java
{ ...
String path = "modalities.xml";
ModalitiesMapperImpXml modXml = new ModalitiesMapperImpXml();
if (modality.equals("list"))
modXml.load(path); //The method return the list that contain the name of modality ( CC - US )
try {
ObjectMapper mp = new ObjectMapper();
return mp.writeValueAsString(modXml);
}
catch (JsonProcessingException jpe) {
return jpe.getMessage();
}
}
Output:
{"modalities":[{"value":"\n\t\t\n\t\t\tCC\n\t\t\n\t\t\n\t\t\tRS\n\t\t\n\t\t\n\t}]}
how can I delete the spaces and the tab character?
Can you help me? Thanks
Regard
Vit
Problem is how you iterate over the XML:
element.getNodeValue()
should be replaced by
element.getTextContent()
I have a problem when using twitter4j, when I get timeline using this code :
try {
ResponseList<Status> tweets = twitter.getHomeTimeline();
for(Status s : tweets){
Tweet temp = new Tweet(new URL(s.getUser().getProfileImageURL()),s.getUser().getName(),"#"+s.getUser().getScreenName() , s.getText());
tweetsPanel.add(temp);
}
} catch (TwitterException | MalformedURLException e) {
e.printStackTrace();
}
(Tweet is local class) everything is OK except the retweets in the timeline are displayed as "Quote Retweet":
RT #SOMEONE : the tweet.
I want it like the website, just a normal retweet.
on twitter4j the retweets are shown in format
RT #user : tweet
because is the actual form a rt takes in text. If you put on twitter a tweet with this same format it will be parsed as a normal retweet from twitter itself.
the only way you can edit this out is to parse the text and eliminate the first part manually.
try something like:
String tweetText = "";
String [] splitted=s.getText().split(":");
if(splitted.lenght>2)
for (int i=1;i<splitted.lenght-1;i++)
{
tweetText+=splitted[i]+":";
}
tweetText+=splitted[splitted.lenght-1];
return tweetText;
by starting the for on i=1 you will avoid adding the first split that contains the RT #user, by adding the splitted[i]+":" you will put back eventual other ":" present in the tweet that split will otherwise eliminate. Of course you don't want to introduce a ":" that was not there, so the last piece of splitted goes outside the for, without the +":"