In my code I use promises to control the asynchrony, in the next request I send the nextPageToken, but then send the request with empty videos
--- CODE -
search_this_q="cats";
function load(){
search(search_this_q)
.then(function(data){
console.log(data)
return next_Page_Search(data.nextPageToken,search_this_q);
})
.then(function(data){
console.log(data)
return next_Page_Search(data.nextPageToken,search_this_q);
})
.then(function(data){
console.log(data)
return next_Page_Search(data.nextPageToken,search_this_q);
})
.then(function(data){
console.log(data)
return next_Page_Search(data.nextPageToken,search_this_q);
})
.then(function(data){
console.log(data)
return next_Page_Search(data.nextPageToken,search_this_q);
})
.then(function(data){
console.log(data)
return next_Page_Search(data.nextPageToken,search_this_q);
})
.then(function(data){
console.log(data)
return next_Page_Search(data.nextPageToken,search_this_q);
})
.then(function(data){
console.log(data)
return next_Page_Search(data.nextPageToken,search_this_q);
})
.then(function (result) {
console.log(".theen finish load")
console.log(result);
console.log(".theen finish load")
});
}
function next_Page_Search (token_Page,search_this) {
return new Promise((resolve, reject) => {
var data={
part: 'id', //'id,snippet',
maxResults: 50,
pageToken:token_Page,
q:search_this,
type:'video',
// videoEmbeddable:true,
key:"mykey"
};
// GET
$.get("https://www.googleapis.com/youtube/v3/search",
data,function (data,status){
resolve(data);
}
);
// end GET
});
}
--- CODE -
The answer after the 9th time is an empty arrangement (items)
I have similar situation with Youtube search method and I can recommend to use publishedAfter and publishedBefore parameters to reduce timeframe for your search. Looks like Youtube trying to optimize cpu server time for every search request with estimates. So, you need to be more specific with your search query or you need to reduce timeframe for your search. For example I've experimented with very specific video with unique number in description. I can find it on Youtube website easily but I can't with search method without adding publishedBefore and publishedAfter about 1 hour of published time. So, try it!
Related
While I run test I get this error..
I am trying to make my own cryptocurrency using the DAPPuniversity tutorial, however, my code keeps throwing an exception.
Contract: ValleyToken
√ initialize the contract with correct values (363ms)
√ sets the initial supply upon deployment (363ms)
1) transfers token ownership
> No events were emitted
2 passing (869ms)
1 failing
1) Contract: ValleyToken
transfers token ownership:
ReferenceError: Faicoin is not defined
at Context.<anonymous> (test\ValleyToken.js:47:5)
at process._tickCallback (internal/process/next_tick.js:68:7)
Replace this code with your test : )
it("transfers token ownership", function () {
return ValleyToken.deployed()
.then(function (instance) {
tokenInstance = instance;
return tokenInstance.transfer.call(accounts[1], 9999999999999999);
})
.then(assert.fail)
.catch(function (error) {
assert(error.message, "error message must contain revert");
return tokenInstance.transfer.call(accounts[1], 250000, {
from: accounts[0],
});
})
.then(function (success) {
assert(success, true, "it returns true");
return tokenInstance.transfer(accounts[1], 250000, {
from: accounts[0],
});
})
.then(function (receipt) {
assert.equal(receipt.logs.length, 1, "triggers one event");
assert.equal(
receipt.logs[0].event,
"Transfer",
'should be the "Transfer" event'
);
assert.equal(
receipt.logs[0].args._from,
accounts[0],
"logs the account the tokens are transferred from"
);
assert.equal(
receipt.logs[0].args._to,
accounts[1],
"logs the account the tokens are transferred to"
);
assert.equal(
receipt.logs[0].args._value,
250000,
"logs the transfer amount"
);
return tokenInstance.balanceOf(accounts[1]);
})
.then(function (reciept) {
return tokenInstance.balanceOf(accounts[1]);
})
.then(function (balance) {
assert.equal(
balance.toNumber(),
250000,
"adds the amount to the recieving amount"
);
return tokenInstance.balanceOf(accounts[0]);
})
.then(function (balance) {
assert.equal(
balance.toNumber(),
750000,
"deducts the amount from the sending account"
);
});
});
Completing my transfer function solved this issue for me.
it("transfers tokens ownership", function() {
return HanuToken.deployed().then(function(tok) {
var token = tok;
return token.transfer.call(accounts[1], 99999999999999);
}).then(assert.fail).catch(function(error) {
assert(error.message.toString().indexOf('revert') >=0, 'error msg must contains revert');
});
});
See below implementation.
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
return true;
}
when i create Pagination this label and i want to control it when i send ajax and then success callback function and then change index
i tried use onchange function and then change current the num but still stay current page not use
Table label have pagination
--like so
pagination={{
total: total,
pageSize: limit,
/* onChange(current) {
dispatch({
type: '#LotteryBetRecord/turning',
payload: {
post: that.getSearchParames(),
pageSize: limit,
current: current - 1
}
})
},*/
onChange:(current,limit)=>{
that.onChange.bind(this,current,limit)
},
showTotal: function () {
return `共${total}条记录`
}
}}
/>
onConfirm={() => {
dispatch({
type: 'operational/betting',
payload: {
blist: JSON.stringify(betListValue),
callback: (res) => {
if (res.error === 0) {
message.success('success')
that.search()
that.onChange(2,10)
}
}
}
})
}}
onChange(current,limit){
const {dispatch} = this.props;
dispatch({
type: '#LotteryBetRecord/turning',
payload: {
post: this.getSearchParames(),
pageSize: limit,
current: current - 1
}
})
}
There was a bug in this component in version 3.13.2. The related issue is here; https://github.com/ant-design/ant-design/issues/14875. When you pass second page, your fill your datasource but your second page seems empty, and there is still only one page. Check newer version or you can use below workaround;
dataSource={[...Array.from({length: (current - 1) * pageSize}), ...dataSource]}
I'm integrating PayPal checkout with an e-com solution, where upon PayPal successfully creating PayPal order/payment, I carry out some server side processing which eventually returns a RedirectResult (with a URL for payment failed or success accordingly) from my controller, back to the client/frontend.
I have the following code below, and was expecting it to redirect automatically, but no redirect occurrs.
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [{
amount: {
value: '5.20',
}
}]
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
});
}).catch(error=>console.log("Error capturing order!", error));
}
}).render('#paypal-button-container');
If I explicitly redirect with the code below, then the action carries out.
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
}).then(function () { window.location.replace('https://www.google.co.uk') });
}).catch(function (error) {
console.log("Error capturing order!", error);
window.location.replace('https://www.bbc.co.uk');
});
}
Basically, I'm wondering why fetch redirect does not follow the Redirect that is returned form my controller. Controller redirect for full completeness:
return new RedirectResult("/checkout/thank-you") ;
Let me try to rephrase your question
You want to know why the browser did not redirect after you made a fetch - even though fetch api response
was a RedirectResult
The reason is simple, you made a request in fetch, which means you are making ajax request (hence browser will not change)
you set the redirect to follow, which means after the first request (i.e after get response from
/umbraco/surface/PayPalPayment/process), it will follow to the url /checkout/thank-you
so, what you get in the then() will be the response of /checkout/thank-you
so overall, it did follow the response but maybe not the way you expected (follow within the ajax request, not browser changing the page)
If what you want is a redirect to specific page, after the success call to /umbraco/surface/PayPalPayment/process
Then do:
Modify your backend to return JsonResult of the url instead of RedirectResult
return Json(new {redirectUrl = "/checkout/thank-you"});
use then to redirect
// other code omitted
.then(function (response) { return response.json(); })
.then(function (data) {window.location.replace(data.redirectUrl)});
ember-data 1.0, ember 1.5.1, rails 3.2
How to handle redirect response from server? In ember-data 0.13 I do:
Staas.Adapter = DS.RESTAdapter.extend
didCreateRecord: (store, type, record, payload) ->
if payload.redirect
window.location.replace payload.redirect
return
#_super(store, type, record, payload)
But now there are no didCreateRecord method in Adapter. I want to implement universal solution, not in each save promises.
Thank you.
You can reopen the RESTAdapter and modify the ajax method method for all instances.
DS.RESTAdapter.reopen({
ajax: function(url, type, hash) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
hash = adapter.ajaxOptions(url, type, hash);
hash.success = function( json ) {
Ember.run(null, resolve, json);
};
hash.error = function(jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, adapter.ajaxError(jqXHR));
};
Ember.$.ajax(hash);
}, "DS: RestAdapter#ajax " + type + " to " + url).then(function(json){
if(json && json.redirect){
//redirect here
alert('redirect');
}
return json;
}, function(jqXHR){
if(jqXHR.status == 302){
//redirect here
alert('redirect');
}
return jqXHR;
});
},
});
Example 302 status: http://emberjs.jsbin.com/OxIDiVU/796/edit
Example payload: http://emberjs.jsbin.com/OxIDiVU/798/edit
I want to have a dropdown with a set of values but also allow the user to "select" a new value not listed there.
I see that select2 supports this if you are using it in tags mode, but is there a way to do it without using tags?
The excellent answer provided by #fmpwizard works for Select2 3.5.2 and below, but it will not work in 4.0.0.
Since very early on (but perhaps not as early as this question), Select2 has supported "tagging": where users can add in their own value if you allow them to. This can be enabled through the tags option, and you can play around with an example in the documentation.
$("select").select2({
tags: true
});
By default, this will create an option that has the same text as the search term that they have entered. You can modify the object that is used if you are looking to mark it in a special way, or create the object remotely once it is selected.
$("select").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
}
});
In addition to serving as an easy to spot flag on the object passed in through the select2:select event, the extra property also allows you to render the option slightly differently in the result. So if you wanted to visually signal the fact that it is a new option by putting "(new)" next to it, you could do something like this.
$("select").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(" <em>(new)</em>");
}
return $result;
}
});
For version 4+ check this answer below by Kevin Brown
In Select2 3.5.2 and below, you can use something like:
$(selector).select2({
minimumInputLength:1,
"ajax": {
data:function (term, page) {
return { term:term, page:page };
},
dataType:"json",
quietMillis:100,
results: function (data, page) {
return {results: data.results};
},
"url": url
},
id: function(object) {
return object.text;
},
//Allow manually entered text in drop down.
createSearchChoice:function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
});
(taken from an answer on the select2 mailing list, but cannot find the link now)
Just for the sake of keep the code alive, I'm posting #rrauenza Fiddle's code from his comment.
HTML
<input type='hidden' id='tags' style='width:300px'/>
jQuery
$("#tags").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0;
}).length===0)
{return {id:term, text:term};}
},
multiple: false,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
Since many of these answers don't work in 4.0+, if you are using ajax, you could have the server add the new value as an option. So it would work like this:
User searches for value (which makes ajax request to server)
If value found great, return the option. If not just have the server append that option like this: [{"text":" my NEW option)","id":"0"}]
When the form is submitted just check to see if that option is in the db and if not create it before saving.
There is a better solution I think now
simply set tagging to true on the select options ?
tags: true
from https://select2.org/tagging
Improvent on #fmpwizard answer:
//Allow manually entered text in drop down.
createSearchChoice:function(term, data) {
if ( $(data).filter( function() {
return term.localeCompare(this.text)===0; //even if the this.text is undefined it works
}).length===0) {
return {id:term, text:term};
}
},
//solution to this error: Uncaught TypeError: Cannot read property 'localeCompare' of undefined
Thanks for the help guys, I used the code below within Codeigniter I I am using version: 3.5.2 of select2.
var results = [];
var location_url = <?php echo json_encode(site_url('job/location')); ?>;
$('.location_select').select2({
ajax: {
url: location_url,
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
results = [];
$.each(data, function(index, item){
results.push({
id: item.location_id,
text: item.location_name
});
});
return {
results: results
};
}
},
//Allow manually entered text in drop down.
createSearchChoice:function(term, results) {
if ($(results).filter( function() {
return term.localeCompare(this.text)===0;
}).length===0) {
return {id:term, text:term + ' [New]'};
}
},
});
I just stumbled upon this from Kevin Brown.
https://stackoverflow.com/a/30019966/112680
All you have to do for v4.0.6 is use tags: true parameter.
var text = 'New York Mills';
var term = 'new york mills';
return text.localeCompare(term)===0;
In most cases we need to compare values with insensitive register. And this code will return false, which will lead to the creation of duplicate records in the database. Moreover String.prototype.localeCompare () is not supported by browser Safary and this code will not work in this browser;
return this.text.localeCompare(term)===0;
will better replace to
return this.text.toLowerCase() === term.toLowerCase();