Bing News Search API language translation of results? - microsoft-cognitive

I am querying Bing News Search for foreign markets like China, Malaysia, Russia etc. The results are not always in English. Is there a way or a parameter I can set which would translate all results to English?
Or would I have to do this separately from the Bing News Search API by calling a different language translation API? The setLang parameter doesn't seem to work.

From the official documentation, setLang should not be used to set the language of search results. I checked the official documents. In 2012, Microsoft recommended using JSON Code Sample (Web SourceType). I tested it and it didn't take effect. You can view related posts.
Bing search API - How to localize results?
Because the existing materials are too old, they are all documents many years ago. So I recommend using Microsoft's Translator.
Below I provide sample code, replacing the values of OcpApimSubscriptionKey1 and OcpApimSubscriptionKey1 and OcpApimSubscriptionRegion, which can be run directly. The effect diagram is as follows.
Note:
1. The sample code provided is only a reference code, and it needs to take into account the processing of special characters when used in a production environment.
2. Sample code The non-optimal sample code is just my sample.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Translate</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
var OcpApimSubscriptionKey1="267****6fac1978";
var OcpApimSubscriptionKey2="00d****bff196393";
var OcpApimSubscriptionRegion="koreacentral";
var tmp_jsonstr="";
$(document).ready(function(){
})
function bingnewssearch(){
$.ajax({
url: 'https://panshubeicognitiveservices.cognitiveservices.azure.com/bing/v7.0/news/search?q='+$("#keywords").val()+"&mkt=zh-CN&setLang=EN&cc=EN&count=5",
method: 'GET',
contentType: "application/x-www-form-urlencoded; charset=urf-8",
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Ocp-Apim-Subscription-Key', OcpApimSubscriptionKey1);
},
success:function(result){
var myJSON = JSON.stringify(result);
tmp_jsonstr=myJSON;
$("#orginresult").html(myJSON)
},
error:function(){
alert("Oop, No Data Response");
}
})
}
function translatejson(){
var str="[{\"Text\":\""+tmp_jsonstr.replace(/\"/g,"'")+"'\"}]";
var jsonData=eval( str);//JSON.parse(str);
$.ajax({
url: "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=zh-Hans&to=en",
method: 'POST',
contentType: "application/json; charset=UTF-8",
dataType: 'json',
data:str,
beforeSend: function (xhr) {
xhr.setRequestHeader('Ocp-Apim-Subscription-Key', OcpApimSubscriptionKey2);
xhr.setRequestHeader('Ocp-Apim-Subscription-Region', OcpApimSubscriptionRegion);
},
success:function(result){
var myJSON1 = JSON.stringify(result);
var str=result[0].translations[0].text;
str="{"+str.replace(/'/g, '"')+"}"
$("#translatedresult").html(str)
},
error:function(){
alert("Oop, No Data Response");
}
})
}
</script>
</head>
<body>
<div>
<div><p>Bing News Search</p></div>
<div>
<input type="text" id="keywords" placeholder="key words"/>
</div>
<div>
<button onclick="bingnewssearch()">Search</button>
</div>
<div>Orgin Result</div>
<div>
<span id="orginresult"></span>
</div>
</div>
<hr/>
<div>
<div>
<button onclick="translatejson()">translate orgindata</button>
</div>
<div>
<span id="translatedresult"></span>
</div>
</div>
</body>
</html>

Related

Adding Basic Authorization for Swagger-UI

I have currently deployed a swagger project but I am having trouble adding some basic authorization to it. Currenty when you click on the "Try it out!" button you are required to log in to an account to access the results. I have an account that I want to automatically be used everytime someone tries to access the api. Bellow is my index.html for the project:
<!DOCTYPE html>
<html>
<head>
<title>Swagger UI</title>
<link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/screen.css' media='print' rel='stylesheet' type='text/css'/>
<script src='lib/jquery-1.8.3.js' type='text/javascript'></script>
<script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='lib/handlebars-1.0.rc.1.js' type='text/javascript'></script>
<script src='lib/underscore-min.js' type='text/javascript'></script>
<script src='lib/backbone-min.js' type='text/javascript'></script>
<script src='lib/swagger.js' type='text/javascript'></script>
<script src='lib/swagger-ui.js' type='text/javascript'></script>
<script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>
<script type="text/javascript">
$(function () {
window.swaggerUi = new SwaggerUi({
discoveryUrl:"https://localhost:8080/AssistAPI/api-docs.json",
apiKey:"",
dom_id:"swagger-ui-container",
supportHeaderParams: true,
supportedSubmitMethods: ['get', 'post', 'put'],
onComplete: function(swaggerApi, swaggerUi){
if(console) {
console.log("Loaded SwaggerUI")
console.log(swaggerApi);
console.log(swaggerUi);
}
$('pre code').each(function(i, e) {hljs.highlightBlock(e)});
},
onFailure: function(data) {
if(console) {
console.log("Unable to Load SwaggerUI");
console.log(data);
}
},
docExpansion: "none"
});
window.authorizations.add("key", new ApiKeyAuthorization("Authorization", "XXXX"header"));
//window.authorizations.add("key", new ApiKeyAuthorization("username", "rmanda", "header"));
window.swaggerUi.load();
});
</script>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io">swagger</a>
<form id='api_selector'>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
<div class='input'><a id="explore" href="#">Explore</a></div>
</form>
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap"> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
I am trying to determine where the information is supposed to go to allow Basic Authorization. I know it involved the following lines of code, but can someone please explain to me in a little more detail where things go exactly. I have come to the realization that the documentation for swagger on GitHub is not very clear or helpful
window.authorizations.add("key", new ApiKeyAuthorization("Authorization", "XXXX"header"));
window.authorizations.add("key", new ApiKeyAuthorization("username", "password", "header"));
Swagger UI 3.x
In Swagger UI 3.13.0+, you can use the preauthorizeBasic method to pre-fill the Basic auth username and password for "try it out" calls.
Assuming your API definition includes a security scheme for Basic auth:
swagger: '2.0'
...
securityDefinitions:
basicAuth:
type: basic
security:
- basicAuth: []
you can specify the default username and password for Basic auth like so:
// index.html
const ui = SwaggerUIBundle({
url: "https://my.api.com/swagger.yaml",
...
onComplete: function() {
// "basicAuth" is the key name of the security scheme in securityDefinitions
ui.preauthorizeBasic("basicAuth", "username", "password");
}
})
"Try it out" will use the specified username and password, and if you click the "Authorize" button in Swagger UI, you will see that the username and masked password are pre-filled in the UI.
This answer also contains a solution for Swagger UI 3.1.6—3.12.1, which do not have the preauthorizeBasic feature.
The correct setting for Basic authentication Header is:
Authorization: Basic username:password
The String username:password needs to be encoded using RFC2045-MIME a variant of Base64.
See more details here: https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side
Then, to configure this header, you should do:
Considering that the Base64 encoding for username:password is dXNlcm5hbWU6cGFzc3dvcmQ=
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", "header"));
Read more about this here:
https://github.com/swagger-api/swagger-ui
I had a similar problem, the suggested answers are correct in my case I end up adding something in the index.html like:
var myAuth = "Basic " + btoa("user:password");
window.authorizations.add("key", neSwaggerClient.ApiKeyAuthorization("Authorization", myAuth, "header"));
I added this on either the marked method addApiKeyAuthorization or you can create another method but call it after the window.swaggerUi.load();
But if you have your swagger-ui running as "stand alone" with something like gulp or grunt you may require to configure the services to accept all OPTIONS request.
I struggle a little with that, I hope it helps someone.
Regards
you can add/change this function in your dist/index.html file
function addApiKeyAuthorization(){
var key = encodeURIComponent($('#input_apiKey')[0].value);
if(key && key.trim() != "") {
key = 'Basic '+key;
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", key, "header");
window.swaggerUi.api.clientAuthorizations.add("Authorization", apiKeyAuth);
log("added key " + key);
}
}
OR you can move on new version of Swagger 2.0 , this is known issue is was fixed.

"TypeError: undefined is not a function" when trying to push() to Firebase

Upon submission of a form, I want to push that data to my Firebase db and so I'm creating a function to do so (addMeeting). However, upon pressing the button to submit I get the error:
TypeError: undefined is not a function
at l.$scope.addMeeting (http://localhost:8000/js/controllers/meetings.js:10:12)
meetings.js:10:12 is right where my $push is if you'll look at my code below.
My HTML:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Angular Data</title>
<meta name="viewport" content="width=device-width, userscalable=no">
<link rel="stylesheet" href="css/style.css">
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/lib/angular/angular-route.min.js"></script>
<script src="js/lib/angular/angular-animate.min.js"></script>
<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/registration.js"></script>
<script src="js/controllers/meetings.js"></script>
</head>
<body>
<header>
<nav class="cf" ng-include="'views/nav.html'"></nav>
</header>
<div class="page">
<main class="cf" ng-view></main>
</div>
</body>
</html>
My apps.js:
var myApp = angular.module('myApp',
['ngRoute', 'firebase', 'appControllers']);
var appControllers = angular.module('appControllers', ['firebase']);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
controller: 'RegistrationController',
templateUrl: 'views/login.html'
}).
when('/register', {
controller: 'RegistrationController',
templateUrl: 'views/register.html'
}).
when('/meetings', {
controller: 'MeetingsController',
templateUrl: 'views/meetings.html'
}).
otherwise({
redirectTo: '/login'
});
}])
meetings.js -the Controller containing the addMeeting function that is failing:
myApp.controller('MeetingsController',
function($scope, $firebaseObject) {
var ref = new Firebase('https://angulardataldc.firebaseio.com/meetings');
var meetings = $firebaseObject(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.$push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
}); //MeetingsController
The view that is calling that function upon submission of a form:
<section class="meetings cf">
<h1>Add Meetings</h1>
<form class="formgroup addmeeting cf"
name="myform"
ng-submit="addMeeting()"
novalidate>
<div class="inputwrapper">
<input type="text" name="meetingname" placeholder="Meeting Name"
ng-model="meetingname" ng-required="true">
</div>
<button type="submit" class="btn"
ng-disabled="myform.$invalid">+</button>
</form>
<h2>Your Meetings</h2>
<div class="meeting" ng-repeat="meeting in meetings">
<p>{{meeting.name}}</p>
</div>
</section>
**Edit: ** It has something to do with the .push() method itself. I see that in the latest version of angularfire/firebase it should be .push, instead of .$push, ad have changed that but it does not solve my problem. I reverted AngularFire and Firebase to versions 0.8.2 and 1.0.21 respectively, re-introduced the .asObject() and $push, and everything works fine. I don't understand why .push() is failing with all the latest (Firebase 2.2.2, AngularFire 1.0).
Firebase's AngularFire library has two primary types: $firebaseObject and $firebaseArray (instantiated through $asObject and $asArray respectively in pre-1.0 versions of AngularFire).
You're using both the wrong type and the wrong method. To quote AngularFire's documentation on its array type:
Synchronized arrays should be used for any list of objects that will be sorted, iterated, and which have unique IDs. The synchronized array assumes that items are added using $add(), and that they will therefore be keyed using Firebase push IDs.
So:
var ref = new Firebase('https://angulardataldc.firebaseio.com/meetings');
var meetings = $firebaseArray(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.$add({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
You made a typo, it should be .push instead of $push
CODE
$scope.addMeeting = function() {
meetings.push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
Reference

jQuery Ajax() doesn't work when the page is accessed as a WordPress template page

In one file (test_ajax.php) I have a which on change loads another page (registration_form_race_type.php) with a short message via jQuery Ajax(). It works fine when "test_ajax.php" is accessed via its absolute URL which is :
http://46.20.119.207/~asuntosf/wordpress_test/wp-content/themes/test_ajax/test_ajax.php
But amazingly enough, the Ajax functionality ceases to work if the exact same page "test_ajax.php" is accessed via its WordPress address which is :
http://46.20.119.207/~asuntosf/wordpress_test/?page_id=13
I insist these both URLs point to the SAME two PHP files.
Here is the code of "test_ajax.php" :
<?php
/*
Template Name: Page Test Ajax 01
*/
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type="text/javascript">
jQuery(function () {
jQuery('#event_id_from_list').change(function() {
var event = jQuery("#event_id_from_list").val();
var data = "event_id=" + event;
jQuery.ajax({
url: 'registration_form_race_type.php',
type: 'GET',
data: data,
success: function(data){
jQuery('#div_race_type').html(data);
}
});
});
});
</script>
</head>
<body>
<select class='required' type="text" name="event_id_from_list" id="event_id_from_list" />
<option value='Paris'>Paris</option>
<option value='London'>London</option>
<option value='Rome'>Rome</option>
</select>
<div id='div_race_type' class='section'>
<?php require_once('registration_form_race_type.php'); ?>
</div>
</body>
<html>
And the code of the page called via Ajax, "registration_form_race_type.php" :
<?php if (isset($_GET['event_id'])) echo 'you selected '.$_GET['event_id']; ?>
There is nothing strange about this behavior. You are simply referring to registration_form_race_type.php in your jQuery and it does just what you are asking it to do, which is to look for registration_form_race_type.php in the current directory. registration_form_race_type.php lives inside http://46.20.119.207/~asuntosf/wordpress_test/wp-content/themes/test_ajax/ and not in http://46.20.119.207/~asuntosf/wordpress_test/.
If you would like to access registration_form_race_type.php from http://46.20.119.207/~asuntosf/wordpress_test/?page_id=13, your code needs to change to:
jQuery.ajax({
url : 'wp-content/themes/test_ajax/registration_form_race_type.php',
type : 'GET',
data : data,
success : function (data) {
jQuery('#div_race_type').html(data);
}
});

How to compile an external handlebars template without using $.ajax

I have 2 files in a very simple web application
The first is a standard index.html and it looks something like the below
<body>
<div id="add-stuff"></div>
<script id="the-template" type="text/x-handlebars-template" src="some-template.erb.html"></script>
<script type="text/javascript">
var data = [];
var source = $("#the-template").html();
var template = Handlebars.compile(source);
$('#add-stuff').html(template(data));
</script>
</body>
The second is my handlebars template "some-template.erb.html" and it looks something like the below
<table>
{{#each item}}
<tr><td>{{ item.name }}</td></tr>
{{/each}
</table>
The problem with the inline javascript I have above is that when I try the ".html()" part it always returns an empty string (as I'm linking in the erb.html file).
I've found a work around that lets me achieve this if I use $.ajax to pull in the template but I'd much prefer something like the above (so I can include the template client side w/out any nested jQuery callbacks).
Is this possible? If not what can I do do improve the $.ajax based approach?
** the ajax based approach that works is shown below **
<body>
<div id="add-stuff"></div>
<script type="text/javascript">
$.ajax({
url: 'some-template.erb.html',
cache: true,
success: function (source) {
var data = [];
var template = Handlebars.compile(source);
$('#add-stuff').html(template(data));
}
});
</script>
</body>
Here is a link to the stackoverflow question that showed the $.ajax version in a bit more detail
maybe its already outdated, but I found your question today and I have a suggestion for you or people who are dealing with the same problem. It's not a perfect one, but for small templates an option if you don't want to use ajax.
What do you think about writing the template as string in a variable in an external JS-file and inlcude it via script tag?
template.js
var source = '<table>\
{{#each item}}\
<tr><td>{{ item.name }}</td></tr>\
{{/each}';
index.html
<body>
<div id="add-stuff"></div>
<script src="template.js"></script>
<script type="text/javascript">
var data = [];
var template = Handlebars.compile(source);
$('#add-stuff').html(template(data));
</script>
</body>

Telerik TreeView for ASP.NET MVC ajax woes

Telerik's TreeView control, although fancy and with a lot of functionality is proving to be a nightmare for me now. However I could not find a better TreeView control which supports collapsing/expanding etc. and has a little bit of documentation. Here's my problem.
This is the site master : _Layout.cshtml
<!DOCTYPE HTML>
<html>
<head>
<title>#ViewBag.Title</title>
<!--
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/custom.css")" rel="stylesheet" type="text/css" />-->
#(Html.Telerik().StyleSheetRegistrar()
.DefaultGroup(group =>
group.Add("telerik.common.css")
.Add("~/Content/Site.css")
.Add("~/Content/custom.css")
.Add("~/Content/themes/humanity/jquery-ui-1.8.18.custom.css")
.Combined(true)
.Compress(true)))
</head>
<body>
<div class="page">
<header>
<div id="header-logo">
<img alt="X" src="../../Content/Images/logo100.png"/>
</div>
<div id="title">
<h1>title</h1>
</div>
#(Html.Telerik().Menu()
.Name("menu")
.Items(menu =>
{
menu.Add().Text("Home").Action("Index", "Home");
menu.Add().Text("Products")
.Items(item =>
{
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
});
menu.Add().Text("Events").Action("Index", "Events");
menu.Add().Text("About Us").Action("About", "Home");
menu.Add().Text("Admin").Action("Index", "Admin");
})
.HtmlAttributes(new { style = "text-align:left;" }))
</header>
<section id="main">
#RenderBody()
</section>
<footer>
</footer>
</div>
#(Html.Telerik().ScriptRegistrar()
.Scripts(script=>script.Add("~/Scripts/custom.js"))
.Globalization(true)
.DefaultGroup(group => group.Combined(true)
.Compress(true)))
</body>
</html>
This is the base page view : Index.cshtml
#{
ViewBag.Title = "Admin";
}
<h2>
Admin Index</h2>
<div id="navAdminLeft">
#(Html.Telerik().TreeView()
.Name("AdminNavTree")
.Items(item =>
{
item.Add().Text("Products");
item.Add().Text("Categories");
item.Add().Text("Materials");
item.Add().Text("Finishes");
item.Add().Text("Packaging");
item.Add().Text("File Manager");
item.Add().Text("CategoryTree");
})
.ClientEvents(events => events.OnSelect("loadAdminContent"))
)
</div>
<div id="adminContent">
</div>
<script type="text/javascript">
function loadAdminContent(e) {
$.ajax({
type: "GET",
cache: false,
url: "Admin/" + e.item.innerText,
data: {},
success: function (data) {
$("#adminContent").html(data);
}
});
}
</script>
whenever the user selects a node on the #AdminNavTree the page fetches the content to be displayed and populates #adminContent. I am trying to build an edit page where there is a category tree listed in one div and when the user clicks on any of the category on that div, the details are ajax loaded into another div on the same page. Here is the partial view with the category tree that gets loaded into #adminContent: _CategoryTree.cshtml
#using xxx.Models.Navigation
#model IEnumerable<NavigationItem>
<div id="categoryTree">
#{Html.Telerik().TreeView()
.Name("ctree")
.BindTo(Model, mappings =>
mappings.For<NavigationItem>(binding => binding
.ItemDataBound((currentItem, navigationItem) =>
{
currentItem.Text = navigationItem.Text;
currentItem.Expanded = true;
})
.Children(child => child.Items)
))
.ClientEvents(events=>events.OnSelect("loadContent"))
.Render();
}
</div>
<div id="detail"></div>
<script type="text/javascript">
function loadCategoryDetail(e) {
$.ajax({
type: "POST",
url: "Admin/CategoryDetails",
data: { id: $("#ctree").data("tTreeView").getItemText(e.item) },
success: function (data) {
$("#detail").html(data);
}
});
}
</script>
the detail page that is ajax loaded does not contain any telerik controls so listing code for that is a non issue.
The PROBLEM : this will not render. As soon as it tries rendering #ctree treeview it starts throwing all kind of script errors, specifically it ignores loadCategories (says not found). So far I think what is happening is the ajax loaded partial page that contains the treeview is reloading the jquery lib destroying all old bindings and functions in the script. Is there a way to make this work, two treeviews on one page, one previously loaded, one in a ajax loaded partial view, both binding to separate data?
I've had good success with jsTree... doesn't help with your telerik question, but might be worth checking out.
http://www.jstree.com/

Resources