Here's how I'm setting up Flatpickr:
import flatpickr from 'flatpickr';
import { DateTime } from "luxon";
flatpickr(`#${this.el.id}`, {
altInput: true,
altFormat: 'M d Y h:i K',
formatDate: (date, format, locale) => {
// ?
}
});
This sends the datetimes back to my backend as UTC which is fine, but I want to show the datetimes in my users local timezone.
How can I accomplish this with Flatpickr and luxon?
Related
I would like my nextjs13 app to serve content based on the subdomain / domain / slug / get_vars in the request.
I need to have access to the request data from within the new appfolder of nextjs 13, so that I can serve the right data on the server side.
e.g., sub-domain.my-domain.com/my-slug?my_var=1&another_var=2
How can I access the following data:
subdomain
domain
slug (this I can achieve using a folder wrapped in [])
get vars
Many thanks to any responders.
Accessing domain & subdomain using headers function:
import { headers } from 'next/headers'
const Page = () => {
const headersInstance = headers()
const [subdomain, domain] = headersInstance.get('host').split('.')
...
}
export default Page
Accessing slug through params prop:
const Page = ({ params: { slug } }) => {
console.log(slug)
...
}
export default Page
Accessing query parameters through searchParams prop (server-components):
Given sub-domain.my-domain.com/my-slug?my_var=1&another_var=2:
const Page = ({ searchParams }) => {
console.log(searchParams) // Logs { my_var: '1', another_var: '2' }
console.log(searchParams.my_var) // Logs 1
console.log(searchParams.another_var) // Logs 2
...
}
export default Page
NextJS 13 has a new router API for params.
You can check the client component documentation for the following methods as they also give examples on how to use it for server side purposes:
useSearchParams
useSelectedLayoutSegment
useSelectedLayoutSegments
Note that everything should be imported from 'next/navigation' (it was from 'next/router' before NextJS 13).
Regarding the domain and subdomain maybe the 'next/headers' documentation can help you.
I am currently using Calendar API using Python to create a google calendar Event and send invitations to an attendee.
Is there an Event link I can send to him by SMS? so that he could join it using that link also.
The Calendar API gives the Event link in response but If I open it as Attendee. It says Event is not found.
My Code
from __future__ import print_function
import datetime
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google.oauth2 import service_account
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.events',
'https://www.googleapis.com/auth/admin.directory.resource.calendar',
'https://www.googleapis.com/auth/gmail.send']
SERVICE_ACCOUNT_FILE = 'credentials.json'
def main():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
creds =service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = creds.with_subject('username#domain.com')
service = build('calendar', 'v3', credentials=delegated_credentials)
event = {
'summary': 'Driving Lessons 5',
'location': 'Location',
'description': 'Usman is Testing',
'start': {
'dateTime': '2022-08-27T09:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'end': {
'dateTime': '2022-08-27T17:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=1'
],
'attendees': [
{'email': 'attendee1#mail.com'},
{'email': 'attendee2#mail.com'},
],
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60}
],
},
}
event = service.events().insert(calendarId='mycalenderid', body=event,sendUpdates='all').execute()
print ('Event created: %s' % (event.get('htmlLink')))
if __name__ == '__main__':
main()
Event link Generated when I run this code
https://www.google.com/calendar/event?eid=OHY5M3JlcmRzZ2RoM2tvMnZuZHQ0dXB1MDRfMjAyMjA4MjdUMTYwMDAwWiB1c21hbkBkcml2aW9sb2d5LmNvbQ
If I copy and Paste this link in browser as an attendee, it says event not found.
The link you get in the response is the htmlLink which will open successfully only with the account you're creating the event from, this contains specifically the event ID that was created in your calendar.
I did some research and unfortunately it seems there is no option with the Google Calendar API to generate an external event link or share a link by SMS, this feature was removed in 2019. You can always send a notification by email by adding the sendUpdates parameter in your code.
Now, the only workaround I found is sharing the link that you can generate directly from the event in the Google Calendar interface, click the three dots to the right, when clicking an event, and select "Publish event". The format to that link is:
https://calendar.google.com/event?action=TEMPLATE&tmeid=YOUR_EVENTID&tmsrc=add_the_attendee_email_address
However, if the attendee clicks on "Save" when openning the link you share, it will be created as a new event, this link is just like a template which means any changes the attendee makes it won't be reflected in your calendar.
If you have any questions let me know!
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
export default functions.auth.user().onCreate(saveUserToDatabase);
async function saveUserToDatabase(event) {
const Users = admin.database().ref('Users');
const authUser = event.data;
let user = await Users.child(authUser.uid).set({
createdAt: authUser.metadata.createdAt.toString(),
email: authUser.email,
facebookId: authUser.providerData[0].uid.replace('http://facebook.com/', ''),
lastSignedInAt: authUser.metadata.lastSignedInAt.toString(),
name: authUser.displayName,
photoUrl: authUser.photoURL,
});
console.log('saveUserToDatabase()');
console.log(authUser);
}
In the above code I save a user to the firebase database when they register. Now unless I use the toString method on the dates they do not save. I looked into this a little further and found that the dates don't come in as strings and that is causing some issues. (I did this with console.log and checking the firebase dashboard)
{ displayName: 'Test User',
email: 'test#example.com',
metadata:
{ createdAt: 2017-05-02T05:18:45.000Z,
lastSignedInAt: 2017-05-02T05:18:45.000Z }
}
When I use the toString method though it converts the output to:
"Tue May 02 2017 05:24:31 GMT+0000 (UTC)"
Dates are also saved in some instances in this format:
"1492213242000"
Why is there so many timestamp formats?
What is the preferred timestamp format for firebase I should be using?
How do I convert the dates into the preferred timestamp using cloud functions?
The object you're receiving in event.data is an admin.auth.UserRecord. Its interface specifies that the createdAt and lastSignedInAt timestamps should be JavaScript Date objects.
The Date type has enough issues that we try to avoid it in newer interfaces. I suspect you may be hitting some of those pain points in the inconsistent toString() serialization.
I agree with Doug that for storage, milliseconds since the epoch should be the preferred format. You should be able to get that from createdAt.value, for example.
I am using percolate:synced-cron in Meteor 1.2
I need to change the timezone 'Asia/Dubai'.
I have tried
SyncedCron.config({
utc: false, (true/false both)
timezone: 'Asia/Dubai'
});
and also in
SyncedCron.add({
name: ....
timezone: 'Asia/Dubai',
.........
});
But no luck.
Thanks in advance
UPDATE:
I have found another fork package where can I use timezone
saucecode:timezoned-synced-cron
From the code in the package:
Meteor.startup(function() {
var options = SyncedCron.options;
log = createLogger('SyncedCron');
['info', 'warn', 'error', 'debug'].forEach(function(level) {
log[level] = _.partial(log, level);
});
// Don't allow TTL less than 5 minutes so we don't break synchronization
var minTTL = 300;
// Use UTC or localtime for evaluating schedules
if (options.utc)
Later.date.UTC();
else
Later.date.localTime();
// collection holding the job history records
SyncedCron._collection = new Mongo.Collection(options.collectionName);
SyncedCron._collection._ensureIndex({intendedAt: 1, name: 1}, {unique: true});
if (options.collectionTTL) {
if (options.collectionTTL > minTTL)
SyncedCron._collection._ensureIndex({startedAt: 1 },
{ expireAfterSeconds: options.collectionTTL } );
else
log.warn('Not going to use a TTL that is shorter than:' + minTTL);
}
});
You'll notice it either uses utc or defaults to local time. There is no way to specify a specific timezone.
recently I deployed ELK and started forwarding logs from nginx through logstash frowarder.
Problem is, that in elasticsearch (1.4.2) / kibana (4) is "bytes" value of request mapped as string.
I uses standard congfiguration found everywhere.
Into logstash patterns added new pattern for nginx logs:
NGUSERNAME [a-zA-Z\.\#\-\+_%]+
NGUSER %{NGUSERNAME}
NGINXACCESS %{IPORHOST:http_host} %{IPORHOST:clientip} \[%{HTTPDATE:timestamp}\] \"(?:%{WORD:verb} %{NOTSPACE:request}(?: HTTP/%{NUMBER:httpversion})?|%{DATA:rawrequest})\" %{NUMBER:response} (?:%{NUMBER:bytes}|-) %{QS:referrer} %{QS:agent} %{NUMBER:request_time:float} %{NUMBER:upstream_time:float}
NGINXACCESS %{IPORHOST:http_host} %{IPORHOST:clientip} \[%{HTTPDATE:timestamp}\] \"(?:%{WORD:verb} %{NOTSPACE:request}(?: HTTP/%{NUMBER:httpversion})?|%{DATA:rawrequest})\" %{NUMBER:response} (?:%{NUMBER:bytes}|-) %{QS:referrer} %{QS:agent} %{NUMBER:request_time:float}
Added these configs for logstash
input {
lumberjack {
port => 5000
type => "logs"
ssl_certificate => "/etc/logstash/tls/certs/logstash-forwarder.crt"
ssl_key => "/etc/logstash/tls/private/logstash-forwarder.key"
}
}
filter {
if [type] == "syslog" {
grok {
match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" }
add_field => [ "received_at", "%{#timestamp}" ]
add_field => [ "received_from", "%{host}" ]
}
syslog_pri { }
date {
match => [ "syslog_timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss" ]
}
} else if [type] == "nginx" {
grok {
match => { "message" => "%{NGINXACCESS}" }
}
date {
match => [ "timestamp" , "dd/MMM/YYYY:HH:mm:ss Z" ]
}
geoip {
source => "clientip"
}
}
}
output {
elasticsearch_http {
host => localhost
}
}
But in elsticsearch I see that as string even if I define "bytes" as long
(?:%{NUMBER:bytes:long}|-)
Does anybody know how to store "bytes" as number type?
Thanks
You're on the right track with (?:%{NUMBER:bytes:long}|-), but "long" isn't a valid data type. Quoting the grok documentation (emphasis mine):
Optionally you can add a data type conversion to your grok pattern. By default all semantics are saved as strings. If you wish to convert a semantic’s data type, for example change a string to an integer then suffix it with the target data type. For example %{NUMBER:num:int} which converts the num semantic from a string to an integer. Currently the only supported conversions are int and float.
Note that this doesn't control the data type that's actually used in the indexing on the Elasticsearch side, only the data type of the JSON document that's sent to Elasticsearch (which may or may not affect which mapping ES uses). In the JSON context there's no difference between ints and longs; scalar values are either numbers, bools, or strings.