I have 2 actions which are :
This is first
I insert person here :
export const InsertOrUpdate = (person) => {
return (dispatch) => {
var instance = Axios.create({
baseURL: 'url',
// timeout: 1000,
headers: {
"Content-Type": "application/json"
}
});
instance.get("/InsertWorker", {
params: {
Name: person.Name,
Surname: person.Surname,
Duty: person.Duty,
DateOfDay: person.Date.substring(0, person.Date.length - 9),
Shift: person.Shift,
WorkDayCount: person.WorkDayCount,
Equipment: person.Equipment,
Sicil: person.Sicil,
Ship: person.Ship
}
});
}
}
This is second
I call workers here :
export const getSignedWorkers = (collection) => {
return (dispatch) => {
var instance = Axios.create({
baseURL: 'url',
// timeout: 1000,
headers: {
"Content-Type": "application/json"
}
});
instance.get('/GetWorkers', {
params: {
DateOfDay: collection.Tarih,
Shift: collection.Vardiya
}
})
.then((response) => response.data)
.then(x => {
const Signed = str3.filter(x => x.Ship != "" && x.Shift != "H");
console.warn('signed', Signed);
const UnSigned = str3.filter(x => x.Ship == "" || null);
const RemoveOnHolidays = UnSigned.filter(x => x.Shift != "H");
const OnHoliday = str3.filter(x => x.Shift == "H");
const AllWorkers = {};
AllWorkers.signed = Signed;
AllWorkers.Unsigned = RemoveOnHolidays;
AllWorkers.OnHoliday = OnHoliday;
dispatch({ type: FETCH_SIGNED_WORKERS_SIGNED, payload: AllWorkers });
})
.catch((error) => {
console.warn('error', error);
})
}
}
I call this actions here :
_Insert = (person) => {
person.Ship = this.props.gemi_Sefer_No;
this.props.InsertOrUpdate(item); <------- Here I call first action
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var tarih = year + "/" + month + "/" + date;
let collection = {};
collection.Tarih = tarih;
collection.Vardiya = this.props.vardiya == 0 ? "S" : this.props.vardiya == 1 ? "A" : this.props.vardiya == 2 ? "G" : null
this.props.getSignedWorkers(collection); <--- Here I call second action
}
I try to insert workers to database then call all workers from database and use another component with redux. However, sometimes it works correctly sometimes not.
I mean , when I insert to database and call back again, insert worker works right however calling all workers come without worker which I insert last one. As I said, it works sometimes right. What should I do ?. Is that wrong to call two actions in same method ? if it is, what should I do ?
Related
I'm facing a strange behavior in Ag-grid (Angular). When I use the serverSide option and when there is no data returned from the server, the grid is showing the loading icon for all the rows mentioned in the cacheBlockSize. I've tried as many options I could to hide these empty loading rows, but nothing has worked out.
I've tried to replicate the same in the official example page. Luckily I could replicate the similar behavior. Refer to this edited version of an official example page, where I'm passing an empty array from the fake server call:
https://plnkr.co/edit/Egw9ToJmNE7Hl6Z6
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.http
.get('https://www.ag-grid.com/example-assets/olympic-winners.json')
.subscribe((data) => {
let idSequence = 0;
data.forEach((item) => {
item.id = idSequence++;
});
const server = new FakeServer(data);
const datasource = new ServerSideDatasource(server);
params.api.setServerSideDatasource(datasource);
});
}
}
function ServerSideDatasource(server) {
return {
getRows: (params) => {
setTimeout(() => {
const response = server.getResponse(params.request);
if (response.success) {
params.successCallback(response.rows, response.lastRow);
} else {
params.failCallback();
}
}, 2000);
},
};
}
function FakeServer(allData) {
return {
getResponse: (request) => {
console.log(
'asking for rows: ' + request.startRow + ' to ' + request.endRow
);
const rowsThisPage = allData.slice(request.startRow, request.endRow);
const lastRow = allData.length <= request.endRow ? data.length : -1;
return {
success: true,
rows: [],
lastRow: lastRow,
};
},
};
}
The screenshot of the plunker output is given below.
Just figured out that its a problem with lastRow value. If the rows are empty but lastRow is not -1, then its trying to load the data and showing the loading icon for all the rows as per the cacheBlockSize.
Fixed code below:
function FakeServer(allData) {
return {
getResponse: (request) => {
console.log(
'asking for rows: ' + request.startRow + ' to ' + request.endRow
);
let data = []; //allData;
const rowsThisPage = data.slice(request.startRow, request.endRow);
const lastRow = data.length <= request.endRow ? data.length : -1;
return {
success: true,
rows: rowsThisPage,
lastRow: lastRow,
};
},
};
}
Update for AG Grid 28:
function FakeServer(allData) {
return {
getResponse: (params) => {
const request = params.request;
console.log(
'asking for rows: ' + request.startRow + ' to ' + request.endRow
);
let data = []; //allData;
const rowsThisPage = data.slice(request.startRow, request.endRow);
const lastRow = data.length <= request.endRow ? data.length : -1;
params.success({ rowData: rowsThisPage, rowCount: lastRow });
},
};
}
does anyone have some bad experience with saving float via executeRaw batch operation? Or at least an idea of how to solve my problem: ExecuteRaw is saving numbers like 7.76e-322. Input is 157 and saved value is 7.76e-322.
const items = [{uniqueId: 1, price: 100},{uniqueId: 2, price: 200}];
const completeKeys: string[] = Object.keys(items[0]);
const updateFieldsMapper = (item: any) => {
return Prisma.sql`(${Prisma.join(
completeKeys.map((key: string) => item[key])
)})`;
};
const insertKeys = completeKeys.map((key) =>
key.toLocaleLowerCase() !== key ? `"${key}"` : `${key}`
);
let insertValues = completeKeys.map((item) => updateFieldsMapper(item));
const updateSet = completeKeys.reduce((updateSet: string[], key: string) => {
if (!ingnoredKeys.includes(key)) {
updateSet.push(`"${key}" = EXCLUDED."${key}"`);
}
return updateSet;
}, []);
try {
await prisma.$executeRaw`
INSERT INTO "Product" (${Prisma.raw(insertKeys.join(","))})
VALUES ${Prisma.join(insertValues)}
ON CONFLICT (uniqueId)
DO UPDATE SET ${Prisma.raw(updateSet.join(","))};`;
} catch (error) {
console.error(util.inspect(error, false, null, true));
Sentry.captureException(error);
}
Thank you very much
I am trying to deploy a scheduled cloud function to Google Firebase, such as this
https://firebase.google.com/docs/functions/schedule-functions
Anytime I deploy the schedule as "every 1 minutes" it gets deployed fine. However, if I try to do anything else, like "every 60 minutes", "every 8 hours", I get the following error.
I am not even getting information about the error so it is hard to debug.
exports.bookingReminder = functions.pubsub.schedule('every 1 minutes').onRun((context) => {
let today = new Date()
var dateArray = []
let year = (today.getYear() - 100) + 2000
dateArray.push(year.toString())
var month = today.getMonth() + 1
if (month < 10) {
month = "0" + month.toString()
}
dateArray.push(month.toString())
var day = today.getDate()
if (day < 9) {
day = "0" + day.toString()
}
dateArray.push(day.toString())
let fullDate = dateArray.join("-")
console.log(fullDate)
const bookingsRef = admin.firestore().collection("bookings").where("date", "==", fullDate).get().then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
return null;
}
var emails = []
snapshot.forEach(doc => {
console.log("yes found them on this date: " + fullDate)
var booking = doc.data()
var clients = booking.clients
clients.forEach(client => {
emails.push(client.email)
})
console.log(emails);
const serviceRef = admin.firestore().collection("services").doc(booking.serviceId)
let servie = {}
const serviceSnap = serviceRef.get().then(doc2 => {
service = doc2.data()
}).then(() => {
const msg = {
//need client email
to: emails, // Change to your recipient
from: '', // Change to your verified sender
//Booking Reminder
};
console.log("running email send")
sgMail.send(msg);
})
})
return emails;
})
});
I want to get the last users exe. last 100 users that committed on github regardless of repo. I've looked around the github api but can't find the specific api call.
You can use Github Events API and filter PushEvent :
https://api.github.com/events?per_page=100
User(s) who have made the last 100 commits on Github
As a PushEvent may have multiple commits, you will have to sum the size for each PushEvent until you reach 100. Note that you also need to exclude PushEvent with 0 commit. You will also have to manage pagination as you can request 100 events max at once (if one request is not enough to get 100 commits).
An example using nodeJS :
var request = require("request");
const maxCommit = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var commitCount = 0;
var page = 1;
var users = [];
while (commitCount < maxCommit) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
commitCount += pushEvents.reduce((it1, it2) => it1 + it2.payload.size, 0);
users = users.concat(pushEvents.map(event => ({
login: event.actor.login,
commitCount: event.payload.size
})));
page++;
}
var count = 0;
for (var i = 0; i < users.length; i++) {
count += users[i].commitCount;
if (count >= maxCommit){
users = users.slice(0, i + 1);
break;
}
}
console.log(users);
}
getEvents();
Last 100 Users who have pushed commits on Github
The only things that changes is that we only check that size field is > 0 and build a map for distinct user.
An example using nodeJS :
var request = require("request");
const maxUser = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var page = 1;
var users = {};
while (Object.keys(users).length < maxUser) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
for (var i = 0; i < pushEvents.length; i++) {
users[pushEvents[i].actor.login] = pushEvents[i].payload.size;
if (Object.keys(users).length == maxUser) {
break;
}
}
page++;
}
console.log(users);
}
getEvents();
I have a couple of forms on a site I'm working on and the script that controls them doesn't include a success message, so when they're submitted the input data just disappears and the user doesn't know if it's been actually sent or not. I've looked around a bit for answers, but because this file controls an email submission form, a contact form, and a twitter feed, it's a bit much for me to see what's what.
Here's the code, I'd just like to let users know that their message has been sent for both the email input form and the contact form. I appreciate any help that's out there!
$(document).ready(function() {
//Set default hint if nothing is entered
setHints();
//Bind JavaScript event on SignUp Button
$('#signUp').click(function(){
signUp($('#subscribe').val());
});
//Bind JavaScript event on Send Message Button
$('#sendMessage').click(function(){
if(validateInput()){
sendMail();
}else
{
alert('Please fill all fields to send us message.');
}
});
//Load initial site state (countdown, twitts)
initialize();
});
var setHints = function()
{
$('#subscribe').attachHint('Enter your email to be notified when more info is available');
$('[name=contact_name]').attachHint('Name');
$('[name=contact_email]').attachHint('Email');
$('[name=contact_subject]').attachHint('Subject');
$('[name=contact_message]').attachHint('Message');
};
var signUp = function(inputEmail)
{
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputEmail)){
isValid = false;
alert('Your email is not in valid format');
}
if(isValid){
var params = {
'action' : 'SingUp',
'email' : inputEmail
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
}
}
}
});
}
};
var initialize = function()
{
var params = {
'action' : 'Initialize'
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('ul.twitts').empty();
if(responseObj.ResponseData.Twitts){
$('a.followUsURL').attr('href','http://twitter.com/#!/'+responseObj.ResponseData.Twitts[0].Name);
$.each(responseObj.ResponseData.Twitts, function(index, twitt){
var twitterTemplate = '<li>'
+ '#{0}'
+ '{2}'
+ '<span class="time">{3}</span>'
+ '</li>';
$('ul.twitts').append(StringFormat(twitterTemplate, twitt.Name, twitt.StatusID, twitt.Text, twitt.Date));
});
}
if(responseObj.ResponseData.Start_Date)
{
setInterval(function(){
var countDownObj = calculateTimeDifference(responseObj.ResponseData.Start_Date);
if(countDownObj){
$('#days').text(countDownObj.Days);
$('#hours').text(countDownObj.Hours);
$('#minutes').text(countDownObj.Minutes);
$('#seconds').text(countDownObj.Seconds);
}
}, 1000);
}
}
}
}
});
};
var validateInput = function(){
var isValid = true;
$('input, textarea').each(function(){
if($(this).hasClass('required'))
{
if($(this).val()!=''){
if($(this).hasClass('email'))
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($(this).val())){
isValid = false;
alert('Your email is not in valid format');
}
}
}else
{
isValid = false;
}
}
});
return isValid;
};
var resetInput = function(){
$('input, textarea').each(function() {
$(this).val('').text('');
});
};
var sendMail = function(){
var params = {
'action' : 'SendMessage',
'name' : $('[name=contact_name]').val(),
'email' : $('[name=contact_email]').val(),
'subject' : $('[name=contact_subject]').val(),
'message' : $('[name=contact_message]').val()
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
$('label.sendingStatus').text(responseObj.ResponseData);
}
resetInput();
$('#sendMail').removeAttr('disabled');
},
error: function (xhr, ajaxOptions, thrownError){
//xhr.status : 404, 303, 501...
var error = null;
switch(xhr.status)
{
case "301":
error = "Redirection Error!";
break;
case "307":
error = "Error, temporary server redirection!";
break;
case "400":
error = "Bad request!";
break;
case "404":
error = "Page not found!";
break;
case "500":
error = "Server is currently unavailable!";
break;
default:
error ="Unespected error, please try again later.";
}
if(error){
$('label.sendingStatus').text(error);
}
}
});
};
var calculateTimeDifference = function(startDate) {
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
var currentDate = new Date();
startDate = new Date(startDate);
var timeCounter = startDate - currentDate;
if (isNaN(timeCounter))
{
return NaN;
}
else
{
days = Math.floor(timeCounter / day);
timeCounter = timeCounter % day;
hours = Math.floor(timeCounter / hour);
timeCounter = timeCounter % hour;
minutes = Math.floor(timeCounter / minute);
timeCounter = timeCounter % minute;
seconds = Math.floor(timeCounter / second);
}
var tDiffObj = {
"Days" : days,
"Hours" : hours,
"Minutes" : minutes,
"Seconds" : seconds
};
return tDiffObj;
};
var StringFormat = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var regExpression = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(regExpression, arguments[i + 1]);
}
return s;
}
You need to hook into the success callbacks of each of the $.ajax calls. You can create a method that will show a message for those:
For example, your signUp function's success callback could look like:
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
showMessage('Your subscription was received. Thank you!');
}
}
}
And you just create a method that will show the message to the user
var showMessage = function (msg) {
// of course, you wouldn't use alert,
// but would inject the message into the dom somewhere
alert(msg);
}
You would call showMessage anywhere the success callback was fired.
You can add your success notifing code in each of the $.ajax success handlers.