投稿時間:2022-04-14 02:44:56 RSSフィード2022-04-14 02:00 分まとめ(51件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
AWS AWS Open Source Blog Scheduling Jupyter Notebooks with AWS Orbit Workbench https://aws.amazon.com/blogs/opensource/scheduling-jupyter-notebooks-with-aws-orbit-workbench/ Scheduling Jupyter Notebooks with AWS Orbit WorkbenchThis post was contributed by Olalekan Elesin Head of Data Platform amp Data Architect at HRS Group and AWS Machine Learning Hero The HRS Group a market leader in the global business travel market is scheduling Jupyter Notebooks with the open source solution AWS Orbit Workbench HRS provides brokerage of hotel rooms for private and … 2022-04-13 16:56:36
AWS AWS Get started with AWS IoT Core for LoRaWAN FUOTA | Amazon Web Services https://www.youtube.com/watch?v=0Yd6PFwL-IM Get started with AWS IoT Core for LoRaWAN FUOTA Amazon Web ServicesWe begin by creating a new wireless device because it s not possible at this time to add FUOTA to an existing device Configure the EUIs and keys in the normal way We then enable FUOTA For LoRaWAN x devices we need to supply the GenAppKey This is the root key for deriving multicast session keys Please check your device documentation For this ST Nucleo device it s just the AppKey again We then need to assign the FPorts for the multicast FUOTA and clock sync packages The default values are usually correct as they are for this ST Nucleo device but please consult your device documentation Select your profiles and destination as you normally would and create the device Now we create a multicast group that FUOTA will target We select the RF region the device is in and select Class C as the type of multicast Normally a multicast group would include multiple devices For this demonstration however just a single device is in the group If you have a heterogenous fleet care should be taken to only add devices that are compatible with the firmware binary image you will send using FUOTA We now introduce the ST Nucleo device s serial terminal Here we can see that the running firmware app version is The device has joined the network and is sending uplinks once per minute We create the multicast group and drill into the group s details The Group status is Pending because no session start time has yet been scheduled The individual device status is Package Attempting because the multicast group has not been initialized on the device Upon the next uplink AWS IoT Core for LoRaWAN issues commands from the Application Clock Layer Synchronization specification to synchronize the time and commands from the Remote Multicast Setup secification to create the multicast group With the multicast group created on the device we can observe that the status of that individual device has changed to Multicast setup ready Note that the multicast group session is not yet scheduled and therefore no start time session duration RX frequency nor RX datarate has yet been assigned We can now proceed to creating a FUOTA task We name the task and select the RF region The FUOTA task can then be configured We select the firmware binary file to upload Recall that the running firmware app version was and this new version is The binary can be uploaded to an existing S bucket or to a new bucket The FUOTA task requires a role granting it permission to get the firmware binary from the S bucket The task can now be created Drilling in to the task details we can see that the status is Pending and the task still lacks target devices and a session start time We add then devices by selecting the multicast group that we created earlier We can now schedule the FUOTA task The session start time has to be at least minutes into the future because AWS IoT Core for LoRaWAN needs to send setup messages to every device in the task The task now has a session start time and the state has changed from Pending to Session Waiting Upon the next uplink AWS IoT Core for LoRaWAN issues a command from the Remote Multicast Setup specification to schedule the multicast class C session The device is now furnished with the session start time session duration RX frequency and RX data rate At some point before the start of the session AWS IoT Core for LoRaWAN issues commands from the Fragmented Data Block Transportation specification to setup the fragmentation session All is now in readiness At the scheduled time the device switches to class C in preparation for receiving firmware binary file fragments A short time later fragment transmission begins on the scheduled frequency and data rate Just under an hour later the fragmentation reaches its conclusion In this case two fragments were lost The device has to continue past fragments to recover those Once done the device reboots authenticates the new firmware and starts it if authentication succeeds As we can see the new firmware version is successfully started and the device rejoins the network Returning to the FUOTA task the device status is now Successful and the task status is now Done Learn more at Subscribe More AWS videos More AWS events videos ABOUT AWSAmazon Web Services AWS is the world s most comprehensive and broadly adopted cloud platform offering over fully featured services from data centers globally Millions of customers ーincluding the fastest growing startups largest enterprises and leading government agencies ーare using AWS to lower costs become more agile and innovate faster AWSIoT AWS AmazonWebServices CloudComputing LoRaWAN FUOTA AWS AmazonWebServices CloudComputing 2022-04-13 16:27:47
AWS AWS Get started with AWS IoT Core for LoRaWAN Multicast Downlink | Amazon Web Services https://www.youtube.com/watch?v=LcCR-1eKX1w Get started with AWS IoT Core for LoRaWAN Multicast Downlink Amazon Web ServicesWe begin by creating a new wireless device We configure the wireless device specification the EUIs and keys and the device name in the normal way We then enable FUOTA because it s currently the only way to assign the ClockSync and Multicast FPorts in the console For LoRaWAN x devices we need to supply the GenAppKey This is the root key for deriving multicast session keys Please check your device documentation For this ST Nucleo device it s just the AppKey again We then need to assign the FPorts for the multicast FUOTA and clock sync packages The default values are usually correct as they are for this ST Nucleo device but please consult your device documentation Select your profiles and destination as you normally would and create the device Now we create a multicast group that the downlink message will target We select the RF region the device is in and select Class C as the type of multicast Normally a multicast group would include multiple devices For this demonstration however just a single device is in the group At this point we introduce the ST Nucleo device s serial terminal Here we can see that the device has joined the network and is sending uplinks once per minute We create the multicast group and drill into the group s details The Group status is Pending because no session start time has yet been scheduled The individual device status is Package Attempting because the multicast group has not been initialized on the device Upon the next uplink AWS IoT Core for LoRaWAN issues commands from the Application Clock Layer Synchronization specification to synchronize the time and commands from the Remote Multicast Setup specification to create the multicast group With the multicast group created on the device we can observe that the status of that individual device has changed to Multicast setup ready Note that the multicast group session is not yet scheduled and therefore no start time session duration RX frequency nor RX datarate has yet been assigned We can now schedule a downlink message The session start time has to be at least minutes into the future because AWS IoT Core for LoRaWAN needs to send setup messages to every device in the multicast group We can select any preferred frequency and data rate The ST Nucleo devices accepts LED on off commands on FPort here we schedule a base encoded command that will turn the LED on The group now has a session start time it s state has changed to Session Waiting and the device state has changed to Session Attempting Upon the next uplink AWS IoT Core for LoRaWAN issues a command from the Remote Multicast Setup specification to schedule the multicast class C session The device is now furnished with the session start time session duration RX frequency and RX data rate Accordingly the individual device state has changed to Foobar At the scheduled time the device switches to class C the downlink message is received and the LED turns on At the expiry of the session timeout the multicast session concludes with the device switching back to Class A With the session finished we can refresh the console and see that the group status has returned to Pending Learn more at Subscribe More AWS videos More AWS events videos ABOUT AWSAmazon Web Services AWS is the world s most comprehensive and broadly adopted cloud platform offering over fully featured services from data centers globally Millions of customers ーincluding the fastest growing startups largest enterprises and leading government agencies ーare using AWS to lower costs become more agile and innovate faster AWSIoT AWS AmazonWebServices CloudComputing LoRaWAN AWS AmazonWebServices CloudComputing 2022-04-13 16:27:42
AWS AWS Get Started with AWS IoT Core for LoRaWAN Network Analyzer | Amazon Web Services https://www.youtube.com/watch?v=Qk9pkhL8xjc Get Started with AWS IoT Core for LoRaWAN Network Analyzer Amazon Web ServicesLearn how to get started with AWS IoT Core for LoRaWAN Network Analyzer Introduction and background Network Analyzer demonstration Add resources Trace a join Trace an uplink Modify the trace configuration Trace a downlink Trace a gateway connectionDeveloper Guide Subscribe More AWS videos More AWS events videos ABOUT AWSAmazon Web Services AWS is the world s most comprehensive and broadly adopted cloud platform offering over fully featured services from data centers globally Millions of customers ーincluding the fastest growing startups largest enterprises and leading government agencies ーare using AWS to lower costs become more agile and innovate faster AWSIoT AWS AmazonWebServices CloudComputing LoRaWAN AWS AmazonWebServices CloudComputing 2022-04-13 16:27:38
python Pythonタグが付けられた新着投稿 - Qiita AutoTrainで文章要約 https://qiita.com/relu/items/129de82967d99ee4c398 autonlp 2022-04-14 01:45:18
python Pythonタグが付けられた新着投稿 - Qiita pythonで複数のPDFファイルを一括で保護解除 https://qiita.com/t-kawashita/items/bec9dfff34080c80099d 解除 2022-04-14 01:31:35
python Pythonタグが付けられた新着投稿 - Qiita python3 -m http.serverをCORSにする【Access-Control-Allow-Origin】 https://qiita.com/relu/items/3461753e3886072349c7 corsreque 2022-04-14 01:04:15
js JavaScriptタグが付けられた新着投稿 - Qiita FirebaseをJavaScriptで使ってみる https://qiita.com/JunichiHashimoto/items/842f2cb612cae44764b0 indexjsindexjsjavascri 2022-04-14 01:01:07
AWS AWSタグが付けられた新着投稿 - Qiita AWS認定クラウドプラクティショナーの勉強方法【AWS初心者】 https://qiita.com/zanigani/items/95eb96230b2eb537392c 資格 2022-04-14 01:53:10
AWS AWSタグが付けられた新着投稿 - Qiita 【AWS】AmazonConnectの電話番号を取得する(2022/4/13時点) https://qiita.com/Aichi_Lover/items/c15b0df871eca3a1108f amazon 2022-04-14 01:09:28
golang Goタグが付けられた新着投稿 - Qiita golangci-lint: exhaustivestruct https://qiita.com/tuuuuuuken/items/c7038165ee2f13451ffd structpattern 2022-04-14 01:26:26
Linux CentOSタグが付けられた新着投稿 - Qiita Timed out waiting for deviceのエラーについて https://qiita.com/SenriQ/items/e872302673df3e98d450 centos 2022-04-14 01:28:20
海外TECH Ars Technica Wikipedia community votes to stop accepting cryptocurrency donations https://arstechnica.com/?p=1847711 consume 2022-04-13 16:35:03
海外TECH Ars Technica Steam Deck’s future-proofed potential borne out by ray-tracing tests https://arstechnica.com/?p=1847549 windows 2022-04-13 16:20:29
海外TECH Ars Technica Scalpers gouge Lego fans desperate for freebie Skywalker Saga minifigure https://arstechnica.com/?p=1847735 deluxe 2022-04-13 16:01:03
海外TECH MakeUseOf 12 Things You Must Do With a Brand New Laptop https://www.makeuseof.com/tag/things-must-do-brand-new-laptop/ computer 2022-04-13 16:30:14
海外TECH MakeUseOf How to Download Your Gmail MBOX Data and What to Do With It https://www.makeuseof.com/tag/use-downloaded-gmail-data/ google 2022-04-13 16:30:14
海外TECH MakeUseOf 7 Tips for an Effective Walking Meeting https://www.makeuseof.com/tips-for-effective-walking-meeting/ effective 2022-04-13 16:30:13
海外TECH MakeUseOf 7 Ways to Fix a Windows Command Prompt That Randomly Appears and Disappears https://www.makeuseof.com/windows-command-prompt-randomly-appears-disappears/ prompt 2022-04-13 16:15:14
海外TECH DEV Community Authenticate Next.js SPA with ASP.NET 6 Identity and Duende Identity Server Part 2 https://dev.to/r3lazx/authenticate-nextjs-spa-with-aspnet-6-identity-and-duende-identity-server-part-2-6a1 Authenticate Next js SPA with ASP NET Identity and Duende Identity Server Part IntroductionIn the previous article we have covered in detail how to authenticate our Swagger UI and Next js application using Duende Identity Server In the previous flows we used the Authorization Code Grant Type to request the access token with this flow we centralize our authentication process to use the consent page from the Identity Server But in some scenarios we want to use the view from our SPA to authenticate directly without going to the Identity Server view Fortunately Identity Server has a flow which let us achieve that simple thing It s it Resource Owner Password Credentials ROPC flow In this article we re going to implement the ROPC flow and use the access token to consume our API Github RepoTo easily follow along with this post you can look into the Github repo SPA Identity Server Authenticate Sample Introduce to Resource Owner Password Credentials Flow The Password grant type is a way to exchange a user s credentials for an access token Because the client application has to collect the user s password and send it to the authorization server it is not recommended that this grant be used at all anymore As of OAuth the ROPC grant type is now deprecated and its use is discouraged by the OAuth security best practices ROPC flow is a simple grant flow used for authenticating a user identity and requesting for user s data from the system by a client It involves the user who is the Resource Owner resource can be the profile or an API resource The Identity Server validates the user credentials username and password against a userstore basically a database and upon successful validation grants the requesting client a token of desired type Since a user is involved in this flow the client can request for an access token used to access the API resource which the user has permission Implementing the ROPC in Duende Identity ServerWe will implement the ROPC using the client config we ve defined in the previous article Config csnew Client ClientId nextjs web app ClientName NextJs Web App ClientSecrets new Secret secret Sha RequireClientSecret false AllowedGrantTypes new GrantType AuthorizationCode GrantType ResourceOwnerPassword Add this to allow the client to use ROPC to authorize AllowOfflineAccess true Add this to recieve the refresh token after login where to redirect to after login RedirectUris http localhost api auth callback sample identity server where to redirect to after logout PostLogoutRedirectUris http localhost AllowedCorsOrigins http localhost AllowedScopes new List lt string gt IdentityServerConstants StandardScopes OpenId IdentityServerConstants StandardScopes Profile SampleAPI Notice the two lines AllowedGrantTypes new GrantType AuthorizationCode GrantType ResourceOwnerPassword Add this to allow the client to use ROPC to authorize AllowOfflineAccess true Add this to recieve the refresh token after loginTo validate the user credentials against our own user store we need to supply our own implementation of the IResourceOwnerPasswordValidator interface which the Identity Server invokes when it receives a token request of Password GrantType Inside the IdentityServerAspNetIdentity project create a class named UserValidator implementing the interface IResourceOwnerPasswordValidator which declare a single method ValidateAsync ResourceOwnerPasswordValidationContext context Identity Server will use this method to validate the credentials and set the context to success or failure UserValidator cspublic class UserValidator IResourceOwnerPasswordValidator private readonly UserManager lt ApplicationUser gt userManager private readonly SignInManager lt ApplicationUser gt signInManager public UserValidator UserManager lt ApplicationUser gt userManager SignInManager lt ApplicationUser gt signInManager userManager userManager signInManager signInManager public async Task ValidateAsync ResourceOwnerPasswordValidationContext context var result await signInManager PasswordSignInAsync context UserName context Password isPersistent true lockoutOnFailure true if result Succeeded var user await userManager FindByNameAsync context UserName if user null var claims await userManager GetClaimsAsync user context set to success context Result new GrantValidationResult subject user Id ToString authenticationMethod AuthenticationMethods Password claims claims return context set to Failure context Result new GrantValidationResult TokenRequestErrors UnauthorizedClient Invalid Crdentials Then we need to tell Identity Server to use the UserValidator class In the ConfigurationServices method of HostingExtensions class HostingExtensions csbuilder Services AddIdentityServer options gt options Events RaiseErrorEvents true options Events RaiseInformationEvents true options Events RaiseFailureEvents true options Events RaiseSuccessEvents true see options EmitStaticAudienceClaim true AddInMemoryIdentityResources Config IdentityResources AddInMemoryApiScopes Config ApiScopes AddInMemoryClients Config Clients AddAspNetIdentity lt ApplicationUser gt AddResourceOwnerValidator lt UserValidator gt Add this line We ve done configuration to accept ROPC authorization for this client We will test whether it s successfully before move on setting up our Next js SPA We will use Postman to call the token endpoint Start the Identity Server project and make a request like below Or you can use the import function of Postman to import the text below curl location request POST https localhost connect token header Content Type application x www form urlencoded data urlencode client id nextjs web app data urlencode scope openid profile offline access SampleAPI data urlencode grant type password data urlencode username bob data urlencode password Pass The response contains the JSON object which is like this access token xxx expires in token type Bearer refresh token xxx scope offline access openid profile SampleAPI Notice we got the access token directly and when the access token is expired we can use the refresh token to exchange for a new access token Configure Next js to use authenticate with Username and passwordTo config our SPA Next js application to authorize using the ROPC flow we have to add another provider NextAuth js already has one that allows us to handle signing with arbitrary credentials such as a username and password We will bring the above Postman request into the Credential provider Back to our Next js application inside the nextauth ts config fileimport CredentialsProvider from next auth providers credentials export default NextAuth providers Other Providers CredentialsProvider name Credentials Demo credentials username label Username type text placeholder alice password label Password type password async authorize credentials req const reqData credentials client id nextjs web app scope openid profile offline access SampleAPI grant type password as any let formBody for let property in reqData let encodedKey encodeURIComponent property let encodedValue encodeURIComponent reqData property formBody push encodedKey encodedValue const formBodyStr formBody join amp const res await fetch https localhost connect token method POST body formBodyStr headers Content Type application x www form urlencoded charset UTF const response await res json If no error and we have user data return it if res ok amp amp response return response Return null if user data could not be retrieved return null The response data schema is like this access token xxx expires in token type Bearer refresh token xxx scope offline access openid profile SampleAPI Start the application and go to http localhost Press the Sign in button on the header you will be navigated to NextAuth js Sign in pageThere will be two options for you to Sign in using the flow in the previous article or sign in directly using the RPOC flow We will test the RPOC flow by entering username and password alice Pass Then you should login successfully and redirected back to http localhost Consume the API with the Access TokenWe have learned how to authorize our users and successfully get the access token from Identity Server Now we will use that token to consume our API The cool thing is that NextAuth js already made it very easy for us It provides a helper call getToken which we can inject everywhere to get the current login JWT token By default NextAuth js doesn t save the OAuth tokens to it provider So to start we want to make those tokens accessible so that we can use them to consume our API In NextAuth js we can define callbacks which allow us to tap into the authentication events and customize what gets returned Open up the nextauth ts and add the following codes export default NextAuth providers callbacks async signIn user account profile email credentials if user access token account access token user access token as string if user refresh token account refresh token user refresh token as string return true async jwt token user account profile isNewUser if account access token token access token account access token if account refresh token token refresh token account refresh token return token A little explaination furtherThe signIn callback will be called before the jwt call back We will make sure the returned token of the jwt callback will always contains the access token and refresh token If we sign in using the ROPC flow then the access token and refresh token will be available in the signIn s user object We will pass down the tokens from the user to account then from account to token inside the jwt callbackIf we sign in using the Authorization Code flow the flow we did in the previous article then the access token and refresh token will be available in the jwt s account object We just have to pass down the tokens from account to token object Then the tokens will be available in the session and we can use it anywhere within the NextAuth js s SessionProviderIn the context of this example we will make a call to our WeatherForecastController s endpoints Remember to start the API application first Inside the pages api folder create a folder called sample and put an index ts file into it This will be used to call our endpoint pages api sampe index tsimport getToken from next auth jwt import type NextApiRequest NextApiResponse from next const secret process env SECRETexport default async function sample req NextApiRequest res NextApiResponse const token await getToken req secret if token access token return res status json status Need Authorization try const result await fetch https localhost WeatherForecast method GET headers Authorization Bearer token access token return res status json status Ok data await result json catch e any return res status json status e message Once we done this we should be able to access this directly in our browser by visiting http localhost api sampleAt the first time the page should return status Need Authorization We have to go back to http localhost perform the login actions then the data at http localhost api sample should be which indicate that we are successfully consuming our API status Ok data date T temperatureC temperatureF summary Bracing date T temperatureC temperatureF summary Chilly date T temperatureC temperatureF summary Balmy date T temperatureC temperatureF summary Hot date T temperatureC temperatureF summary Warm What else can we do Read more about OAuth Grant Types and why ROPC is deprecated Role based AuthorizationFurther to this tutorial I will make another series of how to implement the Role Based Authorization and use it to protect our API Hope that everyone will enjoy it SummaryWe have done the most basic ways to authenticate a Next js SPA with Duende Identity Server There re more things to explore at NextAuth js documentation and Duende Identity Server documentation So remember to give them a visit and try to implement things on your own Thank you for reading References ropc using identityserver 2022-04-13 16:31:08
海外TECH DEV Community Use Copilot to Write and Translate a Binary Search Algorithm https://dev.to/github/use-copilot-to-write-and-translate-a-binary-search-algorithm-lcm Use Copilot to Write and Translate a Binary Search AlgorithmI learn best from reading watching and doing which means I need various resources to create a robust mental model When I ve studied for interviews colleges exams and coding bootcamp I ll watch videos complete LeetCode exercises and write an explanation of the code Copilot Labs serves as an additional resource giving me more context on why and how specific algorithms work I will use Copilot and Copilot Labs to write and understand a binary search algorithm in this blog post Prerequisites Ensure that you ve installed the GitHub Copilot extension AND the GitHub Copilot Labs extension Please note GitHub Copilot is in technical preview and thus not all users will be able to access this feature Please join the waitlist if you d like to sign up for the technical preview Writing Code with CopilotStep Open your IDE For this example I m using Visual Studio Code via Codespaces Type a comment that says Write a binary search algorithm Step Type the keyword const on a new line This should trigger Copilot to provide suggested code to write a binary search algorithm To accept the suggested code press the TAB key Explaining Code with Copilot LabsStep Now we can better understand what the code is accomplishing by converting the code into plain language Let s open the Copilot Labs sidebar Step Highlight the code snippet and on the top left hand corner choose Explain Press the Ask Copilot button to generate a step by step explanation of what s happening in the code snippet Translating Code to a Different Programming Language with Copilot LabsStep We can also convert this code snippet into Python or any programming language of your choice Navigate to the Language Translation of the Copilot Labs sidebar and choose the target language Press the Ask Copilot button to view a version of the code snippet in a different language Follow GitHub and me on DEV for more updates on GitHub s newest features If you have any feedback you want to share with the team at GitHub use the Discussion board 2022-04-13 16:25:39
海外TECH DEV Community Why Use GitHub Copilot And Copilot Labs: Practical Use Cases for the AI Pair Programmer https://dev.to/github/why-use-github-copilot-and-copilot-labs-practical-use-cases-for-the-ai-pair-programmer-4hf4 Why Use GitHub Copilot And Copilot Labs Practical Use Cases for the AI Pair Programmer IntroductionEven though I didn t work at GitHub when they announced Copilot I remember it piqued my interest Perhaps I was mostly excited because it was new and shiny Also because I love predictive text in other environments like writing emails why not in my code editor When I received access to the feature I realized two things It s not magic GitHub Copilot can t read my mind and it will not always spit out perfectly well written up to date code Copilot increases my confidence and velocity as a programmer For me the value of Copilot is that I spend less time stressing over syntax which leaves more time for solving problems More recently GitHub Next a team exploring the future of technology and software beyond the adjacent possible released Copilot Labs This experimental VS Code sidebar enables developers to translate their code from one programming language to another and explains code snippets in plain language With Copilot and Copilot Labs you can Generate predictive lines of code from comments and existing patterns in your codeRead an explanation of a code snippetTranslate code from one programming language to anotherThese sound super cool but when would you use them I share my favorite use cases of GitHub Copilot and GitHub Copilot Labs in this blog post What is Copilot Before I go into how I ve used Copilot I ll explain the feature to those unfamiliar with it GitHub Copilot is an AI pair programmer that helps you write code faster and with less work GitHub Copilot draws context from comments and code and suggests individual lines and whole functions instantly GitHub Copilot is powered by OpenAI Codex a new AI system created by OpenAI The GitHub Copilot technical preview is available as an extension for Visual Studio Code Neovim and the JetBrains suite of IDEs TLDR In other words GitHub Copilot is an IDE extension that provides predictive code based on comments that you write and patterns in your code Please note GitHub Copilot is in technical preview and thus not all users will be able to access this feature Please join the waitlist if you d like to sign up for the technical preview Use CasesCoding a little fasterWhether I m working as a software engineer or a developer advocate I ve found myself in moments where I m writing code at the last minute or I m experiencing a coder s block Reading suggestions from Copilot reminds me of how to solve common day to day algorithms You can read one of my blog posts about how I used Copilot to write and understand a binary search algorithm For example In one project I had to read a file order it alphabetically group it by letter insert a new element in the correct alphabetical spot and then write the updated contents back to the file Fortunately Copilot helped me write a solution See below Writing testsWhile I understand that writing tests for your code are essential I don t enjoy it I often take forever to start trying to remember the difference between keywords like mock nock beforeEach and afterAll Then when I get the pattern down it feels like a tedious process for me to reach a particular test coverage percentage This is where Copilot can come in handy I can write a few comments describing what I want to test then Copilot may suggest the code needed for the test I can also start writing tests and Copilot may provide anticipated code for other needed tests Learn more by reading Using GitHub Copilot to Automate Tests by Colby Fayock Writing better commentsSometimes writing great comments ends up on the backburner There s a tendency to assume your code is clean readable and doesn t need comments until you return to your code the next day and you re unable to decipher the hieroglyphics Since well written comments tend to trigger better results from Copilot I m more motivated to write explicit relevant comments and I leave them in my code insert mindblown emoji Pair programming with a coworkerI m also not fantastic at pair programming especially when I m the less experienced engineer I experience anxiety from people watching my every move especially while I code What stops me in my tracks is that I m often trying to remember the syntax With Copilot my pair programming buddy spends less time watching me Google reduce javaScript array method for the umpteenth time Instead it may suggest the correct syntax for me What is Copilot Labs Before I go into how I ve used Copilot Labs I ll explain the feature to those unfamiliar with it Copilot Labs is separate from and dependent on the GitHub Copilot extension While Copilot continues to march toward general availability Labs will be a proving ground for experimental applications of machine learning that improve the developer experience Currently Copilot Labs consists of a VS Code sidebar that houses distinct features starting with “explain this code and “translate this code Use CasesGetting comfortable in a new codebaseWhether you landed a new gig or joined a new open source community there s no easy answer to building a mental model of a new codebase It can take months and codebases evolve While Copilot Labs can t explain the entire codebase to me I can use it to describe code blocks within a new codebase Understanding solutions you find on StackOverflowTypically software developers copy and paste solutions they find on StackOverflow which is completely fine Still it s necessary for us to understand what we copied and why it works Leveraging Copilot Lab s explain this code feature enables me to copy code from StackOverflow AND understand what the code is doing Gaining context for different data structures and algorithmsI learn best from reading watching and doing which means I need various resources to create a robust mental model When I ve studied for interviews colleges exams and coding bootcamp I ll watch videos complete LeetCode exercises and write an explanation of the code Copilot Labs serves as an additional resource giving me more context on why and how specific algorithms work Be a better mentorI mentor early career developers I m helpful when they are currently students in the program where I mentor but once they graduate and start working at jobs with different technologies I m useless There are multiple moments when they ve asked me to help them with Python or Ruby and I m unable to assist because I m not familiar with those languages With Copilot Labs I can translate my mentee s code snippets to read the code in a familiar language gain a better understanding of their code and then lead them in the right direction It even helps me explain to the mentee what s going on in their code because sometimes as a newer developer you re not sure why code works but it does Want to see Copilot Labs in action Watch this YouTube short as mishmanners uses Copilot Labs to translate code Share ways that Copilot and Copilot Labs are useful to you in the comments below If you have any feedback you want to share with the team at GitHub use the Discussion board 2022-04-13 16:25:05
海外TECH DEV Community What are your top 3 frustrations as a Developer? https://dev.to/veratiago/what-are-your-top-3-frustrations-as-a-developer-4589 developer 2022-04-13 16:17:36
海外TECH DEV Community Database constraints considered harmful? https://dev.to/jonlauridsen/database-constraints-considered-harmful-38 Database constraints considered harmful In relational databases it s common practice to create constraints to lock down the data and its relationship to other tables So a Users table might have an email column that s marked as unique because everyone has their own email right And a Subscription table gets a non nullable User column because every Subscription must be associated with a User Yeah that also sounds reasonable I m here to argue against constraints To some that might sound heretical or at least very stupid but hear me out We use constraints for two reasons For performance it s a lot quicker to search a uniquely indexed column and to guarantee data integrity so we physically can t enter invalid data e g the business requires a subscription to be tied to a user Here s the problem We programmers often optimize too early and SQL constraints don t actually express the business requirements Let me break that down a bit On the topic of performance there are of course valid cases where constraints speed up queries by several magnitudes but unless we see that performance problem and its subsequent remediation with a constraint we run the risk of prematurely optimizing Fewer constraints would make the code more malleable and create less friction for making subsequent changes to the database structure All I m proposing here is that we look for opportunities to defer database optimizations until they are truly needed to counteract our tendency for premature optimizations Constraints that ensure data integrity really are challenged by an inability to actually capture all business requirements I mean in theory database constraints could fully express any business requirement because e g the PostgreSQL dialect is Turing complete but that d be mad We don t program in SQL we program in C Python Javascript etc Actual business functionality belong in our general purpose languages not the data storage language So what constraints should we put in the database I propose no business constraints at all Does that sound barking mad The more I work with SQL the more I get bit by half baked business constraints that almost kinda sort of duplicates what the code already handles What does it really give us to mark a Subscription s User column as non nullable when the code already ensures a Subscription is only ever created in relation to a User It amounts to no help at all because constraints are simply not the actual source of truth But wait I hear some protest it s so simple to add non nullable to the User column Yes but it still does harm because it fundamentally isn t the source of truth for the business requirement At this point we need to discuss the drawbacks of constraints The more of them there are the more difficult the system becomes to test and adjust More difficult to test because to test a Subscription we now also have to create a User and associate them correctly Even if a test has nothing to do with the User entity it must be created And then imagine another handful of entities that have to be put together just right to create a Subscription it quickly becomes very painful to work with Then we might start hiding all that test complexity in entity factories but those are just abstractions on top of complexity that we have caused for ourselves Why not get rid of the complexity entirely And more difficult to adjust because introducing new features ends up requiring careful migrations to keep the constraints synced with code What if we actually can have subscriptions without a user What if an email column doesn t have to be unique If the data storage layer imposes artificial constraints it slows down quickly experimenting with such ideas I think many of us create constraints because we were trained and or told to do so But none of us are realistically implementing of business rules in SQL so where do we draw the line Constraints are of course good when they give real tangible performance benefits but what would happen if we loosen up the system to let those entities be more malleable and easier to work with and test At the end of the day only you know your domain so there are no general answers to my assertions What I m trying to get at is a certain level of dogma I ve felt that sometimes sneak into relational storage design where it is taken as fact that we must blindly create constraints that sounds business logic compatible because that s just how we do it Instead I propose ONLY adding a constraint where and when it is truly necessary That way databases are allowed to focus just on storing and retrieving data which is the role they truly excel at Photo by Sam Moqadam on Unsplash 2022-04-13 16:16:27
海外TECH DEV Community Svelte Share Buttons: using Web Share API with Fallback https://dev.to/askrodney/svelte-share-buttons-using-web-share-api-with-fallback-195b Svelte Share Buttons using Web Share API with Fallback What is the Web Share API In this post we see how you can add Svelte share buttons to your Svelte based app We will follow a roll your own approach here using inbuilt browser APIs rather than adding extra packages or dependencies We will work in SvelteKit though our Svelte components can just as easily be used in Slinkity or Astro Svelte apps We add buttons to a blog starter which let site visitors share blog posts with their friends and followers on WhatsApp Telegram and Twitter as well as Facebook That functionality works in any browser relying on just JavaScript As well as that we make use of the relatively new Web Share API On the visitor s mobile this will bring up a menu making it easy to share your site on any suitable apps they have installed We are going for a progressive enhancement approach This means mobile and Safari on desktop will show the Web Share API button while browsers yet to support it will show our share buttons instead What we re BuildingI mentioned we are working in SvelteKit using the MDsveX blog starter If Astro is your preferred tool for building Svelte sites start with the Astro Svelte Markdown starter instead Of course if you have an existing Svelte app you can create a feature branch and add this functionality there Anyway to start let s clone a repo git clone sveltekit share buttonscd sveltekit share buttonspnpm installcp env EXAMPLE envpnpm run devWith that done we will start by adding the fallback share button functionality We will run through adding Twitter in detail then sketch over adding other networks If you want to add a popular network not mentioned drop a comment below and I will see what I can do Equally feel free to submit a pull request to the repo if you code up support for a well known network not already implemented Initial Share Button ComponentTo get the ball rolling let s create a src lib components ShareButtons folder and inside it add an index svelte file This file will ultimately contain the logic for the Web Share progressive enhancement as well as the fallbacks Progressive enhancement expresses a similar sentiment to graceful degradation The idea is we want to support a new feature which does not currently enjoy wide support We have a baseline which supports all or most devices then the progressive enhancement offers the new feature but only where the user device supports it To get going paste this code into the new file lt script gt import Twitter from lib components ShareButtons Twitter svelte import website from lib config website const siteUrl website export let slug export let title const url siteUrl slug lt script gt lt aside aria label Share buttons class container gt lt div class wrapper gt Share lt div class buttons gt lt Twitter url title gt lt div gt lt div gt lt aside gt Here is some optional styling which you can paste at the end of the file lt style lang scss gt container display flex flex direction row margin top spacing width max width full wrapper display flex flex direction row margin left auto font weight font weight bold font size font size buttons margin left spacing button background transparent border style none transition all s ease in out media prefers reduced motion reduce button transition all s ease in out button focus button hover transform scale lt style gt This will not work yet ーwe need to create the Twitter share button component Nonetheless let s add the ShareButton component to our blog post template now lt script gt import BannerImage from lib components BannerImage svelte import SEO from lib components SEO index svelte import ShareButtons from lib components ShareButtons index svelte import readingTime from reading time lt BannerImage imageData gt lt h gt title lt h gt lt ShareButtons slug title gt With that basic wiring up done we will next create the Twitter share button component The other components work in a similar way though the Twitter API supports the most customisation so it provides a good starting point Twitter Share Button ComponentThis button will be part of the fallback as such we will not show it on devices which support the Web Share API Currently on MacOS Safari does support the API so test this part in Firefox and Chrome The Twitter code together with the other share button components are based off the nygardk react share GitHub repo by Klaus Nygård lt script gt import TwitterIcon from lib components Icons Twitter svelte export let hashtags array of hashtags exclude e g svelte askRodney export let quote undefined export let related array of Twitter users including export let title text in Tweet export let url export let via include e g askRodney const TWITTER BLUE aced const baseUrl const parametersObject url hashtags length gt hashtags hashtags join quote text title related length gt related related join via length gt via via slice const params Object entries parametersObject filter value gt value false map key value gt encodeURIComponent key encodeURIComponent String value join amp const urlWithParameters params baseUrl baseUrl params function handleClick const config height width location no toolbar no status no directories no menubar no scrollbars yes resizable no centerscreen yes chrome yes return window open urlWithParameters Object keys config map key gt key config key join lt script gt lt button on click handleClick gt lt span class screen reader text gt Share on Twitter lt span gt lt TwitterIcon colour TWITTER BLUE width gt lt button gt lt style lang scss gt button background transparent border style none transition all s ease in out media prefers reduced motion reduce button transition all s ease in out button focus button hover transform scale media screen and max width desktop breakpoint button padding left spacing padding right spacing lt style gt In line we import an iconify Twitter icon already used in the project It is fairly easy to add icons from dozens of libraries using iconify In fact this post is a follow up to an earlier post which tells you exactly how to gain access to over SVG icons using a single package So jump back there when you want to see how to add icons to your own project The Twitter API has most bells and whistles you can include hashtags quotes and related accounts as well as a via Twitter account I have added some comments in the code to explain how to use these Here we ll just focus on adding the text title prop and URL Twitter CustomisationsLines above build up the query parameters for the URL which we need to send to Twitter to share the post Because this is a URL some characters are not allowed and we have to encode them In line we make use of encodeURIComponent to URL encode the keys and parameters for us The handleClick code in lines brings up a new window on Twitter s site which lets the visitor log in if they are not already logged in and share The sizes are sensible defaults which work on different sized devices so you will probably not need to adjust these The other components will be similar though with differing baseUrl see line For improved accessibility include some screen reader text on all buttons as in line This will not be visible though screen readers will announce it helping screen reader users know what the button does Other Network ButtonsWe will skim over the other networks now in fact we will only point out details which are different Then in the following section we will add them into the principal component and also wire up the Web Share API Facebook lt script gt import FacebookIcon from lib components Icons Facebook svelte export let hashtag export let quote export let url const FACEBOOK BLUE b const baseUrl const parametersObject u url quote quote hashtag hashtag const params Object entries parametersObject filter value gt value false map key value gt encodeURIComponent key encodeURIComponent String value join amp const urlWithParameters params baseUrl baseUrl params function handleClick const config height width location no toolbar no status no directories no menubar no scrollbars yes resizable no centerscreen yes chrome yes return window open urlWithParameters Object keys config map key gt key config key join lt script gt lt button on click handleClick gt lt span class screen reader text gt Share on Facebook lt span gt lt FacebookIcon colour FACEBOOK BLUE width gt lt button gt lt style lang scss gt button background transparent border style none transition all s ease in out media prefers reduced motion reduce button transition all s ease in out button focus button hover transform scale media screen and max width desktop breakpoint button padding left spacing padding right spacing lt style gt Telegram lt script gt import TelegramIcon from lib components Icons Telegram svelte export let url export let title const TELEGRAM BLUE ae const baseUrl const parametersObject url text title const params Object entries parametersObject filter value gt value false map key value gt encodeURIComponent key encodeURIComponent String value join amp const urlWithParameters params baseUrl baseUrl params function handleClick const config height width location no toolbar no status no directories no menubar no scrollbars yes resizable no centerscreen yes chrome yes return window open urlWithParameters Object keys config map key gt key config key join lt script gt lt button on click handleClick gt lt span class screen reader text gt Share on Telegram lt span gt lt TelegramIcon colour TELEGRAM BLUE width gt lt button gt lt style lang scss gt import styles variables button background transparent border style none transition all s ease in out media prefers reduced motion reduce button transition all s ease in out button focus button hover transform scale media screen and max width desktop breakpoint button padding left spacing padding right spacing lt style gt WhatsApp lt script gt import browser from app env import WhatsappIcon from lib components Icons Whatsapp svelte import isMobileOrTablet from lib utilities device const WHATSAPP GREEN D export let url export let title const baseUrl browser amp amp isMobileOrTablet const parametersObject text title title url url const params Object entries parametersObject filter value gt value false map key value gt encodeURIComponent key encodeURIComponent String value join amp const urlWithParameters params baseUrl baseUrl params function handleClick const config height width location no toolbar no status no directories no menubar no scrollbars yes resizable no centerscreen yes chrome yes return window open urlWithParameters Object keys config map key gt key config key join lt script gt lt button on click handleClick gt lt span class screen reader text gt Share on Whatsapp lt span gt lt WhatsappIcon colour WHATSAPP GREEN width gt lt button gt lt style lang scss gt button background transparent border style none transition all s ease in out media prefers reduced motion reduce button transition all s ease in out button focus button hover transform scale media screen and max width desktop breakpoint button padding left spacing padding right spacing lt style gt There is not already a WhatsApp icon in the starter Add this code or create your own using your preferred icon set lt script gt import Icon addCollection from iconify svelte dist OfflineIcon svelte export let label Whatsapp icon export let colour inherit export let ariaHidden false export let width addCollection prefix simple icons icons whatsapp body lt path fill currentColor d M c c c c c c c c c c c c a c c c c c c c c c m h a l l l l a c c a c m A C c L l a h c a Z gt width height lt script gt lt Icon icon simple icons whatsapp ariaHidden aria label label color colour width gt Also for WhatsApp there are different API URLs depending on whether the visitor is using a mobile device or not We make use of a utility function to check the type of device the user has Create this file if you added the WhatsApp share button code above to your app Returns true if the device is thought to be a mobile or tablet returns boolean export function isMobileOrTablet return android iphone ipad mobile i test navigator userAgent Pulling it all TogetherWe are going back to src lib components ShareButtons index svelte now to tie the new buttons in Feel free to omit any networks you will not need on your app here lt script gt import Facebook from lib components ShareButtons Facebook svelte import Telegram from lib components ShareButtons Telegram svelte import Twitter from lib components ShareButtons Twitter svelte import Whatsapp from lib components ShareButtons Whatsapp svelte import website from lib config website const siteUrl website export let slug export let title const url siteUrl slug lt script gt lt aside aria label Share buttons class container gt lt div class wrapper gt Share lt div class buttons gt lt Twitter url title gt lt Facebook url gt lt Whatsapp url title gt lt Telegram url title gt lt div gt lt div gt lt aside gt I think it will be clear what we are doing here but let me know if I have forgotten to explain something Web Share APIThe final missing piece is the Web Share button We will add a webShareAPISupported boolean variable with a reactive declaration This needs access to the browser navigator object so will not work when the code is running server side SvelteKit provides the browser variable defined in app env which we make use of here If you are working in Astro check for ssr using this snippet ASTRO ONLY IGNORE FOR SVELTEKITconst ssr import meta env SSR Remember when browser in the SvelteKit code is true ssr will be false and vice verse Anyway let s update the file lt script gt import browser from app env import ShareIcon from lib components Icons Share svelte import Facebook from lib components ShareButtons Facebook svelte import Telegram from lib components ShareButtons Telegram svelte import Twitter from lib components ShareButtons Twitter svelte import Whatsapp from lib components ShareButtons Whatsapp svelte import website from lib config website const siteTitle siteUrl website export let slug export let title webShareAPISupported browser amp amp typeof navigator share undefined handleWebShare const handleWebShare async gt try navigator share title text Shared from siteTitle url catch error webShareAPISupported false const url siteUrl slug lt script gt lt aside class container gt lt div class wrapper gt Share lt div class buttons gt if webShareAPISupported lt button on click handleWebShare gt lt span class screen reader text gt Share lt span gt lt ShareIcon width gt lt button gt else lt Twitter url title gt lt Facebook url gt lt Whatsapp url title gt lt Telegram url title gt if lt div gt lt div gt lt aside gt In line we declare the handleWebShare function as reactive using the dollar syntax This will let the interface update if in line the function sets webShareAPISuported to false What have we got here In lines we have a guard so if webShareAPISupported is false the user will see the share buttons we previously defined On the other hand if it is true the user sees the share button which we will add in a moment When the use clicks or taps the share button the handleWebShare function is invoked This is asynchronous so it is best practice to include try catch blocks If for some reason the share fails there is no issue Remember we have our fallback so just show the share buttons for the networks we added initially Lines have the core Web Share code Sharing via the APIThe Web Share API lets users share links text and files We focus on sharing text and links here To share a file just add an extra files field to the share object We share both a link and some related text You can opt to share either one of these on its own and drop the other some browsers do not yet support text though You see the API is fairly simple and there is not much more left to explain…the browsers do all the heavy lifting The final thing worth a mention is the check for support in line To check the latest browser support see MDN Web Share API docs Share IconBefore we can test we need to put the missing share icon into the project feel free to swap this out using your preferred collection lt script gt import Icon addCollection from iconify svelte dist OfflineIcon svelte export let label Share icon export let colour inherit export let ariaHidden false export let width addCollection prefix simple line icons icons share body lt path fill currentColor d M c l c c l C c c S c L c C c c l C c s s zm c s s s zm c s c s zm c s s s z gt width height lt script gt lt Icon icon simple line icons share ariaHidden aria label label color colour width gt Svelte Share Buttons TestYou should now be able to see the share buttons if you open any of the blog posts in a browser To test on desktop at the time of writing the WebShare API was not supported on Firefox and Chrome so these are good for testing the fallback buttons Safari on desktop does support the Web Share API so is fantastic for testing that button Also try deploying your app to a staging environment to test a few mobile browsers Svelte Share Buttons WrapupIn this post we looked at how to add share buttons to a Svelte app with progressive enhancement using the Web Share API to share from a Svelte app adding fallback share icons with iconify I do hope there is at least one thing in this article which you can use in your work or a side project Also let me know if you feel more explanation of the config is needed This post came from a request in a comment on another post so do drop a comment below if there is something else you would like to see a video or post on You can see the full SvelteKit code for this project on the Rodney Lab Git Hub repo If you run into any issues you can drop a comment below as well as reach out for a chat on Element Also Twitter mention if you have suggestions for improvements or questions FeedbackIf you have found this video useful see links below for further related content on this site I do hope you learned one new thing from the video Let me know if there are any ways I can improve on it I hope you will use the code or starter in your own projects Be sure to share your work on Twitter giving me a mention so I can see what you did Finally be sure to let me know ideas for other short videos you would like to see Read on to find ways to get in touch further below If you have found this post useful even though you can only afford even a tiny contribution please consider supporting me through Buy me a Coffee Finally feel free to share the post on your social media accounts for all your followers who will find it useful As well as leaving a comment below you can get in touch via askRodney on Twitter and also askRodney on Telegram Also see further ways to get in touch with Rodney Lab I post regularly on SvelteKit as well as Search Engine Optimisation among other topics Also subscribe to the newsletter to keep up to date with our latest projects 2022-04-13 16:11:15
海外TECH DEV Community Building an API using Express.js, Postgres, Sequelize CLI and Jest for Unit Testing Part 1 https://dev.to/luigimorel_1/building-an-api-using-expressjs-postgres-sequelize-cli-and-jest-for-unit-testing-part-1-2d89 Building an API using Express js Postgres Sequelize CLI and Jest for Unit Testing Part Crafting Application Programming Interfaces APIs is one of the tasks that developers have to do once in a while Web developers use various tools to accomplish these tasks that are required in their day to day schedules In this tutorial we ll explore how to build a simple e commerce like API using PostgreSQL Express js and Sequelize CLI Here s what we will cover What is Sequelize Installing Sequelize CLICreating entity models using the CLIWriting unit tests using JestDeployment to HerokuCreating associations using Postgres and Sequelize CLICI CD using Circle CI What to know before reading furtherBasic knowledge about SQLExpress js basicsHTTP methodsTo follow along with this tutorial you should have the following tools installed on your development machine Nodejs x or higher I m using v Yarn or NPM I m using Yarn v A text editor I m using VS Code A local installation of PostgreSQL What is Sequelize Sequelize is an easy to use JavaScript object relational mapping ORM tool that works with SQL databases Project set upInstalling SequelizeMake a new directory that you ll use while working with this tutorial and install the project s dependencies mkdir sequelize tutorialcd sequelize tutorialyarn add sequelize cors pg morgan helmet amp amp yarn add D sequelize cli nodemon dotenvsequelize Sequelize is a promise based Node js ORM tool for Postgres It features solid transaction support relations eager and lazy loading read replication and more cors CORS is a node js package for providing a Connect Express middleware that can be used to enable CORS with various options pg Non blocking PostgreSQL client for Node js morgan HTTP request logger middleware for node jshelmet Helmet helps you secure your Express apps by setting various HTTP headers sequelize cli The Sequelize Command Line Interface CLI nodemon a tool that helps develop node js based applications by automatically restarting the node application when file changes in the directory are detected dotenv module that loads environment variables from a env file into process envAdd a gitignore and env files to the root of your project s folder touch gitignore envThen add the node modules folder and env file to your gitignore node modules env Before we beginCreating our entitiesOur API has two entitiesProductCategoryRelationshipsOne product belongs to one category One category has many productsLet s jump right into the code Initialize a Sequelize project then open the directory in our code editor VS Code yarn sequelize cli initcode Configure the project to use with a Postgres database as the SQL dialect Go to the config json in the config directory and change the code to this development username postgres password null database db dev host dialect postgres test username postgres password null database database test host dialect postgres production use env variable DATABASE URL dialect postgres dialectOptions ssl rejectUnauthorized false Since we re still in development mode of the project add the username database and password fields to the development object In my case username is postgres password is null I m not using a password bad practice I know and database is db dev Once done with the above step create the database for the project using this command yarn sequelize cli db create Defining modelsOur goal is to associate the products with the categories that they belong to Let s create a Product model yarn sequelize cli model generate name Product attribute name string quantity integer inStock boolean productImage string expiryDate dateBelow are the contents for the migration file that has been created use strict module exports async up queryInterface Sequelize await queryInterface createTable Products id allowNull false primaryKey true type Sequelize UUID defaultValue Sequelize UUIDV name type Sequelize STRING trim true quantity type Sequelize INTEGER trim true allowNull false price type Sequelize INTEGER allowNull false trim true inStock type Sequelize BOOLEAN defaultValue false productImage type Sequelize STRING allowNull false trim true expiryDate type Sequelize DATE allowNull false createdAt allowNull false type Sequelize DATE updatedAt allowNull false type Sequelize DATE async down queryInterface Sequelize await queryInterface dropTable Products Please note that I m using UUID instead of the integer data type for the id field Read about how to use UUID here Here is an article about how to add an extension to your database via PSQL shell When you run the model generate command Sequelize generates a model file and a migration with the attributes specified We can now run the migration to enable us create the Products table in our database yarn sequelize cli db migrateLet s generate the seed file for the Product modelyarn sequelize cli seed generate name productA new file ending with product js has been created in the seeders folder Copy and paste the code below which is sample data of the products use strict module exports async up queryInterface Sequelize await queryInterface bulkInsert Products id c c d ae adfcbe name Bread quantity inStock true productImage Store the price in cents e g if price is multiply by cents e g cents price expiryDate new Date createdAt new Date updatedAt new Date id dfac c f ab aca name Milk quantity inStock true productImage Store the price in cents e g if the price is multiply by cents e g cents price expiryDate new Date createdAt new Date updatedAt new Date async down queryInterface Sequelize await queryInterface bulkDelete Products null That s all for the Products model for now Create the Category model yarn sequelize cli model generate name Category attributes name stringBelow is the migration file for the Category model use strict module exports async up queryInterface Sequelize await queryInterface createTable Categories id allowNull false primaryKey true type Sequelize UUID defaultValue Sequelize UUIDV name type Sequelize STRING trim true allowNull false createdAt allowNull false type Sequelize DATE updatedAt allowNull false type Sequelize DATE async down queryInterface Sequelize await queryInterface dropTable Categories Let s create a seeder file for the Category modelyarn sequelize cli seed generate name categoryBelow is the file with the seeder entries use strict module exports async up queryInterface Sequelize await queryInterface bulkInsert Categories id aa a c bfc aceadf name Confectionaries createdAt new Date updatedAt new Date id aee fc bcd cffea name Drinks createdAt new Date updatedAt new Date async down queryInterface Sequelize await queryInterface bulkDelete Categories null We can now create associations between the Products and the Category each belongs to Read more about associations hereReplace the code in the models product directory with the one below use strict const Model require sequelize module exports sequelize DataTypes gt class Product extends Model static associate models Product belongsTo models Category foreignKey categoryId Product init name DataTypes STRING quantity DataTypes INTEGER inStock DataTypes BOOLEAN productImage DataTypes STRING price DataTypes INTEGER expiryDate DataTypes DATE sequelize modelName Product return Product Replace the code in the models category directory with the one below use strict const Model require sequelize module exports sequelize DataTypes gt class Category extends Model static associate models Category hasMany models Product foreignKey categoryId onDelete CASCADE Category init name DataTypes STRING sequelize modelName Category return Category Let s now add the foreign key to the Product migration file Go to the migrations sub folder and add the code below to the file that ends with create product js categoryId type Sequelize UUID allowNull false onDelete CASCADE references model Categories key id as categoryId The above line of code adds a foreign key to the Products table in our database To add the categoryId column to the Products table check the scripts in the package json file There s a script named db reset It ll help us to drop the database create the database again run the migrations and add the seeder data into our database Run it yarn db resetIf you open PSQL you should see the updated Products table We now have our products and categories table in Part of this tutorial we shall look at how to make requests using Express js You can find the code for this tutorial so far in this GitHub repository 2022-04-13 16:06:14
海外TECH DEV Community Diferença entre Any e Unknown do Typescript https://dev.to/magoacademico/diferenca-entre-any-e-unknown-no-typescript-401e Diferença entre Any e Unknown do Typescript Vocêsabe a diferença entre any e unknown any e unknown são tipos bem parecidos e podem parecer que são atéiguais mas possuem suas diferenças A confusão que se tem sobre esses dois tipos vem do fato de que se criarmos uma função que recebe dois parâmetros um do tipo any e outro do tipo unknown veremos que podemos passar qualquer variável para ambos os tipos sem erros const foo anyType any unknownType unknown gt foo foo foo null null foo gt gt Mas épossível ver a diferença quando se usa essas variáveis Com any vocêpode atribuir qualquer tipo e usar como se fosse qualquer tipo Jáunknown vocêpode atribuir qualquer tipo mas ao usar ele não énenhum tipo e vocêprecisaráverificar qual éo tipo Uma variável do tipo any vocêpode ser usada como uma string ou como uma função e atémesmo como um objeto mostrando que any éequivalente a todos os tipos const foo anyType any unknownType unknown gt const str string anyType gt ok anyType gt ok anyType foo gt ok Jáo unknown mesmo podendo receber qualquer tipo ele da erro quando se tenta usa lo como qualquer tipo portanto não se pode usa lo como uma string função objeto ou qualquer outro tipo diferente de unknown const foo anyType any unknownType unknown gt const str string anyType gt ok anyType gt ok anyType foo gt ok const str string unknownType gt erro unknownType gt erro unknownType foo gt erro Para vocêpoder usar uma variável do tipo unknown épreciso que se verifique o tipo antes Para atribuir unknown para uma string pode se verificar utilizando typeof e ver se o tipo da variável éde fato string e o mesmo pode ser feito para uma função const str string unknownType gt erroif typeof unknownType string const str string unknownType gt ok unknownType gt erroif typeof unknownType function unknownType gt ok Para verificar se uma variável éde um tipo mais especifico como um objeto com algumas propriedades especificas énecessário utilizar um user defined type guard que éuma função que o retorno dela define um type predicate ou seja define que uma variável éde um determinado tipo utilizando is interface Foo foo string user defined type guard type predicate const isFooType foo unknown foo is Foo gt return foo as Foo foo undefined unknownType foo gt erroif isFooType unknownType unknownType foo gt ok Ao utilizar unknown ao invés de any vocêpermite que seu código seja utilizado de forma muito mais segura 2022-04-13 16:04:53
Apple AppleInsider - Frontpage News It's time for Apple to revisit these iconic products https://appleinsider.com/articles/22/04/13/its-time-for-apple-to-revisit-these-iconic-products?utm_medium=rss It x s time for Apple to revisit these iconic productsAmidst all the other updates in the last year Apple has forgotten some of the products in its portfolio Here are five things that we think Apple should show some love iPod Touch and iPod miniSome of these devices are no longer available ーlike AirPort routers ーand others are still available While some are products we love others have glaring missteps that Apple has yet to address Read more 2022-04-13 16:17:11
Apple AppleInsider - Frontpage News Save 85% on a lifetime Microsoft Office for Mac Home & Business 2021 license https://appleinsider.com/articles/22/02/15/lifetime-microsoft-office-for-mac-home-business-2021-license-is-back-for-4999-85-off-while-supplies-last?utm_medium=rss Save on a lifetime Microsoft Office for Mac Home amp Business licenseAfter initially selling out the popular Microsoft Office for Mac deal has returned delivering a lifetime Home Business license for ーand matching the steepest discount on record at off Save on Microsoft Office for Mac or WindowsHigher than expected demand resulted in the deal previously selling out but StackCommerce has replenished inventory of the digital lifetime license of Microsoft Office Select between Microsoft Office Home Business for Mac or Office Professional Plus for Windows ーeach option is Read more 2022-04-13 16:51:12
海外TECH Engadget Governor Newsom faces accusations of meddling in Activision Blizzard lawsuit https://www.engadget.com/dfeh-governor-newsom-interference-allegation-165035369.html?src=rss Governor Newsom faces accusations of meddling in Activision Blizzard lawsuitA former lawyer with California s Department of Fair Employment and Housing has accused Governor Gavin Newsom of interfering with the agency s sexual harassment lawsuit against Activision Blizzard According to an email seen by Bloomberg DFEH assistant chief counsel Melanie Proctor said Tuesday she was resigning her position to protest the abrupt firing of Janette Wipper the watchdog s chief counsel “The Office of the Governor repeatedly demanded advance notice of litigation strategy and of next steps in the litigation Proctor writes in her resignation “As we continued to win in state court this interference increased mimicking the interests of Activision s counsel Proctor alleges Wipper was “abruptly terminated for attempting to protect the DFEH s independence According to the email the former chief counsel is considering “all avenues of legal recourse including a claim under California s Whistleblower Protection Act We ve reached out to the Office of Governor Newsom for comment News of the resignation comes little more than two weeks after a federal judge ordered Activision Blizzard to pay million to settle a US Equal Opportunity Commission lawsuit accusing the publisher of fostering a discriminatory workplace Before that complaint was filed California s fair employment agency launched its own lawsuit against Activision Blizzard following a two year investigation into sexual harassment allegations at the publisher The DFEH case is currently scheduled to go to trial in February but the allegations put forward by Proctor are likely to raise questions about the ultimate fate of the lawsuit 2022-04-13 16:50:35
海外TECH Engadget Apple signs an exclusive deal with Tom Hanks' production company https://www.engadget.com/apple-tv-plus-tom-hanks-playtone-deal-greyhound-163749926.html?src=rss Apple signs an exclusive deal with Tom Hanks x production companyApple is looking to build on the success of TV by locking in Tom Hanks production company to an exclusive multi year deal The agreement with Playtone covers series documentaries and unscripted projects Hanks is also set to star in a sequel to World War II movie Greyhound The thriller was one of the most watched projects on Apple TV according to Deadline Apple scooped up distribution rights to the film in Greyhound was supposed to be released theatrically but the COVID pandemic prevented it from being released in theaters There was a similar situation with Finch a post apocalyptic survival film in which Hanks character is accompanied on the road by his dog and a helper robot That movie hit Apple TV in November Apple has had a working relationship with Playtone which was founded by Hanks and producer Gary Goetzman for a few years It was announced in that the two companies and Steven Spielberg s Amblin Television were working on Masters of the Air a follow up series to Band of Brothers and The Pacific Production of the show has wrapped but a release date hasn t been announced Adding more shows and movies from Playtone to the library will bolster Apple TV which is on a great run It just became the first streaming service to win the Best Picture Oscar for CODA while sitcom Ted Lasso enjoyed huge success at last year s Emmys Recent shows like Severance and Slow Horses have earned acclaim as well 2022-04-13 16:37:49
海外TECH Engadget Meta reportedly plans to release its first AR glasses in 2024 https://www.engadget.com/meta-ar-glasses-2024-release-162237114.html?src=rss Meta reportedly plans to release its first AR glasses in Meta has been conspicuously eager to stake its future on augmented reality and the metaverse but a new report from The Verge might shed light on exactly what the social media giant hopes to deliver According to anonymous sources the company aims to launch its first AR glasses part of its Project Nazare initiative in You would see a quot lighter more advanced quot model in and a third iteration in The initial model would be independent of your phone but you would need a quot phone shaped device quot to handle the computing and rely on a CTRL Labs derived electrical pulse based wristband for control This first model is supposedly based on Android and could offer quot full quot AR with D visuals eye tracking an outward facing camera stereo audio a relatively wide field of view and a quot socially acceptable quot look The centerpiece feature would be communication with other people s quot holograms quot much like Meta portrayed in a video that accompanied its big rebranding last fall Chief executive Mark Zuckerberg apparently believes this will provide a more engrossing experience than simple video calling The tech firm might also hedge its bets by releasing a less exotic wearable A pair of phone paired smart glasses nicknamed Hypernova would show notifications through a small display Hypernova would also debut in Sales expectations are apparently modest for the first Project Nazare glasses Meta might only sell the eyewear in the quot low tens of thousands quot to enthusiasts and developers Zuckerberg however apparently sees them as crucial A former staffer told The Verge that Zuckerberg wants the AR glasses to represent an quot iPhone moment quot for Meta ーthat is a launch that shakes up the industry and redefines the company Whether or not they fulfill that ambition is another matter Meta has faced numerous setbacks including scrapped plans for a custom if Google Fuschia based OS and staff shuffles The prototype hardware also has its limitations While it s using cutting edge microLED projectors and waveguide technology it s about four times heavier than conventional glasses and musters just four hours of battery life Still it s not hard to see why Meta and Zuckerberg might pour so much energy into AR glasses Meta has an increasingly negative reputation due to privacy issues content controversies and regulatory pressure It s also struggling with flat user growth as competition like TikTok eats away at its core business The glasses will theoretically help Meta leave scandals behind and regain the innovator status it had in its early years 2022-04-13 16:22:37
海外TECH Engadget Amazon is rebranding IMDb TV as 'Freevee' https://www.engadget.com/amazon-imdb-tv-freevee-rebranding-160405693.html?src=rss Amazon is rebranding IMDb TV as x Freevee x Amazon s IMDb TV is rebranding Beginning April th the ad supported streaming service will be known as Freevee according to The Hollywood Reporter Amazon s Studios division told the outlet the new name is designed to better reflect how much it costs to access the platform As part of the rebranding Amazon said it would also invest more into original programming with a promise to offer percent more exclusive content than it does currently Among the shows Amazon plans to debut on the platform is High School a coming of age series from indie duo Tegan and Sara The company will announce additional details about Freevee s upcoming slate of originals at its NewFronts presentation on May nd We know from reporting from The Information nbsp that Amazon had been mulling a rebranding of IMDb TV since at least the start of last fall At the time company executives had reportedly considered names like “Zon along with “Free TV and “Free Streaming TV as potential options The thought among executives was that the existing name was too difficult for people to pronounce and was thereby hurting its popularity 2022-04-13 16:04:05
Cisco Cisco Blog About time! Migrating to the new IP67 industrial router https://blogs.cisco.com/internet-of-things/about-time-migrating-to-the-new-ip67-industrial-router deploy 2022-04-13 16:00:55
海外科学 NYT > Science How Nature Becomes a Casualty of War https://www.nytimes.com/2022/04/13/science/war-environmental-impact-ukraine.html environmental 2022-04-13 16:19:52
海外科学 NYT > Science A Wooden Knife Sharper Than Steel? Scientists Say So. https://www.nytimes.com/2022/04/11/us/hardened-wood-knife-history.html A Wooden Knife Sharper Than Steel Scientists Say So Knives are humanity s oldest tool dating back millions of years A group of scientists in Maryland have produced a version made of hardened wood which they say is sharper than steel 2022-04-13 16:44:06
金融 金融庁ホームページ 金融庁職員の新型コロナウイルス感染について公表しました。 https://www.fsa.go.jp/news/r3/sonota/20220413.html 新型コロナウイルス 2022-04-13 18:00:00
金融 金融庁ホームページ 令和4年3月に開催された業界団体との意見交換会において金融庁が提起した主な論点を公表しました。 https://www.fsa.go.jp/common/ronten/index.html 意見交換会 2022-04-13 17:00:00
金融 金融庁ホームページ 店頭デリバティブ取引情報について公表しました。(令和3年(2021年)3月末) https://www.fsa.go.jp/news/r3/shouken/20220413/20220413.html 取引情報 2022-04-13 17:00:00
金融 金融庁ホームページ 「共同データプラットフォームの構築に向けた基礎調査」報告書を公表しました。 https://www.fsa.go.jp/common/about/research/20220413/20220413.html 調査 2022-04-13 17:00:00
金融 金融庁ホームページ 「ソーシャルプロジェクトのインパクト指標等の検討に関する関係府省庁会議」(第2回)議事次第を公表しました。 https://www.fsa.go.jp/singi/social_impact/siryou/20220412.html 関係 2022-04-13 17:00:00
ニュース ジェトロ ビジネスニュース(通商弘報) 第1四半期の輸出入ともに前年同期比20%超の伸び、電子部品が好調維持 https://www.jetro.go.jp/biznews/2022/04/3ce979de985b05e8.html 前年同期 2022-04-13 16:10:00
ニュース BBC News - Home Sir David Amess murder: Ali Harbi Ali given whole-life sentence https://www.bbc.co.uk/news/uk-england-61094059?at_medium=RSS&at_campaign=KARANGA family 2022-04-13 16:32:50
ニュース BBC News - Home Ukraine War: Finland to decide on Nato membership in weeks says PM Marin https://www.bbc.co.uk/news/world-europe-61093302?at_medium=RSS&at_campaign=KARANGA russia 2022-04-13 16:28:40
ニュース BBC News - Home War in Ukraine: Separatist leaders targeted in new UK sanctions https://www.bbc.co.uk/news/uk-61093971?at_medium=RSS&at_campaign=KARANGA ukraine 2022-04-13 16:27:01
ニュース BBC News - Home Morad Tahbaz: Daughter of Iran detainee holds protest https://www.bbc.co.uk/news/uk-england-london-61099820?at_medium=RSS&at_campaign=KARANGA morad 2022-04-13 16:44:57
ニュース BBC News - Home Jersey court seizes $7bn of Roman Abramovich's assets https://www.bbc.co.uk/news/business-61098873?at_medium=RSS&at_campaign=KARANGA billionaire 2022-04-13 16:45:49
ニュース BBC News - Home Easter travel delays: Call to fine airlines over airport travel chaos https://www.bbc.co.uk/news/uk-61094387?at_medium=RSS&at_campaign=KARANGA shambles 2022-04-13 16:40:39
ニュース BBC News - Home Inflation: Five things driving up prices at record rates https://www.bbc.co.uk/news/business-61095186?at_medium=RSS&at_campaign=KARANGA furniture 2022-04-13 16:28:42
ニュース BBC News - Home Killing Eve: Liverpool costume show celebrates Jodie Comer's Villanelle https://www.bbc.co.uk/news/uk-england-merseyside-61085573?at_medium=RSS&at_campaign=KARANGA killing 2022-04-13 16:35:32
海外TECH reddit All Stars 7 Cast Ruveal https://www.reddit.com/r/rupaulsdragrace/comments/u2tpku/all_stars_7_cast_ruveal/ All Stars Cast Ruveal submitted by u TheNewPoetLawyerette to r rupaulsdragrace link comments 2022-04-13 16:03:58

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)