I'm working on Chrome Sender application now and noticed that media.playerState was not properly updated to chrome.cast.media.PlayerState.PLAYING when play request is successfully executed. I understand that it's possible to subscribe to media state update via media.addUpdateListener(onMediaUpdate); but it's not very convenient. Are there any plans to make API more consistent?
/**
* #param {chrome.cast.media.Media} media
* #return {Promise.defer}
*/
function playMedia(media) {
let playDefer = Promise.defer();
let playRequest = new chrome.cast.media.PlayRequest();
media.play(playRequest, onPlaySuccess.bind(null, playDefer, media), onPlayError);
return playDefer;
}
/**
* #param {Promise.defer} defer
* #param {chrome.cast.media.Media} media
*/
function onPlaySuccess(defer, media) {
// Actually `media.playerState` is still chrome.cast.media.PlayerState.PAUSED
// Is it expected behaviour?
console.log('play request success', media.playerState === chrome.cast.media.PlayerState.PLAYING);
defer.resolve(media);
}
/**
* #param {chrome.cast.Error} error
*/
function onPlayError(error) {
console.log(error.code, error.description);
}
Related
I am creating the following Smart contract. It makes a Chainlink request which isn't returning a value from the API. I am using the following [jobID][1] and this [node][2], but the node doesn't start the job and I don't know why. I checked that the node has a balance of LINK tokens but it doesn't have any and I don't know how to send a balance to the contract node.
I am using Kovan Testnet to try the smart contract. Could you tell me something which I can try?
// This example code is designed to quickly deploy an example contract using Remix.
pragma solidity ^0.6.0;
import "#chainlink/contracts/src/v0.6/ChainlinkClient.sol";
contract APIConsumer is ChainlinkClient {
uint256 public volume;
address private oracle;
bytes32 private jobId;
uint256 private fee;
/**
* Network: Kovan
* Chainlink - 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e
* Chainlink - 29fa9aa13bf1468788b7cc4a500a45b8
* Fee: 0.1 LINK
*/
constructor() public {
setPublicChainlinkToken();
oracle = 0x56dd6586DB0D08c6Ce7B2f2805af28616E082455;
jobId = "b6602d14e4734c49a5e1ce19d45a4632";
fee = 0.1 * 10 ** 18; // 0.1 LINK
}
/**
* Create a Chainlink request to retrieve API response, find the target
* data, then multiply by 1000000000000000000 (to remove decimal places from data).
************************************************************************************
* STOP! *
* THIS FUNCTION WILL FAIL IF THIS CONTRACT DOES NOT OWN LINK *
* ---------------------------------------------------------- *
* Learn how to obtain testnet LINK and fund this contract: *
* ------- https://docs.chain.link/docs/acquire-link -------- *
* ---- https://docs.chain.link/docs/fund-your-contract ----- *
* *
************************************************************************************/
function requestVolumeData() public returns (bytes32 requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// Set the URL to perform the GET request on
request.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");
// Set the path to find the desired data in the API response, where the response format is:
// {"RAW":
// {"ETH":
// {"USD":
// {
// ...,
// "VOLUME24HOUR": xxx.xxx,
// ...
// }
// }
// }
// }
request.add("path", "RAW.ETH.USD.VOLUME24HOUR");
//request.add("path", "data.0.Myvalue");
// Multiply the result by 1000000000000000000 to remove decimals
// Multiply the result by 1000000000000000000 to remove decimals
int timesAmount = 10**18;
request.addInt("times", timesAmount);
// Sends the request
return sendChainlinkRequestTo(oracle, request, fee);
}
/**
* Receive the response in the form of uint256
*/
function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId) {
volume = _volume;
}
/**
* Withdraw LINK from this contract
*
* NOTE: DO NOT USE THIS IN PRODUCTION AS IT CAN BE CALLED BY ANY ADDRESS.
* THIS IS PURELY FOR EXAMPLE PURPOSES ONLY.
*/
function withdrawLink() external {
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(msg.sender, linkToken.balanceOf(address(this))), "Unable to transfer");
}
}
``
[1]: https://market.link/jobs/0609deab-6d61-4937-85e4-a8e810b8b272/runs
[2]: https://market.link/nodes/323602b9-3831-4f8d-a66b-3fb7531649eb/metrics?start=1631783169&end=1632387969
Looking at the Etherscan activity, it looks like the node you are using may be inactive. Try this node and jobId:
Oracle = 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8;
JobId = "d5270d1c311941d0b08bead21fea7747";
These were taken from the Chainlink Official Docs.
To check to see if a node may be inactive or not, check out the oracle address in a block explorer. You can see here that the original node you tried to use hasn't posted a transaction in quite a long time.
If a node is inactive you will need to find a new one or host one yourself. To find more nodes and jobs, you can check market.link or use the one found in the docs as mentioned earlier.
Is there a polish translation for dropzone.js (https://www.dropzonejs.com)?
Istnieje polskie tłumaczenie do skryptu dropzone.js?
Yes:
/**
* The text used before any files are dropped.
*/
dictDefaultMessage: "Kliknij i wybierz pliki lub przeciągnij i upuść tutaj",
/**
* The text that replaces the default message text it the browser is not supported.
*/
dictFallbackMessage: "Twoja przeglądarka nie wspiera przeciągania i upuszczania plików.",
/**
* The text that will be added before the fallback form.
* If you provide a fallback element yourself, or if this option is `null` this will
* be ignored.
*/
dictFallbackText: "Użyj poniższego formularza by wgrać pliki.",
/**
* If the filesize is too big.
* `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
*/
dictFileTooBig: "Plik jest zbyt duży ({{filesize}}MiB). Maksymalny rozmiar pliku: {{maxFilesize}}MiB.",
/**
* If the file doesn't match the file type.
*/
dictInvalidFileType: "Nie możesz wgrać plików tego typu.",
/**
* If the server response was invalid.
* `{{statusCode}}` will be replaced with the servers status code.
*/
dictResponseError: "Kod odpowiedzi serwera: {{statusCode}}.",
/**
* If `addRemoveLinks` is true, the text to be used for the cancel upload link.
*/
dictCancelUpload: "Przerwij wgrywanie",
/**
* The text that is displayed if an upload was manually canceled
*/
dictUploadCanceled: "Wgrywanie przerwane.",
/**
* If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
*/
dictCancelUploadConfirmation: "Jesteś pewien, że chcesz przerwać wgrywanie?",
/**
* If `addRemoveLinks` is true, the text to be used to remove a file.
*/
dictRemoveFile: "Usuń plik",
/**
* If this is not null, then the user will be prompted before removing a file.
*/
dictRemoveFileConfirmation: null,
/**
* Displayed if `maxFiles` is st and exceeded.
* The string `{{maxFiles}}` will be replaced by the configuration value.
*/
dictMaxFilesExceeded: "Nie możesz wgrać więcej plików.",
I'm using Laravel 4 with dompdf package: https://github.com/barryvdh/laravel-dompdf
When I generate a report and it converts it to PDF on my local, everything is fine and displays well, but when I do the same exact thing on my production server, it displays random letters where there is either dynamic or static content.
Screenshot of local vs production:
http://s28.postimg.org/u5zk3pc19/report_diff.png
Here is the code that creates the PDF:
/**
* Create PDF
*
*/
public function createPdf( $reportData )
{
if( $this->validate() )
{
// Get Final Data Information
$btu_hp = static::getBtuHp( $reportData['booth_cfm'], $reportData['cure_temp_hp'], $reportData['outside_temp'] );
$btu_current = static::getBtuCurrent( $reportData['booth_cfm'], $reportData['bake_temp_current'], $reportData['outside_temp'] );
$reportData['energy_percentage_per_unit'] = static::getEnergyPercentagePerUnit( $btu_hp, $btu_current );
$reportData['energy_dollar_per_unit'] = static::getEnergyDollarPerUnit( $reportData['cost_per_therm'], $reportData['bake_time_current'], $reportData['cure_time_hp'], $btu_current, $btu_hp );
$reportData['time_savings_per_unit'] = static::getTimeSavingsPerUnit( $reportData['bake_time_current'], $reportData['cure_time_hp'] );
$reportData['time_savings_per_year'] = static::getTimeSavingsPerYear( $reportData['time_savings_per_unit'][0], $reportData['units_per_day'], $reportData['production_days'] );
$reportData['labor_dollar_per_year'] = static::getLaborDollarPerYear( $reportData['labor_rate'], $reportData['time_savings_per_year'][0] );
$reportData['energy_dollar_per_year'] = static::getEnergyDollarPerYear( $reportData['energy_dollar_per_unit'][0], $reportData['units_per_day'], $reportData['production_days'] );
$view = View::make('pages.report.hp-report.print', array('report' => $reportData));
if( ! $this->saveAsPdf($view, $this->generateFileName()) )
{
return false;
}
return true;
}
return false;
}
/**
* Save report as PDF
* #param html HTML of PDF
* #param fileName Name of File
*
*/
public function saveAsPdf( $html, $fileName = null )
{
if(is_null($fileName))
$fileName = $this->generateFileName();
$htmlPath = $this->reportDirectory.'/'.$fileName.'.html';
$pdfPath = $this->reportDirectory.'/'.$fileName.'.pdf';
file_put_contents( $htmlPath, $html );
// set recent PDF to name of PDF
$this->recentReportFile = $fileName . '.pdf';
return PDF::loadFile($htmlPath)->save($pdfPath);
}
/**
* Get most recent uploaded PDF
*
*/
public function getRecentPdf()
{
return $this->recentReportFile;
}
/**
* Generate file name for PDF
*
*/
public function generateFileName()
{
return Auth::user()->id . '_hp_' . str_random(10) . '_' . time();
}
Everything writes fine and it uses the right template and has the styling... Only the static content and dynamic content (values written out with PHP variables) display badly, although you can see some of the static content like Energy Savings and such prints fine.
Is there a reason this could be all jumbled up on the live server, but not local?
Here is the HTML for the view that is being grabbed (the HTML the php variables are injected into): http://pastebin.com/5bMR6G2s
And here is my config file for dompdf:
http://pastebin.com/Ld6MQckG
There are two possible causes for this:
Missing font(s) on the production server. Make sure you have the correct fonts installed on the production site.
Character encoding issues. I'm not sure which site (dev/live) the issue is on, but it may be that one is outputting UTF-8 and the other is not. You could try to sort this out by detecting the encoding on the input file on both dev and live by using mb_detect_encoding and see if they're different. If they are, then use mb_convert_encoding before converting to PDF.
I am using GWT and I want to upload an image and display its preview without interacting with the server, so the gwtupload lib does not look like a way to go.
After the image is uploaded and displayed, user can optionally save it. The idea is to send the image through GWT-RPC as a Base64 encoded String and finally store it in the DB as a CLOB.
Is there any easy way to do it either with GWT or using JSNI?
This document answers your question:
Reading files in JavaScript using the File APIs
/**
* This is a native JS method that utilizes FileReader in order to read an image from the local file system.
*
* #param event A native event from the FileUploader widget. It is needed in order to access FileUploader itself. *
* #return The result will contain the image data encoded as a data URL.
*
* #author Dušan Eremić
*/
private native String loadImage(NativeEvent event) /*-{
var image = event.target.files[0];
// Check if file is an image
if (image.type.match('image.*')) {
var reader = new FileReader();
reader.onload = function(e) {
// Call-back Java method when done
imageLoaded(e.target.result);
}
// Start reading the image
reader.readAsDataURL(image);
}
}-*/;
In the imageLoaded method you can do something like logoPreview.add(new Image(imageSrc)) where the imageSrc is the result of loadImage method.
The handler method for FileUpload widget looks something like this:
/**
* Handler for Logo image upload.
*/
#UiHandler("logoUpload")
void logoSelected(ChangeEvent e) {
if (logoUpload.getFilename() != null && !logoUpload.getFilename().isEmpty()) {
loadImage(e.getNativeEvent());
}
}
Let's say you have camera property which is an instance of FileUploader do the following:
camera.getElement().setAttribute("accept", "image/*");
camera.getElement().setAttribute("capture", "camera");
camera.getElement().setClassName("camera");
And have imgPreview an instance of Image, do the following.
imgPreview.getElement().setAttribute("id", "camera-preview");
imgPreview.getElement().setAttribute("src", "#");
imgPreview.getElement().setAttribute("alt", "#");
Now add a handler on camera object which calls a native method test1(NativeEvent)
camera.addChangeHandler( e-> {
test1(e.getNativeEvent());
});
public static native void test1(NativeEvent event) /*-{
var image = event.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$wnd.$('#camera-preview').attr('src', e.target.result);
}
// Start reading the image
reader.readAsDataURL(image);
}-*/;
I am building up a firefox extension which allows users to drag and drop things. Now if a user closes the application or reloads the page, I want to restore the last activity he did.
Example : User moves a box from point X to Y.
There can be many more boxes as well.
Now after page reload or application startup, if user puts the addon ON, I want the box's position to be Y. So for this purpose should I be using the firefox preference thing or is there any other better way of doing it.
I wrote a Firefox extension for accessing bookmarks from a site a friend of mine developed. I store the bookmarks data locally as JSON in a text file in the user's extension profile directory in case the bookmark service is down.
My function for saving bookmarks JSON is:
/**
* Stores bookmarks JSON to local persistence asynchronously.
*
* #param bookmarksJson The JSON to store
* #param fnSuccess The function to call upon success
* #param fnError The function to call upon error
*/
RyeboxChrome.saveBookmarkJson = function(bookmarksJson, fnSuccess, fnError) {
var cu = Components.utils;
cu.import("resource://gre/modules/NetUtil.jsm");
cu.import("resource://gre/modules/FileUtils.jsm");
var bookmarksJsonFile = RyeboxChrome.getOrCreateStorageDirectory();
bookmarksJsonFile.append("bookmarks.txt");
// You can also optionally pass a flags parameter here. It defaults to
// FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
var ostream = FileUtils.openSafeFileOutputStream(bookmarksJsonFile);
var converter = Components.classes["#mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(bookmarksJson);
NetUtil.asyncCopy(istream, ostream, function(status) {
if ( !Components.isSuccessCode(status) && typeof(fnError) === 'function' ) {
fnError();
} else if ( typeof(fnSuccess) === 'function' ) {
fnSuccess();
}
return;
});
};
The function for reading the data is:
/**
* Reads bookmarks JSON from local persistence asynchronously.
*
* #param fnSuccess Function to call when successful. The bookmarks JSON will
* be passed to this function.
*
* #param fnError Function to call upon failure.
*/
RyeboxChrome.getBookmarksJson = function(fnSuccess, fnError) {
Components.utils.import("resource://gre/modules/NetUtil.jsm");
var bookmarksJsonFile = RyeboxChrome.getOrCreateStorageDirectory();
bookmarksJsonFile.append("bookmarks.txt");
NetUtil.asyncFetch(bookmarksJsonFile, function(inputStream, status) {
if (!Components.isSuccessCode(status) && typeof(fnError) === 'function' ) {
fnError();
} else if ( typeof(fnSuccess) === 'function' ){
var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
fnSuccess(data);
}
});
};
Finally, my getOrCreateStorageDirectory function is:
/**
* Storage of data is done in a Ryebox directory within the user's profile
* directory.
*/
RyeboxChrome.getOrCreateStorageDirectory = function() {
var ci = Components.interfaces;
let directoryService = Components.classes["#mozilla.org/file/directory_service;1"].getService(ci.nsIProperties);
// Reference to the user's profile directory
let localDir = directoryService.get("ProfD", ci.nsIFile);
localDir.append("Ryebox");
if (!localDir.exists() || !localDir.isDirectory()) {
localDir.create(ci.nsIFile.DIRECTORY_TYPE, 0774);
}
return localDir;
};
It was suggested to me by Nickolay Ponomarev that using the following can be a good option:
Annotation Service
SQLite DB
Right now I am planning to use database for the usage.