TECH |
Engadget Japanese |
四方八方から迫るモンスターを蹴散らせ!物量満点の2Dアクション『Rogue Sword』:発掘!スマホゲーム |
https://japanese.engadget.com/rogue-sword-211024297.html
|
roguesword |
2022-03-15 21:10:24 |
IT |
ITmedia 総合記事一覧 |
[ITmedia Mobile] 「Xiaomi 12」シリーズ、グローバルにデビュー 「Snapdragon 8 Gen 1」搭載ハイエンドは999ドルから |
https://www.itmedia.co.jp/mobile/articles/2203/16/news058.html
|
itmediamobile |
2022-03-16 06:46:00 |
Google |
カグア!Google Analytics 活用塾:事例や使い方 |
Amazon Music Studio Tokyoの様子が見られる収録済み配信やイベントやラジオ |
https://www.kagua.biz/marke/podcast/20220316a1.html
|
amazon |
2022-03-15 21:00:19 |
IT |
情報システムリーダーのためのIT情報専門サイト IT Leaders |
日本企業のデータガバナンス成熟度は概して不十分、今後なすべきことは? | IT Leaders |
https://it.impress.co.jp/articles/-/22845
|
日本企業のデータガバナンス成熟度は概して不十分、今後なすべきことはITLeaders日本企業は、データ保護や情報漏洩防止などの領域では比較的高い成熟度にある一方、組織横断型で安全にデータを活用するためのデータガバナンス体制の整備が総じて不十分であるー。 |
2022-03-16 07:00:00 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
Next.jsで作る静的サイトに、use-shopping-cartを使ってStripe Checkoutを利用したECカート機能を実装する |
https://qiita.com/hideokamoto/items/8942af4d056c8e242f8e
|
Nextjsで作る静的サイトに、useshoppingcartを使ってStripeCheckoutを利用したECカート機能を実装する以前「カート機能を簡単に実装できるフックライブラリ」としてuseshoppingcartを紹介しました。 |
2022-03-16 06:45:09 |
海外TECH |
Ars Technica |
Researcher uses Dirty Pipe exploit to fully root a Pixel 6 Pro and Samsung S22 |
https://arstechnica.com/?p=1841295
|
handsets |
2022-03-15 21:10:01 |
海外TECH |
MakeUseOf |
5 Features We Want to See on the iPhone 14 |
https://www.makeuseof.com/tag/wanted-features-next-iphone/
|
current |
2022-03-15 21:16:13 |
海外TECH |
DEV Community |
Understanding Callbacks |
https://dev.to/i3uckwheat/understanding-callbacks-2o9e
|
Understanding Callbacks Understanding CallbacksCallbacks seem to be a sticking point for people new to programming Put simply callbacks are functions that are passed into another function as an argument With the many ways one can define a function in JavaScript it s no wonder why callbacks get confusing Anatomy of a FunctionJavaScript has many ways of defining a function but they all follow a similar pattern and have the same pieces they just look a bit different There is more technical terminology surrounding functions but we are going to gloss over them for now If you are interested feel free to look up Function Declarations and Function Expressions Normal Functions Named Functions Normal functions probably the first way you learned about creating functions Understanding the anatomy of these will help you understand the other types of functions as well function funkyFunction music isWhiteBoy if isWhiteBoy console log Play music This is actually called a function declaration and is broken into a few parts The function keywordThis tells the JavaScript compiler you are making a named functionThe nameThis is the name of the function and what you will use when you call it It is also used in stack traces The parameterseverything between and is a parameter these must be separated by commas if there is more than one There may also be nothing between the if the function does not take any parameters The parenthesis are required The function bodyThis is where the function actually does something This code gets run with whatever values are passed into the parameters Calling a function looks similar to declaring it When you call the function you type the name of the function and add after without the function keyword and the body Inside the you may pass it the values you want the parameters you defined to represent These arguments are used like variables inside the body of the function Calling a functionfunkyFunction that funky music true This prints Play that funky music in the terminal Anonymous FunctionsThese are very similar to normal functions with just a few differences Anonymous functions are not named and have a few different syntaxes Even though they cannot have a name they can be assigned to a variable Even though when assigned to a variable they show up in stack traces they are still considered an anonymous function They may show up as anonymous function in stack traces when passed into other functions as callbacks however Anonymous functions are mostly used by passing them into other functions as a callback This will become more clear later Each of the functions below are identical to the funkyFunction above in their funk tionality This example is still an anonymous function even though we used the function keyword as it doesn t have a name const funkyFunction function music isWhiteBoy if isWhiteBoy console log Play music This is called an arrow function we ll get into these soon const funkyFunction music isWhiteBoy gt if isWhiteBoy console log Play music An anonymous function is just a function that does not have a name this doesn t mean that it cannot be called Each of the above functions can be called exactly the same way funkyFunction that funky music true And this is because functions are first class citizens in JavaScript and can be assigned to variables Or passed as an argument to another function Arrow FunctionsThese are just a shorter way to write a function They do have some special rules however and understanding the rules imposed by arrow functions will help you understand callbacks We re going to ignore the this binding rules for these functions for now If there is only one argument the parenthesis can be omittedif arrow functions are one line the brackets can be omitted When omitting the brackets the arrow function returns the evaluated expression without requiring the return keyword The functions below are variations of the rules aboveconst playThe funky gt return funky music const playThe funky gt return funky music const playThe funky gt funky music You can call all of these functions like playThe blues Below are some examples of an arrow function without an argument These functions are all identical as well Notice the in place of any named arguments It is required because there aren t any parameters const playThat gt funky music const playThat gt return funky music const playThat gt return funky music Key PointTake some time and study the function examples above and note how they are similar and how the same parts exist in both with the exception of the function keyword What Callbacks Look LikeYou most likely have seen or even used callbacks and not realized it They are used frequently in JavaScript Understanding JavaScript is impossible without understanding callbacks Below is an example of something you may have run into before const notes do re me notes forEach note gt console log note This is the forEach array method This method simply takes a callback function as its argument Don t forget that forEach is a function itself There are many other ways to do the same thing as is tradition in JavaScript below are a few more ways to write this code const notes do ray me notes forEach note gt console log note notes forEach function note console log note This one is tricky but will make more sense laternotes forEach console log How Callbacks WorkTo state it once more Callbacks are just functions passed into other functions as arguments as a parameter Iterator FunctionsBelow is what forEach might look like under the hood notice it calls the callback function each time it loops over an item function myForEach array callback for let i i lt array length i callback array i This is when the callback function gets called or executed You would call it like this const myArry myForEach myArry item gt console log item WHOA hold up Where did item come from This came from the function myForEach calling the callback with an argument The line with callback array i is calling the callback function with an argument which we defined inline as an anonymous function Below are more examples of how this could be called const myArry We do not need the in this case as we only have one argument and we are using an arrow functionmyForEach myArry item gt console log item We can pass arguments to this kind of anonymous function as wellmyForEach myArry function item console log item This time we are declaring the function we want to use as a callback Notice we define item as a parameter to be passed in when it s called by the myForEach function function printItemPlusTwo item console log item item is passed into the function we do not need to declare it here because we declared it elsewhere It is the same as the console log example above except we declared our own function myForEach myArry printItemPlusTwo Another good example of how callbacks work might be the map method read more on MDN below is one way it might be implemented function myMap array callback const myNewArray for let i i lt array length i const callbackResult callback array i myNewArray push callbackResult return myNewArray This could be called like this const addedArray myMap arrayNum gt return arrayNum ORconst addedArray myMap arrayNum gt arrayNum Event Listeners DOM Event listeners in JavaScript seem to be confusing to people but after understanding callbacks these should be a lot easier to understand Let s review what they look like see if you can pick out the different things going on const element document querySelector myId element addEventListener click event gt console log event target value event is passed into the callback from the addEventListener function when it receives a click event If you notice the second argument value you pass into a function to addEventListener is a function In this case it s an anonymous arrow function This piece of code could have also have been written like this and it would behave identically const element document querySelector myId element addEventListener click function event console log event target value Part of what confuses people is the event object Where does it come from How does it get there This event object is passed into the callback function by the addEventListener function A function is calling another function This is because Callbacks are just functions passed into another function as arguments That means we can declare a function outside of the argument list and just add it by its name as well Like so function myEventHandler event do something probably with event const element document querySelector myId element addEventListener click myEventHandler Notice how we didn t call the function called myEventHandler If we were to call it inside the parameter list the function we called myEventHandler would run immediately and give the addEventListener the result of calling that function in this case it would be undefined ConclusionCallbacks are an important part of JavaScript they are vital to understand even with the onset of promises and async await Callbacks get called by another function so you don t have to call them in the arguments Calling a function is using a function s name and adding to the end of it like console log These are something that you will learn if you give yourself time understanding how they work will make your JavaScript career a lot easier |
2022-03-15 21:27:29 |
海外TECH |
DEV Community |
Early Return Pattern |
https://dev.to/i3uckwheat/early-return-pattern-558i
|
Early Return Pattern Early Return PatternPeople new to programming sometimes struggle to understand returning early inside a function especially if they come from a language like Ruby which has implicit returns Today we re going to explore what an early return is and what it can be used for in the context of JavaScript Understanding returnTo understand what an early return is you must first understand what return does in a function Put simply return returns a value from the function it could be anything In JavaScript you can return anything a string an object or even another function When a return statement has been found the function ends immediately and returns the value to whatever called the function function timesTwo x return x console log timesTwo In this example you would expect to be logged to the console and you d be correct The timesTwo function returned the result of x to console log and console log printed the value to the console Early ReturnsAn early return is a return statement that is placed before some other code has been run function notFunkyFunction console log And just when it hit me somebody turned around and shouted return console log Play that funky music white boy notFunkyFunction This function will only log And just when it hit me somebody turned around and shouted and will never log Play that funky music white boy due to the return statement Using this we can do some neat things to make our code look cleaner Early Return patternSince we can use a return statement to end a function immediately we can take advantage of it Let s look at a traditional if else statement and how one might convert it to the early return pattern function healthBarColor health maxHealth hasShield const percentLeft health maxHealth if hasShield return blue else if percentLeft lt return red else if percentLeft lt return yellow else return green console log healthBarColor false In this case we will find the value yellow in the console This looks OK but it can be cleaner with the use of an early return Let s refactor healthBarColor to use this pattern now function healthBarColor health maxHealth hasShield const percentLeft health maxHealth if hasShield return blue if percentLeft lt return red if percentLeft lt return yellow return green console log healthBarColor false This code is functionally the same as the code above but it is arguably more readable and is shorter This works because when we return from a function the function ends then and there and gives us the value we desire We can clean this up even more though with a quirk of JavaScript In JavaScript if you have an if statement that is one line you can omit the curly braces That would look like this function healthBarColor health maxHealth hasShield const percentLeft health maxHealth if hasShield return blue if percentLeft lt return red if percentLeft lt return yellow return green console log healthBarColor false Now we have some clean and easy to understand code that is still performant Gotcha sAlthough the early return pattern can be very clean there are times where it is contraindicated mainly in non functional style functions function attackedHandler damage const armorStrength getArmorStrength let damageValue if damage gt armorStrength damageValue calculateDamage damage armorStrength if damage armorStrength damageValue damage if damage lt armorStrength damageValue applyDamage damageValue setArmorStrength damageValue This looks clean but is a bad idea because each if statement has to be evaluated even if the first one is true This technically isn t an early return pattern but it does mimic it even though it is bad practice To fix this you would have to use the standard if else statement function attackedHandler damage const armorStrength getArmorStrength let damageValue if damage gt armorStrength damageValue calculateDamage damage armorStrength else if damage armorStrength damageValue damage else if damage lt armorStrength damageValue applyDamage damageValue setArmorStrength damageValue Another time the early return pattern will not work is when you have to run code after the if else statement The above code is a good example of this If you were to return from the function within the if statements the rest of the function would not run This is called unreachable code and would introduce bugs and logic errors in your program ConclusionThe early return pattern have I said early return pattern enough yet is a popular pattern and something you might see in other s code Understanding why it s used and when to use it is important when it comes down to using it yourself Now get out there and use this newfound knowledge to write better code P S This pattern can be used with multi line conditionals as well The example below is perfectly fine function attackedHandler damage const armorStrength getArmorStrength if damage gt armorStrength let damageValue calculateDamage damage armorStrength return takeDamage damageValue if damage armorStrength return takeArmorDamage damage |
2022-03-15 21:25:06 |
海外TECH |
DEV Community |
Towards Vendure v2.0 |
https://dev.to/michlbrmly/towards-vendure-v20-1aao
|
Towards Vendure vToday sees the release of version of Vendure the open source headless commerce framework This release sees Vendure reach a point of high stability amp maturity with all major APIs completed and almost a year of bug fixes and refinements behind us Just months after the v launch Vendure is now being used in production in dozens of stores from small boutique print shops to huge Europe wide marketplaces to billion dollar startups and yes even giants like IBM With a active and growing community Vendure is truly a mature proven and production ready headless commerce platform So what s next Let s talk about the future Let s talk about Vendure v What s special about v Well there are a number of changes and features I d like to introduce which I cannot since they would require breaking changes I try my best to follow semantic versioning which means that all v x x releases should be backwards compatible In other words updating the Vendure package versions should not require any changes to your existing code So far we ve done a pretty good job of this However certain changes simply cannot be made without changing the database schema updating dependent libraries with breaking API changes or altering parts of the Vendure data model Here are some examples of breaking changes which need to wait until v Updating the underlying libraries that Vendure is built on to their latest versions namely NestJS GraphQL Apollo Server amp Angular Modifying the data model to support multiple stock locations Adding support for bundle products allowing custom products to be assembled from disparate product variants Improving support for true multivendor marketplaces this will be a major focus of the next version since there is huge demand for it and there seems to be very few alternatives out there at present If you are interested in this feature I invite you to share ideas amp feedback in this issue Removing deprecated APIs All of the above and more are planned for Vendure v You can see the status of these issues in our roadmap It is also possible to start testing these changes now by using the next tag npm install vendure core nextThis will install a version like next which reflects the major branch of the Vendure repo Changes in these pre release versions can be found in the CHANGELOG NEXT md file I m using the next version in my own Vendure projects but the usual caveats about using pre release software apply I have no set timeline for the release of v but I would expect it to be ready within the next six months Thanks for reading and if you d like to find out more about Vendure head over to our Getting Started guide |
2022-03-15 21:19:00 |
海外TECH |
DEV Community |
Introdução a Testes no Back-end |
https://dev.to/gabrielhsilvestre/introducao-a-testes-no-back-end-4la8
|
Introdução a Testes no Back end Tipos de Testes UnitárioTestes unitários trabalham no menor escopo do código testando funções ou classes individualmente variando de acordo com o paradigma IntegraçãoTestes de integração utilizam a junção de múltiplos escopos na hora de testar ou seja uma função que se utiliza de outras funções essas que devem possuir seus próprios testes unitários Ponta a PontaTeste de Ponta a Ponta EE verificam o fluxo da aplicação como um todo para isso presumem que testes de menor escopo como os Unitários e os de Integração játenham sido ou irão ser desenvolvidos Escrevendo Testes Estrutura com Mocha O que é Mocha éum framework para testes em JS nós iremos utilizar a estrutura e a interface disponibilizadas por ele para a realização de nossos testes SintaxeA sintaxe para a estruturação dos testes éexatamente a mesma que vimos no Jest temos um bloco describe que irádescrever um ou mais testes e temos o bloco it que irádefinir o teste em si Ambas as funções describe e it recebem dois parâmetros o primeiro éuma string que seráa descrição do bloco e o segundo uma arrow function que irádefinir o bloco describe First block test gt it First test gt it Second test gt Apesar de ter focado apenas na estrutura de tests com o Mocha nesse artigo háoutras diversas funcionalidades que esse Framework pode fazer segue a documentação do Mocha Aferindo com Chai O que é Chai éuma biblioteca para a asserção dos resultados recebidos a os resultados esperados ou seja criamos uma relação entre os resultados dessa forma caso a relação seja verdadeira o teste irápassar SintaxeA sintaxe geral segue a mesma do Jest temos uma função expect que iráreceber o resultado de nossa função e a partir do expect chamados um método de asserção para verificar se o resultado obtido éválido Existem diversos métodos de asserção no Chai alguns similares aos do Jest outros não então a recomendação ésempre consultar a documentação do Chai expect equals Executando Testes Definindo scriptPara executarmos os testes em nosso projeto primeiro precisamos estar trabalhando em um pacote Node então caso ainda não exista um arquivo package json basta executar o comando npm init yTendo o package json tudo o que precisamos fazer édefinir o Mocha como script de testes para isso passamos na chave test o valor mocha tests E obviamente énecessário ter o Mocha instalado scripts test mocha tests Ao definir o script como fizemos acima iremos executar os testes contidos no diretório tests ou seja o valor que passamos no script de teste após o mocha refere se ao diretório que iráconter os testes scripts test mocha lt diretório dos testes gt Executando o scriptApós o script ter sido definido tudo que precisamos fazer érodar o seguinte comando no terminal npm testE se quisermos rodar um teste em outro diretório que não faça sentido alterar o script por qualquer motivo podemos excutar os testes a partir do npxnpx mocha lt path atéos tests gt npx mocha my folder my testsAlém disso também háoutras flags que podemos usar ao executar o comando elas podem ser vistas na documentação do Mocha CLI TDD O que é Éuma metodologia de desenvolvimento na qual a pessoa desenvolvedora começa a desenvolver a aplicação a partir dos testes PassosPara usarmos essa metodologia de forma ativa podemos seguir quatro passos simples Antes de iniciarmos a escrita de código precisamos interpretar os requisitos necessários para a implementação da funcionalidade Com os requisitos em mente começamos a escrever as estruturas descritivas dos testes com describe e it Com as estruturas descritivas jáimplementadas passamos a verdadeiramente escrever os testes utilizando as asserções para verificar o comportamento esperado Por fim agora que os testes jáforam criados nos resta partir para a implementação da funcionalidade pensada Lembrando que não háproblema em realizar pequenos ajustes nos testes afinal criamos eles para código que ainda nem existe então um detalhe ou outro pode ser esquecido Isolando Testes O que é O isolamento de testes éa simulação de um comportamento esperado de uma função para que não seja necessário interagir com recursos externos como arquivos APIs e Bancos de Dados Por que isolar No Front end trabalhamos com a manipulação do DOM jáno Back end a maioria das operações serão de Input ou Output de dados esses que podem ser provenientes de uma API externa uma requisição do Front ou uma consulta no Banco de Dados Logo trabalhar todas essas operações em ambiente de teste seria extremamente complexo por exemplo depois de testarmos a integração entre nosso Back end e um Banco de Dados o DB teria seus dados modificados sendo necessário reseta lo após cada teste Então para solucionar esse problema tem se o conceito de Test Doubles que nada mais são que objetos que fingem ser outros objetos para fins de testes Podemos ainda comparar esse conceitos às Mocks do Front end apesar de não serem exatamente a mesma coisa servem para o mesmo propósito Como isolar Para isolarmos os testes iremos utilizar a biblioteca Sinon ela oferece diversos recursos para a criação de Test Doubles Para instalar a biblioteca basta utilizar o comando npm install D sinon SintaxePodemos utilizar diversos métodos para a criação de Test Doubles com Sinon porém o mais básico entre eles éo stub ao chamarmos passamos dois parâmetros o primeiro éo objeto e o segundo caso exista éo método a ser simulado Além desses parâmetros precisamos definir o valor a ser retornado quando os testes chamam o método que criamos o stub para isso chamamos o método returns logo após o método stub sinon stub fs readFileSync returns lt conteúdo do arquivo gt Caso não definirmos o retorno do Test Double ela iráretornar undefined porém háuma vantagem em fakear sem definir retorno pois assim a função a ser fakeada perde a funcionalidade e a momentos que isso pode ajudar Outros isolamentos Como dito acima podemos simular comportamentos através de diversos métodos do sinon não se limitando apenas ao stub onde cada um desses métodos possui sua especificidade assim como um caso de uso Para mais detalhes sobre tais métodos consulte a documentação do Sinon |
2022-03-15 21:06:47 |
海外TECH |
DEV Community |
Show off your Lighthouse scores as static HTML in Eleventy with the PageSpeed Insights API |
https://dev.to/philw_/show-off-your-lighthouse-scores-in-eleventy-with-the-pagespeed-insights-api-1cpp
|
Show off your Lighthouse scores as static HTML in Eleventy with the PageSpeed Insights APIThe Eleventy community is focused on performance in a way that you don t tend to see with other tools mostly because it tends to attract fans of keeping things lean and appreciating the fundamentals of the web the holy trinity of HTML CSS and minimal JS in that order of priority and perhaps partly due to the Eleventy Leaderboards baiting everyone s competitive sides When I first started building my personal site I was very focused on getting a good Lighthouse score It s dipped then recovered a few times over the years but it has been at the point where it s something I ve wanted to show off in my site s footer for a while At first I did this using Zach Leatherman s lt speedlify score gt web component which uses the Eleventy Leaderboards Speedlify as its source of data This worked well but the leaderboards are only updated every so often so it took time for improvements to show up It also felt counter productive to be using a third party package with its own client side JavaScript and CSS to report on performance metrics I started looking at something I could use at build time instead and found that the PageSpeed Insights API can return the results of a Lighthouse test Getting data from the PageSpeed Insights API and using it in EleventyThis isn t a full tutorial and assumes some prior knowledge of working with npm APIs and environment variables Let s take a look at how I got my Eleventy site to trigger a Lighthouse test each time it is built and to show the results in my site footer Get an API key and store it in an environment variableHead to the PageSpeed Insights API s getting started guide and follow the links to get an API Pop the key into an environment variable locally and on your remote environments called PAGESPEED API KEY Create a JavaScript data file to hold our API callCreate a lighthouse js file inside your data directory Make sure you have installed the dotenv and ty eleventy cache assets packages or alternatives if you prefer Add the script below swapping for your own URL or an environment variable representing your own URL require dotenv config const Cache require ty eleventy cache assets module exports async function const params new URLSearchParams params append url params append key process env PAGESPEED API KEY We use the fields query string param to ask the Google API to only return the data we need a score and title for each category in the Lighthouse test Without this the API returns a lot of data which isn t the end of the world but is also unnecessary params append fields lighthouseResult categories score lighthouseResult categories title params append prettyPrint false I use the mobile strategy but desktop is a valid value too params append strategy mobile I ve not used the PWA category but you could if it is relevant to your site params append category PERFORMANCE params append category ACCESSIBILITY params append category BEST PRACTICES params append category SEO let data await Cache params toString duration d type json data data lighthouseResult categories const getGrade function score if score lt return bad if score lt return ok return good Object keys data map function key data key score data key score toFixed data key grade getGrade data key score return categories data The function will return an object containing another object called categories inside of which will be your scores I nested the scores inside of the categories object in case we ever want to return anything else from lighthouse js like some Core Web Vitals scores perhaps Example output categories performance title Performance score grade good accessibility title Accessibility score grade good best practices title Best Practices score grade good seo title SEO score grade good Using the data in a templateThanks to the magic of Eleventy data files you can now loop over the scores via lighthouse categories almost anywhere you like Most of my site uses the Eleventy Vue plugin but my footer is still using a Nunjucks file so here s how I displayed the scores I m using Tailwind here for styling but of course you can style the output however you like it s your website lt div class flex flex wrap items center gap gt lt p id homepage lighthouse scores gt Homepage Lighthouse scores lt p gt lt ul class flex items center space x aria labelledby homepage lighthouse scores gt for key result in lighthouse categories lt li class flex items center justify center cursor help rounded full h w border border green if result grade good else border yellow title result title gt lt span class sr only gt result title lt span gt result score lt li gt endfor lt ul gt lt div gt …and here s how it looks Room for improvementHere are some ideas for ways to adapt this to make it your own My site is basically a single giant page so I only bother to test one URL Perhaps you d like to swap the data file for a template function so you can run an individual test for each page on your site by using this page url My colour scheme for my footer is yellow so that s the default colour I ve used for my rings Even if I got a bad Lighthouse score the rings would still be yellow not red If you are getting some low scores you should probably add some extra Nunjucks code to output a red border if result grade bad otherwise the yellow colour I am using would make it look like all your grades are ok |
2022-03-15 21:06:11 |
海外TECH |
DEV Community |
Don't use String.ToLower() in C# when comparing strings |
https://dev.to/davidkroell/dont-use-stringtolower-in-c-when-comparing-strings-1hdi
|
Don x t use String ToLower in C when comparing stringsWhen comparing strings often the casing should be ignored in the comparison Most of the times this is required because every user writes text different I do not really care when there is “Apple or “apple in a dataset To me this is the same On the other side “A and “a are different characters for computers To overcome this problem a working and very wide spread approach is to first lowercase or uppercase all letters and then compare them Most of us done it me too but no longer Although there is a drawback you should keep in mind when it comes to performance I ve created a litte benchmark program an I ll evaluate the results afterwards First I ll explain the benchmark setup Benchmark setupI ve evaluated three types of string equality comparison Strings which are equal except casing Strings which are not equal differing in the last characterStrings which are not equal differing in the first characterThese three test cases were applied to string with lengths of and charactersMy benchmark code looks like the below code snippet where StringToCheck and VerifyString are generated Benchmark public void StringComparison Equals var result StringToCheck Equals VerifyString StringComparison CurrentCultureIgnoreCase Benchmark public void StringComparison EqualityOperator var result StringToCheck ToLower VerifyString ToLower Benchmark resultsI ve used BenchmarkDotNet to run my test and enable the MemoryDiagnoser to also anaylse memory usage allocations BenchmarkDotNet v OS Windows H Intel Core i U CPU GHz Kaby Lake R CPU logical and physical cores NET SDK Host NET X RyuJIT DefaultJob NET X RyuJIT Method Length Mean Error StdDev Median Gen Allocated StringComparison Equals ns ns ns ns StringComparison Equals b Start ns ns ns ns StringComparison Equals b End ns ns ns ns StringComparison EqualityOperator ns ns ns ns B StringComparison EqualityOperator b Start ns ns ns ns B StringComparison EqualityOperator b End ns ns ns ns B StringComparison Equals ns ns ns ns StringComparison Equals b Start ns ns ns ns StringComparison Equals b End ns ns ns ns StringComparison EqualityOperator ns ns ns ns B StringComparison EqualityOperator b Start ns ns ns ns B StringComparison EqualityOperator b End ns ns ns ns B StringComparison Equals ns ns ns ns StringComparison Equals b Start ns ns ns ns StringComparison Equals b End ns ns ns ns StringComparison EqualityOperator ns ns ns ns B StringComparison EqualityOperator b Start ns ns ns ns B StringComparison EqualityOperator b End ns ns ns ns B As you can seee in the above table the Equals method is sometimes faster but does not allocate any memory The biggest difference is when the strings differ in the first character It takes about the same time to compare string with and if they differ at the start In contrast to that with EqualityOperator this cannot be seen For the version with EqualityOperator it takes the same time no matter where the difference is This is not true for the Equals this gets faster the earlier the difference is This is probably only because of the ToLower in the first place In addition memory is allocated when using EqualityOperator with ToLower That s because of a new instance with all lowercased letters has to be created See String ToLower Method Microsoft DocsAdditional memory allocations are bad because the garbage collector needs to clean them up again which will cost valuable CPU time and therefore slows down the application SummaryDon t use ToLower when comparing strings neither use ToUpper This also applies to related string operations like StartsWith EndsWith Contains and so on I also interpret this as a code smell because the available language features are not used In addition some IDE s even detect this smell As always the code can be found at my GitHub There you can also find the benchmark report in CSV format |
2022-03-15 21:05:48 |
海外TECH |
DEV Community |
Semantic HTML: What, Why, and How |
https://dev.to/abbeyperini/semantic-html-what-why-and-how-3b34
|
Semantic HTML What Why and How WhatUse HTML elements for their intended purpose Separate content and presentation WhyIt s easier to read and naturally leads to more consistent code Consistent HTML code is easier to style It will help your SEO HTML will literally do your work for you including making your page much more accessible At its core a webpage is a document you want anyone to be able to read Use HTML to create that document Javascript and CSS are add ons HowAsk yourself if there s a tag with more meaning you can use when you reach for a lt div gt or lt span gt Google if HTML does it before building it Root Structure of a Page lt DOCTYPE html gt and lt html lang “en gt tell the machines that this is an HTML document written in English The lt head gt element contains your metadata lt meta charset utf gt is important It tells the browser how to decode and encode your characters for machines and humans Finally the lt body gt tag wraps the content of your page SEOBefore we move on to the content in lt body gt let s talk about the elements that go in lt head gt First don t forget your lt title gt Keep it descriptive and under characters Include the brand if you ve got one Use lt link rel icon type image x icon href images favicon ico gt to set your favicon the little logo in the browser tab lt meta gt tag types description Keep it under characters descriptive with short keywords or let search engines write it for you keywords If you want to suggest keywords you don t think a search engine will pull do open graph Control how your content is displayed on social media sites like Facebook and LinkedIn Twitter Cards Control how your site looks in Twitter Cards robots Tell search engine crawlers what to do with your site s information Always add your viewport meta tag it tells search engines you ve got a responsive site and prevents devices from resizing your viewport lt meta name viewport content width device width initial scale gt Finally use a lt script gt tag to add schema markup to control how your site is displayed in search engines Sectioning ContentGetting started Put your top of the page things like your logo main navigation and a heading in lt header gt Any navigation menu goes in lt nav gt All that good content unique to the page goes in lt main gt The main point of your page if you will Bottom of the page things like copyright authorship contact and maybe some more navigation like a link back to the top go in lt footer gt Use lt p gt for your text Use lt ul gt or lt ol gt containing lt li gt s for your lists Remember separate content and presentation lt nav gt is for site navigation not lists of links lt header gt and lt footer gt are branding and navigational content you d have at the top and bottom of every page on your site lt article gt vs lt section gt vs lt aside gt Use lt article gt and lt section gt to group content within lt main gt Content in lt article gt should still make sense if it was dropped by itself in a completely different page lt section gt groups together content along the same theme It can even go inside lt article gt The stuff that isn t the main content goes in lt aside gt It s complementary but not vital Nest this element inside the element that contains the content to which it s related It can be inside lt main gt but doesn t have to be Content wrapped in lt aside gt can be in a sidebar but sidebar is a presentational concept HeadingsWe re talking about lt h gt through lt h gt They must be in your page in ascending order starting with lt h gt without skipping levels There s rarely any reason to go below lt h gt Using consistent query like headings only helps your SEO You must have ONE and ONLY ONE lt h gt per page MYTH lt section gt restarts heading order TRUTH Browsers did not implement that feature listed in the HTML spec TablesGone are the days of using tables to layout content that s presentation Use the lt table gt element to structure tabular data A basic column row table Enhance your tables with lt col gt lt colgroup gt lt tbody gt lt thead gt lt tfoot gt and lt scope gt FormsWrap your form in lt form gt Use lt fieldset gt to group form options together and lt legend gt to label them You can use lt li gt lt ul gt lt ol gt lt p gt lt section gt and headings within the lt form gt element More on form controls later Check your OutlineSectioning and heading elements work together to create a document outline for your page Once you think you ve got your page set up try to navigate it with a screen reader If you find there are gaps in your document outline you can add ARIA landmark roles using the role “ attribute in your container elements This is manually adding what semantic HTML does for you A screen reader would read “navigation to a user for both lt div role “navigation gt and lt nav gt Landmark roles like lt main gt lt header gt and lt footer gt should only appear once on a page Enrich Your Content with HTML lt em gt will produce italicized text It also tells a screen reader to tell the user that the text has been emphasized lt strong gt will produce bolded text It also tells a screen reader to tell the user that the text has added importance Use CSS instead of lt b gt and lt i gt If the image content is necessary for understanding the content around it use lt figure gt and lt figcaption gt If not use lt img gt and don t forget your alt text lt blockquote gt creates a block quote like display block lt q gt creates a inline quote lt blockquote gt and lt q gt will tell a screen reader to tell a user it s a quote Use lt cite gt to cite your sources If you wanted to use a quote say who said the quote and cite your source it would look like Give the Machines More Information lt date gt and lt time gt be nice to the computer and tell it that this is a date or time lt abbr gt always define your abbreviations lt dd gt lt dl gt lt dt gt define other stuff lt pre gt preformatted text lt code gt it s code lt var gt it s a variable lt data gt machine readable data lt address gt contact info for the parent element Inside lt footer gt lt address gt is identified as the contact info for the web page owner Let HTML Do Your Work for You Form Controls lt textarea gt allows the user to submit freeform text It has a lot of attributes you can use including enabling spellcheck lt select gt creates a drop down for you and using the multiple attribute allows users to select multiple options lt option gt creates an option for lt select gt When multiple lt option gt s are wrapped in lt datalist gt they create suggestions for autocomplete lt progress gt and lt meter gt create progress and meter bars for you Using lt form gt s action and method attributes activates built in HTTP messaging lt button gt or lt button type “submit gt inside lt form gt will automatically create a submit send button for your HTTP messaging lt button type reset gt inside lt form gt automatically creates a button that will reset all the lt forms gt s controls lt input type gt Yeah built in HTTP messaging is cool but if you ve got users submitting data you re probably using lt input gt lt input type image gt creates an image that acts like a button Why build your own pickers or file uploader when you have lt input type color gt lt input type datetime local gt and lt input type file gt Types like email and password have built in validation options This codepen demonstrates all the different types of lt input gt lt label gt Associating a lt label gt with an lt input gt is not only accessible but also provides programmatic advantages in your code and in HTTP messages For example clicking a lt label gt is the same as clicking its associated lt input gt Don t associate a lt label gt with a lt button gt or lt input gt with type button reset or submit Never put a heading in your lt label gt lt button gt vs lt a gt Literally never build your own button Just use lt button gt A screen reader treats buttons and links very differently They have different built in properties behaviors and states Buttons made with lt a gt which again you should never do will be grouped with other links Buttons are for performing an action unless that action is navigating to another page Buttons and inputs are in tab order and can be triggered with space and enter for keyboard users The lt button gt element automatically provides hover and focus states Anchor tags lt a gt are for links and provide useful SEO Anchor tags are not in tab order and are only triggered on enter Special mention lt button gt vs lt input type button gt A lt button gt can have content and is easier to style A lt button gt inside a lt form gt without a type specified will automatically become a lt button type submit gt lt input type button gt has no default behavior making it less semantic and accessible It does make it behave more consistently across browsers This was particularly important when trying to support IE IE lt input type submit gt and lt input type reset gt do have the default behavior of submitting a form or resetting all the form controls when inside a lt form gt but nothing else Other Elements That Do a Ton of Work lt details gt and lt summary gt work together to create a toggle lt audio gt and lt video gt have built in players with controls lt picture gt wraps multiple lt img gt or lt source gt elements and chooses the best one based on display device scenarios lt iframe gt can be used to trap remote code or user input in a separate context from your page for security reasons ConclusionLearning and using semantic HTML gives you a ton of functionality without lifting a finger It also allows you to bake accessibility and SEO in with very little effort Not to mention it leads to cleaner code and cleaner code is easier to style There are around semantic HTML elements don t build what HTML hands to you on a silver platter |
2022-03-15 21:04:12 |
海外TECH |
DEV Community |
Draft: Using DEV.to as CMS for my blog |
https://dev.to/infinitenil/draft-using-devto-as-cms-for-my-blog-27oo
|
Draft Using DEV to as CMS for my blogHello everyone welcome to my blog this is my first post in a language that are not my mother language and I m really excited to start this First of all thanks for your time and I hope you enjoy my content Before we startFirst things first I decided to create a blog using Dev to as CMS because I tried everything in the past believe me everything from markdown files to some more complex CMS system like Sanity Each options has good and bad points let me explain why not choose them Using markdown files is a good option it s really simple and just works but I don t like the idea to commit and push manually to update my blog it should be automatic Sanity is nice but is too much for small projects it s like use a sledgehammer to crack a nut I even tried to use Notion as CMS and at the first moment it looks nice but when you try to traverse the Notion api response you see the horror When you realize you are writing things like this and this After a lot of tries with a vary of tools and some POCs I decided that my choice should be based in some points Automatic update I want to publish with one click Simple api I don t want to read five pages of docs just to render one string Easy to replace If the tool don t feel the right one for the job I want to replace them fast With this in mind I tried two platforms Hashnode and Dev to I know that both of them has public API s and a great and easy to use interface to publish new content Unfortunately Hashnode does not provide what I need in the API you can check here So I came to Dev to API and voilà everything I need List publications and publication details with a simple response Json and Markdown This is what I m looking for Getting startedOnce the content platform was chosen I could start working on the code My stack for this project is Typescript Remix Vercel Stitches for styling and Radix for some components I ll not cover all aspects of the project setup because is very simple and is better to read from the Remix run documentation |
2022-03-15 21:00:44 |
Apple |
AppleInsider - Frontpage News |
Portion of Apple Park evacuated due to possible hazmat situation |
https://appleinsider.com/articles/22/03/15/portion-of-apple-park-evacuated-due-to-possible-hazmat-situation?utm_medium=rss
|
Portion of Apple Park evacuated due to possible hazmat situationA portion of Apple Park ーthe company s headquarters in Cupertino California ーhas been evacuated because of a possible hazmat situation local reports indicate Apple ParkFirst responders reportedly discovered an envelope containing a white powder substance the Santa Clara County Fire Department said NBC Bay Area reports that the substance has not yet been identified Read more |
2022-03-15 21:11:42 |
海外TECH |
Engadget |
Cadillac will offer two new features to select Super Cruise drivers this summer |
https://www.engadget.com/cadillac-will-offer-lane-change-assist-to-select-super-cruise-drivers-this-summer-214935540.html?src=rss
|
Cadillac will offer two new features to select Super Cruise drivers this summerGM s Super Cruise will learn two new tricks this summer GM announced on Tuesday that the driver assist system will offer Automatic Lane Change and Trailering capabilities for eligible owners Owners of the Cadillac CT and CT will have the opportunity to purchase Automatic Lane Change capabilities while Escalade owners will be given the Trailering option which allows the SUV to tow without touching the steering wheel The company estimates that some CTs s and Escalades will be eligible for the paid updates quot Eligible customers will receive communication from Cadillac about pricing and how they can purchase and install these new upgrades in the near future quot a GM spokesperson told Engadget via email Super Cruise which can be found on a variety of GM products including the new Hummer EV is a Level system in that it is a driver assist and not fully autonomous It relies on a mixture of LiDAR mapping GPS visual cameras and radar sensors to navigate traffic GM originally announced these new features back in however the COVID pandemic and a global processor shortage have hampered their rollout nbsp |
2022-03-15 21:49:35 |
海外TECH |
Engadget |
Apple employees evacuate Cupertino campus following potential hazmat situation |
https://www.engadget.com/apple-cupertino-potential-hazmat-situation-212015574.html?src=rss
|
Apple employees evacuate Cupertino campus following potential hazmat situationApple ordered the evacuation of a quot portion quot of its Apple Park headquarters on Tuesday after first responders from the Santa Clara County Fire Department found an envelope containing an unidentified powdery white substance according to NBC Bay Area We ll update this article once more information on the situation becomes available nbsp nbsp Developing |
2022-03-15 21:20:15 |
海外TECH |
Engadget |
Microsoft updates Xbox Cloud Gaming to reduce input lag on iOS |
https://www.engadget.com/xbox-cloud-gaming-ios-update-211043722.html?src=rss
|
Microsoft updates Xbox Cloud Gaming to reduce input lag on iOSSince last June Microsoft s Xbox Cloud Gaming service has been broadly available on iOS devices but for many iPhone and iPad owners the experience wasn t up to what the company offered on other platforms On Monday however Microsoft announced it had implemented a series of enhancements that would improve performance on all iPhone and iPad devices At the time it didn t provide details on the work it had done noting only they would lead to a “smoother and more responsive gameplay experience But following an email from Engadget Microsoft has shared more details on the update The company says it optimized video output and network data transmission on iOS devices It also found a way to reduce overall input lag Since input lag is something that can easily take you out of a game the work Microsoft did there should be easily noticeable One of the tricky things about Xbox Cloud Gaming on iOS is that Microsoft is forced to offer it through Safari as opposed to a dedicated app due to Apple s policies on game streaming apps Browser APIs have come a long way in the past few years but a web experience still isn t a substitute for a native app |
2022-03-15 21:10:43 |
Cisco |
Cisco Blog |
Cisco Training Bootcamps Are Intense, but Worth the Experience |
https://blogs.cisco.com/learning/cisco-training-bootcamps-are-intense-but-worth-the-experience
|
Cisco Training Bootcamps Are Intense but Worth the ExperienceDiscover the intensive learning model that s enabling individuals and teams to develop practical hands on skills more efficiently than ever |
2022-03-15 21:17:19 |
海外科学 |
NYT > Science |
Mounting Data Shows J&J Vaccine as Effective as Pfizer and Moderna |
https://www.nytimes.com/2022/03/15/health/covid-johnson-vaccine.html
|
Mounting Data Shows J amp J Vaccine as Effective as Pfizer and ModernaOnce dismissed as less effective the vaccine now seems to be preventing infections and illness about as well as the two mRNA options |
2022-03-15 21:47:11 |
海外科学 |
NYT > Science |
How Shackleton’s Endurance Was Found |
https://www.nytimes.com/2022/03/15/climate/endurance-shipwreck-shackleton.html
|
legendary |
2022-03-15 21:24:45 |
金融 |
ニュース - 保険市場TIMES |
アドバンスクリエイトの保険証券管理アプリ「folder」に画面共有機能が追加! |
https://www.hokende.com/news/blog/entry/2022/03/16/070000
|
アドバンスクリエイトの保険証券管理アプリ「folder」に画面共有機能が追加「folder」アプリがさらに便利に国内最大級の保険選びサイト「保険市場」を運営するアドバンスクリエイトは月日、同社が開発した保険証券管理アプリ「folder」に新たに画面共有機能を追加したと発表した。 |
2022-03-16 07:00:00 |
ニュース |
BBC News - Home |
FIA changes F1 safety car rules in wake of controversial 2021 title decider |
https://www.bbc.co.uk/sport/formula1/60758648?at_medium=RSS&at_campaign=KARANGA
|
FIA changes F safety car rules in wake of controversial title deciderFormula s safety car rules have been changed to make it impossible for a race to be conducted in the manner of s controversial title decider |
2022-03-15 21:30:05 |
ビジネス |
東洋経済オンライン |
「結婚減」は飲み会が減ったせい!?意外すぎる関係 単身男性の外での飲酒が減るほど初婚数も減る | ソロモンの時代―結婚しない人々の実像― | 東洋経済オンライン |
https://toyokeizai.net/articles/-/539022?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
東洋経済オンライン |
2022-03-16 06:30:00 |
Azure |
Azure の更新情報 |
Generally available: Azure Database for MySQL – Flexible Server in two new regions |
https://azure.microsoft.com/ja-jp/updates/generally-available-azure-database-for-mysql-flexible-server-in-two-new-regions/
|
north |
2022-03-15 21:24:11 |
ニュース |
THE BRIDGE |
インドネシアのGoToは4月4日にIPO、約1,260億円の調達を目指す——当初予想額の半分、ウクライナ危機が影響か |
https://thebridge.jp/2022/03/goto-aims-to-raise-us1-25b-in-ipo-20220315
|
インドネシアのGoToは月日にIPO、約億円の調達を目指すー当初予想額の半分、ウクライナ危機が影響かインドネシアのテック大手GoToGojekとTokopediaの合併企業体は、インドネシア証券取引所IDXでのIPO新規株式公開で少なくとも兆億インドネシアルピア約億円の調達を目指している。 |
2022-03-15 21:05:50 |
コメント
コメントを投稿