投稿時間:2021-07-22 01:38:38 RSSフィード2021-07-22 01:00 分まとめ(41件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
TECH Engadget Japanese 『ゴースト・オブ・ツシマ ディレクターズ・カット』ストーリー予告編公開。新章『壹岐之譚』のドラマ描く https://japanese.engadget.com/ghost-of-tsushima-directors-cut-story-trailer-151428321.html ghost 2021-07-21 15:14:28
AWS AWS News Blog AWS Contact Center Day – July 2021 https://aws.amazon.com/blogs/aws/aws-contact-center-day-july-2021/ AWS Contact Center Day July Earlier this week I ordered from Amazon fr a box of four toothpaste tubes but only one was in the box I called Amazon s customer center The agent immediately found my order without me having to share the long order number She issued a refund and told me I even can keep the one tube I … 2021-07-21 15:25:48
AWS lambdaタグが付けられた新着投稿 - Qiita 超爆速でLamndaでDenoを動かしてみる https://qiita.com/yamachita0109/items/17baca2978e372c90c47 超爆速でLamndaでDenoを動かしてみる私はLmabdaが大好きだ。 2021-07-22 00:45:08
js JavaScriptタグが付けられた新着投稿 - Qiita Kintoneのトップページのポータルをタブ化しオリジナルのポータルとアプリ一覧を表示する https://qiita.com/ricorico/items/e6c86b9eb680e577bc8c そういったことをやりたい人はポータル管理アプリを別で作ってカスタマイズするという方法を選んだほうが良いと思います。 2021-07-22 00:07:45
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) AttributeError: 'WSGIRequest' object has no attribute 'site'のエラーを何とかしたい https://teratail.com/questions/350694?rss=all AttributeErrorxWSGIRequestxobjecthasnoattributexsitexのエラーを何とかしたい質問内容wagtailのライブラリを漁っています。 2021-07-22 00:51:54
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) WordPressの多言語プラグイン「Bogo」で投稿のカテゴリーページ https://teratail.com/questions/350693?rss=all WordPressの多言語プラグイン「Bogo」で投稿のカテゴリーページ前提・実現したいことWordPressの多言語プラグイン「Bogo」で投稿のカテゴリーを作成する場合の最適な方法が知りたいです。 2021-07-22 00:42:14
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) ciscoがline protocol is upしない https://teratail.com/questions/350692?rss=all cisco 2021-07-22 00:42:11
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) ApacheのaliasでError 403が取れません! https://teratail.com/questions/350691?rss=all 2021-07-22 00:29:00
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Tkinterでのwindowを閉じる処理について教えてください https://teratail.com/questions/350690?rss=all ネットを参考にflameでボタンの配置等はできましたが肝心のボタンにcommandをつける部分で詰まりました。 2021-07-22 00:20:22
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) PHP password_verifyを使う必要性 https://teratail.com/questions/350689?rss=all 2021-07-22 00:18:23
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) beatifulsoupを利用したjs形式の連想配列を取得するには https://teratail.com/questions/350688?rss=all beatifulsoupを利用したjs形式の連想配列を取得するにはこんにちはpython諸学者です。 2021-07-22 00:03:59
AWS AWSタグが付けられた新着投稿 - Qiita エンジニア夫婦が自分たちの結婚式用にプロフィールサイトとウェブアプリを作った話 https://qiita.com/danishi/items/6f0f2b3052bb1a841d11 クイズアプリ出題側予めURLを伝えたスタッフさんに操作してもらうPC用画面で、順番に問題を出題、最後に問題の正解とランキングの発表ができます。 2021-07-22 00:50:13
AWS AWSタグが付けられた新着投稿 - Qiita 超爆速でLamndaでDenoを動かしてみる https://qiita.com/yamachita0109/items/17baca2978e372c90c47 超爆速でLamndaでDenoを動かしてみる私はLmabdaが大好きだ。 2021-07-22 00:45:08
Docker dockerタグが付けられた新着投稿 - Qiita 'docker-compose'より'docker compose'を使うべき? https://qiita.com/kondo0602/items/81420bd1dd58f5c6ba3b 言われたので、試してみる同様にDockerComposeが使用できているが、何が違うのかいまいちわからない。 2021-07-22 00:51:31
Docker dockerタグが付けられた新着投稿 - Qiita Docker React環境簡単構築 https://qiita.com/A-Kira/items/d2f9c8cef9346cb32229 環境macOSBigSurDockerdockercompose構成├docker│└node│└Dockerfile├node│└reactsample└dockercomposeyml手順今回は、reactsampleという名前でアプリケーションが作成されます。 2021-07-22 00:48:30
Git Gitタグが付けられた新着投稿 - Qiita Git操作とブランチ戦略 https://qiita.com/itawn/items/959d3a0383bb384c5426 あくまでも指定したコミットを打ち消す変更を加えるだけで、指定したコミットよりも前の状態に戻してくれる指定したコミットを完全になかったことにしてくれるわけではないため、注意。 2021-07-22 00:35:28
海外TECH DEV Community 5 Packages to Optimize and Speed Up Your React App During Development https://dev.to/nilanth/5-packages-to-optimize-and-speed-up-your-react-app-during-development-4h5f Packages to Optimize and Speed Up Your React App During DevelopmentOptimize your React App during the development stage using these packages and avoid issues during production We keep on building apps without considering side effects due to time constraints and other factors But sometimes an app will cause major issues in live scenarios Then we might need to update our app and sometimes we might need to reconstruct some modules or make some architectural level changes to solve the issue Instead of handling such cases in production we can avoid giving rise to such issues during development itself So I have listed some packages that will help you find such issues during development Let s dive into these Why Did You Render K ️ Why did you render is a React package that allows you to find potentially avoidable re renders Most of the performance issues will arise from unwanted re renders If a big list component re renders multiple times It will make the app unresponsive To avoid these issues we will use pureComponents or useMemo but in some cases those also re render due to misuse of state updates We can avoid these using the why did you render package It will notify when and why the component re rendered Note For development use only Check the below image for how the warning message is consoled Source Map Explorer K ️ Source Map Explorer gives a view of the build with each file size that occupies the build It allows knowing which dependency occupies a larger file size in the bundle We could optimize the file based on the view Why this important As your app features grow the build size also increases A large build size will take more time to build We need to keep the build size small as much as we can Using Source Map Explorer we can analyze the build and optimize it It also supports Sass and LESS files Note For development use only Check the below image You can see the file size occupied percentage Also we can have a detailed view of each file Redux Immutable State Invariant ️ Redux Immutable State Invariant is a Redux middleware It detects mutations between and outside Redux dispatches If you are using Redux for state management you should not mutate the state in the reducer or outside As reducer always returns a new state object Mutating the state will lead to several issues in your app To avoid this we can use Redux Immutable State Invariant middleware This package will throw an error if the state is mutated So we can fix these issues in the development stage itself Note For development use only Bundle Size K ️ Bundle Size allows keeping your bundle size in check We can configure each file size in the config file So we will get a warning If the size exceeds It ensures the bundle size is in control Check the below bundle size config used by bootstrap You can also add it to your GitHub to check on every pull request Check the below image Immer K ️ Mutating a state will lead to more issues To avoid this we need to manually clone every state object and mutate it Instead of a manual clone We can use Immer which will handle it in a more efficient and optimized way Immer allows mutating states more conveniently You can also use Immer to mutate states in Redux Check the below code for Immer usage with Redux ResourcesWhy did you renderSource Map ExplorerRedux Immutable State InvariantBundle SizeImmer ConclusionWe can also use react devtools and redux devtools for optimizing the app I hope you have found this useful Thank you for reading Get more updates on Twitter More BlogsHow To Use Axios in an Optimized and Scalable Way With React Custom Hooks to Make your React Component Lightweight Ways to Host Your React App For FreeReact Alpha A Quick OverviewRedux Auth Starter A Zero Config CRA Template 2021-07-21 15:46:46
海外TECH DEV Community Setting up CI/CD Pipeline With Circle CI https://dev.to/kalashin1/setting-up-ci-cd-pipeline-with-circle-ci-49i9 Setting up CI CD Pipeline With Circle CIDevOps or CI CD as it is commonly called is practice that involves automating everything and anything we can from writing our code to deploying it Most of the time you are just building on existing knowledge just leveraging tools provided to you to automate certain repetitive parts of the software development cycle Things like running tests linting your code or deploying to your production environment they are often repetitive and impacts your productivity as developer But if we are super hero developers we would use CI CD tools to automatically do all this for us when we push our code to our repository By the end of this article you will be using CI CD to automate your workflow and become a super hero developer let s decipher what this term really is I will be using circle CI for setting up this workflow Let s dive in Continuous Integration CIContinuous Integration is concerned with all practices geared towards automating the process of adding new code to the code base we might have a project we are working with alone or with some other developer we can set up a CI pipeline that will test any new code that is being added to the code base this will keep our focus on writing code because immediately we have a pull request or a push to the repo the tests will automatically run and we get a console where we can see the logs coming from the process Head to circle ci to create an account when you are done create an empty git repository on github Go back to your circle ci dashboard click on projects and create a new project Select from the repo dropdown the repository which you just created circle ci will automatically give you a setup from which you can start a workflow If you pay attention to the logs on the project in your dashboard you will see information about the process and it will tell you why your workflow failed if it did Normally it will fail for the first time because we have not added any code whatsoever or dependencies let s go ahead and do that Assuming a dummy project and we have some test that we want to automate with our workflow the project structure looks like this Root spec node modules gitignore package json package lock jsonOur tests are contained inside the spec folder and i will not go into detail or show any code example about the tests because it is outside the scope of this article We need to add some circle ci configuration files to define a workflow that will help us automate our test First create a directory in the root folder and it should be named circleci and create a file config yml inside this folder This should give you a big hint the configuration file for setting up a circle ci workflow is written in yml if you have used github acitons then the process becomes a lot more easier Root spec node modules gitignore package json package lock json circleci config ymlLet s look at the actual structure of the config yml file You must choose a version of circle ci you want to use all config files requires thisversion You can use already packaged circle ci workflows they are called orbsorbs node circleci node We use the orbs for creating a node js workflowjobs This is where we define our actual process each process is classified into a job we can run multiple jobs Each job should have a name you can call it whatever you like test code Executor we must define one you can use circle ci s docker executors or your own custom docker executors docker image cimg node next we define the steps involved in creating the workflow steps Checkout the code as the first step move our code to the host machine checkout Install our dependencies with npm we can use circleci to cache dependencies them for future use node install packages We specify commands to run each command has a name and the actual terminal command like below run name Run tests command npm testworkflows Below is the definition of your workflow Inside the workflow you provide the jobs you want to run e g this workflow runs the test my code job above CircleCI will run this workflow on every commit sample jobs test codeif you save this file commit and push it to the repo associated with your circle ci project the workflow will immediately trigger and you should see the result of the workflow and the logs from the process in your dashboard it will enable you to see what went wrong so you would know how to tackle it if the test passed you can then merge it to the code base that is where continuous deployment comes in Continuous DeploymentIf continuous integration is about adding new code to existing code base then continuous deployment is concerned with automating the deployment of the newly added coded You might run your deploy command directly from the terminal after working on your project but it makes no sense to automate your tests then manually deploy your code But we are superhero developers so we will set up a circle ci CD pipeline to help us automate our code deployment we will be deploying to firebase hosting so i will assume that you are already familiar with firebase Assuming that our working directory above now contains a firebase project that we want to deploy Obviously we need to obtain our login credentials we can use in the CD From the command line run firebase login ci This will return us a login credential in the command line copy the credentials Head over to your circle ci dashboard navigate to the current project that we setup a CI for enter project settings From the project settings select environment variables and add new environment variable It s name should be FIREBASE TOKEN paste in the login credentials that firebase gave to us as it s value Head back to your local projects we will make some changes to our config yml we will be adding two commands one to build the project and another to deploy the project PAY ATTENTION TO NEW JOBS ADDEDversion orbs node circleci node jobs test and deploy code docker image cimg node next we define the steps involved in creating the workflow steps checkout node install packages run name Run tests command npm test This command builds the project e g a react or angular project run name Build Project command npm run build This command deploys to the project to firebase using the FIREBASE TOKEN we set earlier run name Deploy Project command node modules bin firebase deploy token FIREBASE TOKEN workflows sample jobs test and deploy codeNow if you save commit and push your local project to github circle ci will immediately run your workflow to test build and deploy the project But it doesn t make any sense to deploy the project every time there is a commit So you might want to create another branch makes continue working and push the code to the repository with this new branch thus anytime there is a pull request to the master branch we can tell cirlce ci to run our workflow Enter project settings on circle ci dashboard click on advanced settings Turn on only build pull requests That s it for this article i hope you find this useful maybe we might see how to set up pipelines to test and deploy to other platforms in the future 2021-07-21 15:44:38
海外TECH DEV Community 25 Vue Tips You Need to Know https://dev.to/michaelthiessen/25-vue-tips-you-need-to-know-2h70 Vue Tips You Need to KnowLearning to be a better Vue developer isn t always about the big concepts that take time and effort to master It s also about the short tips and tricks that can make your life a whole lot easier ーwithout a whole lot of work I ve picked up a ton of useful tips over the years developing and writing about Vue Some are clever some I use almost every day and some are more advanced ー but they re all useful All of these were first published in my weekly newsletter Make sure to sign up if you want more great tips like these Restrict a prop to a list of typesUsing the validator option in a prop definition you can restrict a prop to a specific set of values export default name Image props src type String style type String validator s gt square rounded includes s This validator function takes in a prop and returns either true or false ーif the prop is valid or not I often use this when I need more options than a boolean will allow but still want to restrict what can be set Button types or alert types info success danger warning are some of the most common uses ー at least in what I work on Colours too are a really great use for this But there are many more Default Content and Extension PointsSlots in Vue can have default content which allows you to make components that are much easier to use lt button class button click emit click gt lt slot gt lt Used if no slot is provided gt Click me lt slot gt lt button gt My favourite use for default slots though is using them to create extension points Basically you take any part of a component wrap it in a slot and now you can override that part of the component with whatever you want By default it ll still work the way it always has but now you have more options lt template gt lt button class button click emit click gt lt Adding in the slot tag does nothing at first gt lt We can override this by providing content to the slot gt lt slot gt lt div class formatting gt text lt div gt lt slot gt lt button gt lt template gt Now you can use this component in many different ways The easy default way or your own custom way lt Uses default functionality of the component gt lt ButtonWithExtensionPoint text Formatted text gt lt Use the extension point to create custom behaviour gt lt ButtonWithExtensionPoint gt lt div class different formatting gt Do something a little different here lt div gt lt ButtonWithExtensionPoint gt Here s a Codesandbox you can dive into Use quotes to watch nested valuesYou may not have known this but you can easily watch nested values directly just by using quotes watch route query id This is really useful for working with deeply nested objects Know when to use v if and when to avoid it Instead of using v if it s sometimes more performant to use v show instead lt ComplicatedChart v show chartEnabled gt When v if is toggled on and off it will create and destroy the element completely Instead v show will create the element and leave it there hiding it by setting it s style to display none Doing this can be much more efficient if the component you re toggling is expensive to render On the flip side if you don t need that expensive component immediately use v if so that it will skip rendering it and load the page just a bit faster Shorthand for single scoped slot no template tag needed Scoped slots are lots of fun but in order to use them you have to use a lot of template tags too Luckily there s a shorthand that let s us get rid of it but only if we re using a single scoped slot Instead of writing this lt DataTable gt lt template header tableAttributes gt lt TableHeader v bind tableAttributes gt lt template gt lt DataTable gt We can write this lt DataTable header tableAttributes gt lt TableHeader v bind tableAttributes gt lt DataTable gt Simple straightforward and marvelous Ok maybe not quite marvelous but still pretty good All of these tips were first published in my weekly newsletter Make sure to sign up if you want more great tips like these Conditionally Rendering Slots and why you d need to First I ll show you how then we ll get into why you d want to hide slots Every Vue component has a special slots object with all of your slots in it The default slot has the key default and any named slots use their name as the key const slots default lt default slot gt icon lt icon slot gt button lt button slot gt But this slots object only has the slots that are applied to the component not every slot that is defined Take this component that defines several slots including a couple named ones lt Slots vue gt lt template gt lt div gt lt h gt Here are some slots lt h gt lt slot gt lt slot name second gt lt slot name third gt lt div gt lt template gt If we only apply one slot to the component only that slot will show up in our slots object lt template gt lt Slots gt lt template second gt This will be applied to the second slot lt template gt lt Slots gt lt template gt slots second lt vnode gt We can use this in our components to detect which slots have been applied to the component for example by hiding the wrapper element for the slot lt template gt lt div gt lt h gt A wrapped slot lt h gt lt div v if slots default class styles gt lt slot gt lt div gt lt div gt lt template gt Now the wrapper div that applies the styling will only be rendered if we actually fill that slot with something If we don t use the v if we would end up with an empty and unnecessary div if we didn t have a slot Depending on what styling that div has this could mess up our layout and make things look weird So why do we want to be able to conditionally render slots There are three main reasons to use a conditional slot When using wrapper divs to add default stylesThe slot is emptyIf we re combining default content with nested slotsFor example when we re adding default styles we re adding a div around a slot lt template gt lt div gt lt h gt This is a pretty great component amirite lt h gt lt div class default styling gt lt slot gt lt div gt lt button click emit click gt Click me lt button gt lt div gt lt template gt However if no content is applied to that slot by the parent component we ll end up with an empty div rendered to the page lt div gt lt h gt This is a pretty great component amirite lt h gt lt div class default styling gt lt No content in the slot but this div is still rendered Oops gt lt div gt lt button click emit click gt Click me lt button gt lt div gt Adding that v if on the wrapping div solves the problem though No content applied to the slot No problem lt div gt lt h gt This is a pretty great component amirite lt h gt lt button click emit click gt Click me lt button gt lt div gt Here s a Codesandbox with a working demo if you want to take a look I wrote more tips on slots in this article Tips to Supercharge Your Slots Named Scoped and Dynamic How to watch a slot for changesThis tip comes from Austin Gil ー check out his awesome blog post on this here Sometimes we need to know when the content inside of a slot has changed lt Too bad this event doesn t exist gt lt slot change update gt Unfortunately Vue has no built in way for us to detect this However my friend Austin figured out a very clean way of doing this using a mutation observer export default mounted Call update when something changes const observer new MutationObserver this update Watch this component for changes observer observe this el childList true subtree true You ll also need to clean up the observer but Austin covers that and more in his article Mixing local and global styles togetherNormally when working with styles we want them to be scoped to a single component lt style scoped gt component background green lt style gt In a pinch though you can also add a non scoped style block to add in global styles if you need it lt style gt Applied globally component p margin bottom px lt style gt lt style scoped gt Scoped to this specific component component background green lt style gt Be careful though ー global styles are dangerous and hard to track down Sometimes though they re the perfect escape hatch and are exactly what you need Overriding styles of a child component ーthe right wayScoped CSS is fantastic for keeping things tidy and not accidentally bleeding styles into other parts of your app But sometimes you need to override the styles of a child component and break out of that scope Vue has a deep selector just for this lt style scoped gt Override CSS of a child component while keeping styles scoped my component gt gt gt child component font size px lt style gt Yes a couple months ago I covered exactly why you shouldn t do this but overriding styles can be the best solution we don t believe in best practices here Note If you re using a CSS pre processor like SCSS you may need to use deep instead Creating Magic with Context Aware ComponentsContext aware components are magical ー they adapt to what s going on around them automatically handling edge cases state sharing and more There are main types of context aware components but configuration is the one I find most interesting State SharingWhen you break up a large component into multiple smaller ones they often still need to share state Instead of pushing that work on whoever s consuming the components you can make this happen behind the scenes You may break up a Dropdown component into Select and Option components to give you more flexibility But to make it easier to use the Select and Option components share the selected state with each other lt Used as a single component for simplicity gt lt Dropdown v model selected options gt lt Split up for more flexibility gt lt Select v model selected gt lt Option value mustard gt Mustard lt Option gt lt Option value ketchup gt Ketchup lt Option gt lt div class relish wrapper gt lt Option value relish gt Relish lt Option gt lt div gt lt Select gt ConfigurationSometimes the behaviour of a component needs to be changed based on what s going on in the rest of the application This is often done to automagically handle edge cases that would otherwise be annoying to deal with A Popup or Tooltip should re position itself so it doesn t overflow out of the page But if that component is inside of a modal it should re position itself so it doesn t overflow out of the modal This can be done automagically if the Tooltip knows when it s inside of a modal StylingYou already create context aware CSS applying different styles based on what s happening in parent or sibling elements statistic color black font size px font weight bold Give some separation between stats that are right beside each other statistic statistic margin left px CSS variables let us push this even further allowing us to set different values in different parts of a page Check out this thread on Twitter if you want to discuss this concept Michael Thiessen michaelthiessen Context aware components are magical ー they adapt to what s going on around them automatically handling edge cases state sharing and more There are main types of context aware components Configuration is the most interesting one IMO PM Apr Exclusive tips and insights every weekJoin other Vue devs and get exclusive tips and insights like these delivered straight to your inbox every week You have great content in your emails I seriously learn something from every one of them ー Titus DecaliThanks for another beautiful tip ー Victor OnuohaLoving these and the spaced repetition ー Mark GoldsteinSign up here How to make a variable created outside of Vue reactive Vue and If you get a variable from outside of Vue it s nice to be able to make it reactive That way you can use it in computed props watchers and everywhere else and it works just like any other state in Vue If you re using the options API all you need is to put it in the data section of your component const externalVariable getValue export default data return reactiveVariable externalVariable If you re using the composition API with Vue you can use ref or reactive directly import ref from vue Can be done entirely outside of a Vue componentconst externalVariable getValue const reactiveVariable ref externalVariable Access using valueconsole log reactiveVariable value Using reactive instead import reactive from vue Can be done entirely outside of a Vue componentconst externalVariable getValue Reactive only works with objects and arraysconst anotherReactiveVariable reactive externalVariable Access directlyconsole log anotherReactiveVariable If you re still on Vue as many of us are you can use observable instead of reactive to achieve exactly the same result Destructuring in a v forDid you know that you can destructure in a v for lt li v for name id in users key id gt name lt li gt It s more widely known that you can grab the index out of the v for by using a tuple like this lt li v for movie index in Lion King Frozen The Princess Bride gt index movie lt li gt When using an object you can also grab the key lt li v for value key in name Lion King released director Jon Favreau gt key value lt li gt It s also possible to combine these two methods grabbing the key as well as the index of the property lt li v for value key index in name Lion King released director Jon Favreau gt index key value lt li gt Looping Over a Range in VueThe v for directive allows us to loop over an Array but it also let s us loop over a range lt template gt lt ul gt lt li v for n in gt Item n lt li gt lt ul gt lt template gt This will render out Item Item Item Item Item When we use v for with a range it will start at and end on the number we specify Watch anything in your componentIt took me a very long time to realize this but anything in your component that is reactive can be watched export default computed someComputedProperty Update the computed prop watch someComputedProperty Do something when the computed prop is updated You can watch computed propspropsnested valuesIf you re using the composition API any value can be watched as long as it s a ref or reactive object Stealing Prop TypesOften I find that I m copying prop types from a child component just to use them in a parent component But I ve discovered that stealing those prop types is much better than just copying them For example we have an Icon component being used in this component lt template gt lt div gt lt h gt heading lt h gt lt Icon type iconType size iconSize colour iconColour gt lt div gt lt template gt To get this to work we need to add the correct prop types copying from the Icon component import Icon from Icon export default components Icon props iconType type String required true iconSize type String default medium validator size gt small medium large x large includes size iconColour type String default black heading type String required true What a pain And when the prop types of the Icon component are updated you can be sure that you ll forget to come back to this component and update them Over time bugs will be introduced as the prop types for this component start to drift away from the prop types in the Icon component So that s why we ll steal them instead import Icon from Icon export default components Icon props Icon props heading type String required true It doesn t have to get any more complicated than that Except in our example we have icon added to the beginning of each prop name So we ll have to do some extra work to get that to happen import Icon from Icon const iconProps Do some processing beforehandObject entries Icon props forEach key val gt iconProps icon key toUpperCase val export default components Icon props iconProps heading type String required true Now if the prop types in the Icon component are modified our component will stay up to date But what if a prop type is added or removed from the Icon component To cover those cases we can use v bind and a computed prop to keep things dynamic All of these were first published in my weekly newsletter Make sure to sign up if you want more great tips like these Detecting clicks outside of an element or inside Once in awhile I need to detect whether a click happens inside or outside of a particular element el This is the approach I typically use window addEventListener mousedown e gt Get the element that was clicked const clickedEl e target el is the element you re detecting clicks outside of if el contains clickedEl Clicked inside of el else Clicked outside of el Recursive slotsOne time I decided to see if I could make a v for component using only the template Along the way I discovered how to use slots recursively too This is what the component looks like lt VFor vue gt lt template gt lt div gt lt Render the first item gt list lt If we have more items continue But leave off the item we just rendered gt lt v for v if list length gt list list slice gt lt div gt lt template gt If you wanted to do this with scoped slots ー and why wouldn t you ーit just takes a few tweaks lt template gt lt div gt lt Pass the item into the slot to be rendered gt lt slot v bind item list gt lt Default gt list lt slot gt lt v for v if list length gt list list slice gt lt Recursively pass down scoped slot gt lt template v slot item gt lt slot v bind item item gt lt template gt lt v for gt lt div gt lt template gt Here is how this component is used lt template gt lt div gt lt Regular list gt lt v for list list gt lt List with bolded items gt lt v for list list gt lt template v slot item gt lt strong gt item lt strong gt lt template gt lt v for gt lt div gt lt template gt For a more detailed explanation of this example and nested slots check out my blog post on it How to Use Nested Slots in Vue including scoped slots Component MetadataNot every bit of info you add to a component is state Sometimes you need to add some metadata that gives other components more information For example if you re building a bunch of different widgets for an analytics dashboard like Google Analytics If you want the layout to know how many columns each widget should take up you can add that directly on the component as metadata export default name LiveUsersWidget Just add it as an extra property columns props data return You ll find this metadata as a property on the component import LiveUsersWidget from LiveUsersWidget vue const columns LiveUsersWidget You can also access the metadata from within the component through the special options property export default name LiveUsersWidget columns created options contains all the metadata for a component console log Using this options metadata columns Just keep in mind that this metadata is the same for each instance of the component and is not reactive Other uses for this include but are not limited to Keeping version numbers for individual componentsCustom flags for build tools to treat components differentlyAdding custom features to components beyond computed props data watchers etc and many more I can t think of See a live example here Multi file single file componentsHere s a little known feature of SFC You can import files just like you would with a regular HTML file lt A single file component gt lt template src template html gt lt template gt lt script src script js gt lt script gt lt style scoped src styles css gt lt style gt If you need to share styles docs or anything else this can come in really handy Also perfect for that super long component file that s wearing out your finger from all the scrolling Here s a working demo of it in action Reusable Components Aren t What You ThinkReusable components don t have to be big or complex things I often make small and short components reusable Because I m not re writing this code all over the place updating it becomes much easier and I can make sure that every OverflowMenu looks and works exactly the same ー because they are the same lt OverflowMenu vue gt lt template gt lt Menu gt lt Add a custom button to trigger our Menu gt lt template button v slot bind gt lt Use bind to pass click handlers ay attributes etc gt lt Button v bind bind gt lt Use our own icon and no text for this button gt lt template icon gt lt svg src ellipsis svg gt lt template gt lt Button gt lt template gt lt Menu gt lt template gt Here we re taking a Menu component but adding a ellipsis icon to the button that triggers it open It almost seems like it s not worth making a reusable component out of this because it s only a few lines Can t we just add the icon every time we want to use a Menu like this But this OverflowMenu will be used dozens of times and now if we want to update the icon or it s behaviour we can do it very easily And using it is much simpler too lt template gt lt OverflowMenu menu items items click handleMenuClick gt lt template gt If you want to go even deeper on building highly reusable components I have a course that teaches you a completely different way of thinking about your components Calling a Method from Outside of the ComponentYou can call a method from outside of a component by giving it a ref lt Parent vue gt lt template gt lt ChildComponent ref child gt lt template gt Somewhere in Parent vuethis refs child method Let me explain this one a bit more Every now and then the best practices don t work for what you re doing and you need an escape hatch like this Typically we communicate between components using props and events Props are sent down into child components and events are emitted back up to parent components lt template gt lt ChildComponent tell me what to do someInstructions something happened hereIWillHelpYouWithThat gt lt template gt Once in a while though you may end up in a situation where you need your parent to trigger a method in the child component This is where only passing props down doesn t work as well You could pass a boolean down and have the child component watch it lt Parent vue gt lt template gt lt ChildComponent trigger shouldCallMethod gt lt template gt Child vueexport default props trigger watch shouldCallMethod newVal if newVal Call the method when the trigger is set to true this method This works fine but only on the first call If you needed to trigger this multiple times you d have to clean up and reset the state The logic would then look like this The Parent component passes true to trigger propWatch is triggered and the Child component calls the methodThe Child component emits an event to tell the Parent component that the method has been triggered successfullyThe Parent component resets trigger back to false so we can do this all over againUgh Instead if we set a ref on the child component we can call that method directly lt Parent vue gt lt template gt lt ChildComponent ref child gt lt template gt Somewhere in Parent vuethis refs child method Yes we re breaking the props down events up rule and we re breaking encapsulation but it s so much cleaner and easier to understand that it s worth it Sometimes the best solution ends up being the worst solution Watching Arrays and ObjectsThe trickiest part of using a watcher is that sometimes it doesn t seem to trigger properly Usually this is because you re trying to watch an Array or an Object but didn t set deep to true export default name ColourChange props colours type Array required true watch Use the object syntax instead of just a method colours This will let Vue know to look inside the array deep true We have to move our method to a handler field handler console log The list of colours has changed Using the reactivity API from Vue would look like this watch colours gt console log The list of colours has changed deep true Here are the docs for Vue and Vue if you want to read more on this Deep Linking with Vue RouterYou can store a bit of state in the URL allowing you to jump right into a specific state on the page For example you can load a page with a date range filter already selected someurl com edit date range last weekThis is great for the parts of your app where users may share lots of links for an app that is server rendered or communicating more information between two separate apps than a regular link normally provides You can store filters search values whether a modal is open or closed or where in a list we ve scrolled to ーperfect for infinite pagination Grabbing the query using vue router works like this this will work on most Vue frameworks like Nuxt and Vuepress too const dateRange this route query dateRange To change it we use the RouterLink component and update the query lt RouterLink to query dateRange newDateRange gt Here s a demo of this in action Another Use for the Template TagThe template tag can be used anywhere inside of your template to organize code better I like to use it to simplify v if logic and sometimes v for too In this example we have several elements that all use the same v if condition lt template gt lt div class card gt lt img src imgPath gt lt h gt title lt h gt lt h v if expanded gt subheading lt h gt lt div v if expanded class card content gt lt slot gt lt div gt lt SocialShare v if expanded gt lt div gt lt template gt It s a little clunky and not obvious at first that a bunch of these elements are being shown and hidden together On a bigger more complicated component this could be an even worse situation But we can fix that We can use the template tag to group these elements and lift the v if on to the template tag itself lt template gt lt div class card gt lt img src imgPath gt lt h gt title lt h gt lt template v if expanded gt lt h gt subheading lt h gt lt div class card content gt lt slot gt lt div gt lt SocialShare gt lt template gt lt div gt lt template gt Now we have something that s much easier to read And it s much easier to understand what s going on at a glance A better way to handle errors and warnings You can provide a custom handler for errors and warnings in Vue Vue const app createApp App app config errorHandler err gt alert err Vue Vue config errorHandler err gt alert err Bug tracking services like Bugsnag and Rollbar hook into these handlers to log errors but you can also use them to handle errors more gracefully for a better UX For example instead of the application just crashing if an error is unhandled you can show a full page error screen and get the user to refresh or try something else In Vue the error handler only works on template and watcher errors but the Vue error handler will catch almost everything The warning handler in both versions only works in development I created a demo showing how this works It uses Vue but Vue works nearly the same Error Handler Demo Exclusive tips and insights every weekJoin other Vue devs and get exclusive tips and insights like these delivered straight to your inbox every week You have great content in your emails I seriously learn something from every one of them ー Titus DecaliThanks for another beautiful tip ー Victor OnuohaLoving these and the spaced repetition ー Mark GoldsteinSign up here 2021-07-21 15:32:40
海外TECH DEV Community It's alive! Simulate organisms with Conway's game of life on a canvas 🧫🔋 https://dev.to/thormeier/it-s-alive-conway-s-game-of-life-on-a-canvas-25ja It x s alive Simulate organisms with Conway x s game of life on a canvas Today we create living organisms We ll kind of at least It s the next best thing to becoming a st century digital Web Dev Doctor Frankenstein Conway s game of life What Excellent question The best actually Let me explain John Horton Conway was a British mathematician He contributed to a lot of different fields in mathematics such as number theory algebra geometry combinatorial game theory algorithmics group theory and analysis He developed a ton of remarkable algorithms such as the Doomsday algorithm that lets you find out the weekday of any given date with a only a few steps I ve explained the Doomsday rule in this post some time ago Algorithm explained The Doomsday rule Pascal Thormeier・Nov ・ min read computerscience php tutorial maths Conway developed the Game of Life in as an applied example of abstract computers It s a dimensional field with X and Y coordinates where each integer coordinate represents a cell that can be either alive or dead depending on some rules But since it s a game how is it played The rules of the gameYou can think of the Game of Life as a sandbox Originally no cell is alive Alive cells can be either set by the user or sprinkled in randomly In each game tick the game determines which cells are alive and which ones are dead in the next generation This step is then repeated until the user interrupts To determine the next generation the game looks at each cells neighbors and applies a set of rules If a cell was alive in the current generation If it has less than loneliness or more than overpopulation alive neighbors it dies in the next generation otherwise it stays aliveIf a cell was dead in the current generation If it has exactly alive neighbors it will become alive in the next generation otherwise it stays dead These rules allow for some pretty complex structures but we ll come to that later Let s make an example or twoLet s consider a by grid We re going to see how the rules work by applying them to the center cell All other cells are the center cell s neighbors Here we can see what happens if less than neighboring cells are alive The filled cell in the middle is alive in this generation but dies the next generation In the following picture we can see how it could look like if a cell is being born One thing is important though The next generation needs to be calculated all at once Meaning If the game sets cell as alive that was dead before and starts applying the rules to its immediate neighbor cell it should not consider the new state of cell alive but the old one dead for the calculation of cell But this begs a question What does it do at the border of the field There s two possibilities Either we consider the border as always dead they are neighbors but the rules are never applied to them or the world is actually formed like a donut Tasty torusWhen the field is shaped like a donut it behaves like this Whatever leaves either side will reenter on the opposite side When you connect those sides the shape will actually look like a donut Or in mathematics speech A torus So that s all the info we need Let s start implementing this Coding out the game of lifeLet s start with the field I will create the field as a nested array of by boolean variables const field for let y y lt y field y for let x x lt x field y x false By setting everything false the code will consider all cells as dead True on the other hand would mean that a cell is alive Next I need a function to get any cell s neighbors A cell is identified by its X and Y values so I can add and subtract to to those values to get all neighbors const getNeighbors x y field gt let prevX x let nextX x let prevY y let nextY y return field prevY prevX field prevY x field prevY nextX field y prevX field y x That s the cell itself we don t need this field y nextX field nextY prevX field nextY x field nextY nextX But wait the field is a donut So I need to catch the border cases as well const getNeighbors x y field gt let prevX x if prevX lt prevX field length let nextX x if nextX field length nextX let prevY y if prevY lt prevY field length let nextY y if nextY field length nextY So this function now returns an array of boolean values The game s rules don t care about which neighbors are alive or dead only how many of them are The next step is to actually implement the rules Ideally I ve got a function that takes X and Y values as well as the field and returns the state of the cell for the next generation const getDeadOrAlive x y field gt const neighbors getNeighbors x y field const numberOfAliveNeighbors neighbors filter Boolean length Cell is alive if field y x if numberOfAliveNeighbors lt numberOfAliveNeighbors gt Cell dies return false Cell stays alive return true Cell is dead if numberOfAliveNeighbors Cell becomes alive return true Cell stays dead return false And that s pretty much it for the game rules Now I create a function to draw the entire field on a square canvas const scaleFactor const drawField field gt const canvas document querySelector canvas const context canvas getContext d Fill entire field context fillStyle fff context fillRect scaleFactor scaleFactor context fillStyle Fill alive cells as small rectangles field forEach row y gt row forEach cell x gt if cell context fillRect x scaleFactor y scaleFactor scaleFactor scaleFactor Now let s add some control buttons to let the game automatically calculate and draw new generations each ms let nextField fielddrawField field const step gt nextField nextField map row y gt row map x gt return getDeadOrAlive x y nextField drawField nextField let interval nulldocument querySelector step addEventListener click step document querySelector start addEventListener click gt interval setInterval step document querySelector stop addEventListener click gt clearInterval interval And some more controls for defaults random reset etc document querySelector reset addEventListener click gt for let y y lt y for let x x lt x field y x false nextField field drawField field document querySelector glider addEventListener click gt for let y y lt y for let x x lt x field y x false field true field true field true field true field true nextField field drawField field document querySelector random addEventListener click gt for let y y lt y for let x x lt x field y x Math random gt nextField field drawField field document querySelector canvas addEventListener click event gt const x Math floor event offsetX scaleFactor const y Math floor event offsetY scaleFactor field y x field y x nextField field drawField field Of course this needs some HTML too lt DOCTYPE html gt lt html gt lt head gt lt style gt canvas box sizing border box border px solid width px height px container box sizing border box width px border px solid margin top px padding px lt style gt lt head gt lt body gt lt h gt Conway s game of life on a canvas lt h gt lt canvas id canvas width height gt lt canvas gt lt div class container gt lt button id start gt Start lt button gt lt button id stop gt Stop lt button gt lt button id step gt Step lt button gt lt div gt lt div class container gt lt button id reset gt Reset to empty lt button gt lt button id glider gt Set single glider lt button gt lt button id random gt Random alive lt button gt lt div gt lt script src index js gt lt script gt lt body gt lt html gt The final resultAnd here s a codepen where you can play around with it Because of the size of the canvas and the non responsive nature of the example I recommend running it in scale Have fun exploring Some remarkable structuresThere s some cell structures that are worth mentioning A rather simple one is called a glider As you can see this thing actually moves in a straight line by one unit on the X and Y axis every generations Since it s going back to its original state again this structure is able to move indefinitely But there s more Some structures are static for example a by alive square flip between two states one example being a straight line along either the X or Y axis consisting of alive cells others are capable of moving and even producing gliders at intervals You see this really is the closest thing to creating living organisms as you can get with around lines of JS and a canvas I hope you enjoyed reading this article as much as I enjoyed writing it If so leave a ️or a I write tech articles in my free time and like to drink coffee every once in a while If you want to support my efforts buy me a coffee or follow me on Twitter You can also support me directly via Paypal 2021-07-21 15:26:46
海外TECH DEV Community React useState hook usage https://dev.to/pa1sathvik/react-usestate-hook-usage-b8 React useState hook usageHi everyone today we will see how to use React useState hook Hooks are a new addition in React They let u use state and other React features without writing a class Before React we don t have state feature usage in functional components as if they were like side characters in React From React React team decided to make functional components as main roles in react development with introduction of hooks Hooks plays a pivotal role in bridging the gap between State and functional components Now we can develop React applications with major usage of functional components I am doing the same now Though I don t dare to rewrite existing class based components Ok let get into React useState Trust me I will not bore you with classic traditional You clicked count times example In class based components we use this state to declare state variables and its initial values A good fat example below in which state maintains multiple data constructor props super props this state currentPageBuilds downloadedData filteredData builds sort submittedDate page order desc limit Type boxId boxName selectedRows data q totalCount loading false isFiltered false failure false Now we will see how to use useState in Functional Components First we will import the required modules from react import React useState from react here we have imported the useState to maintain the state of the React component Now we will create test functional component to use state import React useState from react function State return lt div gt lt div gt export default StateNow we will create state variable using React useState to store data returned by Free JSON API Link const characters setCharactersData useState In the above declaration of state We used array destructuring to give names to our current state and function to update that state characters holds characters data returned by API setCharactersData function is used to set update data to characters variable As part of useState you are using react hook to create state with array data type and initial data is empty array useState will take initial value as parameter Here we initialized with empty array Lets use this as part of CharacterSummary functional component to fetch data from API and to store names as part of state import styles css import React useState from react export default function App const characters setCharactersData useState const fetchData async gt await fetch then res gt res json then data gt let names data forEach function item names push item name setCharactersData names return lt div gt lt label gt Data is lt label gt lt p gt characters lt p gt lt button onClick gt fetchData gt Click lt button gt lt div gt In the above component we are displaying a button in UI When the above JSX rendered a button will be shown in the UI Data will be null as state is empty array When we click on button fetch will get the details from API and all names will be stored as part of characters state Same will be displayed in the UI Some questions on React useState What if we want to use more than one state variable Simply use useState multiple times to declare multiple state variables If you want to use only one useState variable then declare all variables as a object in one useState Sample below const multiple setMultiple useState currentPageBuilds downloadedData filteredData builds sort submittedDate page order desc limit Type boxId boxName selectedRows data q totalCount loading false isFiltered false failure false You can update any variable in this complex state like this setMultiple multiple failure true Can we use useState any where No React hooks can be used only at top level Don t call Hooks inside loops conditions or nested functions Only call hooks in React functions not from any Java script functions Some more points on useState The update function of useState doesn t update the value right away It is asynchronous If same value is updated to the state React wont re render the component as React uses Object is to compare the updated state values with previous one In case of complex objects useState replaces the objects instead of merging If you use the previous value to update state you must pass a function that receives the previous value and returns an updated value Sample below setMessage previousVal gt previousVal currentVal Thats all I have reg useState Will update the article once i found more details Thanks 2021-07-21 15:25:24
海外TECH DEV Community Enums in C#: Hidden Pitfalls https://dev.to/vasilievserg/enums-in-c-hidden-pitfalls-3254 Enums in C Hidden PitfallsC has low barriers to entry and forgives a lot Seriously you may not understand how things work under the hood but still write code and remain easy going about this Though you still have to deal with different nuances over time Today we ll look at one of such subtle aspects handling enumerations Rarely do we get the chance to find a developer who hasn t encountered enumerations However anyone can make an error when using them It is more likely if it is not an error but an optimization issue in the application For example this due to high GC pressure you have to write a lot of code There is no time to delve into all nuances of the language Besides in practice the problems below may not be issues for your application However if such code repeatedly executes like tens of millions of times and starts inconveniencing you ll already know what you re dealing with Note All the research we will be doing below has been done for NET Framework It s an important comment We ll talk about NET a bit later Unexpected GC PressureI encountered this problem not long ago when I was dealing with various optimizations of the C PVS Studio analyzer Yes we already had one article on this subject but I think there will be more During this process I was fixing various places in code As practice has shown even small edits can boost performance if made in the app s bottlenecks At some point based on the profiling results I got to VariableAnnotation class We ll consider its simple version enum OriginType Field Parameter Property class VariableAnnotation lt T gt where T Enum public T Type get public SyntaxNode OriginatingNode get public VariableAnnotation SyntaxNode originatingNode T type OriginatingNode originatingNode Type type public override bool Equals object obj if obj is null return false if obj is not VariableAnnotation lt T gt other return false return Enum Equals this Type other Type amp amp this OriginatingNode other OriginatingNode public override int GetHashCode return this OriginatingNode GetHashCode this Type GetHashCode Now let s write two simple methods in which VariableAnnotation type instances are compared in the loop VariableAnnotation type instance is created and has a hash code calculated in the loop Corresponding methods static void EqualsTest var ann new VariableAnnotation lt OriginType gt new SyntaxNode OriginType Parameter var ann new VariableAnnotation lt OriginType gt new SyntaxNode OriginType Parameter while true var eq Enum Equals ann ann static void GetHashCodeTest var ann new VariableAnnotation lt OriginType gt new SyntaxNode OriginType Parameter while true var hashCode ann GetHashCode If you run any of these methods and watch the application in dynamics you can note nasty specifics it puts pressure on GC For example this can be seen in Visual Studio Diagnostic Tools window Process Hacker on the NET performance tab of process information also shows this Above examples clearly indicate two culprits Enum Equals ann ann ann GetHashCode Let s deal with them one by one Enum EqualsHere s the code we ll investigate next static void EnumEqTest OriginType originLhs OriginType originRhs while true var eq Enum Equals originLhs originRhs The first thing experts will pay attention to is that there is no Enum Equals IDE will help here by the way In this case the Object Equals object objA object objB method is called The IDE itself drops a hint about this We work with instances of value type whereas we need reference types to call the method Therefore boxing will take place before the method call By the way if you look into the IL code you can find boxing commands method private hidebysig static voidEnumEqTest valuetype EnumArticle Program OriginType originLhs valuetype EnumArticle Program OriginType originRhs cil managed Code size x maxstack IL ldarg IL box EnumArticle Program OriginType IL ldarg IL box EnumArticle Program OriginType IL c call bool mscorlib System Object Equals object object IL pop IL br s IL Here we clearly see the call of the System Object Equals object object method The command of arguments boxing box IL IL is also called Since we box objects only to call the method the corresponding references are not saved anywhere Hence the boxed objects will be cleaned up during garbage collection Note Someone may say ーeveryone can see that Enum Equals Object Equals Look even IDE highlights this The answer is no no and again no The simplest proof is that such code was written And I m sure some developers use a similar way of comparison As for obviousness very often people fall into the trap of thinking that if something is obvious to them it s obvious to everyone That s not the case If we change the Enum Equals call in fact ーObject Equals to compare through we get rid of unnecessary boxing var eq originLhs originRhs However we should remember that the generic code version the VariableAnnotation type was generic will not compile static void EnumEq lt T gt T originLhs T originRhs where T Enum while true error CS Operator cannot be applied to operands of type T and T var eq originLhs originRhs Calls of instance Enum Equals and Enum CompareTo methods will not work out for usーthey entail boxing The way out can be the generic EqualityComparer type For example one can safely use a default comparator The code will roughly look as follows static void EnumEq lt T gt T originLhs T originRhs where T Enum while true var eq EqualityComparer lt T gt Default Equals originLhs originRhs The EqualityComparer Equals T x T y method receives arguments of generic type and therefore does not require boxing at least before its call Inside the method call it s okay too Boxing commands are gone in the IL command code method private hidebysig static voidEnumEq lt mscorlib System Enum T gt T originLhs T originRhs cil managed Code size xf maxstack IL call class mscorlib System Collections Generic EqualityComparer lt gt class mscorlib System Collections Generic EqualityComparer lt T gt get Default IL ldarg IL ldarg IL callvirt instance bool class mscorlib System Collections Generic EqualityComparer lt T gt Equals IL c pop IL d br s IL Visual Studio profiler doesn t capture any garbage collection events in this code Process Hacker indicates the same thing You might become interested in how EqualityComparer really works on the inside As for me I got curious The source code of this type is available for example at referencesource microsoft com Enum GetHashCodeNow consider what is going on with the Enum GetHashCode method Let s start with the following code static void EnumGetHashCode OriginType origin while true var hashCode origin GetHashCode You may be surprised by what is happening here boxing and as a result the GC pressure The profiler and Process Hacker signals us about this again So why not indulge yourself and get nostalgic Let s compile this code via Visual Studio We ll get the IL code like this method private hidebysig static void EnumGetHashCode valuetype EnumArticleVS Program OriginType origin cil managed Code size xe maxstack IL ldarg IL box EnumArticleVS Program OriginType IL callvirt instance int mscorlib System Object GetHashCode IL b pop IL c br s IL Everything seems to be expected the box command is in the right place IL This answers the question where the boxing and the GC pressure come from Let s return to the modern world and now compile the code in Visual Studio We got the following IL code method private hidebysig static void EnumGetHashCode valuetype EnumArticle Program OriginType origin cil managed Code size x maxstack IL ldarga s origin IL constrained EnumArticle Program OriginType IL callvirt instance int mscorlib System Object GetHashCode IL d pop IL e br s IL Suddenly the box command disappeared just like a pencil in The Dark Knight Yet the boxing and the GC pressure remained At this point I decided to check out the Enum GetHashCode implementation at referencesource microsoft com System Security SecuritySafeCritical public override unsafe int GetHashCode Avoid boxing by inlining GetValue return GetValue GetHashCode fixed void pValue amp JitHelpers GetPinningHelper this m data switch InternalGetCorElementType case CorElementType I return sbyte pValue GetHashCode case CorElementType U return byte pValue GetHashCode case CorElementType Boolean return bool pValue GetHashCode default Contract Assert false Invalid primitive type return The most intriguing part here is the comment Avoid boxing It s like something doesn t add up Boxing must be missing as well as the box command in the IL code But memory allocation in the managed heap and garbage collection events are in place Let s see the CIL specification to get a better deal with IL code I cite the method call again so that you have it right in front of your eyes ldarga s originconstrained EnumArticle Program OriginTypecallvirt instance int mscorlib System Object GetHashCode As for the ldarga s instruction it s all simple The address of the method argument is loaded to the evaluation stack Next comes the constrained prefix Prefix format constrained thisTypeStack transition ptr arg argN gt ptr arg argDepending on what thisType is the way the ptr managed pointer is handled differs if thisType is a reference type ptr is dereferenced and passed as a this pointer to a method called through callvirt if thisType is a value type that implements the called method ptr is passed to this method as this pointer as is if thisType is a value type that does not implement the called method then the ptr pointer is dereferenced the object is boxed After this the resulting pointer is passed as a this pointer to the called method As noted in the specification the latter case is only possible when the method is declared in System Object System ValueType and System Enum and not is overridden in the child type The second case in the list above allows you to exclude an object boxing when a method is called if possible But we faced a third case GetHashCode is overridden in System Enum System Enum is the base type for OriginType However the enumeration itself does not override the methods from System Enum This is why the boxing happens when they are called I d like to emphasize that this is relevant for any value types If you don t override the base method the object will be boxed to call it struct MyStructBoxing private int field struct MyStructNoBoxing private int field public override int GetHashCode return field static void TestStructs MyStructBoxing myStructBoxing MyStructNoBoxing myStructNoBoxing while true var hashCode myStructBoxing GetHashCode boxing var hashCode myStructNoBoxing GetHashCode no boxing But let s go back to the enumerations We can t override the method in enumeration So what can we do with them The System Collections Generic EqualityComparer type that I have mentioned before may be really helpful here This type contains the generic GetHashCode method public abstract int GetHashCode T obj var hashCode EqualityComparer lt OriginType gt Default GetHashCode origin NET VS NET Framework in Considered ExamplesAs I said earlier everything said above was relevant to the NET Framework Let s see how things are going in NET shall we EqualsAs expected boxing is present No surprise here as we still need to call the Object Equals object object method So it s not worth comparing enumeration elements in this way anyway Speaking about the Enum Equals instance method the argument still has to be boxed GetHashCodeAnd this is where a nice surprise was waiting for me Let s recall the code example static void GetHashCodeTest OriginType origin while true var hashCode origin GetHashCode Let me remind you that when you run this code in NET Framework new temporary objects are created because of boxing The result is additional GC pressure But nothing similar happens when using NET and NET Core No temporary objects no GC pressure PerformanceOkay we kind of dealt with the boxing issue Let s move on to the performance question At the same time we ll compare the speed of the same code for NET Framework and NET All the code for the compared methods is the same There will be two differences how we compare enumeration elements and how we get hash codes EqualsDescription of comparison ways used in methods ObjectEquals Object Equals lhs rhs Enum Equals lhs Equals rhs Enum CompareTo lhs CompareTo rhs EqualityComparerEquals EqualityComparer Default Equals lhs rhs DirectComparison lhs rhs Execution times are compared below NET Framework NET I m thrilled with the results of EqualityComparer on NET As for the performance we got about the same time as in direct comparison of enumeration items Kudos to Microsoft When you update the target framework runtime you get optimization out of the box without changing C code GetHashCodeDescription of ways to get hash code used in methods EnumGetHashCode origin GetHashCode UnderlyingValue int origin UnderlyingValueGetHashCode int origin GetHashCode EqualityComparerGetHashCode EqualityComparer Default GetHashCode origin The first and the last points are clear now The second and third are hash code hacks inspired by Enum GetHashCode and Int GetHashCode implementations They are still unresistant to changes of underlying type and not very obvious I m not encouraging to write like this Yet I added them to the tests for the sake of interest Execution times are compared below NET Framework NET We ve got good news at once in NET there is no boxing when calling GetHashCode directly EqualityComparer the same as with Equals now shows better performance ConclusionC is cool You can code in it for years and not know about nuances related to basic things why out parameters can remain uninitialized why the result of nullable value boxing can be null why boxing happens when you call GetHashCode for enumerations And when you have to deal with something like this it may be extremely engaging to get the point I m getting high from that I hope you do as well As usual consider subscribing to my Twitter so you don t miss out on anything noteworthy 2021-07-21 15:23:30
海外TECH DEV Community Road To An Internship - Starting Off [0/3] https://dev.to/codechem/road-to-an-internship-starting-off-0-3-2h14 Road To An Internship Starting Off Hey folks In December of I decided to pursue a career as a web developer in this series of articles I ll be talking about the steps I took You don t have to follow these exact steps however I wanted to write about my experience and on top of that I hope to motivate some of you future developers who are currently trying to forge your own path I m far from a full stack web developer nevertheless I have the mindset of learning new things everyday Taking that in account I ve accomplished a lot of my goals that I had in mind when I was starting One of them was securing an internship and working what I love Starting Off I have to say that I had prior programming knowledge before I started learning with a more serious approach Where did I start CSS I practiced CSS a LOT It might sound weird but if you start working with responsive designs grid designs flexbox and the rest you need to know CSS quite well I recommend everyone who s a beginner to use Bootstrap s Grid system As I was working through the grid system I was acquiring knowledge in colors Adobe Color is an amazing tool which assisted me in choosing and picking colors My way of learning is making projects in my opinion that is the best way to learn a skill I picked up a Udemy course about CSS and created a website called Omnifoods It s not the finest websites however I acquired plenty of knowledge Some other pretty useful websites if you re starting areGlyphs to and last but not least Octopus I m in love with Octopus since it makes sure you plan out your website prior to doing the programming To be continued That s how I started out in the next article I ll be talking how I learned about API s Node js and much more Thanks for reading 2021-07-21 15:07:09
海外TECH DEV Community FullStack React - Code Examples to start fast https://dev.to/sm0ke/fullstack-react-code-examples-to-start-fast-2o38 FullStack React Code Examples to start fastHello Coders This article presents a curated list with FullStack React Examples that are more than templates All mentioned products come with JWT token authentication database SQLite or Mongo and API backend servers provided in different technologies like Node JS Flask and Django The open source fullstack starters can be downloaded from Github and used for hobby and commercial products Thanks for reading Content provided by App Generator Free React Node JS Berry fullstack React sample Free React Node JS Datta Able fullstack React sampleReact Node JS Datta PRO premium fullstack React sampleThe above products can be used and combined with more than one Backend because the API interface is common to all servers Free Node JS API Typescript SQLite TypeORM Free Django API simple JWT API server Free Flask API simple JWT API serverNode JS API PRO comes with more features and MongoDB Mongoose as database interface Typescript and Docker scripts Fullstack React BerryBerry is a creative React Dashboard build using the Material UI It is meant to be the best User Experience with highly customizable feature riched pages It is a complete game changer React Dashboard Template with an easy and intuitive responsive design as on retina screens or laptops The product comes with a simple JWT authentication flow login register logout React Node JS Berry product pageReact Node JS Berry LIVE Demo Fullstack React Datta AbleDatta Able is an open source React Dashboard that provides a colorful and modern design Datta Able React Free is the most stylized React Free Admin Template around all other admin templates in the market It comes with high feature rich pages and components with fully developer centric code The product comes with a simple JWT authentication flow login register logout React Node JS Datta Able product pageReact Node JS Datta Able LIVE Demo Fullstack React Datta Able PRODatta Able is a premium React Dashboard that provides a colorful and modern design Datta Able React PRO is the most stylized React Free Admin Template around all other admin templates in the market It comes with high feature rich pages and components with fully developer centric code React Nodejs Datta Able PRO product pageReact Nodejs Datta Able PRO LIVE DemoAs mention before all the above samples are configured to communicate with a unified simple API interface that shares all necessary actions to manage a simple JWT Authentication API login logout registereditUser allows updating user related informationTo make this article really useful we can build the Node JS API server using the information provided by the project README Step Clone the sources git clone cd api server nodejsStep Install modules using NPM or Yarn npm i OR yarnStep Run the SQLite migration via TypeORM yarn typeorm migration runStep Start the API server development mode npm dev OR yarn devAt this point the API server should be up amp running and we can use POSTMAN or mentioned React Samples to have a complete fullstack experince Thanks for reading For more resources and support feel free to access Open source Dashboards provide by AppSeedFree React Dashboards a curated list published on Dev to 2021-07-21 15:05:43
Apple AppleInsider - Frontpage News Verizon Fios TV Home App coming to Apple TV on July 22 https://appleinsider.com/articles/21/07/21/verizon-fios-tv-home-app-coming-to-apple-tv-on-july-22?utm_medium=rss Verizon Fios TV Home App coming to Apple TV on July The Verizon Fios TV Home App enables subscribers to watch the company s cable service on smart devices and the app is finally launching on Apple TV hardware on July Fios TV coming to the Apple TVCable TV companies have shifted to digital distribution methods to keep people from cutting the cord Verizon Fios still requires a cable box to view content unlike digital only competitors like Sling Read more 2021-07-21 15:50:59
Apple AppleInsider - Frontpage News Best deals for July 21 - Apple's iPhone cases, Kindles, networking, and more! https://appleinsider.com/articles/21/07/21/best-deals-for-july-21---apples-iphone-cases-kindles-networking-and-more?utm_medium=rss Best deals for July Apple x s iPhone cases Kindles networking and more Wednesday s best deals features a multitude of Apple s own iPhone cases discounts on Amazon s Echo Frames and more sales on networking devices for your home Best deals for July Shopping online for the best discounts and deals can be a difficult and annoying task Rather than sifting through miles of advertisements check out this list of sales we ve hand picked just for the AppleInsider audience Read more 2021-07-21 15:31:03
海外TECH Engadget Epic Games buys 3D asset platform Sketchfab https://www.engadget.com/epic-games-3d-asset-platform-sketchfab-unreal-engine-153014312.html?src=rss Epic Games buys D asset platform SketchfabEpic Games seems determined to give developers everything they need to make games in Unreal Engine without having to look elsewhere for parts The company has bought Sketchfab a D asset platform quot By joining forces Epic and Sketchfab will be able to make D AR and VR content more accessible and grow the creator ecosystem which are critical to an open and interconnected Metaverse quot Epic wrote in a blog post quot Sketchfab will continue to operate as an independently branded service while collaborating closely with the Unreal Engine team quot Sketchfab hosts more than million D assets Users can edit buy and sell content on the platform Epic has dropped Sketchfab s store fees to percent which matches the Epic Games Store cut so people making D assets receive a larger slice of sales revenue Epic also says it will maintain Sketchfab s integrations with D creation and publishing platforms The assets will still work elsewhere including in rival game engines such as Unity The Sketchfab Plus plan ーwhich allows users to upload more assets with larger file sizes ーis now free to everyone Current Plus subscribers are being bumped up to the Pro plan at no extra cost and Sketchfab is increasing the monthly upload limit on the Pro tier from to The Sketchfab deal follows Epic s acquisition of ArtStation a hub where CGI and game focused artists can host their portfolios and sell work Epic slashed that marketplace s fees from percent to percent as well 2021-07-21 15:30:14
海外TECH Engadget UK man arrested over 2020 Twitter celebrity hacks https://www.engadget.com/uk-man-arrested-twitter-celebrity-hack-151050042.html?src=rss UK man arrested over Twitter celebrity hacksAuthorities are still cracking down on participants in the July Twitter celebrity hacks Spanish National Police have arrested UK citizen Joseph O Connor at the US request over his alleged involvement in compromising over Twitter accounts Officials didn t detail how O Connor contributed to the campaign but O Connor has also been charged with hijacking TikTok and Snapchat accounts as well as cyberstalking a quot juvenile quot victim O Connor faces a total of ten charges including six related to unauthorized computer access two for cyberstalking and one each for extortion and threats The Twitter hacks compromised accounts for a wide range of companies and personalities including Apple Uber Elon Musk and eventual US President Joe Biden The attackers apparently used social engineering to gain access to internal Twitter tools and promote a Bitcoin scam It didn t take long for police to arrest the claimed mastermind teen hacker Graham Ivan Clark who later pled guilty to charges O Connor s arrest won t topple a criminal organization as a result However it s evident that US authorities want to send a message to would be social media hackers ーthose perpetrators are risking serious charges even if they re not primarily responsible for the attacks 2021-07-21 15:10:50
海外TECH CodeProject Latest Articles A Complete Tutorial to Connect Android with ASP.NET Core Web API https://www.codeproject.com/Articles/5308542/A-Complete-Tutorial-to-Connect-Android-with-ASP-NE android 2021-07-21 15:54:00
海外科学 NYT > Science The Bootleg Fire Is Now Generating Its Own Weather https://www.nytimes.com/2021/07/19/climate/bootleg-wildfire-weather.html The Bootleg Fire Is Now Generating Its Own WeatherUnpredictable winds fire clouds that spawn lightning and flames that leap over firebreaks are confounding efforts to fight the blaze which is sweeping through southern Oregon 2021-07-21 15:48:44
海外TECH WIRED Venmo Gets More Private—but It's Still Not Fully Safe https://www.wired.com/story/venmo-privacy-by-default-global-feed fully 2021-07-21 15:47:40
海外科学 BBC News - Science & Environment Russia sends long-delayed module to space station https://www.bbc.co.uk/news/science-environment-57921439 nauka 2021-07-21 15:55:04
金融 RSS FILE - 日本証券業協会 株主コミュニティの統計情報・取扱状況 https://www.jsda.or.jp/shiryoshitsu/toukei/kabucommunity/index.html 株主コミュニティ 2021-07-21 15:30:00
ニュース BBC News - Home Brexit: UK wants to redraw Northern Ireland Protocol https://www.bbc.co.uk/news/uk-politics-57911148 renegotiate 2021-07-21 15:09:28
ニュース BBC News - Home Keir Starmer to isolate after his child tests positive for Covid https://www.bbc.co.uk/news/uk-politics-57918823 child 2021-07-21 15:37:13
ニュース BBC News - Home Priti Patel defends deal to stop rising numbers crossing Channel https://www.bbc.co.uk/news/uk-57916659 channelthe 2021-07-21 15:22:11
ニュース BBC News - Home Neo-Nazi Andrew Dymock jailed for terror offences and hate crimes https://www.bbc.co.uk/news/uk-england-somerset-57920928 dymock 2021-07-21 15:42:01
ニュース BBC News - Home Milton Ernest misspelt as Milton Earnest on new sign https://www.bbc.co.uk/news/uk-england-beds-bucks-herts-57900909 earnest 2021-07-21 15:41:15
ニュース BBC News - Home Covid: Who has to self-isolate and what if I'm fully vaccinated? https://www.bbc.co.uk/news/explainers-54239922 isolate 2021-07-21 15:25:46
サブカルネタ ラーブロ 21/210 天金狗:天金狗つけ麺並 http://feedproxy.google.com/~r/rablo/~3/mW9USvAVK9E/single_feed.php 明るい未来 2021-07-21 16:15:04
サブカルネタ ラーブロ くじら食堂@東小金井 「煮干、ほか」 http://feedproxy.google.com/~r/rablo/~3/B9ybybLqARc/single_feed.php 東小金井 2021-07-21 16:01:20

コメント

このブログの人気の投稿

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