PHP code for Bing/Microsoft/Azure translator

Microsoft has yet again changed the API service for the translator api they offer (formerly known as Bing translator, Microsoft Translator, Azure Translator?). It’s now been moved to Azure, and is under the “Cognitive Services” offerings. Maybe it will stay here for more than a couple months before they mess with it again?

I needed to update a PHP app that calls the bing translator API, and couldn’t find anything that did the trick. Prior to the full Azure move, the service has been put under a data market portal, and later the simple basic auth api was updated to use OAuth for security. The latest iteration still uses Oath, but it’s simplified now to the point that all you need to pass is the secret key to get the authorization token – as opposed to previously requiring an app name, some domain scope thing, etc- a lot of moving parts. Now all that is needed to get a token is this:

Option 1: Pass key using header

curl --header 'Ocp-Apim-Subscription-Key: ' --data "" 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken'

Option 2: Pass key using query string parameter
curl --data "" 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key='

The body of the request is the token you use- so you don’t need to parse a JSON result or anything.

Here is a PHP class you can use with the latest greatest api- Note that this code hits the issuetoken request with every request, the tokens are good for a period of time (30 minutes if I recall) so this code could use caching to only request a new token after it expires. I’ll update this later. Also the code is pretty hackish, needs a lot of cleanup.

Edit the file to with your actual key. Then create an instance of AzureTranslator, set properties for the src and dest languages, and the phrase to translate. Call getTranslateByCurl() and it will return your translated phrase.

class AccessTokenAuthentication {

function getTokens2($clientKey, $authUrl){
try {
//Initialize the Curl Session.
$ch = curl_init();
//Set the Curl URL.
curl_setopt($ch, CURLOPT_URL, $authUrl . '?Subscription-Key=' . $clientKey);
//Set HTTP POST Request.
curl_setopt($ch, CURLOPT_POST, TRUE);
//Set data to POST in HTTP "POST" Operation.
curl_setopt($ch, CURLOPT_POSTFIELDS, ""); // $paramArr);
//CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
//CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Execute the cURL session.
$strResponse = curl_exec($ch);
//Get the Error Code returned by Curl.
$curlErrno = curl_errno($ch);
if($curlErrno){
$curlError = curl_error($ch);
throw new Exception($curlError);
}
//Close the Curl Session.
curl_close($ch);
return $strResponse ;
} catch (Exception $e) {
return ""; // echo "Exception-".$e->getMessage();
}
}
}

/*
* Class:AzureTranslator
*
* Processing the translator request.
*/
Class AzureTranslator {

private $clientSecret = "";
private $authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
private $phrase = null;
private $sourceLang = "";
private $targetLang = "";

public function setPhrase ($phrase = "")
{
$this->phrase = "";
if (!empty($phrase))
$this->phrase = trim($phrase);
}

public function setSourceLang ($sLang = "")
{
$this->sourceLang = "";
if (!empty($sLang))
$this->sourceLang = trim($sLang);
}

public function setTargetLang ($tLang = "")
{
$this->targetLang = "";
if (!empty($tLang))
$this->targetLang = trim($tLang);
}

public function getTranslateByCurl()
{
try {

//Create the AccessTokenAuthentication object.
$authObj = new AccessTokenAuthentication();

$accessToken = $authObj->getTokens2($this->clientSecret, $this->authUrl);
//Create the authorization Header string.
$authHeader = "Authorization: Bearer ". $accessToken;

$contentType = 'text/plain';
$category = 'general';

$params = "text=".urlencode($this->phrase)."&to=".$this->targetLang."&from=".$this->sourceLang;

$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";

//Get the curlResponse.
$curlResponse = $this->curlRequest($translateUrl, $authHeader);

//Interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}

return $translatedStr;
//return $curlResponse;

} catch (Exception $e) {
return "";
//return $e->getMessage();
}
}

/*
* Create and execute the HTTP CURL request.
*
* @param string $url HTTP Url.
* @param string $authHeader Authorization Header string.
* @param string $postData Data to post.
*
* @return string.
*
*/
function curlRequest($url, $authHeader, $postData=''){
//Initialize the Curl Session.
$ch = curl_init();
//Set the Curl url.
curl_setopt ($ch, CURLOPT_URL, $url);
//Set the HTTP HEADER Fields.
curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
//CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
//CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
if($postData) {
//Set HTTP POST Request.
curl_setopt($ch, CURLOPT_POST, TRUE);
//Set data to POST in HTTP "POST" Operation.
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
//Execute the cURL session.
$curlResponse = curl_exec($ch);
//Get the Error Code returned by Curl.
$curlErrno = curl_errno($ch);
if ($curlErrno) {
$curlError = curl_error($ch);
throw new Exception($curlError);
}
//Close a cURL session.
curl_close($ch);
return $curlResponse;
}
}

 

Oculus Rift Green Screen Mixed Reality

If anyone needs me, I’ll be in my green screen vr room for the next year ūüėČ I’ll need to try this same setup with one of the dirt/rally sims I prefer to run instead of the more usual road racing variety.

I’d thought this kind of thing would be awesome, to use the oculus camera and do some kind of mixed reality, almost like a reversed AR (?), but I’d assumed the camera processing was not performant enough to make it work well. This demo seems to prove otherwise. New ideas much?

How to be an Online Broadcaster

I casually¬†asked TK today about online broadcasting, and he managed to deliver a lot of knowledge on the topic. I didn’t even know he was into that kinda thing ūüėČ I’d asked about twitch.tv after seeing an article able using twitch to control paintbrushes to create painting, in a strange crowd-sourced kind of artwork (article at intel.com). ¬†I’m logging all this here for my own future reference, or for any other lonely stranger who may come across it.

Most important thing I’ve seen that make for a great show is
-a good mic
-a compressor (so you don’t get too loud)
-good lighting
-an ability to talk to chat.

(The last item refers to the live chat in mediums such as twitch.tv provides. it can get distracting trying to do a show while also interacting with chats, especially when they come in a fast rate.)

I don’t even think having a great camera makes as much of a difference as the mic and compressor.

(doing ok in the mic department – see pic below!)

Blue Yeti mic on arm and vibration isolation mount
Blue Yeti mic on arm and vibration isolation mount

If you are loud with hissing and popping no one is watching you.

Info on sound compression, to smooth out the hiss/pop sounds: https://theproaudiofiles.com/voice-processing-eq-cuts-boosts/

Basically you want to do whatever you can to have that radio DJ sound, not annoying, just one even level of volume.

This link is the OBS Project – Open source casting software – https://obsproject.com/
It’s used by just about everyone, supports scenes / multi inputs.. supports¬†youtube streaming as well as twitch and others.

Another trick is to use a dedicated monitor devoted to chat, put in portrait mode if possible. Twitch chat is built on IRC so you can use an irc client to connect to chat, makes it much easier to read and can fill this devoted screen easily.

Oh and get good moderators for chat.¬†Even with good mods,¬†I’ve seen streams come to a halt because the streamer happened to see an inappropriate message in chat before it could be deleted.
One streamer even recently talked about this, how that out of 1k people watching and having a good time, you just latch on to that one negative comment and your whole stream is ruined.

Will add more here as more is discovered. Still need to cover lighting topic a bit more.

I’m on hold song on uberconference.com

Called into an uberconference conference call today and was a little early. Noticed the hold music was a little different than what I’m used to.
Then I noticed the guy singing mentioned being “on hold, for a conference call” and “wonder where my friends are”. Awesome! A bit of googling found this is the song I heard on soundcloud

So far I’m impressed with uberconference.com, their basic service is free and their call quality has been adequate so far. I’d like to find out if they have an uberconference affiliate program so I can try sending some referrals their way (call me, guys).

Using GIT with Visual Studio and a Local project

Git usage with visual studio has become easier in recent times, but I always still have a bit of a headache remembering a few basic items. For instance, I use bitbucket.org for a lot of private repositories, and I often will have source code on my local machine that I’d like to add to git and then sycn with bitbucket. Visual studio seems to not like creating a new git repository in a folder that has files in it already, but I don’t usually want to move files into a new folder. Apparently I have to drop to the commandline and run:

cd <my project path>
git init

After this, you can go back into visual studio and add the newly initialized git repo to it, while you already have the solution open: go to Add, then navigate to the folder and add it.

Then, do a commit.

Then, you can go to sync, to sync it with bitbucket- but you’ll need to go to bitbucket and create the repo there first, then copy the url to the repo. Enter this in the visual studio prompt and then complete the sync.

 

 

PokeFind.com РPokémon Go finder map app

A lot of these “pokemon finder” apps have popped up since the pokemon go app became such a big deal. Check out the http://pokefind.com app for a good example of a pokemon finder (aka pokefind).

A blog is going live soon on the site so you can keep up with both news about pokefind as well as the pokemon go game in general.

Updating here as more is available as well.

Pistol Gun Emoji in Apple iOS and Windows

Big news today was Apple replacing the “pistol” emoji with a water gun design, apparently in an effort to make fonts less violent? The old and new emoji’s look like this:

Pistol on Apple iOS 9.3
Apple iOS original Pistol
Apple iOS Squirt Gun

But, what I didn’t see in the news is that the major “Windows 10 Anniversary Update” released today, does the exact opposite- Windows 10 (and maybe 8? 7?) has had a space-man style pew-pew gun instead of the typical revolver.. but the update today actually changed this back to a traditional revolver desgin.

Pistol on Microsoft Windows 10
Windows 10 original “space man” pistol
Pistol on Microsoft Windows 10 Anniversary Update
Windows 10 Anniversary Update pistol

I suspect this was accidental on Microsoft’s part, as they did a big overhaul of the emoji system in general and probably overlooked this.¬†The timing of the two company’s swapping these designs is pretty funny/spooky though.

Amazon CPM versus Adsense Ads

Been testing Amazon CPM ads on a couple sites lately to see how they perform. So far, my main test was to place it in a lower quality position on a site that has a techie audience, so the visitors typically have very low click rates on adsense ads. The cpm rate for the one ad has settles in at over $1, which actually compares favorably with adsense and may even beat it for this one spot. The next step is to try replacing the remaining adsense ads on this site and see if my overall earnings increase or not. But I’m being hampered by Amazon shortcoming #1:

-Con: Amazon CPM ads do not offer a responsive ad unit option

The current site has responsive ads, so the page can resize and they will resize with it. Amazon only offers the standard sizes like 728×90, 160×600, 350×200 etc. These are great, but I can’t just swap out the responsive ads with them, so I’d have to add some coding to determine if the user is mobile and skip the amazon ads in these instances. This is too much effort at the point so I haven’t gotten around to doing it. (Maybe this could be a future service offering?)

A few other observed Pro’s and Cons:

-Pro (or Con?) – Amazon is CPM based only, and requires you place backup ad code and set a CPM floor for the ads.

This is considered a more advanced option for many users, so it makes implementation a bit more of a headache. You can set up an adsense ad to fill in for the cpm one if it doesnt have anything to show, but this will be driven by the floor cpm you set- go too high, and nothing will show- too low, and you’ll likely loose out on revenue. So, it becomes something you have to watch and fiddle with a bit to optimize, instead of the set-it-and-forget-it way that adsense typically works.

-Con- Amazon Javascript is not async?

I haven’t fully checked this out, but the code script provided by amazon cpm ads appears to not be asyncronous. This could potentially cause your site to load slower than before. Async is almost a basic requirement for sites nowdays, so it’s strange that Amazon would do things this way.

-Con- Reporting РAmazon  reporting for the cpm ads is pretty basic

Overall, it feels like this ad offering was rushed out and perhaps amazon will continue to improve upon it over time. Even the other affiliate ad offerings from amazon are pretty polished nowdays, so the cpm one is lagging even against other amazon offerings.

But in the end, the main thing we care about is- will Amazon make more revenue for you than Adsense? My initial testing looks like it’s a good way to make some extra revenue off your website without diminishing your adsense revenue dramatically- so, the answer is “Yes, sorta”. It may even outperform Adsense on sites that get a lot of traffic but the visitors tend to not click ads, since Amazon is CPM based and not as concerned about actual clicks. But overall, (sigh), at least for now, Adsense still seems to be king.

anrdoezrs.net

What is this weird URL that seems to show up in the strangest places?

anrdoezrs.net is a redirect url used by Commission Junction (cj.com) to sort of anonymize links to individual offers on their platform. So when you post a link to an affiliate offer from CJ (for instance,¬†http://www.anrdoezrs.net/links/3904395/type/dlg/http://www.gearbest.com/tablet-pcs/pp_365835.html ), they use this link to make it less obvious that the link is an affiliate link. Or at least that’s what I assume.

Malware removal toolkit – step by step

I recently suspected my laptop may have some malware (though now I think it’s just some new evil ad stuffing technique used on the web, but digress do I), so I consulted my guru buddy “tk” which malware removal tool he currently recommends. And he dumped the following list on me ūüėČ

me: What’s the best malware scanner n0wdays?
tk: There isn’t one really. You have to weed the sh*t out. One sec and I’ll get you a list.

1.  Start with http://www.bleepingcomputer.com/download/rkill/
2. Then after step 1, go to windows\temp and %temp% and empty those.
3. Then run http://www.bleepingcomputer.com/download/malwarebytes-anti-malware/ ¬†(Don’t install the “free” realtime scanner. it’s a check box. )
4. Then run http://www.bleepingcomputer.com/download/adwcleaner/ (it may find some scheduler stuff or something malwarebytes missed.)
5. Once all that is done, run this to manually see what is starting on the PC: http://www.bleepingcomputer.com/download/hijackthis/
6. Then run this to see if you can spot anything out of the norm (this and the prior step take some understanding of how windows works) http://www.bleepingcomputer.com/download/process-explorer/
7. Then run this hosts file editor to check if any domain redirs are hiding in the hosts file: http://www.amazify.com/windows-hosts-file-editor

tk: If it was just something dumb downloaded with a silent installer, the first two things will clean it up. The last stuff is for the really sh*tty malware.

Migrating from Orchard to WordPress

I still like the Orchard CMS project, but I’ve found it taking too much maintenance time and having weird issues over the years, so I finally caved and moved this site (and a number more to follow) to (or back to) wordpress.

Even this process was made way more difficult than it should have, the basic process went something like this:

-Over time, my site had become so slow it was hurting indexing and other issues- so I had to look into why. Finally figured out spammers had been comment spamming the site so hard, it had over 45k comments in the database and it was hurting performance. The site had an akismet plugin, which was detecting much of the spam, but it was still staying in the database.

-Run an old version of a BlogML export module so I could move the content to wordpress, but the content it exported messed up categories and tags. Tried upgrading to the latest blogml export module, but it doesnt work with my old 1.2 version of orchard, so it promptly crashed and had to be backed out.

-Orchard site was pretty old version (because it doesn’t do auto updating like wordpress does, so I never have time to go manually update the versions), so I first attempted to update from version 1.2 up to 1.10. After a lot of finagling, I actually got the site to load… at first, it just bombed and wouldn’t let me log in. Digging through log files, finding out what was crashing etc., hours later it finally let me in.

-The blog was not shown in the admin, nor on the live site. Where did all the content go?? Found a way to pull the blog content out, but it’s a mess.

-Tried several more ways to export content from the blog, but either the original slug url’s were missing, or the export content was mangled in some other way. Finally decided to just use the original blogml export, sans tags, and just recreate them by hand. UGH.

Oddly enough, the only blogml import module I found for WordPress also was outdated and no longer worked in current wordpress (actually, php) versions. I had to edit the php to fix this module… I *hate* php code! But at least I got it work. Finally get the import completed, and have been messing around with tags. I wanted to map the old orchard /Tags/tagname to the wordpress /tag/tagname, so I added a url rewrite rule to do this.

Now my site is back in commission, running fast, and will auto update when new versions of wordpress comes out. Oh, I’m still running on a windows server though, so I’m not completely mainstream just yet ūüėČ

Where does that leave my relationship with Orchard? I wish the project much success, and I will be still using it for select projects, but for basic blog-type content, I’ll just use WP for a quick setup and execution going forward.

Starbucks CEO Pay

The CEO of starbucks made about 21.5 million in 2014 (combined salary, options, stocks etc.)

Starbucks made 16.4 Billion in 2014

Starbucks employs nearly 200,000 full time employees and over 20,000 stores. 

I often see Starbucks accused of overpaying their CEO (even though he is getting paid only .1% of the company’s revenue) and that they should pay their employees more instead of him. 

So: What would happen if we gave 100% of the the CEO’s pay to all teh employees instead? How much per hour of a pay raise could we give them? 

          200,000   employees
          x 2,000   hours (40 hours per week for a year is 2000 hours)  
=  400,000,000   paid hours in a year (that’s 400 million)

Let’s split up the CEO pay and give it to all those hours.

      21,500,000     ceo pay
/   400,000,000
=        0.05375, OR 5 cents per employee hour.

This means that giving 100% of the CEO pay to all the starbucks employees would result in a whopping 5 CENTS per hour pay raise.

Put another way: The CEO of starbucks gets paid a full 5 cents per hour for every employee his company employs.

  

OneDrive reducing from 15gb to 5gb for free accounts

This is amazing- Microsoft sent a notice today that the free tier for their onedrive offering (basically cloud storage) will be dropping from 15gb down to 5gb. This is in a world where storage continues to get cheaper and storage offerings are continuing to grow their free tiers larger and drop their prices on non-free. Even though Microsoft claims this was a very “hard decision” for them to make, the only logical explanation for this decision would have to be something like:

-implement onedrive way back in windows 7ish (or was it 8?) and make it confusingly integrated with your local document folders
-get a gazillion people to accidently start using the service
-get a second gazillion to start using it after the forced win10 upgrade. 
-ms noticed 60jillion users with 5.623 gb in use and laments how much storage that adds up
-ms genius says “man, if we dropped the free limit to 5gb, we’d be RIIIICH(er)!”
-publish some contrived reason why the limit must be dropped, attempting deperately to not sound like a big stupid lie.

You can read the announcement here if you care to: https://support.office.com/en-us/article/Microsoft-OneDrive-storage-changes-bf91132d-d0cb-4cbb-96ba-86278c5c1c2f?WT.mc_id=PART_OneDrive-Unknown_OneRM_StorageChanges_FAQ&ui=en-US&rs=en-US&ad=US

basically, tons of users will be scrambling to figure out what to do with their files if they are over the 5gb limit, and a large number will feel it necessary to shell out cash for a big ol upgrade.

(Note: my “RICH” joke above is not some bernie-esque hatred of the rich, in fact I’m quite fond of them. I just hate seeing big companies make stupid decisions… over… and over…. and over…)

Prosper 202 on Windows IIS

I’ve been running more PHP and Mysql apps on windows IIS servers lately… I hope this is not the result of some disorder ;p

Wanted to try out Prosper202 Click tracking software. Downloaded the latest, version 1.9.29 as of writing. 

First issue encountered – the app highly recommends installing memcache for performance. I did some checking and memcache on windows looks like it hasn’t been done in a while… the couple binaries I found that might work are pretty outdated or were just broken links. Decided to skip this for now and revisit later (maybe). 

Second issue was a bit trickier- the app loaded and installed the database, but one I logged in, some things were obviosuly not working correctly. I noticed that many of the ajax widgets on the page just kept showing spinners, never loading. I looked at the source on the page and all the realtive links in the page were prepended with “\” instead of “/” – an obvious goof related to how the windows os uses backslashes instead of forward slashes like linux os’es use. 

I traced this down to a function, in the \202config\functions.php file- Update your get_absolute_url() function with this code: 

function get_absolute_url() {

$tmp = substr(substr(dirname( __FILE__ ), 0,-10),strlen(realpath($_SERVER[‘DOCUMENT_ROOT’])));

$tmp = str_replace(‘\\’, ‘/’, $tmp);

return $tmp; 

}

The first line is pretty much what the original used, but then we add a replace for any backslashes to make them into a fwd slash. I haven’t checked further if maybe we could slice off the first char every time and replace it instead, but this broad replace function seems to work so far. 

The software seems to work now, but will proceed next to actually try it – and see if any other problems or performance issues arise. 

Converting DirectX to Vulcan API

Vulcan API spec is out there now and is looking to directly compete with the DirectX api for gaming (and others), for Linux and other platforms. 

I’m sure there will be a lot of discussion about porting from DirectX and/or OpenGLcode to the Vulcan API, so I’ll be adding more content here as I discover more about it. 

update: apparently some are calling it vulcun api instead of vulcan. Learn to spell!