投稿時間:2022-04-04 17:28:46 RSSフィード2022-04-04 17:00 分まとめ(32件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 東証、60年ぶりに市場再編 「プライム」など3市場に、狙いは? https://www.itmedia.co.jp/business/articles/2204/04/news119.html itmedia 2022-04-04 16:24:00
IT ITmedia 総合記事一覧 [ITmedia エンタープライズ] DX人材をどう育てるか、富士通の取り組みに見る勘所とは https://www.itmedia.co.jp/enterprise/articles/2204/04/news058.html itmedia 2022-04-04 16:15:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 新入社員の6割、入社前から「転職に興味あり」 その理由は? https://www.itmedia.co.jp/business/articles/2204/04/news109.html fondesk 2022-04-04 16:05:00
IT 情報システムリーダーのためのIT情報専門サイト IT Leaders 大阪メトロ、直営店舗「Metro Opus 梅田店」でマスク顔認証決済の実証実験 | IT Leaders https://it.impress.co.jp/articles/-/22949 オープンから同年月日までの期間、コロナ禍における新しい駅ナカ店舗のあり方を検証するため、「マスク対応顔認証決済」の実証実験を実施する。 2022-04-04 16:34:00
python Pythonタグが付けられた新着投稿 - Qiita kaggle jigsawコンペで銀メダルを獲得しました https://qiita.com/kun4qi/items/13448a1b12e6d1b18ebd 最後に、このコンペの振り返りをすると、このコンペはpublicleaderboardとprivateleaderboardのスコアの差がありすぎてそこはどうなのかなと思うところはありますが、kaggleの回目のコンペだったので、初回よりもデータに対してどう工夫したらよい結果が得られるかを考えたり、学習のさせ方やCVが高くなるようなアンサンブルの方法などをかなりいろいろなことを学べたので私自身的にはとても楽しかったです。 2022-04-04 16:25:09
AWS AWSタグが付けられた新着投稿 - Qiita [EC2]windowsではsshを使えないと思い込んでいたけどそんなことなかった。 https://qiita.com/kmmz/items/135c08824919c7263976 適当なecへログインします。 2022-04-04 16:09:52
Git Gitタグが付けられた新着投稿 - Qiita Visual Studio CodeとGitHubを用いたGitバージョン管理方法 https://qiita.com/Nemoto_N/items/2061b3bfa14099d7623c 作成元にしたいブランチが表示されない場合にはフェッチPruneを再度実行することで作成元の一覧に追加されます上記の作業が完了すると以下の画像のようにローカルブランチがmainからfeatureupdateReadmeに切り替わります。 2022-04-04 16:12:12
技術ブログ Developers.IO Amazon Redshift คืออะไร และ เริ่มใช้งานอย่างไร https://dev.classmethod.jp/articles/what-is-amazon-redshift-and-how-to-get-started/ Amazon Redshift คืออะไรและเริ่มใช้งานอย่างไรสวัสดีครับผมไลท์ครับวันนี้จะมาแนะนำทุกท่านให้รู้จักกับบริการAWS Redshift และวิธีการเริ่มใช้งานเบื้องต้นครับ 2022-04-04 07:53:53
海外TECH MakeUseOf Why Twitch Is Killing Its Desktop App and What to Use Instead https://www.makeuseof.com/why-twitch-killing-desktop-app/ browser 2022-04-04 07:19:49
海外TECH DEV Community How to Work Consistently? https://dev.to/sakshamceo/how-to-work-consistently-3fhi How to Work Consistently Hi Welcome Again It All Started Few days backWhen I felt that I am losing my consistency There are some moments when you automatically realize that you are declining in your performance at that point either You ProcrastinateOr You let it continue which results in a long break from things Taking breaks too often Always remember this quote from Bruce Lee I fear not the man who has practiced kicks once but I fear the man who has practiced one kick times Its very very necessary to HAVE CONSISTENCY Without consistency No EXAM No Code No Work can be achieved How to Work Consistently Now the questions arises How to Work Consistently Step Remember Whenever you start feeling any of the above indications start analyzing what could be the most defensible reasons for such decline Saturation Point Either you are doing the same thing for a much longer period Working without any progress Taking no day off Not spending adequate time on managing time Toxic peers Not accomplishing targets Step Your body needs a balance to work efficiently Plan Your day in such a way that it contains sufficient time for joy and health activities despite of hectic schedule You must allocate a holiday once in a week for yourself Step Make daily short achievable goals don t plan for a month in advance Complete those Goals strikethrough the completed task in your diaryStep Create your own environment Add the people who have same mentality like you they should be motivated and focused Comment Down More Such Topics 2022-04-04 07:20:25
海外TECH DEV Community Luxury Car Rental in India https://dev.to/rentzluxury/luxury-car-rental-in-india-ckh Luxury Car Rental in IndiaRentz Luxury provides fantastic car for rent services for various purposes ranging from corporate events and conferences long vacations weddings and airport transfers Rentz Luxury offers self drive car rental luxury car rental and budget rental cars packages for their customers Rentz Luxury is available in Chandigarh Delhi Gurgaon Jaipur Noida and other cities will be joining the list soon website 2022-04-04 07:20:21
海外TECH DEV Community Why do farmers want to give up farming? https://dev.to/ndrohith09/why-do-farmers-want-to-give-up-farming-jn2 Why do farmers want to give up farming India is a rising economy with tremendous development potential We have wonderful land that can yield gold if utilized properly India is now one of the world s largest producer of a variety of dry fruits agricultural based textile raw materials roots and tuber crops pulses farmed fish eggs coconut sugarcane and a variety of vegetables As of India exported agricultural goods worth almost million USD Despite the fact that we are one of the world s top agricultural producing countries our farmers want to give up farming According to a poll of farm households from states of farmers would prefer to pursue anything other than farming of these farmers would prefer to work in cities due to better education health care and career opportunities A substantial majority of farmers reported recurring losses indicated their crops were damaged due to unseasonal rainfall drought floods and insect infestation Our farmers as businessmen who spend money on land and grow products to sell for profit encounter a number of challenges in my opinion Financial Knowledge Some people lag a lot when they have no plans Sometimes everything works out well and they receive a large sum of money but they do not have a solid plan for utilising the money They become entangled in a slew of commitments resulting in massive debt Innovation Our farmers don t come up with fresh ways to improve their farming practises They want their tasks completed and make no plans for the future This is due to a lack of knowledge and understanding regarding forthcoming or ongoing agricultural trends Taking risk As risk takers they frequently blindly follow what others are doing which results in massive destruction in the supply chain causing the price to decrease Loss of agricultural land As agricultural land is lost it will become increasingly difficult to produce the amount of food needed to feed the world s rising population Seeds Seed is a vital and fundamental component for increasing crop yields and sustaining agricultural output growth Unfortunately excellent quality seeds are out of reach for the majority of farmers particularly small and marginal farmers due to expensive rates for superior seeds Fertilizers Over thousands of years Indian soils have been utilized to cultivate crops with little regard for replenishment This has resulted in soil depletion and fatigue leading in low output Soils as nutritious nourishment for the body is primarily supported by manures and fertilizers It is estimated that increased fertilizer application accounts for around of plant growth in agricultural output And cow dung is the greatest manure for soils Irrigation In India there is a significant geographical imbalance in rainfall and water supply Due to India s low irrigation efficiency water supply has increased rapidly Climate change poses a threat to water resources Soil Erosion It is a progressive process that happens when water or wind detaches and removes soil particles causing the soil to degrade Soil degradation and low water quality as a result of erosion and surface runoff have become a global issue Lack of Capital Agriculture being one of the most significant sectors need money The function of capital input is more vital for the growth of agricultural technology Agricultural marketing in rural India remains poor Farmers in rural communities sell their goods to moneylenders from whom they frequently borrow money Transport One of the primary disadvantages of Indian agriculture is the lack of adequate transportation As a result the items are progressively wasted resulting in a loss Farmers lifestyleimage source unplash This only applies to people who possess at least acres of agricultural property with irrigation Work related stress is reduced as is living with having a lot of leisure time The quality of living in the community air and water In between seasons you can run a secondary business such as cattling dairy goods etc You may experiment with organic vegetable cultivation very high rates in market Farmers in India are largely uneducated thus they practise traditional farming and have two harvests every year You may apply your skills to farming and grow three crops every year and I am confident that you will be able to earn nearly twice as much from your farm Around lacs each year The cost of life in a village is extremely cheap much below anything you can imagine You d be able to put more money aside for the future Why are rural youth leaving farming image source unsplashRural youth recently claimed that a lack of information a shortage of financing and poor attitudes of farming are the primary reasons why young people are abandoning small scale farming at such alarming rates Many young people abandon rural life because they are unable to make a livelihood in their community One of the main reasons is that females do not advance in life by marrying farmers since their income is not considered to be reliable For the majority of girls farmers are the final option which has a significant influence on young boys in rural areas Most people want to live a materialistic lifestyle which is difficult to achieve in rural regions therefore they relocate to cities One of the main reasons is that young people have various responsibilities such as family etc which drives them to choose earning money in a secure manner as opposed to an unreliable method in farming Most of them believe the tag Farmer to be less financially and materially valuable than other tags such as Engineers Lawyers Doctors and so on When they pursue farming as a career choice they develop an inferiority complex in reality society convinces them that if they fail they would never be able to recover This demonstrates that if society considers farming to be trivial young people will refuse to pursue it as a career How Education can help farmer in improving his agriculture image source unsplashAdopting updated technologies by educated farmers can result in significant savings in both money and time GPS may be used for precision farming in which satellites and drones collect data on plants and weather directly from the sky The acquired data is kept in agricultural maps which trained farmers may examine and utilise Precision agriculture allows farmers to minimise the quantity of fertiliser put to the field This not only saves money for the farmer but it also saves the environment from unwanted pollution For healthy seed development plants require sunshine fertiliser and a suitable amount of water A crop might be harmed by either too much or too little water SMOS technology can forecast agricultural production characteristics such as floods droughts and so on The farmer can efficiently monitor crop productivity with the use of this information Note This post is not intended to do harm to anyone References agrifarming UN quora downtoearth newsworldprojectmage 2022-04-04 07:18:51
海外TECH DEV Community Lets Build a Twitter Clone in <= 30 minutes https://dev.to/ricardoagz/lets-build-a-twitter-clone-in-30-minutes-1851 Lets Build a Twitter Clone in lt minutes A MERN Stack Tutorial Using Neutrino JS PrefaceI ve been building web and mobile apps for a couple of years now and what I hate the most has consistently been the hassle of starting a new project It takes hours of coding and debugging just to get to a pretty generic point of in the application s process I came across Ruby on Rails around a year and a half ago and it pretty quickly became my go to when creating new web apps Its CLI and generators are pretty unmatched when trying to build a prototype as quickly as possible while completely eliminating the need to write any boilerplate code I recently came across this pretty cool dev tool called Neutrino that s basically an online web builder for MERN stack web apps I d call it a glorified GUI for what would be the equivalent of Rails s generators but it would really be doing it a disservice since it really it quite a bit more powerful This tutorial will be demonstrating how to use Neutrino to build a simplified Twitter clone in under minutes   What is the MERN StackMERN stack refers to MongoDB Express React and Node Mongo A popular no sql database programExpress A backend JavaScript web application framework React A front end JavaScript library for building user interfacesNode An open source JavaScript runtime environment  MVC ArchitectureMVC is an architectural pattern for building software and web applications that consists of parts the Model the View and the ControllerModel handles all data logic and directly interacts with the database In this case we will be using MongoDB and Mongoose which is a library built on top of Mongo that we will use to define our model schema and interact with our Express serverView handles all client side logic this is the React side of the application and will be what the user interacts withController acts as an interface between the Model and View It processes all requests fetches data from the Model to send to the View and takes in information from the View to update the Model  Getting StartedNeutrino uses MongoDB to power its database in this tutorial we will be using MongoDb Atlas but you could run MongoDB locally as well if you wanted We won t go over how to set up a new MongoDB Atlas cluster and database but you can follow this tutorial to get started Once you ve created your cluster and set up your database you re going to want to get your connection string You re also going to want to make sure you have Node js installed to run your application   Setting Up the ModelsFirst let s start a new Neutrino project at app neutrinojs devIf you re curious and want to check out their documentation you can find it at neutrinojs dev docs UserWe want users to be able to have a name username and bio as well as be able to register to our app which will require us to define email and password parameters as well So our params will be name stringusername stringemail stringpassword stringbio textnote Here we differentiate string from text but text is nothing more than a string without character limits It will also default to a textarea component in React PostWe want users to be able to make posts and posts to contain a few different parameters such as the number of likes title content and comments We could build comments right into the post but it would be much better practice to separate them out into their own model with their own CRUD functionality Similarly for likes we could build them right into a number parameter for post but what if we want to access the people who liked the post Or get a list of all the posts a user has liked We d need more than a simple number keeping track of the number of times a user has pressed like We will go over this later Therefore our data parameters will look like this title stringcontent text CommentWe want users to be able to comment on different posts and we want these comments to be associated with the user that posted them Therefore out data parameters will look like this content stringuser string actually this will be a Mongoose id but we will discuss this later   Defining Model RelationsWhen we discuss model relations we re going to bring up terminology such as one to many or many to many these are terms typically used in SQL databases and the meaning doesn t really apply in the same way as it would in an SQL database Nevertheless they are still effective at conveying the hierarchy of our models and how they will interact with each other We want users to be able to make posts therefore a user will be able to have many posts but a post will belong to only one user This is a one to many relationship between users and posts We also want users to be able to comment on different posts Therefore a post can have many comments but a comment can only belong to one post This again is a one to many relationship between posts and comments By extension we can also represent a one to many relationship between users and comments however Neutrino currently doesn t support a multiple one to many relationships for the same many model so we will just have to do this manually To summarize a user has many postsa post belongs to a usera post has many commentsa comment belongs to a post  Implementing in NeutrinoStep Create a new model and name it User by convention Neutrino requires you to name your models as singular nouns   Adding Data ParametersStep Click on authentication which will automatically create the username email and password parameters and manually pass in the name string and bio text params by clicking on ADD PARAM Step Create the Post and Comment models and pass in their required data parameters that we specified before So for Post it would be title string and content text and for Comment it would be content string and user string After doing this your models page should look like this   Implementing Model RelationsStep We said we wanted two one to many relationships one between User and Post and one between Post and Comment We can do this by passing a has many Post param for User and a belongs to User param for Post After doing this for Post and Comment your models page should look like this And well the Relations page doesn t really do much yet but if you did everything correctly it should look like this   RoutingStep We enabled authentication by defining User as an authObject in the Models page now we want to specify which routes we actually want and which ones we want to protect Lets head to the Routes page which should originally look like this Neutrino scaffolds create all of the RESTful routes for each model by default so for user it would be index show create update destroy etc Note that the new and edit routes are created only in the frontend they simply render a form and don t actually call the backend until you hit submit with the exception that edit actually makes a GET request to load all the current model info   Disabling Unnecessary RoutesStep a We clearly don t want each route available for every model so let s start out by disabling a couple We don t really want users to be able to access a list of all comments ever created so lets disable the index route for CommentWe also don t need an individual page to display a singular comment so we can go ahead and disable the show route for for CommentAnd finally let s say we don t want Users to be able to modify a comment after commenting so let s disable the update route for Comment note that this automatically disables the edit route too Your Comment routes should now look like this   Route ProtectionStep b By enabling route protection we are enabling two things The verifyJWT middleware in the backend which will make sure the user is authenticated before enabling them access to the route The PrivateRoute component in the frontend which will automatically redirect the user to the login page if they re not authenticated We can split all routes into two main categories public routes accessible to anyone regardless of whether or not they re signed in and private routes which should only be accessible to logged in users We want users to be able to see all posts and be able to click on a post to see its comments even if they re not logged in so we can leave both the Post index and show routes as public We also want unauthenticated users to be able to create a new user by registering an account so we can leave User create as public too However we want Users to be authenticated to do anything else Let s protect all other routes by clicking on the protected lock icon Your routes should look like this   Route LogicStep c Neutrino has a pretty neat feature of offering route logic templates for certain routes these can be anything from hiding certain parameters such as passwords on GET requests to verifying to see if a user is trying to modify another user s content Lets look at these route by route User show A GET request to User will return all of the user s parameters by default the password will be hashed but we still don t need other users to see this Lets enable the protect info logic template by clicking on the gear button and then on protect info to automatically hide the password field for the logged in user and the password and email field for anyone else even if a user is signed in we don t want them to access another user s email You could also hide other parameters if you wanted so if you didn t want other users to access the name parameter you could pass that into hide as well Make sure to hit SAVE User update We clearly don t want users to edit other users information so lets enable logic and click on the protect update template User delete We don t want users to be able to delete other users accounts so lets enable logic and click on the protect action template Let s understand what we just did req user id Refers to the ID that is associated with the currently authenticated user making the request This only works if VerifyJWT was enabled for this particular route data id toString The data object is the object that we are trying to access from the database We are then accessing the data s which is of type User id parameter Lastly we have to convert the id object into a string so we use toString hide Refers to a special shorthand that removes certain keys from the response object In our example in the if statement we try to hide password and email so on the user side when the response object is received the response will never contain the password as it is sensitive information and will only include the email if the user fetched is the same user making the request error Error is a special shorthand to send a response to the user with the given Error message after the sign So if we wanted to send an error with a different message “Not Nice we could replace the error line with error Not Nice Now for Post Post createWhen a user creates a new Post we don t want them to be able to modify the id of the user that created it as this would essentially be impersonating another user So let s enable route logic and click on the protect create template Post updateWe obviously don t want users editing other users posts We also don t want a user to be able to modify the user parameter for a post even if it is their own because this would essentially be impersonating another user Let s enable route logic and click on the protect update template Post deleteWe don t want users to be able to delete another user s post so lets pass in some route logic Now for CommentComment createNeutrino actually doesn t provide any templates for this route since we didn t specify a one to many with the authObject User but we can use what we just learned about routes to do the same thing Since we don t want users to be able to make comments on behalf of another user if req user id req body user error Incorrect parameters Comment deleteSince we don t want users to be able to delete other users comments if req user id data user error Cannot delete another users comment Lets understand what this is doing Remember that we re passing user String as a parameter when creating a comment That means that we re storing the id of the user that created the comment As such we can compare it with the id of the user making the request through req user id to see if the user making the request is the same user that created the comment   RewindWe still haven t discussed how we will implement likes This is partially by design since I didn t want to intimidate beginners with too much information but now you ve made it this far so let s implement likes Likes will be a many to many relationship between User and Post Even though we previously declared them to have a one to many relationship they now have both That is a user can like many posts and a post can have likes from many users   Implementing LikesStep Lets go back to the Models page and add another has many Post param for User and a has many User param for PostYour Models page should look like this Your Relations page should look like this Note that Neutrino automatically adds two new routes for Many to Many relationships addPost and dropPostaddUser and dropUserThese routes will be helpful since they automatically provide the logic to add a post to the user s liked array and a user to a post s liked by array we can change the name of the route methods later if we want   Adding Mongo Connection StringStep Go to the Settings page and add your MongoDB Connection string if you have it You could also do this later you ll just have to insert it in the index js page of your server before you can run your application For help accessing your MongoDB Atlas Connection string follow this guide  Saving Your ProjectsNeutrino lets you create an account to save your projects which may be helpful in debugging or adding new features as your project grows However this is fully optional   ExportStep Click on the EXPORT button on the sidebar and add a project name and your email and you re done If you followed along correctly Neutrino should download a zip folder containing all of your project s code You re Done almost   Running Your CodeExtract the zip folder and open it up in your editor Run the following commands in this order cd servernpm inode index jsnote If you haven t added a Mongo Connection String you ll get the following error throw new MongoParseError Invalid scheme expected connection string to start with mongodb or mongodb srv On a new terminal run cd clientnpm inpm run startIf everything went correctly you should see the following page Nothing quite too interesting yet but you can see that you can register a new user then log in with the specified username and password You can also try to create a new post and comment if you try to pass in anything other than your own user s id for the user parameter when creating a new comment you should get an error However the whole frontend is pretty generic and we ll get around to fixing it Let s fix up a couple of things in the backend first though   Model Files  User Model server models User jsYour code should look like this const mongoose require mongoose const UserSchema new mongoose Schema username type String required true email type String required true password type String required true name type String required true bio type String required true likes type mongoose Schema Types ObjectId ref Post UserSchema virtual posts ref Post localField id foreignField user UserSchema set toObject virtuals true UserSchema set toJSON virtuals true const User mongoose model User UserSchema module exports User Each object in the schema represents a parameter for the object likes represents the Many to Many association we created with Posts which is simply an array of Object IDs for different posts The latter code in UserSchema virtual specifies our One to Many relationship with Post Mongoose virtuals allow us to fetch the posts associated with the given user without actually storing them in the User document in the database which will help performance You can read more about Mongoose virtuals here  Post Model server models Post jsYour code should look like this const mongoose require mongoose const PostSchema new mongoose Schema title type String required true content type String required true user type mongoose Schema Types ObjectId ref User required true liked by type mongoose Schema Types ObjectId ref User PostSchema virtual comments ref Comment localField id foreignField post PostSchema set toObject virtuals true PostSchema set toJSON virtuals true const Post mongoose model Post PostSchema module exports Post   User Controller server controllers UserController jsNeutrino sometimes messes up the route methods whenever you have different relationships between the same two models remember how we had both a One to Many and a Many to Many between User and Post so make sure your User Controller has these two methods addPost async req res gt const user id post id req params UserModel findByIdAndUpdate user id push likes post id err data gt if err res status send err console log err else res status send data console log Post added dropPost async req res gt const user id post id req params UserModel findByIdAndUpdate user id pull likes post id err data gt if err res status send err console log err else res status send data console log Post dropped Let s also fix up the populate function in find as Neutrino may have written a slight bug First we need to populate posts since Mongoose virtuals only gives us the ids of the posts belonging to the given user The populate function replaces this id with an object containing the actual posts information specifically the parameters defined in selectWe also need to populate likes with the objects corresponding to actual post dataYou can read more about Mongoose s populate function hereYour find function should look as follows find async req res gt const id req params try const data await UserModel findById id populate path posts select title populate path likes select title content if req user id data id toString data password undefined data email undefined else data password undefined res status send data catch err res status send err message console log err   Post Controller server controllers PostController jsLets rename some variables in the addUser and dropUser methods In push and pull rename users to liked byaddUser async req res gt const post id user id req params PostModel findByIdAndUpdate post id push liked by user id err data gt if err res status send err console log err else res status send data console log User added dropUser async req res gt const post id user id req params PostModel findByIdAndUpdate post id pull liked by user id err data gt if err res status send err console log err else res status send data console log User dropped note Since we renamed the users array to liked by in the Post model we ll run into a few errors if we don t also change the naming in PostController Make sure find and index look like this find async req res gt const id req params try const data await PostModel findById id populate path comments select content user populate path liked by select username name res status send data catch err res status send err message console log err all async req res gt try const data await PostModel find populate path comments select content user populate path liked by select username name res status send data catch err res status send err message console log err   Server IndexThe server index page defines all of our RESTful routes and pointes them to the appropriate controller method It also includes verifyJWT a middleware function that checks for a valid JWT token to ensure the user is authenticated Including verifyJWT in a route will require the user to be authenticated before calling the controller function server index jsMake sure to include verifyJWT for the following routes addPostdropPostaddUserdropUserYour code should look like this const express require express const mongoose require mongoose const cors require cors const jwt require jsonwebtoken const app express const PORT const corsOptions origin app use express json app use cors corsOptions mongoose connect lt YOUR OWN CONNECT STRING HERE gt useNewUrlParser true function verifyJWT req res next if req headers authorization return res status json message No Token Given isLoggedIn false const token req headers authorization split if token jwt verify token pleasechange err decoded gt if err return res status json message Failure to Auth isLoggedIn false req user req user id decoded id req user username decoded username next else return res status json message Incorrect Token Given isLoggedIn false CONTROLLERSconst UserController require controllers UserController const PostController require controllers PostController const CommentController require controllers CommentController ROUTESapp get users verifyJWT UserController all app get users id verifyJWT UserController find app post users UserController register app put users id edit verifyJWT UserController update app delete users id verifyJWT UserController delete app post users user id add post post id verifyJWT UserController addPost app post users user id drop post post id verifyJWT UserController dropPost app get posts PostController all app get posts id PostController find app post posts verifyJWT PostController create app put posts id edit verifyJWT PostController update app delete posts id verifyJWT PostController delete app post posts post id add user user id verifyJWT PostController addUser app post posts post id drop user user id verifyJWT PostController dropUser app post comments verifyJWT CommentController create app delete comments id verifyJWT CommentController delete AUTHapp post login UserController login app post register UserController register app listen PORT console log Server running on port   Fixing Up the Front EndEach Model comes with pages built in corresponding to each of the CRUD functions ModelA s js an index page containing a list of all ModelA s created ModelA Show js a page displaying all information corresponding to a single ModelA ModelA Edit js a page rendering a form to update a specific ModelA ModelA New js a page rendering a form to create a new ModelA   Display User Page client src Pages User UserShowUserShow js renders a pretty generic page lets change a few things to make it look more like a profile page Displaying ParamsYou can change the header to greet the user with their username rather than id also since we added logic for hiding the user s email and password you can delete the password parameter and add a conditional to only render email if its not null Conditional RenderingAs for the EDIT and DELETE buttons we only want to display them if the currently authenticated user is the same user we re displaying To do so first import useContext from react and include the following lines import UserContext from hooks UserContext export default function UserShow props const authUser useContext UserContext Now we can access the signed in user if it exists by simply calling authUserWrap both buttons with the following conditional authUser id id amp amp lt div gt lt Button variant outlined style marginRight onClick gt navigate users id edit gt edit lt Button gt lt Button variant contained color error onClick handleDelete gt delete lt Button gt lt div gt Displaying Liked PostsWe can display liked posts by simply calling the user likes array It might look something like this lt div className displayContainer gt lt h gt Liked Posts lt h gt lt ul gt user likes amp amp user likes map post i gt lt div className listItem key i gt lt li gt post title lt li gt lt Button variant outlined size small onClick gt navigate posts post id gt show lt Button gt lt div gt lt ul gt lt div gt   Display Post Page client src Pages Post PostShowAgain this page is currently pretty generic but we can fix it up a bit by changing the header and how we display some of the params What s a bit more interesting though is how we re dealing with likes Liking PostsChange the addUser and dropUser functions to the following function likePost try axios post http localhost posts id add user authUser amp amp authUser id headers authHeader axios post http localhost users authUser amp amp authUser id add post id headers authHeader catch e console log e window location reload function unlikePost droppedId try axios post http localhost posts id drop user authUser amp amp authUser id headers authHeader axios post http localhost users authUser amp amp authUser id drop post id headers authHeader catch e console log e window location reload All we re doing is changing the name of the function for readability and changing the user id to the id of the currently authenticated user This will require you to import useContext UserContext define authUser like we did in UserShow Conditional RenderingIf we only want to display the edit and delete buttons if the post belongs to the authenticated user wrap the buttons in the following conditional post user authUser id amp amp lt div gt lt Button variant outlined style marginRight onClick gt navigate posts id edit gt edit lt Button gt lt Button variant contained color error onClick handleDelete gt delete lt Button gt lt div gt Displaying Like Unlike ButtonThis button will render depending on whether or not the currently authenticated user has already liked the post Therefore we can create two new buttons for liking and unliking and wrap them in the following ternary opertor post liked by amp amp post liked by some user gt user id authUser id lt Button variant contained color error onClick unlikePost gt unlike lt Button gt lt Button variant contained color success onClick likePost gt like lt Button gt Lets understand what this is doing post liked by is the array of users that have liked this post some user gt condition returns true if any user matches the following conditionIn this case we want to return true if the currently authenticated user has liked the post that is if authUser is included in the posts liked by arrayIf true we want to display the unlike button otherwise display the like button  Finishing ThoughtsOkay there s a chance after reading everything and making the slight changes this project took a little over minutes But really we had the bulk of our functionality up and running in only a couple of minutes due to Neutrino There s obviously a lot more that can be done fixing up the frontend and customizing it to look more like an actual blog app but hopefully after following these examples with UserShow and PostShow you gathered enough on your own to get started with the rest Happy Coding 2022-04-04 07:18:29
海外TECH DEV Community Myfe - The End? https://dev.to/vulcanwm/myfe-the-end-jgo Myfe The End So I ve lost momentum of making Myfe Should I continue on Myfe even if it is boring change Myfe to a place where there will be cryptography competitions start on a projectComment below on what you think I should do and if you think I should start another project then comment on what ideas you have for that 2022-04-04 07:17:23
海外TECH DEV Community AWS open source news and updates, #107 https://dev.to/aws/aws-open-source-news-and-updates-107-4kll AWS open source news and updates April th Instalment Newsletter Welcome to edition of the AWS open source newsletter and we have a bumper edition this week packed with more great new open source projects and content for you to consume Topics featured this week include optimising open source big data tools developer tooling case studies and we even some some great open source content for NET core developers This weeks projects include a really nice handy browser plugin called aws search extension that lets you search and find developer information from the AWS docs a tool that will help you detect whether you have configured or using dockershim in your Kubernetes clusters a library to help you integrate Amazon Cognito in your Laravel PHP applications and plenty more developer tools and sample projects If reading is more your thing check out the content featuring Kubernetes PostgreSQL Magma Apache Airflow Apache Flink Apache Hive OpenZFS Karpenter Apache Hadoop Medusa cdks OpenSearch Projen Spline and more This weeks video feature a quick walk through of using RepliByte and looking at your options of using Blazor on AWS Do you have an interesting open source project you want to share As always if you are working on anything interesting you would like me to include in this weekly round up please drop me a line at ricsue amazon com Celebrating open source contributorsThe articles posted in this series are only possible thanks to contributors and project maintainers and so I would like to shout out and thank those folks who really do power open source and enable us all to build on top of what they have created So thank you to the following open source heroes Ualter Otoni Pereira Noam Dahan Martin Andreev Carlos Padilla Romaric Philogène Michael Brewer Pit Julio Faerman Jens Uwe Walther Jesse Butler David Pérez Caparrós Alexander Hobmeier Benjamin Maier Fuchs Rabi Abdel Praveen Kumar Avnish Jain Praveen Panati Suthan Phillips Aditya Shah Syed Shameerur Rahman Gowtham S Abhishek Nanda Anurag Gupta Philip M Gollucci Khoa Nguyen Krithivasan Balasubramaniyan Francois Bouteruche and Rahul Shaurya Make sure you find and follow these builders and keep up to date with their open source projects and contributions Latest open source projects Communityawsbe siteawsbe site AWS Community Builder Ualter Otoni Pereira has created this tool written in Go to help handle AWS Session connections on terminals It uses your configured AWS Shared Config and Credentials files and manages Roles to Assume MFA Token requests AWS SSO Sign in AWS SSO Tokens and the expiration of opened sessions aws lambda eventsaws lambda events this open source tool from AWS Community Builder Michael Brewer provides a collection of resources and tools on the different input and outputs that AWS Lambda expects You can use this tool to publish your locally defined test events to the Lambda Console and the project has s of different examples and cli tools with examples to help get you started task treetask tree this new tool from my friend and former colleague Julio Faerman looks to help you automate complex maintenance and troubleshooting tasks in cloud computing One of the things this tool can help you with is to cleanup AWS resources based on a naming prefix Julio warmly welcomes any contributions and has provided a wish list of things he wants to add to this project aws search extensionaws search extension so I missed this project from Pit but thanks to the AWS Community Builders who shared this project in our Slack channel This is a browser plugin that provides a search extension providing quick fuzzy search results for AWS developers Includes AWS API AWS CLI and AWS CloudFormation references and opens the official AWS documentation page when you select an item Looks like it is compatible with most browsers but I only tried with Chrome Firefox Once you have it installed from the tab just type in ase and then space and you will see a new search bar appear Very nice Toolskubectl detector for docker socketkubectl detector for docker socket this tool will help you detect whether you are using the dockershim that is being removed from Kubernetes It is a kubectl plugin to detect if active Kubernetes workloads are mounting the docker socket docker sock volume nestjs snestjs s NestJS is an AWS S library allows you to use the AWS SDK v in a more friendly and familiar way by providing injectable services for managing things like buckets and objects There is a great write up from Martin Andreev on the backstory for this project so make sure you read NestJS AWS S From an idea to reality SlytherSlyther this open source tool from Avantika is AWS Security tool to check read write delete access for S buckets aws cognitoaws cognito this package provides a simple way to use AWS Cognito authentication in Laravel x for Web and API Auth Drivers Check out the demo application and nice examples and documentation of how to use it within your PHP Laravel projects Demos and Samplesaws do pmaws do pm this sample repository is an all in one template for building a predictive modelling application built on the Do framework a prescriptive project structure and a set of simple management scripts for building and running your application The example walks you through modeling Electric Vehicles EVs and covers the process of building running and scaling a demo application step by step starting from a fresh clone of the aws do pm repository to building and automatically deploying continuously updating predictive models for a fleet of Electric Vehicles using Artificial Neural Networks trained by PyTorch amazon mwaa extract metadataamazon mwaa extract metadata This repository contains sample code for persisting and analyzing metadata in a transient Amazon MWAA environment Storing this metadata in your data lake enables you to better perform pipeline monitoring and analysis You can dive deeper into this by reading the blog post below on how you can use this project aws apprunner netcoreaws apprunner netcore this project and detailed walk through will show you how you can build a Microsoft NET Web API application with Amazon Aurora Database using AWS App Runner This is the architecture you will build s bucketkey pocs bucketkey poc this is an intriguing project S Bucket Key Proof of concept POC will demonstrate how request traffic decreases up to from Amazon S to AWS KMS when you enable the S Bucket Key Amazon S Bucket Keys reduce the cost of Amazon S server side encryption using AWS Key Management Service SSE KMS This new bucket level key for SSE can reduce AWS KMS request costs by up to percent by decreasing the request traffic from Amazon S to AWS KMS sigva signing examplessigva signing examples AWS is rolling out an extension to SigV called Signature Version A SigVA This extension enables signatures that are valid in more than one AWS Region This is required for signing multi Region API requests for example with Amazon S Multi Region Access Points This repository servers to provide examples how to sign requests with SigVA to make Rest API requests to AWS services Currently there are samples for Python Node and Java with more coming cloudfront signed cookie examplecloudfront signed cookie example this is a sample project that provisions a serverless web app protecting cached assets in CloudFront by using signed cookie aws elastic beanstalk hardened security cdk sampleaws elastic beanstalk hardened security cdk sample if you use AWS Elastic Beanstalk then this project is for you The repo contains a CDK script which deploys an AWS Elastic Beanstalk application with a hardened security configuration amazon ivs fitness web demoamazon ivs fitness web demo I am not sure if this project is going to shake my personal fitness regime up a level but who knows This demo showcases how customers can use Amazon Interactive Video Service IVS to create live interactive fitness experiences with a leaderboard and basic user interactions You can check out some of the other IVS code samples and live demos incase you just want to see how they look first AWS and Community blog postsAccess UndeniedIn I shared a new open source tool called access undenied aws This project from Ermetic received a lot of attention the tool parses your logs for AWS AccessDenied CloudTrail events and then explains the reasons for them and offers actionable remediation steps I missed this blog post Access Undenied on AWS from Noam Dahan that provides a guided tour and shows you how you can use this tool RepliByteI introduced this project in which is a very nice open source tool written in Rust to synchronise cloud databases and hide sensitive data CEO of Qovery Romaric Philogène has put together this blog post How to seed your dev Postgres DB with your prod DB with RepliByte that shows you exactly how you can get started and use it taking a quick look at some of the features with examples Very nice project so check this out hands on Projenprojen is a very cool open source tool for developers to help them define and maintain complex project configuration through code So I was very interested to read this post from AWS Community Builder Philip M Gollucci Projen External Project Types provides you with a very nice example use case and walk through of how you can use this project Very nice and essential reading this week hands on cdksAWS Community Builder Vu Dao has put together another great blog post for you this time on cdks Similar to AWS CDK in how it works cdks is an open source software development framework for defining Kubernetes applications and reusable abstractions using familiar programming languages cdks apps synthesise into standard Kubernetes manifests which can be applied to any Kubernetes cluster AWS Controllers for Kubernetes ACK is a tool that lets you directly manage AWS services from Kubernetes Putting these two things together Vu s post Use CDKS To Create AWS Controllers for Kubernetes Custom Resources shows you how you generate Kubernetes manifest of ACK using cdks typescript hands on OpenSearchA couple of posts this weeks on OpenSearch The first came courtesy of the only other newsletter you need in your life oy news so hat tip to Michael In the post Getting started with Fluent Bit and OpenSearch Anurag Gupta provides a getting started guide on the OpenSearch plugin for Fluent Bit and you will soon know how you can send logs to OpenSearch immediately from your Windows Linux Container Mac or Kubernetes environments hands on Following that we had the post Dejavu The missing web UI for OpenSearch which takes a look at this popular data browser for Elasticsearch and how with the latest release they have added first class data browser support for OpenSearch as well MedusaMedusa is an open source headless commerce engine that enables developers to create digital commerce experiences think Shopify alternative Carlos Padilla has put together this blog post Set up Open source Ecommerce in the cloud on how you can deploy this on AWS Elastic Beanstalk Very nice walk through hands on KarpenterKarpenter is a high performance open source Kubernetes cluster autoscaler that can help you autoscale your groupless nodes by letting you schedule layered constraints using the Provisioner API Karpenter also makes node upgrades easy through the node expiry TTL value ttlSecondsUntilExpired In the post Managing Pod Scheduling Constraints and Groupless Node Upgrades with Karpenter in Amazon EKS Gowtham S and Abhishek Nanda provide a walk through on how you can set this up hands on SplineSpline is a free and open source tool for automated tracking data lineage and data pipeline structure in your organisation The Spline agent for Apache Spark is a complementary module to the Spline project that captures runtime lineage information from the Apache Spark jobs In the post Build data lineage for data lakes using AWS Glue Amazon Neptune and Spline Khoa Nguyen Krithivasan Balasubramaniyan and Rahul Shaurya walk you through three steps in building an end to end automated data lineage solution for data lakes lineage capturing modelling and storage and finally visualisation hands on Apache AirflowPraveen Kumar and Avnish Jain have collaborated on this great new blog post Persist and analyze metadata in a transient Amazon MWAA environment They provide a solution that will help you understand how to export persist and analyse Airflow metadata in Amazon S enabling you to run and perform pipeline monitoring and analysis There are several uses cases including so you can spin down Airflow instances without losing operational metadata hands on Apache FlinkIn the post Use Amazon CodeGuru Profiler to monitor and optimize performance in Amazon Kinesis Data Analytics applications for Apache Flink Praveen Panati shares how you can set up and use CodeGuru Profiler to monitor an application s health and capture important metrics to optimise the performance of Kinesis Data Analytics for Apache Flink applications hands on Apache HiveApache Hive is a data warehouse software project built on top of Apache Hadoop for providing data query and analysis In their collaboration Up to times improvement in Hive write performance with the Amazon EMR Hive zero rename feature Suthan Phillips Aditya Shah and Syed Shameerur Rahman explore how the Hive EMRFS S optimized committer improves write performance compared to the default Hive commit logic using the TPCx BB performance benchmark as a guide MagmaMagma is an open source flexible and extendable mobile core network solution In a previous newsletter I shared the post that showed you how you can setup and install this project on AWS If you want to know how you can fully automate the deployment and lifecycle management of Magma on the AWS Cloud then you are in luck David Pérez Caparrós Alexander Hobmeier Benjamin Maier Fuchs and Rabi Abdel have huddled together to put together this post Fully automated CI CD pipelines for deploying and managing Magma on AWS hands on Other posts worth checking outEnabling Amazon Simple Storage Service Amazon S Access Points in Apache Hadoop SA announce and show you how you can use Amazon S Access Points in Apache Hadoop and any framework consuming the SA connector or relying on the Hadoop Distributed File System such as Apache Spark Apache Hive Apache Pig and Apache Flink How to integrate AWS IoT Core with Amazon MSK will show you how you can set up AWS IoT Core to stream events to Amazon MSK hands on Deploy bastion hosts into private subnets with AWS CDK explains how to provision scalable and extendable secure bastion hosts in private subnets using AWS CDK hands on Optimizing AWS Lambda function performance for Java shows how to optimise the performance of AWS Lambda functions written in Java without altering any of the function code hands on Synchronize your Oracle databases quickly and easily with Amazon FSx for OpenZFS provides an overview of how you can use Amazon FSx for OpenZFS with Oracle Database running on Amazon EC to accelerate and optimise your database cloning processIntegrating with GitHub Actions CI CD pipeline to deploy a Web App to Amazon EC shows you how you can setup GitHub Actions to create a CI CD workflow and AWS CodeDeploy to deploy a sample Java SpringBoot applicationCase StudiesHow governments can use open source solutions for faster transformation and more looks at some of the ways open source is being used to drive transformation within the Government sectorData Science workflows at insitro using redun on AWS Batch interesting look at a new data science tool called redun from insitro that helps data scientists to define complex scientific workflows that scale Quick updatesKubernetesAmazon Elastic Kubernetes Service Amazon EKS now supports using the Amazon EKS console AWS Command Line Interface CLI and EKS API to install and manage the the Amazon Elastic Block Store EBS Container Storage Interface CSI driver This launch enables a simple experience for attaching persistent storage to an EKS cluster The EBS CSI driver provides a CSI interface used by container orchestrators to manage the lifecycle of Amazon EBS volumes Since announcing preview EKS add ons support now includes Windows compatibility dynamic snapshotting and resizing of EBS volumes via the Kubernetes API and backwards compatibility with the in tree EBS driver The EBS CSI driver can be installed managed and updated directly through the EKS console CLI and API You can see available add ons and compatible versions in the EKS API select the version of the add on you want to run on your cluster and configure key settings such as the IAM role used by the add on when it runs Using EKS add ons you can go from cluster creation to running applications in a single command and easily keep tooling in your cluster up to date Jens Uwe Walther and Jesse Butler have put together this blog post Amazon EBS CSI driver is now generally available in Amazon EKS add ons dives deeper into this announcement together with some of the historical and background of the project before demonstrating how to create an Amazon EBS CSI EKS add on using it in the context of a Kubernetes workload hands on PostgreSQLFollowing the announcement of updates to the PostgreSQL database by the open source community we have updated Amazon Aurora PostgreSQL Compatible Edition to support PostgreSQL and These releases contain bug fixes and improvements by the PostgreSQL community Refer to the Aurora version policy to help you to decide how often to upgrade and how to plan your upgrade process In addition Babelfish for Aurora PostgreSQL version has been released for PostgreSQL providing improvements in support for GRANT REVOKE ROWVERSION JSON QUERY and more Read more in the full announcement Amazon Aurora supports PostgreSQL and Babelfish for Aurora PostgreSQL Also new last week was news that Amazon Aurora PostgreSQL Compatible Edition now supports a foreign data wrapper that can connect to databases that use the Tabular Data Stream TDS protocol such as Sybase databases and Microsoft SQL server You can use this foreign data wrapper to connect to data sources in other databases eliminating the need to replicate or copy data AWS CDKCheckout the latest release notes for AWS CDK v with support for AWS SSO cli and features including Amazon Cognito autoscaling EC AWS CloudWatch and more Videos of the weekBlazorBlazor is a free and open source web framework that enables developers to create web apps using C and HTML Building a SPA fully in NET with Blazor WebAssembly has become a hot topic in the last few months AWS offers you several hosting options for your Blazor WASM apps However if you want to interact with AWS Services there are a few things you need to know Check out this YT video of my colleague Francois Bouteruche as he demonstrates the different hosting options you have on AWS Then I will discuss what you need to know to interact with AWS Services from your Blazor WASM app RepliByteThe project was featured in a previous newsletter and you can read more about this by checking out the blog post above from CEO of Qovery Romaric Philogène If you prefer video as a medium this short video will help you understand what it does and why developers are already using this tool Events for your diaryIf you have an event you want me to publish here please contact me and I will include it in this listing GitOpsCon EuropeMay th Valencia SpainGitOpsCon Europe is designed to foster collaboration discussion and knowledge sharing on GitOps This event is aimed at audiences that are new to GitOps as well as those currently using GitOps within their organisation Get connected with others that are passionate about GitOps Learn from practitioners about pitfalls to avoid hurdles to jump and how to adopt GitOps in your cloud native environment The event is vendor neutral and is being organised by the CNCF GitOps Working Group Topics include getting started with GitOps scaling and managing GitOps lessons learned from production deployments technical sessions and thought leadership Read more about this from the official page here CDK DayMay th VirtualThis is a community organised event about AWS CDK cdktf projen and cdks This will be third year they run this event and if the previous two are anything to go by this will be essential viewing live streamed via You Tube Check out and register for the event over at their home page at OpenSearchEvery Tuesday pm GMTThis regular meet up is for anyone interested in OpenSearch amp Open Distro All skill levels are welcome and they cover and welcome talks on topics including search logging log analytics and data visualisation Sign up to the next session OpenSearch Community Meeting Feb Stay in touch with open source at AWSI hope this summary has been useful Remember to check out the Open Source homepage to keep up to date with all our activity in open source by following us on AWSOpen 2022-04-04 07:17:03
海外TECH DEV Community An easy way to provide parameters in PowerShell https://dev.to/codbugs/an-easy-way-to-provide-parameters-in-powershell-7mh An easy way to provide parameters in PowerShellMy nickname in the networks is Coding Bugs and I have been working as a software architect and developer from In my dashboard you will find articles about programming languages programming techniques and other concepts that will help you improve You already know that PowerShell is the programming language that Microsoft makes available to us for a cross platform task automation solution composed of a command line shell a scripting language and a configuration management framework In this article I will show you a different way to provide parameters to scripts and commands This is a simple and easy way of declaring parameters and assigning their values that will allow you to organize your scripts so that everything makes more sense Standard wayIf you know PowerShell you already know how to provide parameters in your calls If you don t just type the name of the parameter preceded by a dash then type its value Get ChildItem Path C Filter txt Returns all existing text files in C As you can see the standard way is very easy and for cases where you make immediate invocations it is the best way to provide parameters However imagine that you have to count the number of files of a certain type located in a specific place on your machine In this case we would have to repeat as many times as necessary the invocation of the above command Get ChildItem providing the Filter parameter based on the requested file type Get ChildItem Path C Filter html Measure Select Count Returns all existing HTML files in C Get ChildItem Path C Filter css Measure Select Count Returns all existing CSS files in C Get ChildItem Path C Filter js Measure Select Count Returns all existing JS files in C To save us time each time we are asked for this information we are going to generate our own script in which we add these calls In addition we are going to incorporate a parameter in the script to specify the location where to count each one of the HTML CSS and JS files param Parameter Mandatory true String Location Return Html Get ChildItem Path Location Filter html Measure Count Css Get ChildItem Path Location Filter css Measure Count Js Get ChildItem Path Location Filter js Measure Count What happens if we are now asked to include more and more file types with different extensions The answer would be to include more and more lines to our script to fulfill the request But what if there was another simpler and more versatile way giving our script the ability to abstract from extension types A hashtable for passing parametersWe will start by adding a new parameter indicating the extensions of the files we have to count Now we will only have to iterate over these values and pass the corresponding extension to the Get ChildItem command param Parameter Mandatory true String Location Parameter Mandatory true String Extensions Return Extensions Foreach CurrentExtension ToLower Transform extension to lower case Return Get ChildItem Path Location Filter CurrentExtension Measure Count Return an object with the extension as the key and the count obtained as the value This would be enough for our purpose but as a programmer we want it to be even more abstract and allow us to keep the Get ChildItem command call cleaner avoiding having to modify it again with new parameters Being a somewhat complex command line it is better to avoid modifying it as much as possible or to make it simpler by breaking it into simpler pieces For the sake of this article we choose the first option PowerShell allows the passing of a hashtable object to provide each of the parameters we need from the command to be executed In our case the command is Get ChildItem and the parameters we are using are Path and Filter The hashtable variable that we will create will look like the following one CmdParams Path Filter And the command call is like the following important the use of characterGet ChildItem CmdParamsAs in the previous case we have to update our hashtable variable with the corresponding extension in each iteration of the Foreach param Parameter Mandatory true String Location Parameter Mandatory true String Extensions CmdParams Path Location Filter Return Extensions Foreach CurrentExtension ToLower Transform extension to lower case CmdParams Filter CurrentExtension Set the filter to the current extension Return Get ChildItem CmdParams Measure Count Return an object with the extension as the key and the count obtained as the value We have achieved what we were looking for we have abstracted the call to the Get ChildItem command with respect to the parameters we need to pass to it This way we can modify the CmdParams variable by adding changing or removing any key value pair based on the functional needs we have We can see here the second principle of the SOLID paradigm Open Closed Principle which states that the code should be closed to any modification but open to extend its functionality We can say that the purpose of the iteration over each of the extensions is to return the number of existing files in the indicated location The Get ChildItem command can be invoked with other parameters that will modify the number of files returned but its result will remain the same closed to modification therefore our CmdParams variable allows that the files to be returned can be different depending on the parameters received open to extension Imagine that we are asked for another new functionality Now we need to count the files in the location provided and the files in the folders immediately inside i e the first level Let me explain that the Get ChildItem command has parameters that allow us to implement this type of requirements without the need to do any advanced engineering we will use the Recurse parameters to establish that the search is performed in the indicated location and in all the ones below and Depth to establish the maximum number of recursion that we need in our case the value is Surely you have already visualized the change to be made to the previous code From my point of view something very simple that will not take us more than minutes between the change and the tests to verify that it is correct In our code we have to include the above two parameters in the CmdParams variable for it to be applied It is a clean change just add new elements in our hashtable without having to modify the command line where the command is located which as we have said is certainly complex param Parameter Mandatory true String Location Parameter Mandatory true String Extensions CmdParams Path Location Filter Recurse true Depth Return Extensions Foreach CurrentExtension ToLower Transform extension to lower case CmdParams Filter CurrentExtension Set the filter to the current extension Return Get ChildItem CmdParams Measure Count Return an object with the extension as the key and the count obtained as the value SummarizingPassing parameters to PowerShell commands and scripts is simple We can use the standard way for command calls or simple scripts And also we can use more advanced techniques that allow us to have a cleaner code and implement modifications in a simpler way Using hashtables is an easy way to visualize the parameter values of the commands we invoke In addition it structures our code making it more readable for others or even for ourselves after a while The code for this article can be found in this gist FeedbackIf you liked this article do not forget to click on the heart or the unicorn and share it with your friends and colleagues Leave me your comments at the bottom about what you liked or how to improve and if you want me to write about other topics send me a direct message to my Twitter account CreditsThe header image comes from Unsplash and is courtesy of Markus Spiske 2022-04-04 07:10:13
海外TECH DEV Community Una forma fácil de pasar parámetros en tus scripts de PowerShell https://dev.to/codbugs/una-forma-facil-de-pasar-parametros-en-tus-scripts-de-powershell-1pfi Una forma fácil de pasar parámetros en tus scripts de PowerShellMi apodo en las redes es Coding Bugs y llevo desde el año trabajando como desarrollador y arquitecto de software En mi dashboard encontrarás artículos con información sobre lenguajes de programación técnicas de programación y otros conceptos que te ayudarán a mejorar Ya sabéis que PowerShell es el lenguaje de programación que Microsoft pone a nuestra disposición para la automatización de tareas multiplataforma compuesta por un shell de línea de comandos un lenguaje de scripting y un marco de gestión de la configuración En este artículo mostraréuna manera diferente de proporcionar valores a los parámetros de comandos y scripts Esta es una forma sencilla y simple de declarar parámetros y asignar sus valores que os permitiráorganizar vuestros scripts de forma que todo tenga más sentido Forma estándarSi conoces PowerShell ya sabes como proporcionar parámetros en tus llamadas Si no lo conoces simplemente indica el nombre del parámetro antecedido por un guion y a continuación escribe su valor Get ChildItem Path C Filter txt Devuelve todos los ficheros de texto existentes en C Como puedes observar la forma estándar es muy fácil y para casos en los que hagas invocaciones inmediatas es la mejor manera de proporcionar parámetros Sin embargo imagina que tienes que contar el número de ficheros de un determinado tipo ubicados en una localización específica de tu máquina En este caso tendríamos que repetir tantas veces como fuera necesario la invocación al comando anterior Get ChildItem proporcionando el parámetro Filter en base al tipo de fichero solicitado Get ChildItem Path C Filter html Measure Select Count Devuelve todos los ficheros HTML existentes en C Get ChildItem Path C Filter css Measure Select Count Devuelve todos los ficheros CSS existentes en C Get ChildItem Path C Filter js Measure Select Count Devuelve todos los ficheros JavaScript existentes en C Para ahorrarnos tiempo cada vez que nos soliciten esa información vamos a generar un script propio en el que añadamos estas llamadas Además vamos a incorporar un parámetro en el script para especificar la ubicación concreta donde contar cada uno de los ficheros HTML CSS y JS que hay param Parameter Mandatory true String Location Return Html Get ChildItem Path Location Filter html Measure Count Css Get ChildItem Path Location Filter css Measure Count Js Get ChildItem Path Location Filter js Measure Count ¿Quésucede si ahora nos piden incluir más y más tipos de fichero con diferentes extensiones La respuesta sería incluir más y más líneas a nuestro script para cumplir con lo que nos solicitan Pero ¿y si hubiera otra forma más sencilla y más versatil dotando a nuestro script de la capacidad de abstraerse de los tipos de extensión Una hashtable para pasar parámetrosEmpezaremos por añadir un nuevo parámetro donde se indiquen las extensiones de los ficheros que tenemos que contar Ahora sólo tendremos que iterar sobre estos valores y pasar la extensión correspondiente al comando Get ChildItem param Parameter Mandatory true String Location Parameter Mandatory true String Extensions Return Extensions Foreach CurrentExtension ToLower Transformar la extensión a minúsculas Return Get ChildItem Path Location Filter CurrentExtension Measure Count Devuelve un objeto con la extensión como clave y el recuento obtenido como valor Con esto sería suficiente para nuestro objetivo pero como programador que somos queremos que sea aún más abstracto y nos permita mantener la llamada al comando Get ChildItem más limpia evitando tener que volver a modificarla con nuevos parámetros Al ser una línea de comandos un poco compleja es mejor evitar su modificación al máximo posible o hacerla más simple diviéndola en trozos más simples Por el bien de este artículo elegimos la primera opción PowerShell permite el paso de un objeto hashtable para proporcionar cada uno de los parámetros que necesitamos del comando a ejecutar En nuestro caso el comando es Get ChildItem y los parámetros que estamos utilizando son Path y Filter La variable hashtable que crearemos serácomo la siguiente CmdParams Path Filter Y la llamada al comando es como la siguiente importante el uso de en el paso de nuestro hashtableGet ChildItem CmdParamsIgual que en el caso anterior tenemos que actualizar nuestra variable hashtable con la extensión correspondiente en cada iteración del Foreach param Parameter Mandatory true String Location Parameter Mandatory true String Extensions CmdParams Path Location Filter Return Extensions Foreach CurrentExtension ToLower Transformar la extensión a minúsculas CmdParams Filter CurrentExtension Establecer el filtro en la extensión actual Return Get ChildItem CmdParams Measure Count Devuelve un objeto con la extensión como clave y el recuento obtenido como valor Ya hemos conseguido lo que buscabamos hemos abstraido la llamada al comando Get ChildItem con respecto a los parámetros que necesitamos pasarle De esta forma podemos modificar la variable CmdParams añadiendo cambiando o quitando cualquier par clave valor en base a las necesidades funcionales que tengamos Podemos ver aquíel segundo principio del paradigma SOLID Open Closed Principle en el que se indica que el código debe ser cerrado a cualquier modificación pero abierto para extender su funcionalidad Podemos decir que el propósito de la iteración sobre cada una de las extensiones es retornar el número de ficheros existentes en la ubicación indicada El comando Get ChildItem puede ser invocado con otros parámetros que modificaráel número de ficheros que retorne pero su resultado seguirásiendo el mismo cerrado a modificación por tanto nuestra variable CmdParams permite que los ficheros a devolver pueda ser diferente dependiendo de los parámetros que reciba abierto a extensión Imagina que nos solicitan otra nueva funcionalidad Ahora se necesita contabilizar los ficheros de la ubicación proporcionada y los ficheros de las carpetas que se encuentran inmediatamente dentro es decir el primer nivel Déjame explicarte que el comando Get ChildItem dispone de parámetros que nos permiten implementar este tipo de requisitos sin necesidad de hacer ningún tipo de ingeniería avanzada usaremos los parámetros Recurse para establecer que se realice la búsqueda en la localización indicada y en todas las que hay por debajo y Depth para establecer el máximo número de recursividad que necesatimos en nuestro caso el valor es de Seguro que ya has visualizado el cambio que hay que realizar al código anterior Desde mi punto de vista algo muy sencillo que no nos llevarámás de minutos entre el cambio y las pruebas para verificar que es correcto En nuestro código tenemos que incluir los dos parámetros anteriores en la variable CmdParams para que se aplique Es un cambio limpio sólo añadir nuevos elementos en nuestro hashtable sin tener que modificar la línea de comandos donde se encuentra el comando que como hemos dicho es ciertamente compleja param Parameter Mandatory true String Location Parameter Mandatory true String Extensions CmdParams Path Location Filter Recurse true Depth Return Extensions Foreach CurrentExtension ToLower Transformar la extensión a minúsculas CmdParams Filter CurrentExtension Establecer el filtro en la extensión actual Return Get ChildItem CmdParams Measure Count Devuelve un objeto con la extensión como clave y el recuento obtenido como valor ResumiendoEl paso de parámetros en comandos y o scripts en PowerShelles sencillo Podemos utilizar la forma estándar para llamadas a comandos o en scripts sencillos Y también podemos usar técnicas más avanzadas que nos permitan tener un código más limpio e implementar modificaciones de forma más sencilla El uso de hashtables es una forma fácil de visualizar los valores de los parámetros de los comandos que invocamos Además estructura nuestro código haciendo que sea más legible para los demás o incluso para nosotros mismos despues de pasado un tiempo El código de este artículo lo tenéis en este gist FeedbackSi te ha gustado este artículo no olvides clicar en el corazón o el unicornio y compartirlo con tus amigos y compañeros Déjame tus comentarios en la parte inferior sobre lo que te ha gustado o como mejorar y si quieres que escriba acerca de otros temas mándame un mensaje directo a mi cuenta de twitter CréditosLa imagen de cabecera procede de Unsplash y es cortesía de Markus Spiske 2022-04-04 07:10:05
海外TECH DEV Community The Multi-Region road https://dev.to/aws-builders/the-multi-region-road-160h The Multi Region roadBuilding a multi region application is hard and there are a lot of questions to answer Therefore this blog post series is not aiming to cover every single scenario The first question I should answer is Why bother with multi region architectures My personal answer is to learn and explore possibilities that I am not exposed to in my typical day to day work life It is difficult to get exposure to such scenarios and of course each application is different from the other so there is no standard way to do it I created a challenge building a hypothetical application to explore possible ways and throw questions that perhaps I will not answer RequirementsThe application X got viral so it must handle the following The application is used in multiple European countries The application is serverless The application should have low latency The application should be able to stand to a region failure The application should scale And last but not least the application should comply with data privacy laws like the GDPR ConsiderationsThe requirements are very generic so that I will make assumptions during my multi region quest My regional application architecture is like this This blog series will focus on each component and answer each requirement RegionsEach region is a separate geographic area and they are designed to be isolated from each other Each region has multiple isolated locations called Availability Zones You can have a look at the AWS global infrastructure here I am interested in European countries and so from the map I can see that I have regions and all of them have availability zones Serverless comes with built in features like MultiAZ Autoscaling easing and leveraging each region s potential ScalabilityUnfortunately in the serverless world the regions are not born equals I have written here how it isn t easy to reach some scalability in some regions This should be considered in this context where the application will be under heavy traffic A way to help the scalability of the applications is to leverage for example the cache avoiding putting pressure on one of the chain s components For instance in our architecture I can apply cache at each level reducing the end user latency and the pressure of each service and their quotas Availability ReliabilityI know that I can count on AWS services and infrastructure so I need to make my service available It is worth remembering that even if my application is available does not mean that it is reliable For example I could contact the endpoint but still return errors because I have reached the Lambda burst concurrency However making the application more reliable will generally speaking also make the application more available Some patterns and techniques can be used and to mention some queuestreamretriescircuit breakerDepending on requirements and needs combining them will help minimize failures SecurityOne of the requirements is the GDPR but I am not an expert on this matter and I can safely assume that some data cannot be visible and cannot be moved outside the residency region One thing that I can do is intercept data before the application process So for example I could leverage the Lambda Edge where I intercept data and encrypt all sensitive data Then when it reaches my services like APIGW Lambda or DynamoDB it is already encrypted I wrote a PoC a while ago and the repository is available here About not leaving the region I do not have an answer yet but I guess not all the data stored is the same and so I could have maybe opportunities on this ConclusionMulti region architecture comport many challenges and I cannot cover all This series aims to analyze the primary options at my disposal and in each post I will try to evaluate what options AWS offers to handle this situation Stay tuned because in the following posts I will have a look at how to leverage Amazon CloudFrontAmazon API GatewayAmazon DynamoDBTo achieve my goal of Multi region architecture on AWS 2022-04-04 07:07:52
金融 日本銀行:RSS 日本銀行が保有する国債の銘柄別残高 http://www.boj.or.jp/statistics/boj/other/mei/release/2022/mei220331.xlsx 日本銀行 2022-04-04 17:00:00
金融 日本銀行:RSS 日本銀行による国庫短期証券の銘柄別買入額 http://www.boj.or.jp/statistics/boj/other/tmei/release/2022/tmei220331.xlsx 国庫短期証券 2022-04-04 17:00:00
金融 日本銀行:RSS 日本銀行が受入れている担保の残高(3月末) http://www.boj.or.jp/statistics/boj/other/col/col2203.xlsx 日本銀行 2022-04-04 17:00:00
金融 日本銀行:RSS FSBが「2022年の作業計画」を公表 http://www.boj.or.jp/announcements/release_2022/rel220404a.htm 作業計画 2022-04-04 17:00:00
ニュース ジェトロ ビジネスニュース(通商弘報) WTO、農産品の輸入管理手続き改正、途上国に配慮 https://www.jetro.go.jp/biznews/2022/04/d0e500a0b33242ab.html 途上国 2022-04-04 07:30:00
海外ニュース Japan Times latest articles Global leaders condemn ‘despicable’ civilian killings in towns near Kyiv https://www.japantimes.co.jp/news/2022/04/04/world/russia-ukraine-war-atrocities/ Global leaders condemn despicable civilian killings in towns near KyivUkraine accused Russia of war crimes after bodies were found bound and shot prompting calls for further sanctions against Moscow 2022-04-04 16:05:09
海外ニュース Japan Times latest articles Hong Kong leader Carrie Lam says she won’t seek second term https://www.japantimes.co.jp/news/2022/04/04/asia-pacific/politics-diplomacy-asia-pacific/hong-kong-carrie-lam-no-second-term/ electoral 2022-04-04 16:26:26
海外ニュース Japan Times latest articles Japan wingers Junya Ito and Kaoru Mitoma star in Belgian top-flight wins https://www.japantimes.co.jp/sports/2022/04/04/soccer/belgian-ito-mitoma-genk-royale-union/ Japan wingers Junya Ito and Kaoru Mitoma star in Belgian top flight winsIto the standout performer for Japan as they qualified for their seventh straight World Cup finals scored Genk s third goal during their trouncing of Eupen at 2022-04-04 16:16:04
ニュース BBC News - Home Hungary election: PM Viktor Orban criticises Ukraine's Zelensky as he wins vote https://www.bbc.co.uk/news/world-europe-60977917?at_medium=RSS&at_campaign=KARANGA election 2022-04-04 07:42:17
ニュース BBC News - Home Covid: Fines issued over No 10 event and EasyJet cancels flights https://www.bbc.co.uk/news/uk-60974408?at_medium=RSS&at_campaign=KARANGA coronavirus 2022-04-04 07:28:57
マーケティング MarkeZine アドテク企業のOgury、日本法人を設立 カントリーマネージャーに松本亮氏が就任 http://markezine.jp/article/detail/38719 ogury 2022-04-04 16:30:00
IT 週刊アスキー 新会社パナソニック コネクト設立─樋口泰行社長、想いを語る https://weekly.ascii.jp/elem/000/004/088/4088281/ 記者発表 2022-04-04 16:30:00
IT 週刊アスキー スシロー6日間の超短期フェアを開催!いつものフェアでは提供困難なネタがズラリ https://weekly.ascii.jp/elem/000/004/088/4088245/ 期間限定 2022-04-04 16:15:00
IT 週刊アスキー 『Re:ゼロから始める異世界生活 Lost in Memories』で本日4月4日より「クルシュ誕生日記念 交換イベント」を開催! https://weekly.ascii.jp/elem/000/004/088/4088285/ lostinmemories 2022-04-04 16:15:00

コメント

このブログの人気の投稿

投稿時間: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件)