python |
Pythonタグが付けられた新着投稿 - Qiita |
Qiita API v2を使ってContributionっぽいものを計算してみた |
https://qiita.com/tetutaro/items/0106728f534b349190ce
|
QiitaAPIvで、多分Contributionって自分の投稿数とか計算してるんだろうと。 |
2021-10-10 02:49:15 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
p5.js と anime.js を組み合わせた Tweenアニメーション |
https://qiita.com/youtoy/items/361282f1113d88ff5f05
|
animejsを使うanimejsについて以下の公式ページの説明によると、animejsは「軽量さと、シンプルでパワフルなAPI」を売りにしているライブラリのようです。 |
2021-10-10 02:29:55 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
自分が試そうと思っているダウンサンプリングの合理性を伺いたい |
https://teratail.com/questions/363648?rss=all
|
自分が試そうと思っているダウンサンプリングの合理性を伺いたい今私が行っていることは、ダウンサンプリングを行っても音声データによる機械学習の精度は落ちないのかの検証を行なっています。 |
2021-10-10 02:56:00 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
最近傍探索無しで対応点がわかっている前提でICPアルゴリズムを実装させたいです |
https://teratail.com/questions/363647?rss=all
|
|
2021-10-10 02:44:20 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
何を処理しているのかわからない |
https://teratail.com/questions/363646?rss=all
|
何を処理しているのかわからない下記の処理が何を行なっているのかわからないです。 |
2021-10-10 02:38:20 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Android StudioでDesignエディタとCompoent Treeが表示されない |
https://teratail.com/questions/363645?rss=all
|
AndroidStudioでDesignエディタとCompoentTreeが表示されないスクショのようにDesignエディタにツールマーク個が表示されるのみでコンポーネントツリーはNothingnbsptonbspshowになっています。 |
2021-10-10 02:22:13 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
PythonライブラリfastFMのハイパーパラメータの調節をしたいです。SGD(勾配降下法)ソルバーを使用しています。 |
https://teratail.com/questions/363644?rss=all
|
現在fastFMの勾配降下法SGDソルバーを用いたいと思っていますが、ハイパーパラメータの調節の仕方が分かりません。 |
2021-10-10 02:21:20 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
非同期処理・並行処理のコードでのマルチスレッドの動きを確認したい。 |
https://teratail.com/questions/363643?rss=all
|
非同期処理・並行処理のコードでのマルチスレッドの動きを確認したい。 |
2021-10-10 02:07:11 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
線分とその線分上の点から垂線をひき、曲線との長さを求める方法 |
https://teratail.com/questions/363642?rss=all
|
|
2021-10-10 02:04:06 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
Ruby on Jetsでサーバーレス |
https://qiita.com/ryooo321/items/11198e564f3a2081730f
|
Jetsはデフォルトでは「ServerlessGems」というサービスを使っていて、このサービスからLambda用にコンパイルされたgemコードをzipでダンロードしてLambdaに展開する作りになっています。 |
2021-10-10 02:28:21 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
Ruby on Jetsでサーバーレス |
https://qiita.com/ryooo321/items/11198e564f3a2081730f
|
Jetsはデフォルトでは「ServerlessGems」というサービスを使っていて、このサービスからLambda用にコンパイルされたgemコードをzipでダンロードしてLambdaに展開する作りになっています。 |
2021-10-10 02:28:21 |
海外TECH |
DEV Community |
Peregrine Rewrite - The python-like language that's as fast as C |
https://dev.to/ethanolchik/peregrine-rewrite-the-python-like-language-that-s-as-fast-as-c-1bfp
|
Peregrine Rewrite The python like language that x s as fast as CHey guys My name is Ethan and I m one of Peregrine developers Some of you may already know what Peregrine is some of you don t but this article is going to explain the current state at where Peregrine is at What is PeregrineIf you know Python you know how easy it is However it also comes with a big downgrade Python is slow and I m pretty sure every python developer knows this by now This is kind of annoying That s where Peregrine comes in Me and other friends have been working on Peregrine for the past few months starting as a hobby project Peregine s syntax is very similar to Python s and it gets trans compiled to C thus making it as fast as C Update on Peregrine s current status NamePeregrine s name has been getting more popular ever since I posted my last article and a lot of things has been changed The most noticeable thing that has changed is the name A lot of people recommended a name change from Swallow so it is now called Peregrine which we think suits the language more RewriteYou probably already know this from the title Peregrine is getting a rewrite The Lexer is already complete We are going to rebuild the parser and codegen so it will be more efficient and hopefully faster This is all being done on a different branch Peregrine as a scripting languagePeregrine uses tcc as a secondary backend to allow it to be used as a scripting language It uses vlibtcc which is a V wrapper for libtcc It was implemented yesterday and is still at a very early stage Some features do not work with it so it is not recommended to use it at this stage however it will be updated and fixed in the rewrite FAQ Q Is Peregrine a hobby project A As of Peregrine is no longer a hobby project Q Can I join the developer team A Peregrine is not in need of new Developers at the moment however you can always contribute to the repository Q Is there a discord server A Yes you can join it by clicking here Q Why not contribute to Nim or Julia A Peregrine has different goals than Nim and Julia They also achieve different things in different ways Q Will all python modules be compatible with Peregrine A Yes that s the plan It will take a long time to implement as it is a difficult task however it will be there Got any more questions that you would like to be answered You can open a new discussion that discusses your questions You can also email saptakbhoumik gmail com or join our discord server ConclusionPeregrine is planned to release version sometime in March so make sure to show some support by starring the repo and make sure to press on the Watch button so you don t miss any updates We would greatly appreciate any contributions so if you find something that you can improve open a pull request You can also check out our open issues Please make sure you contribute to the rewrite branch as we are going to replace the main branch with the rewrite Thanks so much for reading lt |
2021-10-09 17:31:42 |
海外TECH |
DEV Community |
Simple CRUD App with Express.js, SQLite & MVC pattern |
https://dev.to/dejansdev/simple-crud-app-with-express-js-sqlite-mvc-pattern-4nd8
|
Simple CRUD App with Express js SQLite amp MVC patternDISCLAIMER This is not the best way or should do blog post instead I will just try to share my experience and what I find to work out The goal is to create an application that will implement CRUD operations in Node js using the Express js framework and SQLite database using the MVC design pattern It will be a simple To Do List Application in which the user can Create Read Update and Delete a task The application is available on the following link To Do Application and the complete code is available on the GitHub repository Content Getting startedTemplate engineRoutesDatabaseMVC architectural patternMore setupCreate taskDelete and update taskData validationConclusion Getting startedThe first step is to create a new directory and initialize the project using a terminal To Do Application npm init yAfter that it is necessary to install the project dependencies To Do Application npm install express sqlite ejs express validatorexpress is the most popular Node js framework and it enables fast and easy web application development sqlite is simply a module that allows interaction with the SQLite database ejs is one of the many templating engines to choose from essentially allows the generation of HTML markup using javascript express validator is a module that gives the ability to validate entries so that for example the end user could not enter an empty task or exceed the allowed number of characters The main entry point of the application is the app js file and it is located in the root directory app js Load modulesconst express require express Create express applicationconst app express Listen on port for connectionsapp listen gt console log Server started and listening at http localhost Respond when a GET request is made to the index pageapp get request response gt response send To Do Application require function loads the Express module and puts it in a variable with the same name Express function express puts a new Express application inside the app variable listen method simply listening for incoming requests on a defined port Express method app get handle GET requests and when they match with the defined route the method calls the callback function which takes a request and a response object as arguments Then express send method returns the string To Do Application To start the application it is necessary to run the following command in the terminal To Do Application node appIf everything is ok the following text will appear Server started and listening at http localhost While in the browser at http localhost the result will be the string To Do Application When Node js applications are developed and some changes are made to the code to see their effect it is necessary to restart the server which is very annoying It is much easier to install a tool Nodemon that will monitor any changes in the code and restart the server automatically To Do Application npm install g nodemon To Do Application nodemon app Template engineThe template engine is used to create HTML templates using HTML syntax but also allows the injection of dynamic data and logic The first step is to define the engine and the directory where the templates will be located in the app js file Load modules const path require path Set view engine and views directoryapp set view engine ejs app set views path join dirname views The set method is used to configure application behavior by assign setting names to value It is also necessary to create directory views in the root directory The path is a core Node js module and does not need to be installed In this case join method is used to connect Node js environment variable dirname with directory views It is defined from where the template files will be rendered and which template engine will be used For now three files will be defined in the views directory index ejsheader ejsfooter ejsThe visual look of the application will be created with the help of the Bootstrap framework and explaining this framework goes beyond the scope of this article index ejs lt include header gt lt div class container my gt lt h gt Index page lt h gt lt div gt lt include footer gt lt is just EJS tag for injection unescaped value into the template and include is command for including other ejs files in this case header ejs and footer ejs header ejs lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta http equiv X UA Compatible content IE edge gt lt meta name viewport content width device width initial scale gt lt title gt To Do Application lt title gt lt Bootstrap CSS gt lt link href dist css bootstrap min css rel stylesheet integrity sha EVSTQN azprGAnmQDgpJLImNaoYzztcQTwFspdyDVohhpuuCOmLASjC crossorigin anonymous gt lt head gt lt body gt footer ejs lt Bootstrap Bundle with Popper gt lt script src dist js bootstrap bundle min js integrity sha MrcWZMFYlzcLANl NtUVFsAMsXsPUyJoMpYLEuNSfAP JcXn tWtIaxVXM crossorigin anonymous gt lt script gt gt lt body gt lt html gt And this is how the index html file will be displayed to the end user header ejs index ejs footer ejs index ejs lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta http equiv X UA Compatible content IE edge gt lt meta name viewport content width device width initial scale gt lt title gt To Do Application lt title gt lt Bootstrap CSS gt lt link href dist css bootstrap min css rel stylesheet integrity sha EVSTQN azprGAnmQDgpJLImNaoYzztcQTwFspdyDVohhpuuCOmLASjC crossorigin anonymous gt lt head gt lt body gt lt div class container my gt lt h gt Index page lt h gt lt div gt lt Bootstrap Bundle with Popper gt lt script src dist js bootstrap bundle min js integrity sha MrcWZMFYlzcLANl NtUVFsAMsXsPUyJoMpYLEuNSfAP JcXn tWtIaxVXM crossorigin anonymous gt lt script gt gt lt body gt lt html gt RoutesRoutes determine how the application will respond to different end user requests One route is already defined in the application and using the get method if the end user requests it the application will execute the handler function and show the string To Do Application For the app js file to remain clean and readable the routes will be defined in a separate taskRoutes js file which will be located in the routes directory taskRoutes js Load modulesconst express require express Create route handlerconst router express Router Respond when a GET request is made to the index pagerouter get request response gt response render index Export routermodule exports router The express Router method is used to create a new instance of the router object router that will handle incoming requests And instead calling send method on response object method render will render index ejs file The last line just exporting the router so that it could be used in the app js file app js Load modules const taskRoutes require routes taskRoutes Application routesapp use taskRoutes DatabaseThe first step is to install the SQLite database and in Linux operating system it is very simple To Do Application sudo apt install sqliteNow create a new directory database where the database will be located navigate within it and create the SQLite database To Do Application database sqlite To Do Application DatabaseWhen the database is created it is necessary to create a table and fill it with data sqlite gt CREATE TABLE Tasks gt Task TEXT NOT NULL gt Status TEXT NOT NULL gt Task Id INTEGER PRIMARY KEY AUTOINCREMENT sqlite gt INSERT INTO Tasks VALUES Task One Completed Task Two Canceled Task Three In progress sqlite gt quit Sometimes it s easier to create and design a database visually and DB Browser for SQLite is a great software for that purpose The database connection to the application will be made in the database js file database js Load modulesconst sqlite require sqlite verbose const path require path Connect with SQLite databaseconst db path path join dirname database To Do Application Database const appDatabase new sqlite Database db path sqlite OPEN READWRITE err gt if err console error err message console log Successful connected to the database Export database objectmodule exports appDatabase There is no more need to explain loading modules or exporting modules In the variable db path is simply defined path to the database in the database directory In this case console log db path will give the next output home my computer name To Do Application database To Do Application DatabaseInside Database method as arguments are entered database information such as the path to the database opening mode a callback function and result is the database object stored in appDatabase variable The callback function just checks for a connection error and depending on the results prints the appropriate message in the console This is the current status of the project tree MVC architectural patternThis is a very trivial and simple application and therefore the organization of the code itself is not a problem but to understand how to organize the code the MVC pattern will be applied MVC stands for Model View Controller and represents one of the most popular approaches to application architecture Model is the part of the application that works with data View represents everything the end user will see Controller is responsible for the logic of the application it requests data from the Model and delivers it in View to render the appropriate page to the end user It is necessary to create the following directory models and inside it the file taskModels js directory controllers and inside it the file taskControllers js taskRoutes js Load modulesconst express require express const taskController require controllers taskControllers Create route handlerconst router express Router GET Index Pagerouter get taskController task index Export routermodule exports router taskControllers js Load modulesconst taskModel require models taskModels Index page controllerfunction task index request response taskModel getTasks queryResult gt console log queryResult response render index tasks queryResult Export controllersmodule exports task index taskModels js Load modulesconst database require database database Get all tasks from databaseconst getTasks callback gt const sql SELECT FROM Tasks database appDatabase all sql error rows gt if error console error error message callback rows Export modelsmodule exports getTasks What exactly is going on here In taskRoutes js get method on router object as second argument call task index function from taskController js task index function as before has two parameters request and response but this time also calls function getTasks from taskModel js getTasks function has a specified arrow function with parameter queryResult as an argument After appDatabase object method all get result that result will be stored in queryResult an error or rows from database and with help of render method available for use in index ejs index ejs lt include header gt lt div class container gt lt h class mt mb gt To Do List lt h gt lt table class table gt lt thead gt lt tr gt lt th scope col gt Task lt th gt lt th scope col gt Status lt th gt lt th class d print none gt Actions lt th gt lt tr gt lt thead gt lt tbody gt lt for const task of tasks gt lt tr gt lt td gt lt task Task gt lt td gt lt td class status gt lt task Status gt lt td gt lt td class d print none gt lt a class btn btn sm btn warning gt Update lt a gt lt a class btn btn sm btn danger gt Delete lt a gt lt td gt lt tr gt lt gt lt tbody gt lt table gt lt div gt lt include footer gt tasks queryResult this part enables usage of queryResult inside the index ejs with variable name tasks ejs tags lt gt are for control flow no output and lt gt output value into the template This code simply loops through each row and prints the values in a table And this is the current state of the project tree More setupTo serve static files such as CSS files and JavaScript files the express middleware function will be used app js Serve static filesapp use express static path join dirname public Now it is necessary to create a public directory and inside it a css directory with a custom css file and a js directory with a main js file Access to these files is now possible via url css custom css or js main js The custom css file is used to overriding some Bootstrap styles and the main js file is used to color tasks depending on their status They are not shown in this blog post but they can be easily accessed via the GitHub repository Small changes were made to the header ejs file due to the visual appearance header ejs lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta http equiv X UA Compatible content IE edge gt lt meta name viewport content width device width initial scale gt lt title gt To Do Application lt title gt lt link rel icon href favicon favicon svg type image x icon gt lt link href dist css bootstrap min css rel stylesheet integrity sha EVSTQN azprGAnmQDgpJLImNaoYzztcQTwFspdyDVohhpuuCOmLASjC crossorigin anonymous gt lt link rel stylesheet href css custom css gt lt head gt lt body gt lt nav class navbar navbar expand lg navbar dark bg dark gt lt div class container gt lt a class navbar brand href gt To Do Application lt a gt lt button class navbar toggler type button data bs toggle collapse data bs target navbarSupportedContent aria controls navbarSupportedContent aria expanded false aria label Toggle navigation gt lt span class navbar toggler icon gt lt span gt lt button gt lt div class collapse navbar collapse me auto id navbarSupportedContent gt lt ul class navbar nav mb mb lg ms auto gt lt li class nav item gt lt a class nav link href gt Home lt a gt lt li gt lt li class nav item gt lt a class nav link gt Create a task lt a gt lt li gt lt li class nav item gt lt a class nav link href about gt About lt a gt lt li gt lt ul gt lt div gt lt div gt lt nav gt In footer ejs is inserted following line lt script src js main js gt lt script gt about ejs page was created with the appropriate route and controller about ejs lt include header gt lt div class container my gt lt h class my gt Simple CRUD Application with Express js and SQLite database lt h gt lt p gt The application is a simple To Do List which implements CRUD operations in the Node js javascript runtime environment lt p gt lt div gt lt include footer gt taskRoutes ejs GET About Pagerouter get about taskController task about taskControllers ejs About page controllerconst task about request response gt response render about Export controllersmodule exports task about The application currently looks like this And the project tree looks like this Create taskCurrently the application just reads the results from the database and displays them in a table To be able to add new tasks it is necessary to create a new view create ejs create ejs lt include header gt lt div class container gt lt h class mt mb gt Create a new task lt h gt lt form action task create method post gt lt div class mb gt lt label for inputTask gt Task lt label gt lt input autofocus type text class form control shadow none mb id inputTask name Task gt lt label for inputStatus gt Status lt label gt lt select disabled class form select shadow none id inputStatus name Status gt lt option value In progress selected gt In progress lt option gt lt select gt lt div gt lt button type submit class btn btn primary gt Add lt button gt lt a class btn btn outline dark cancel href gt Cancel lt a gt lt form gt lt div gt lt include footer gt And it will look something like this Adding routes to taskRoutes is also pretty straightforward taskRoutes js GET POST Create pagerouter get task create taskController task create get router post task create taskController task create post In the case of the controllers the situation is a little different taskControllers js Create task page controllers GETfunction task create get request response response render create POSTfunction task create post request response const task request body Task const status In progress taskModel createTask task status result gt console log result response redirect Export controllersmodule exports task create get task create post task create get controller has the task of just rendering create ejs file However when the end user wants to add a new task the task create post function enters the scene The variable task with help of request property body and input name Task store value of user input taskModels js Create new taskconst createTask task status callback gt const sql INSERT INTO Tasks Task Status VALUES task status database appDatabase run sql error row gt if error callback error message const successMessage The task was entered successfully callback successMessage Export modelsmodule exports createTask Now with the help of the variables task and status the function createTask completes the query After the appDatabase object method run stores the result in the database the createTask function in callback loads either an error or a sucessMessage and forwards it back to taskController variable result For this to work at all the app js file needs to include the next piece of code To recognize the incoming request object as strings or arraysapp use express urlencoded extended true express urlencoded is a method inbuilt in express to recognize the incoming Request Object as strings or arrays Delete and update taskDelete and update task processes are very similar and do not differ much from the create process The first step is to add the appropriate href tag to the existing links in the index ejs file index ejs lt a class btn btn sm btn warning href task update lt task Task Id gt gt Update lt a gt lt a class btn btn sm btn danger href task delete lt task Task Id gt gt Delete lt a gt With the help of ejs tags and task Task Id link to each individual delete task update task view will be defined by a unique id delete ejs lt include header gt lt div class container gt lt h class mt mb gt Delete task lt h gt lt form action task delete lt task Task Id gt method post gt lt div class mb gt lt label for inputTask gt Task lt label gt lt input readonly autofocus type text class form control shadow none mb id inputTask name Task value lt task Task gt gt lt label for inputStatus gt Status lt label gt lt select disabled class form select shadow none aria label Default select example id inputStatus name Status gt lt option value In progress selected gt In progress lt option gt lt option value Completed gt Completed lt option gt lt option value Canceled gt Canceled lt option gt lt select gt lt div gt lt button type submit class btn btn danger gt Delete lt button gt lt a class btn btn outline dark cancel href gt Cancel lt a gt lt form gt lt div gt lt include footer gt update ejs lt include header gt lt div class container gt lt h class mt mb gt Update task lt h gt lt form action task update lt task Task Id gt method post gt lt div class mb gt lt label for inputTask gt Task lt label gt lt input autofocus type text class form control shadow none mb id inputTask name Task value lt task Task gt gt lt label for inputStatus gt Status lt label gt lt select class form select shadow none aria label Default select example id inputStatus name Status gt lt option value In progress selected gt In progress lt option gt lt option value Completed gt Completed lt option gt lt option value Canceled gt Canceled lt option gt lt select gt lt div gt lt button type submit class btn btn warning gt Update lt button gt lt a class btn btn outline dark cancel href gt Cancel lt a gt lt form gt lt div gt lt include footer gt The routes are also very similar taskRoutes js GET POST Delete Pagerouter get task delete id taskController task delete get router post task delete id taskController task delete post GET POST Update Pagerouter get task update id taskController task update get router post task update id taskController task update post The links contains id variable it is specified in index ejs links with lt task Task Id gt and will be used using request params id in taskControllers js taskControllers js Delete task page controllers GETconst task delete get request response gt const id request params id taskModel getTask id result gt console log result response render delete task result POSTconst task delete post request response gt const id request params id taskModel deleteTask id gt response redirect Update task page controllers GETconst task update get request response gt const id request params id taskModel getTask id result gt response render update task result POSTconst task update post request response gt const task request body Task const status request body Status const id request params id taskModel updateTask task status id gt response redirect Export controllersmodule exports task delete get task delete post task update get task update post Simply the controllers task delete get and task update get use the getTask function and provide the already mentioned id as an argument The task update post controller must provide two more arguments task and status in addition to id taskModels js Get taskconst getTask id callback gt const sql SELECT FROM Tasks WHERE Task Id id database appDatabase get sql error row gt if error callback error message callback row Delete task const deleteTask id callback gt const sql DELETE FROM Tasks WHERE Task Id id database appDatabase run sql error row gt if error callback error message const successMessage The task was successfully deleted callback successMessage Update task const updateTask task status id callback gt let sql UPDATE Tasks SET Task task Status status WHERE Task ID id database appDatabase run sql error row gt if error callback error message const successMessage The task was successfully updated callback successMessage Export modelsmodule exports getTask deleteTask updateTask The logic in these functions is identical to that in the createTask function So the functions will use the id task and status arguments to fill in the sql query and after the appDatabase methods get the results or error place them in the callback and allow the functions in taskControllers to use them Data validationIt is currently possible to enter any task even one without a single letter or with letters To prevent such things an express validation module will be used The first step is to create a validation directory and a taskValidator js file in it taskValidator js Load function checkconst check require express validator Export function validateTaskexports validateTask check Task isLength min max withMessage The task must have between and characters Very simply the check function is loaded from the express validator module and used in the validateTask function which is also exported at the same time Many different restrictions can be set but only the isLength is used here So the number of letters must be between and and if it is not the withMessage will return a warning validateTask function must be used inside the taskRoutes js file taskRoutes js const taskValidator require validation taskValidator router post task create taskValidator validateTask taskController task create post router post task update id taskValidator validateTask taskController task update post It is referred to as an argument in post methods for creating and updating a task It is necessary to make some changes in taskControllers file taskControllers js const validationResult require express validator Create task page controllers GETfunction task create get request response response render create errors POSTfunction task create post request response const errors validationResult request if errors isEmpty return response render create errors errors mapped const task request body Task const status In progress taskModel createTask task status result gt console log result response redirect Update task page controllers GETconst task update get request response gt const id request params id taskModel getTask id result gt response render update task result errors POSTconst task update post request response gt const errors validationResult request if errors isEmpty return response render update task request body errors errors mapped const task request body Task const status request body Status const id request params id taskModel updateTask task status id gt response redirect The validationResult method extracts any validation errors from the request object and places them in the result object in this case the errors variable After that it is simply checked for errors and if there are any they are forwarded to the views to be displayed create ejs update ejs lt input autofocus type text class form control shadow none mb id inputTask name Task gt lt if errors Task gt lt div class text danger mb gt lt errors Task msg gt lt div gt lt gt ConclusionWhen you are a beginner it is very difficult to make any application and even harder to explain how you managed it So when you find some mistake which there are many of them whether it is not understanding the concept wrong code expression or just grammar please correct me in the comment I will be very grateful |
2021-10-09 17:27:46 |
海外TECH |
DEV Community |
Build a Free NextJS Commenting System using Github [Part 2/2] |
https://dev.to/pandasekh/build-a-free-nextjs-commenting-system-using-github-part-2-2-39oo
|
Build a Free NextJS Commenting System using Github Part In the previous article we built the basic interface for our commenting system Now we need to program the API endpoints to communicate with Github s API in order to save and retrieve the comments Save CommentsLet s start by saving some comment In the pages api path let s create a new folder named comments inside of which we ll create another folder named save and finally inside that a file named slug ts Of course you can change the naming as you wish You can also create a single path for example api comment and then call different functions depending on the method used To save a comment we need to Check if the comment has a parent or not If it has a parent then we need to append this comment to the parentElse we can insert this comment into the array of comments we might already have In both cases we first need to request the data we already have modify it and then update the repo Prepare the dataLet s start from a basic NextJS API function import type NextApiRequest NextApiResponse from next export default req NextApiRequest res NextApiResponse Promise lt void gt gt return new Promise async resolve gt Our code here Inside this function we ll first prepare the data sent to the API Import the modules we needimport encrypt from lib encryption crypto import Comment from interfaces Comment const newComment Comment date req body date parentCommentId req body parentCommentId id req body id username req body username email encrypt req body email as string content req body content children req body children const slug req query Merge parent and child commentsWe need a function that will merge a child comment with its parent Because we work with a basic Javascript object we ll needto use recursion to find the actual parent function appendToParent comments Array lt Comment gt newComment Comment Array lt Comment gt comments forEach comment gt if comment id newComment parentCommentId comment children push newComment else if comment children amp amp comment children length gt comment children appendToParent comment children newComment return comments Update the dataNow we have the new comment data so we need to get the previous data and modify it To communicate with Github s API I used the official library octokit request From now on we ll work inside a try block import request from octokit request try Here we request the document in JSON vnd github v json because with raw we don t have the file sha const prevComments await request we request a GET on this path GET repos owner repo contents path headers github private token authorization token process env GITHUB TOKEN how we want the file In this case we want a JSON accept application vnd github v json Owner of the repo owner PandaSekh Name of the repo repo my blog repo the path I save the comments in a folder named comments in the root path comments slug json the branch ref prod catch e gt We accept and will handle a because not every post will have comments For any other error statusCode throw an error if e status throw new Error e We ll add more code here Now that we have the new comment and if present the previous comments we can merge them and save the updated data How we do this depends on the presence of previous comments Still in the try block if prevComments is undefined there are no previous comments This is the first possibility if prevComments get the data from the base encoded content and parse it as JSON let data JSON parse Buffer from prevComments data content base toString ascii Save the sha We need it to update the file later on const sha prevComments data Merge the new comment to the parent if it has one Else simply add it to the array if newComment parentCommentId data appendToParent data newComment Merge the parent and the child comment else data push newComment Save the updated comments to Github const update await request PUT repos owner repo contents path headers github private token authorization token process env GITHUB TOKEN how we want the file In this case we want a JSON accept application vnd github v json Owner of the repo owner PandaSekh Name of the repo repo my blog repo the path I save the comments in a folder named comments in the root path comments slug json branch prod message Updated comment on post slug Git commit message sha The sha we saved before content Buffer from JSON stringify data ascii toString base res status json JSON stringify update resolve And now we write the else in case there were no comments before the new one else const data newComment Save the new comment to Github const update await request PUT repos owner repo contents path headers github private token authorization token process env GITHUB TOKEN how we want the file In this case we want a JSON accept application vnd github v json Owner of the repo owner PandaSekh Name of the repo repo my blog repo the path I save the comments in a folder named comments in the root path comments slug json branch prod message New comment on post slug Git commit message content Buffer from JSON stringify data ascii toString base res status json JSON stringify update resolve catch e res status json e resolve Full API methodBelow the complete API method for reference import request from octokit request import type NextApiRequest NextApiResponse from next import Comment from interfaces Comment import encrypt from lib encryption crypto function appendToParent comments Array lt Comment gt newComment Comment Array lt Comment gt comments forEach comment gt if comment id newComment parentCommentId comment children push newComment else if comment children amp amp comment children length gt comment children appendToParent comment children newComment return comments export default req NextApiRequest res NextApiResponse Promise lt void gt gt return new Promise async resolve gt const newComment Comment date req body date parentCommentId req body parentCommentId id req body id username req body username email encrypt req body email as string content req body content children req body children const slug req query try const prevComments await request GET repos owner repo contents path headers authorization token process env GITHUB TOKEN accept application vnd github v json owner PandaSekh repo my blog repo path comments slug json ref prod catch e gt if e status throw new Error e if prevComments let data JSON parse Buffer from prevComments data content base toString ascii const sha prevComments data if newComment parentCommentId data appendToParent data newComment else data push newComment const update await request PUT repos owner repo contents path headers authorization token process env GITHUB TOKEN accept application vnd github v json owner PandaSekh repo my blog repo path comments slug json branch prod message Updated comment on post slug sha content Buffer from JSON stringify data ascii toString base res status json JSON stringify update resolve else const data newComment const update await request PUT repos owner repo contents path headers authorization token process env GITHUB TOKEN accept application vnd github v json owner PandaSekh repo my blog repo path comments slug json branch prod message New comment on post slug content Buffer from JSON stringify data ascii toString base res status json JSON stringify update resolve catch e res status json e resolve Get CommentsThe method to retrieve comments depends on how you want to build your website As I expected very few comments and I wanted the website to be fully static I get the comments in a GetStaticProps method inside the slug tsx page Every new comment triggers a re deploy and rebuild the site This is not the best approach if you expect a moderate amount of comments in that case it might be a better idea to use GetServerSideProps This method will vary depending on your needsexport async function getStaticProps params params slug string Promise lt props Props gt const comments await getComments params slug return props comments async function getComments slug string Promise lt Array lt Comment gt null gt try const comments await request GET repos owner repo contents path headers authorization token process env GITHUB TOKEN accept application vnd github v raw owner PandaSekh repo your blog repo path comments slug json ref prod return JSON parse comments data as unknown as string catch e return null That s all This is how I built my free static commenting system If you have any doubts you can comment here or write me on my social media |
2021-10-09 17:23:54 |
海外TECH |
DEV Community |
Build a Free NextJS Commenting System using Github [Part 1/2] |
https://dev.to/pandasekh/build-a-free-nextjs-commenting-system-using-github-part-1-2-225e
|
Build a Free NextJS Commenting System using Github Part In a recent project of mine built with NextJS I wanted to implement a simple but functional commenting system While I already did a commenting system it was using an external CMS Sanity io Sanity is great but for this project I had two different goals I wanted it to be totally free without limitsI wanted total control over the dataThe solution I came up with was using Github as a database for the comments Github s API allows us to make commits save comments and retrieve files from a repository get the comments Please note that this is a great solution for a cheap and low traffic website otherwise it s just better to use a database Anyway this was a fun little challenge The features of this commenting system are It s totally freeInfinite child commentsCan have any parameters you want Profile pictures date of comment etc Privacy is maintained even if the repo is publicData is yours and easily manageable it s just a JSON It this series of articles I ll illustrate how I managed to use Github as my comments database for a NextJS and typescript commenting system Basic UtilsFirst of all we need to create some basic utils that we ll use later on Email EncryptionIn this series of articles I ll build a commenting systems that requires an email and as such I ll encrypt just that You can skip this step if you don t need to encrypt sensitive data To protect the users privacy I ll use the crypto library of Node js with the AES algorithm import crypto from crypto const algorithm aes ctr const iv crypto randomBytes const encrypt text string Hash gt const secretKey process env CRYPTO SECRET KEY Random secret key if secretKey throw new Error No secret const cipher crypto createCipheriv algorithm crypto createHash sha update String secretKey digest base substr iv const encrypted Buffer concat cipher update text cipher final return iv iv toString hex content encrypted toString hex const decrypt hash Hash string gt const secretKey process env CRYPTO SECRET KEY if secretKey const decipher crypto createDecipheriv algorithm crypto createHash sha update String secretKey digest base substr Buffer from hash iv hex const decrpyted Buffer concat decipher update Buffer from hash content hex decipher final return decrpyted toString throw Error No secret key export encrypt decrypt export interface Hash iv string content string The details of the crypto library can be found in the official docs The important thing to understand is that we pass to the encrypt method a string the email and it returns an Hash object which we ll save in the comment JSON instead of the email itself When we need the user s email we call the decrypt method InterfacesAs we re working with Typescript We first need to create the interfaces of the objects we ll be using Comment Interface IComment tsimport Hash from lib encryption crypto That s the Hash interface we created beforeexport default interface Comment Mandatory parameters id string Unique id of the comment content string The comment itself children Array lt Comment gt Children of this comment parentCommentId string Optional parent comment id These are optionals based on one s needs username string date Date email Hash Design the Comments SectionStarting from the basics we need a simple comments section I won t cover css as it s out of the scope of this articles Single Comment ComponentIn our components folder let s create a folder Comments and a component called Comment tsx This component will render a single comment and its children This structure is based on what I needed but can be changed accordingly import dynamic from next dynamic import useEffect useRef useState from react import IComment from interfaces Comment import decrypt Hash from lib encryption crypto export default function Comment comment slug comment IComment slug string JSX Element const reply setReply useState false This state will manage the reply form const AddComment dynamic gt import AddComment No need to import this component if the user won t click on Reply return lt div If this is a child component we apply a custom class This is useful to offset child comments from the parent and make a hierachy effect className comment parentCommentId child gt lt div gt lt div gt lt span gt comment date lt span gt lt span gt comment username lt span gt lt div gt lt div gt lt p gt comment content lt p gt lt button type button onClick gt setReply reply gt Reply lt button gt If the reply button is clicked render the lt AddComment gt form that we ll build next reply amp amp lt AddComment slug slug parentCommentId comment id gt If there is any child comment render those too comment children amp amp comment children map child index gt lt Comment comment child slug slug key index gt lt div gt Add Comment FormThen we need to create the AddComment component that will render a form to create new comments or replies import useEffect useState from react import DeepMap FieldError SubmitHandler useForm UseFormHandleSubmit UseFormRegister from react hook form import getKey from lib utils import IComment from interfaces Comment export default function AddComment slug parentCommentId slug string parentCommentId string JSX Element const commentSent setCommentSent useState false const isLoading setIsLoading useState false const register handleSubmit reset formState errors useForm lt FormData gt function sendData data FormData setIsLoading true Prepare the new comment data const newComment IComment date new Date toLocaleDateString en US p parentCommentId parentCommentId undefined If this new comment has a parent put the id here id generateUUID generate the unique id here however you want username data username Anonymous email data email content data content children Send the new comment to an API endpoint we ll build later It s important to pass the slug parameter and I m doing that with a path parameter fetch api comments save slug method POST headers content type application json body JSON stringify newComment then res gt if res ok Comment was sent setCommentSent true setIsLoading false reset username email content catch gt setCommentSent true setIsLoading false handle the error const onSubmit SubmitHandler lt FormData gt data gt sendData data return lt gt isLoading amp amp commentSent amp amp lt CommentForm onSubmit onSubmit register register handleSubmit handleSubmit errors errors gt isLoading amp amp lt p gt Loading lt p gt lt p gt The component is a basic react hook form form and it can be done however you want depending on your specific needs Full Comment BlockThis component is the one that will be imported in every post CommentBlock will require two props slug and comments slug is the slug of the post we re in and will be used to create new comments while comments is an array of comments retrieved in the page using GetStaticProps or GetServerSideProps depending on our preference import dynamic from next dynamic import useState from react import IComment from interfaces Comment export default function CommentBlock slug comments slug string comments Array lt IComment gt null JSX Element Dynamically import everything to reduce the first load of a page Also there might be no comments at all const Comment dynamic gt import Comment const AddComment dynamic gt import AddComment const showAddComment setShowAddComment useState false return lt div gt lt p gt Comments lt p gt comments comments map c gt lt Comment comment c key getKey slug slug gt lt p gt There are no comments lt p gt showAddComment lt AddComment slug slug gt lt div gt lt button type submit onClick gt setShowAddComment true gt Comment lt button gt lt div gt lt div gt ConclusionsWe just finished preparing the basic React structure of the commenting systems Right now we just need to import the CommentBlock component where we want to display comments In the next article we ll build the APIs that will interface with Github in order to store and retrieve the comments |
2021-10-09 17:23:33 |
海外TECH |
DEV Community |
What makes languages "fast" or "slow"? |
https://dev.to/vibalijoshi/what-makes-languages-fast-or-slow-3l44
|
What makes languages quot fast quot or quot slow quot In his article Naser Tamimi compares C and Python and this is what he observed As you can see Python is much slower than C but in reality no programming language is fast or slow The machine code generated by the programming language is either simple or complex All Languages have the same goalThe low level languages like the machine code displayed in binary digits runs very fast because no translation program is required for the CPU but it very inconvenient to write High Level Languages HLL such as C and JavaScript provide a simple human language like environment for programmers to communicate with computers Programming languages may differ in their syntax but the common goal of all of them is to generate Machine Code which is the only language that a computer can understand As a result it all comes down to how the code is converted into machine code To understand this we must first understand the differences between statically and dynamically typed programming languages Statically and Dynamically Typed LanguagesStatically typed LanguageA statically typed language is one in which variable types are known at the time of compilation The data types of the variables must be specified in statically typed languages and once defined the variable type cannot be modified eg C C Rust Java C C code int number integernumber digit ERROR cannot be changed to stringAt compile time type verification is performed As a result these checks will catch things like missing functions invalid type arguments or a mismatch between a data value and the type of variable it s allocated to before the program runs A programmer can t run code unless it passes these type checks thus it pushes them to rectify bugs by throwing errors and warnings during the compilation process A substantial number of errors are discovered early in the development process Dynamically typed languagesThose where the interpreter assigns variables a type at runtime based on the variable s value at the time Eg JavaScript Pythonvar name name name Vibali this will not throw any error There is no compilation phase in JavaScript Instead a browser interpreter examines the JavaScript code understands each line and then executes it If the type checker identifies an issue at this point the developer will be notified and given the option to fix the code before the program crashes You don t have to wait for the compiler to finish before testing your code modifications because there isn t a separate compilation process This makes the debugging process much faster and easier Related Difference between Compiler and Interpreter How does this matter Look at this python example def fact n if n return n return n fact n What is the value of n Is it a numerical value Is it string Is it a class you created previously The interpreter has no way of knowing what kind of data it will get At run time you have to do a lot more checking which implies you re doing more implicit work for basic actions All of these lookups are extremely difficult to complete quickly As a result the time it takes to generate machine code increases making these languages appear slower On the other hand the Statically Typed languages like C or Java results in compiled code that executes more quickly because when the compiler knows the specific data types that are in use it can produce optimized machine code i e faster and or using less memory Which language should I choose This isn t to say that languages like JavaScript aren t useful It is entirely dependent on the use case Each language focuses on a distinct aspect Dynamic typing allows programmers to construct types and functionality based on run time data but it comes at the sacrifice of speed Programmers can fine tune their code to operate effectively in any context even when there is little hardware space or energy available to power the application by using C C or Rust when building an operating system driver or file system So it all depends on the task that we want to achieve Let me know in the comments below which language you prefer and why |
2021-10-09 17:20:38 |
ニュース |
BBC News - Home |
Sarah Everard: BT 888 phone service floated to protect lone women |
https://www.bbc.co.uk/news/uk-58854578?at_medium=RSS&at_campaign=KARANGA
|
violence |
2021-10-09 17:41:06 |
コメント
コメントを投稿