投稿時間:2022-05-04 21:23:42 RSSフィード2022-05-04 21:00 分まとめ(27件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
Ruby Rubyタグが付けられた新着投稿 - Qiita RailsにFactoryBotを入れるときはfactory_bot_railsを使おう https://qiita.com/yocajii/items/d9b2a7e7968cf60c4de5 factorybot 2022-05-04 20:34:45
Ruby Railsタグが付けられた新着投稿 - Qiita RailsにFactoryBotを入れるときはfactory_bot_railsを使おう https://qiita.com/yocajii/items/d9b2a7e7968cf60c4de5 factorybot 2022-05-04 20:34:45
海外TECH MakeUseOf 11 C++ Code Snippets for Everyday Programming Problems https://www.makeuseof.com/cpp-code-snippets-everyday-programming/ snippets 2022-05-04 11:30:13
海外TECH DEV Community When Disaster Strikes: Production Troubleshooting https://dev.to/codenameone/when-disaster-strikes-production-troubleshooting-7a0 When Disaster Strikes Production TroubleshootingTom Granot and myself have had the privilege of Vlad Mihalcea s online company for a while now As a result we decided to do a workshop together talking about a lot of the things we learned in the process This workshop would be pretty informal ad hoc just a bunch of guys chatting and showing off what we can do with tooling In celebration of that I thought I d write about some of the tricks we discussed amongst ourselves in the past to give you a sense of what to expect when joining us for the workshop but also a useful tool in its own right The ProblemBefore we begin I d like to take a moment to talk about production and the role of developers within a production environment As a hacker I often do everything That s OK for a small company but as companies grow we add processes Production doesn t go down in flames as much Thanks to staging QA CI CD and DevOps who rein in people like me…So we have all of these things in place We passed QA staging and everything s perfect Right Well…Not exactly Sure Modern DevOps made a huge difference to production quality monitoring and performance No doubt But bugs are inevitable The ones that slither through are the worst types of vermin They re hard to detect and often only happen on scale Some problems like performance issues Are only noticeable in production against a production database Staging or dev environments can t completely replicate modern complex deployments Infrastructure as Code IaC helps a lot with that but even with such solutions production is at a different scale It s the One Place that REALLY MattersEverything that isn t production is in place to facilitate production That s it We can have the best and most extensive tests With coverage for our local environments But when our system is running in production behavior is different We can t control it completely A knee jerk reaction is “more testing I see that a lot If only we had a test for that…The solution is to somehow think of every possible mistake we can make and build a test for that That s insane If we know the mistake we can just avoid it The idea that a different team member will have that insight is again wrong People make similar mistakes and while we can eliminate some bugs in this way More tests create more problems…CI CD becomes MUCH slower and results in longer deploy times to production That means that when we do have a production bug It will take much longer to fix because of redundant tests It means that the whole CI quality process which we need to go through will take longer It also means we ll need to spend more on CI resources… LoggingLogging solves some of the problems It s an important part of any server infrastructure But the problems are similar to the ones we run into with testing We don t know what will be important when we write a log Then in production we might find it s missing Overlogging is a huge problem in the opposite direction It can Demolish performance amp cachingIncur huge costs due to log retentionMake debugging harder due to hard to wade through verbosityIt might still be missing the information we need…I recently posted to a reddit thread where this comment was also present “A team at my company accidentally blew k on Azure Log Analytics during the span of a few days They set the logging verbosity to a hitherto untested level and threw in some extra replicas as well When they announced their mistake on Slack I learned that yes there is such a thing as too much logging full thread here Again logging is great But it doesn t solve the core problem AgilityOur development team needs to be fast and responsive We need to respond quickly to issues Sure we need to try and prevent them in the first place…But like most things in life the law of diminishing returns is in effect here too There are limits to tests logs etc For that we need to fully understand the bug fast Going through the process of reproducing something locally based on hunches is problematic at best We need a way to observe the problem This isn t new There are plenty of solutions to look at issues in production e g APM tools provide us invaluable insight into our performance in production They don t replace profilers They provide the one data point that matters how fast is the application that our customers are using But most of these tools are geared towards DevOps It makes sense DevOps are the people responsible for production so naturally the monitoring tools were built for them But DevOps shouldn t be responsible for fixing R amp D bugs or even understanding them…There s a disconnect here Enter Developer ObservabilityDevelopers observability is a pillar of observability targeted at developers instead of DevOps With tools in this field we can instantly get feedback that s tailored for our needs and reduce the churn of discovering the problem Before these tools if a log didn t exist in the production and we didn t understand the problem…We had to redeploy our product with “more logs and cross our fingers… In Practice and The Workshop…I got a bit ahead of myself explaining the problem longer than I will explain the solution I tend to think that s because the solution is so darn obvious once we “get it It s mostly a matter of details Like we all know the devil is in the details…Developer observability tools can be very familiar to developers who are used to working with debuggers and IDEs But they are still pretty different One example is breakpoints It s Snapshots NowWe all know this drill Set a breakpoint in the code that doesn t work and step over until you find the problem This is so ingrained into our process that we rarely stop to think about this at all But if we do this in a production environment the server will be stuck while waiting for us to step over This might impact all users in the server and I won t even discuss the security stability implications you might as well take a hammer and demolish the server It s that bad Snapshots do everything a breakpoint does They can be conditional like a conditional breakpoint They contain the stack trace and you can click on elements in the stack Each frame includes the value of the variables in this specific frame But here s the thing they don t stop So you don t have “step over as an option That part is unavoidable since we don t stop You need to rethink the process of debugging errors currentTimeMillis I love profilers But when I need to really understand the cost of a method I go to my trusted old currentTimeMillis call There s just no other way to get accurate consistent performance metrics on small blocks of code But as I said before Production is where it s at I can t just stick micro measurements all over the code and review later So developer observability tools added the ability to measure things Count the number of times a line of code was reached Or literally perform a tictoc measurement which is equivalent to that currentTimeMillis approach See You There“Only when the tide goes out do you discover who s been swimming naked Warren BuffettI love that quote We need to be prepared at all times We need to move fast and be ready for the worst But we also need practicality We aren t original there are common bugs that we run into left and right We might notice them faster but mistakes aren t original In the workshop we ll focus on some of the most common mistakes and demonstrate how we can track them using developer observability We ll give real world examples of failures and problems we ran into in the past and as part of our work I m very excited about this and hope to see you all there 2022-05-04 11:36:48
海外TECH DEV Community What and how do I perform a search operation in Typesense? https://dev.to/aviyel/what-and-how-do-i-perform-a-search-operation-in-typesense-5gc5 What and how do I perform a search operation in Typesense Almost every app or website has the ability to allow users to search for what they want Search based apps have this search feature and use it as the entry point for users to query their products or obtain information Understanding how to build well functioning search based apps will yield a huge return on your time investment It s extremely difficult to create search engines that are typo tolerant effective and efficient A typographical error could cause the search to fail even if the requested item is in the database By removing the need to build a search engine from the ground up Typesense could save a lot of time and effort Users will also be able to use the app s search tool successfully resulting in a positive user experience Typesense is a free open source typo tolerant search engine for programmers that aims to reduce the amount of time needed to conduct effective and efficient searches To learn more about typesense visit here gt What exactly is TypesenseSearch Operations in TypesenseA search in Typesense consists of a query against one or more text fields as well as a set of filters against numerical or facet fields You can sort and facet your results as well Using JAVASCRIPTlet searchParameters q godfather query by movie name filter by average rating gt sort by average rating desc client collections movies documents search searchParameters Using PHP searchParameters q gt godfather query by gt movie name filter by gt average rating gt sort by gt average rating desc client gt collections movies gt documents gt search searchParameters Using PYTHONsearch parameters q godfather query by movie name filter by average rating gt sort by average rating desc client collections movies documents search search parameters Using RUBYsearch parameters q gt godfather query by gt movie name filter by gt average rating gt sort by gt average rating desc client collections movies documents search search parameters Using SHELLcurl H X TYPESENSE API KEY TYPESENSE API KEY http localhost collections movies documents search q godfather amp query by movie name amp filter by average rating gt amp sort by average rating desc The following is the final sample response you will receive facet counts found out of page request params q search time ms hits highlights field movie name snippet lt mark gt Godfather lt mark gt matched tokens Godfather document id movie name Godfather average rating Group ByBy specifying one or more group by fields you can aggregate search results into groups This method of grouping hits is only beneficial in the following situations Deduplication You can combine items and remove duplicates in the search results by using one or more group by fields If there are multiple movies of the same rating for example doing a group by rating amp group limit ensures that only one movie of each individual rating appears in the search results Correcting skew If a particular type of document dominates your results you can use group by and group limit to correct the skew If your search results for a query contain a lot of documents from the same company for example you can use group by company amp group limit to ensure that only the top three results from each company are returned in the search results Unlike the plain JSON response format we saw earlier grouping returns the hits in a nested structure Let s run the same query with a group by parameter as we did before Using JAVASCRIPTlet searchParameters q godfather query by movie name filter by average rating gt sort by average rating desc group by genre group limit client collections movies documents search searchParameters Using PHP searchParameters q gt godfather query by gt movie name filter by gt average rating gt sort by gt average rating desc group by gt genre group limit gt client gt collections movies gt documents gt search searchParameters Using PYTHONsearch parameters q godfather query by movie name filter by average rating gt sort by average rating desc group by genre group limit client collections movies documents search search parameters Using RUBYsearch parameters q gt godfather query by gt movie name filter by gt average rating gt sort by gt average rating desc group by gt genre group limit gt client collections movies documents search search parameters Using SHELLcurl H X TYPESENSE API KEY TYPESENSE API KEY http localhost collections movies documents search q godfather amp query by movie name amp filter by average rating gt amp sort by average rating desc amp group by genre amp group limit The following is the final sample response you will receive facet counts found out of page request params q search time ms grouped hits group key DRAMA hits highlights field movie name snippet lt mark gt Godfather lt mark gt document id movie name Godfather average rating genre DRAMA Search Argumentsq It is simply used to search terms to use in the collection To get all documents use the search string This is most useful when combined with filter by For example q amp filter by average rating will return all documents that match a filter query by There should be one or more string string fields to be queried against Use a comma to separate multiple fields for example movie name genre A record that matches on a field earlier in the list is considered more relevant than a record that matches on a field later in the list As a result documents that match the movie name field are ranked higher than documents that match on the genre field query by weights When ranking results the relative weight to give each query by field When looking for matches this can be used to boost fields in priority In the same order as the query by fields separate each weight with a comma For example using query by weights with query by field a field b field c will give field a and field b equal weight and field c twice the weight sort by A list of numerical fields and sort orders that will be used to order your results Use a comma to separate multiple fields You can specify up to three sort fields average rating desc release date ascprefix The prefix argument is a Boolean field that indicates whether the query s last word should be treated as a prefix rather than a whole word This is required for the development of autocomplete and instant search interfaces facet by facet by will help you facet your results Don t forget to use a comma to separate multiple fields filter by The filter by argument is used to refine your search results by filtering conditions One or more values can be matched against a field genre CRIME genre ROMANTIC COMEDY You must mark a field as a facet and use the operator to match a string field exactly For example genre ROMANTIC will return documents from the genre ROMANTIC rather than a genre like ROMANTIC COMEDY You can also use multiple values to filter genre Romantic Comedy Using the range operator min max you can get numeric values between a minimum and maximum value Also not only that you can separate multiple conditions with the  amp amp  operator For example average rating gt amp amp genre ROMANTIC DRAMA max facet values This argument simply returns the maximum number of facet values num typos This argument will help to tolerate either or typological errors facet query This parameter can be used to filter the facets that are returned page This argument helps to fetch the results from the specific page per page This argument helps to fetch the results per each individual page group by By specifying one or more group by fields this argument aids in the grouping of search results into groups or buckets group limit This argument aids in limiting the total number of hits returned for each group If the group limit is set to A the response will only include the top A hits in each group include fields This argument is used to list all of the document s Comma separated fields that will be included in the search result exclude fields This argument is used to list all of the document s Comma separated fields that will be excluded in the search result highlight full fields This argument is used to list all of the document s Comma separated fields that will be highlighted in the search result fully without snippeting highlight affix num tokens This argument determines how many tokens should be used to surround the highlighted text on each side highlight start tag This argument is used as the start tag for the highlighted snippets highlight end tag This argument is used as the end tag for the highlighted snippets snippet threshold Field values under this length will be fully highlighted instead of showing a snippet of the relevant portion drop tokens threshold If the number of results returned for a query is less than the number specified in this argument Typesense will attempt to drop tokens from the query until enough results are returned Individually hit tokens are dropped first To disable dropping of tokens set the drop tokens threshold to typo tokens threshold If the number of results returned for a query is less than the number specified in this argument Typesense will attempt to look for tokens with more typos until enough results are found Default pinned hits This argument helps to display a list of records that can be included in the search results at specific positions A perfect example would be to feature or promotion of certain items on the top of search results hidden hits This argument helps to display a list of records that can be hidden in the search results at specific positions limit hits This argument helps to fetch the maximum number of hits from the collection Federated or Multi Search operations Using this Federated Multi Search feature you can send multiple search requests in a single HTTP request This is particularly useful for avoiding the round trip network latencies that would otherwise be incurred if each of these requests were sent as separate HTTP requests This feature can also be used to perform a federated search across multiple collections in just one HTTP request Multi search using Javascriptlet searchRequests searches collection movies q fiction filter by average rating collection director q quentin tarantino let commonSearchParams query by name client multiSearch perform searchRequests commonSearchParams Multi search using PHP searchRequests searches gt collection gt movies q gt fiction filter by gt average rating collection gt director q gt quentin tarantino commonSearchParams query by gt name client gt multiSearch gt perform searchRequests commonSearchParams Multi search using PYTHONsearch requests searches collection movies q fiction filter by average rating collection director q quentin tarantino common search params query by name client multi search perform search requests common search params Multi search using RUBYsearch requests searches collection movies q fiction filter by average rating collection director q quentin tarantino common search params query by name client multi search perform search requests common search params Using SHELLcurl http localhost multi search query by name X POST H Content Type application json H X TYPESENSE API KEY TYPESENSE API KEY d searches collection movies q fiction filter by average rating collection director q quentin tarantino The following is the final sample response you will receive results facet counts found hits document name Pulp fiction director quentin tarantino id average rating highlights field name matched tokens fiction snippet Pulp lt mark gt fiction lt mark gt text match out of page request params per page q fiction search time ms facet counts found hits document name Real fiction director Kim Ki duk id average rating highlights field name matched tokens fiction snippet lt mark gt Real lt mark gt fiction text match out of page request params per page q fiction search time ms Typesense was built with several distinctive features primarily aimed at making the developer s job easier while also giving the customer as well as users the ability to provide a better search experience as possible Join Aviyel s community to learn more about the open source project get tips on how to contribute and join active dev groups Aviyel is a collaborative platform that assists open source project communities in monetizing and long term sustainability To know more visit Aviyel com and find great blogs and events just like this one Sign up now for early access and don t forget to follow us on our socials 2022-05-04 11:31:35
海外TECH DEV Community Build a robot NFT on the Ethereum blockchain with Solidity and Replit (part 1) https://dev.to/ritza/build-a-robot-nft-on-the-ethereum-blockchain-with-solidity-and-replit-part-1-4ne3 Build a robot NFT on the Ethereum blockchain with Solidity and Replit part Non fungible tokens NFTs have been a source of much news and speculation over the past few years Their most widely known use case has been the sale of digital art assets commonly used as profile pictures The most famous examples are CryptoPunks and Bored Apes While many NFTs are collections of pre generated artwork some incorporate a dynamic generative aspect in which the art is created on the fly as individual tokens are minted This is very feasible for profile picture NFTs which often consist of a single base image in a variety of colors and with different features and accessories In some cases such as CryptoKitties new child tokens can be created by breeding existing tokens giving the child token characteristics of both parents In this two part tutorial we ll create a simple generative art NFT ReplBots The first part of the tutorial will focus on the NFT s Ethereum smart contract and the second part will focus on building the web frontend or dApp In this tutorial you ll Learn how to create a generative art NFT on the Ethereum blockchain Learn important smart contract development concepts such as randomness Learn how to interact with the blockchain from frontend JavaScript code Getting startedWe need two things to get started with this project a Solidity repl and a browser wallet Solidity replSign in to Replit or create an account if you haven t already Once logged in create a Solidity starter repl The Solidity starter repl works a little differently from other repls you may have used in the past Rather than running our repl every time we want to test out a new piece of code we can run our repl once to start it up and it will automatically reload when changes are made to our Solidity code in contract sol The Solidity starter repl comes with a friendly web interface built using the web Ethereum JavaScript API which we will use to deploy and interact with our contracts We will deploy to Replit Testnet a custom version of the Ethereum blockchain managed by Replit and optimised for testing Browser walletWe will need a browser based web wallet to interact with the Replit Testnet and our deployed contracts MetaMask is a popular and feature rich wallet implemented as a WebExtension You can install it from MetaMask s download page Make sure you re using a supported browser either Chrome Firefox Brave or Edge Once you ve installed MetaMask follow the prompts to create a wallet and sign in MetaMask will give you a word secret recovery phrase this is your wallet s private key and must be kept safe and secret If you lose this phrase you will not be able to access your wallet If someone else finds it they will If you re already using MetaMask we recommend creating a new account for testing with Replit You can do this from the account menu which appears when you click on the account avatar in the top right corner of the MetaMask interface Introduction to smart contract developmentFeel free to skip this section if you ve written Solidity contracts before or completed our escrow tutorial Now that we ve got our repl and wallet set up we can start developing We will be writing contracts which are the basic building blocks of Ethereum programs An individual contract can have state variables and functions and can inherit from multiple other contracts Contracts in Solidity are equivalent to classes in a language like Python or Java Contracts on Ethereum and Ethereum based networks such as the Replit Testnet and Binance Chain are compiled to bytecode which runs on the Ethereum Virtual Machine EVM This is similar to how Java code compiles to bytecode for the JVM A list of opcodes for EVM is provided here Many of the opcodes dealing with arithmetic and logical operations should be familiar if you ve worked with any kind of assembly before The EVM also has opcodes for blockchain specific operations such as getting information about the current block or chain An additional consideration unique to blockchain development is that each opcode has an associated price listed here Users of smart contracts pay a fee known as gas to invoke state changing functions This fee is determined by the opcodes used and so it is in the interest of developers to keep their code as simple as possible Solidity which we will be using below is the most popular language for developing smart contracts on Ethereum Alternatives such as Vyper exist but are not as widely used NFT designOur ReplBot NFT will consist of a base robot and three accessories The base robot looks like this Each NFT will have three different colors for its frame visor and background Each NFT will also have three different accessories headgear a hat or wig eargear animal ears or headphones and facegear glasses or masks Some examples Which colors and accessories each NFT has will be randomly determined at creation time Contract code scaffoldLet s start on our NFT contract code Open contract sol delete the file s contents and add the following skeleton SPDX License Identifier MITpragma solidity import openzeppelin contracts token ERC extensions ERCEnumerable sol import openzeppelin contracts utils Strings sol contract ReplBots is ERCEnumerable uint public tokenCounter constructor ERC ReplBots RBNFT function mint address recipient public returns uint uint tokenId tokenCounter tokenCounter safeMint recipient tokenId return tokenId The first line of our contract is the license identifier Smart contracts are usually open source and reuse of other projects code is common in DeFi so it s a good idea to include a license that indicates how you would like others to use or not use your code Supported licenses are listed here In the next line we define the version of Solidity we re using in this case any version newer than up to Solidity is an evolving language and often introduces breaking changes so our code may not compile under older or newer versions of the language Following the pragma statement we import some contracts from the OpenZeppelin contract library This library includes inheritable base contracts for a wide variety of common smart contract development needs including base implementations of Ethereum token standards The Ethereum token standard for NFTs is ERC Rather than implementing all of the functionality in this specification ourselves we can import and use OpenZeppelin s version Note that while OpenZeppelin has a base ERC contract we will use the ERCEnumerable extension child contract which in addition to all the standard ERC functionality will allow us to list which NFTs belong to which owners This functionality is vital for our front end We also use OpenZeppelin s Strings library which provides some useful functions for working with strings Our contract definition indicates that we will inherit from ERCEnumerable contract ReplBots is ERCEnumerable In the contract body we define a tokenCounter state variable This will provide us with unique incrementing IDs for tokens as they are minted Solidity automatically initializes all variables to so we don t need to do so explicitly Note the use of uint as the type for these values Because most of the values we deal with in Solidity programs are monetary we use unsigned integers to avoid storing negative numbers In versions of Solidity before this sometimes led to dangerous overflows but overflow protection is now built into the language Next we have the constructor method which calls a parent constructor to define our NFT s name and symbol stock ticker constructor ERC ReplBots RBNFT We then define a mint function so that we can create NFTs function mint address recipient public returns uint uint tokenId tokenCounter tokenCounter safeMint recipient tokenId return tokenId For now all this does is increment tokenCounter create a new token using ERC safeMint and return the numeric ID of the minted NFT Using safeMint instead of mint will prevent us from minting tokens to a recipient that does not have an implemented method for receiving them This will prevent our tokens from getting stuck in contract addresses and becoming unusable The mint function is a public function which means it can be called by both external users and by other functions in this contract or any contracts that inherit from it Solidity provides granular function and variable visibility options which are explained here NFT data structuresLet s fill out our code skeleton starting with the data structures we ll need to store information about each NFT we mint As per our design each NFT will have three accessories and three colors We can represent the accessories as strings and the colors as RGB values We ll start by defining a string array for each type of accessory Add the following code above the constructor definition string private headgear Cowboy Hat Fro Baseball Cap Viking Helmet string private eargear Bunny Ears Headphones string private facegear Sunglasses Moustache Nose DOOM Mask Feel free to draw and add other accessories to these lists Next we ll create a struct for defining colors Add this code below your array definitions struct Color uint red uint green uint blue Each color will have a red green and blue component represented as an bit unsigned integer Most unsigned integers we work with in contracts are bit to the point that Solidity provides the alias uint for uint However it is good practice to use smaller values where possible due to gas costs this is known as tight variable packing An bit unsigned integer can contain a value from to which is precisely the range we need for storing standard RGB values Next we ll create a struct for the ReplBot itself consisting of our three colors and three accessories Add this code below the previous struct definition struct ReplBot Color frame Color visor Color background uint head uint ears uint face To save space we ll store our accessory values as indexes in the arrays we defined above uint allows us to define a maximum of accessories per type which is more than enough Finally we ll define a mapping type that will allow us to associate numeric token IDs with ReplBot structs Add this line below your last struct definition mapping uint gt ReplBot private replbots Minting NFTsNow that we have our data structures in place we can return to our mint function and expand it Replace your mint function s body with the following code function mint address recipient public returns uint Get ID and increment counter uint tokenId tokenCounter tokenCounter Determine colors Color memory frameCol Color uint random tokenId QWERT uint random tokenId YUIOP uint random tokenId ASDFG Color memory visorCol Color uint random tokenId HJKL uint random tokenId ZXCVB uint random tokenId BNM Color memory backgroundCol Color uint random tokenId uint random tokenId uint random tokenId Determine accessories uint headIdx uint random tokenId qwert headgear length uint earIdx uint random tokenId yuiop eargear length uint faceIdx uint random tokenId asdfg facegear length Create bot replbots tokenId ReplBot frameCol visorCol backgroundCol headIdx earIdx faceIdx Mint token safeMint recipient tokenId return tokenId The bulk of this code consists of retrieving random numbers and using the modulo operator to convert them into a number in the range we need for colors this will be a number between and and for accessories this will be a valid index in the relevant accessory array When we define our Color structs we specify the data location memory The data location must be specified for all complex data types arrays structs and strings For variables that are local to a function memory is usually correct Once that s done we create the ReplBot struct assign it to our token ID through the mapping and then mint the token However if you try to compile this code you ll notice that random is not defined Unlike many traditional languages Solidity has no native way of generating pseudorandom numbers So we ll need to define one ourselves Randomness in Ethereum contracts is a difficult thing to get right and one that can be dangerous if done wrong depending on what it s used for If you ve delved into randomness in other languages you ll know that the random numbers we use in programming are usually only pseudorandom originating from a predetermined seed or based on the time of execution This is okay when we re generating a Minecraft world but presents problems for say a blockchain based lottery Because Ethereum is a transparent and distributed network we have no way to hide a seed and values like the current time can be manipulated by miners looking to profit The only foolproof way to generate random numbers at the moment is to use a trusted external source of randomness such as Chainlink s VRF oracle an oracle is a data feed built for use by smart contracts However as we re building on the Replit Testnet we won t have access to such an oracle so we ll need to settle for the best pseudorandomness we can get If we were building a lottery contract this would be a problem but for this project manipulation can only get you a slightly different looking ReplBot Our random function should be inserted below the mint function It looks like this function random uint tokenId string memory input internal view returns uint bytes blckhash blockhash block number return uint keccak abi encodePacked block difficulty blckhash tokenId abi encodePacked input This is a view function because it does not change state In the first line we re getting the blockhash of the last block to be mined In the second line we use abi encodePacked to concatenate the following The blockhash we previously retrieved The difficulty of the current block The ID of the token we re minting The input string we passed in when calling random All but the last of these values will be the same for every invocation of random in an individual mint call This is why we ve specified different strings for each one We then hash our big chunk of data using keccak A good hash function will return very different outputs given similar inputs so this ensures that every call to random will return a sufficiently distinct result even when most of the inputs are the same Finally we convert this hash into an unsigned integer to be returned as our final random number Viewing token dataNow that we can generate tokens with interesting looking ReplBots we need a way of retrieving information about them so that we ll be able to display them on the web frontend we ll build in Part of this tutorial To this end we ll write two functions botAccessories and botColors These will be externally callable view functions that will take the token ID and return three strings detailing accessories and colors respectively As external calls to view functions are free we don t have to worry too much about gas costs in these functions Enter the following code between the definitions of mint and random function botAccessories uint tokenId public view returns string memory string memory string memory require exists tokenId ReplBots Query for nonexistent token ReplBot memory bot replbots tokenId return headgear bot head eargear bot ears facegear bot face Our function body starts with a require statement This is an error handling function in Solidity If the condition in the first argument is not met the current transaction will revert undoing all previous actions and the error message in the second argument will be displayed In this instance we re using it to prevent the details of unminted tokens from being queried Once we ve confirmed that tokenId is valid we retrieve its associated ReplBot struct Solidity allows us to return multiple values from a function which we use to return three different strings Now let s create botColors Add the following code below the definition of botAccessories function botColors uint tokenId public view returns string memory string memory string memory require exists tokenId ReplBots Query for nonexistent token ReplBot memory bot replbots tokenId return colorToString bot frame colorToString bot visor colorToString bot background This function is quite similar to botAccessories but as our colors are structs rather than strings we will need to define a new function colorToString to convert them Let s do that now Add the following code below the definition of botColors function colorToString Color memory color internal pure returns string memory string memory parts parts color red toString color blue toString color green toString return string abi encodePacked parts parts parts parts parts parts parts While Solidity does not currently have a string concatenation function we can use abi encodePacked on an array of strings to achieve the same result similar to what we did in random Solidity also doesn t have any syntactic sugar for expanding splatting arrays into function arguments so we have to specify each element individually But wait Where does toString come from If you try to compile this contract now you ll find that this method is undefined Rather than being a Solidity built in this comes from the OpenZeppelin Strings library that we imported at the beginning of this tutorial To use this library we need to add the following line to our contract definition right below contract ReplBots is ERCEnumerable using Strings for uint Solidity s using Library for type directive attaches all functions in the specified library to the specified type When a library function is called on an object of that type it will receive that object as its first parameter Testing our contractNow that we ve implemented our NFT s core functionality it s time to deploy to the Replit Testnet and test it out We ll use our repl s web interface to do this First run your repl Once all of the dependencies are installed you should see the Replit Ethereum web interface in your repl s browser It looks like this Connect your MetaMask wallet to the web interface and switch to the Replit Testnet Then click the link to get ETH for testing Wait until ETH shows up in your wallet balance on the top right of the page Now you can deploy your contracts Select ReplBots from the drop down box and click Deploy Approve the MetaMask pop up that appears Once this contract has been deployed it will show up as an expandable box below the drop down box Expand it and take a look at all the different functions available Mint your first NFT by navigating to the mint function Click on your wallet address in the top right corner of the page to copy it and then paste it into the recipient field Then run the function and approve the MetaMask pop up that appears After a few seconds you should see a pop up indicating that your transaction has gone through Congratulations you re the proud owner of a ReplBot NFT Check out its colors and accessories by entering ID into botColors and botAccessories If you mint again you should receive a ReplBot with ID and a different set of colors and accessories Breeding botsWe can now mint ReplBots with random characteristics which fulfills the specification we laid out at the start of this tutorial But with a bit of additional code we can introduce a second way to create ReplBots breeding For our breed function we ll accept two separate ReplBots owned by the caller and create a new one with the following characteristics Its colors will be an equal mix of both parents Its headgear will come from the first parent Its eargear will come from the second parent Its facegear will be randomized To keep track of which bots are minted and which bots are bred we ll add a few additional fields to our ReplBot struct Go to the top of your contract and edit the struct to resemble the following struct ReplBot Color frame Color visor Color background uint head uint ears uint face uint generation new field uint parentOneId new field uint parentTwoId new field We ll store our bot s generation and both parent IDs Bots created through mint will have for all three of these values To avoid making it look as though all minted bots have token for both parents we ll start the tokenCounter from Edit its declaration near the top of your contract as follows uint public tokenCounter no more token Then we need to add three zeros to the creation of the ReplBot struct in mint Find and edit the line below Create bot replbots tokenId ReplBot frameCol visorCol backgroundCol headIdx earIdx faceIdx lt ZEROS ADDED Mint token safeMint recipient tokenId return tokenId Now we can start on our breed function Add the following code below the definition of mint function breed uint parentOneId uint parentTwoId address recipient public returns uint Require two parents require parentOneId parentTwoId ReplBots Parents must be separate bots Check ownership require ownerOf parentOneId msg sender ReplBots You don t own parent require ownerOf parentTwoId msg sender ReplBots You don t own parent ReplBot storage parentOne replbots parentOneId ReplBot storage parentTwo replbots parentTwoId Check age require parentOne generation parentTwo generation ReplBots Parents must belong to the same generation We start our function off with some checks The two parent IDs must be different they must be owned by the function caller msg sender and they must be in the same generation Next comes our bot creation code which will be similar to the code in our mint function Add the following code below the final require statement in the breed function above Increment token counter uint tokenId tokenCounter tokenCounter Interpolate colors Color memory frameCol Color meanOfTwo parentOne frame red parentTwo frame red meanOfTwo parentOne frame green parentTwo frame green meanOfTwo parentOne frame blue parentTwo frame blue Color memory visorCol Color meanOfTwo parentOne visor red parentTwo visor red meanOfTwo parentOne visor green parentTwo visor green meanOfTwo parentOne visor blue parentTwo visor blue Color memory backgroundCol Color meanOfTwo parentOne background red parentTwo background red meanOfTwo parentOne background green parentTwo background green meanOfTwo parentOne background blue parentTwo background blue Choose accessories uint headIdx parentOne head uint earIdx parentTwo ears uint faceIdx uint random tokenId asdfg facegear length Create bot replbots tokenId ReplBot frameCol visorCol backgroundCol headIdx earIdx faceIdx parentOne generation parentOneId parentTwoId Mint token safeMint recipient tokenId return tokenId All of our bot s colors and attributes are generated according to the breeding process we specified above One last thing we ll need to do is define the meanOfTwo function we re using to determine the child bot s colors Add the following code to the bottom of your contract just below the definition of random function meanOfTwo uint first uint second internal pure returns uint return uint uint first uint second Here we convert first and second into uint values to prevent them from overflowing which would cause our function to revert divide the result by two and return it as a uint Lastly we ll need to define a new view function to return the generation and parentage of individual tokens Insert the definition of the following function botParentage just below the definition of botColors function botParentage uint tokenId public view returns uint uint uint require exists tokenId ReplBots Query for nonexistent token ReplBot memory bot replbots tokenId return bot generation bot parentOneId bot parentTwoId Compile and deploy your contract as you did before Because it s a new contract you ll need to mint two new ReplBots before you can try out the breed function Do so now and check that your child bot ID looks as expected Then call botParentage to check its generation and parents Adding eventsOur contract is now fully functional but there are a few niceties we can add in the form of events Events provide a user friendly form of logging on the blockchain and are commonly used by dApps It s considered best practice to emit events whenever a state change is made so we should define events for our contract s two state changing actions minting and breeding Event definitions are commonly placed at the bottom of contracts Add the following code just above your contract s final closing brace event ReplBotCreated address recipient uint tokenId event ReplBotBorn address recipient uint tokenId uint parentOneId uint parentTwoId uint generation Then insert an event emission near the end of your mint function as below safeMint recipient tokenId emit ReplBotCreated recipient tokenId lt NEW LINE return tokenId And another one near the end of your breed function safeMint recipient tokenId emit ReplBotBorn recipient tokenId parentOneId parentTwoId parentOne generation lt NEW LINE return tokenId Next stepsWe re done with our contract code In the second part of this tutorial we ll build a dApp frontend for users to mint view and breed ReplBot NFTs If you d like to spend a bit more time exploring Solidity first here are some ways you might want to change and expand this contract Add more accessories You ll need to draw these yourself Refactor the code to reduce the size of the contract and make individual functions more gas efficient One quick way to do this would be to change the visibility of the public functions to external Tweak the breeding algorithm Introduce a siring mechanism that allows users to breed ReplBots they don t own You can find our repl here 2022-05-04 11:29:02
海外TECH DEV Community Do I build or buy an API? https://dev.to/ummshivacodes/do-i-build-or-buy-an-api-ep9 verification 2022-05-04 11:14:15
海外TECH DEV Community HoverAssist v0.3 https://dev.to/saisaaketh/hoverassist-v03-4dfi HoverAssist v HoverAssist Github Repo Url About HoverThe Github Link Below Github Repo Url HoverAssist Is a voice Assistant ‍Which help to to do tasks and Many things Easily Just With Your VoiceHoverAssist is Here To manage Your Tasks Play Music Shutdown your System take screnshot Switch Windows Searh Stuff on the Internet Keep Your Device secure using secure cam while you are AFK Automate Your Desktop As you like Just with your voice Join Now Discord Hover Community FeaturesHover Can Search The Web Take ScreenShots Shutdown Your PCPlay Youtube VideosTake Notes Switch Windows Keep Your Device Secure Usinng Secure Cam Open Youtube Wikipedia Open YoutubeOpen Stack OverflowOpen Camera Features Going To be Added Open Any App Installed On your pc Open Any Websites WikiHow searches Google webscraping search results Android and IOS Support License And Copyrights HoverAssist is Licensed to SaiSaaketh Under MIT License Github Repo Url 2022-05-04 11:02:31
海外TECH DEV Community Dockerize NodeJs Application https://dev.to/drsimplegraffiti/dockerize-nodejs-application-2p3i Dockerize NodeJs Application gt Docker is an open platform for developing shipping and running applications In other words It enables developers to package applications into containersーstandardized executable components combining application source code with the operating system OS libraries and dependencies required to run that code in any environment Lets look at practical example on how we can use Docker to ship our NodeJs app and all the development dependencies using Docker PrerequisiteDocker downloadNodeJs download ️SetupMake sure your docker daemon is active Click on the Docker Desktop Icon to start the Docker engine Check if docker is installed on your PC correctlyRun this command docker version Result Dockerize NodeJS AppLet initiate our NodeJs Project using the npm init y command Install Project DependenciesInstall Express using npm i express create index js file and create a NodeJs Server Let s test our appFor simplicity sake i edited the package json file and fired the app using npm start Dockerizing your NodeJs AppCreate a Dockerfile and Paste the below code Code explanation The FROM command tells Docker to use the node alpine image as the base image for the Dockerfile WORKDIR app tells Docker to set the working directory for the container to app ADD package json tells Docker to copy the package json file into the container RUN npm install tells Docker to run npm install inside the container ADD index js tells Docker to copy the index js file into the container EXPOSE tells Docker to expose the port on the container CMD node index js tells Docker to run node index js inside the container Let s Build our appThe dockerized app is the name i gave my Docker Image that i want to build You can use any descriptive name of your choice The is referring to the current folder Let s check our built image Next we run our container from the images Explanation The d flag is used to run the container in the background The p flag is used to set the port that the container will listen on The port number is your localhost port and the port that you are making the request to i e the Container port that we exposed earlier The name of the container is node api The dockerized app image is the name of the image that you are going to run Check all running containers Lets test our exposed port of our running instance on browser Inspect your running instance Stop a running container Restart a running container Remove the running container force remove ConclusionI hope this post was helpful ResourcesTechWorld with NanaDocker AmigoesDocker 2022-05-04 11:01:33
Apple AppleInsider - Frontpage News A foldable iPhone isn't the future, but a folding iPad or MacBook might be https://appleinsider.com/articles/22/05/04/a-foldable-iphone-isnt-the-future-but-a-folding-ipad-or-macbook-might-be?utm_medium=rss A foldable iPhone isn x t the future but a folding iPad or MacBook might beA foldable iPhone might be cool in concept but the form factor is not likely to be the future of Apple s flagship product Instead Apple could use folding display technology to make a more useful device Foldable iPhone renderLet s be honest ーcurrent folding devices have many issues that have yet to be fixed Given that Apple typically waits before coming out with its versions of new and unproven technology there s a good chance that the fad of the folding smartphone may have passed by the time Apple is ready Read more 2022-05-04 11:46:33
Apple AppleInsider - Frontpage News Apple stops BOE OLED iPhone screen production over unauthorized design change https://appleinsider.com/articles/22/05/04/apple-stops-boe-oled-iphone-screen-production-over-unauthorized-design-change?utm_medium=rss Apple stops BOE OLED iPhone screen production over unauthorized design changeBOE has reportedly made almost no OLED iPhone displays since February and it may be because Apple discovered the company had altered the components BOE has previously been reported to be having production problems with its OLED display panels That was originally believed to be because of the global chip shortage making it harder to source the processors required for the panels Now however The Elec claims that BOE has made only a low number of panels since February ーand that it is no longer because of the processor shortage Rather unspecified sources have told the publication that the dramatic drop in production volume is most likely to be because the company changed part of the design Read more 2022-05-04 11:43:58
Apple AppleInsider - Frontpage News Young filmmaker given 'Dream Studio Makeover' by Apple https://appleinsider.com/articles/22/05/04/young-filmmaker-given-dream-studio-makeover-by-apple?utm_medium=rss Young filmmaker given x Dream Studio Makeover x by AppleApple has kitted out an aspiring documentary and music video filmmaker with a Mac Studio and an array of accessories in what it s calling a Dream Studio Makeover project Filmmaker Cam Blumberg learns he s being given a Mac StudioFilmmaker Cam Blumberg had been struggling to make films on a MacBook Pro with GB SSD He s now been given at least worth of Apple gear plus further accessories including a TB external drive Read more 2022-05-04 11:25:30
Apple AppleInsider - Frontpage News Allison Janney joins 'Mrs American Pie' on Apple TV+ https://appleinsider.com/articles/22/05/04/allison-janney-joins-mrs-american-pie-on-apple-tv?utm_medium=rss Allison Janney joins x Mrs American Pie x on Apple TV Forthcoming Apple TV comedy Mrs American Pie has signed The West Wing and Mom star Allison Janey Allison Janney in a guest appearance at the White House in The part comedy is set in s Palm Beach and stars Kristen Wiig as Maxine Simmons trying to get into the area s high society It s based on Juliet McDaniel s novel Mr and Mrs American Pie and has been developed for Apple TV by actor producer Laura Dern Read more 2022-05-04 11:01:17
海外TECH Engadget The Morning After: Apple may have hired a longtime Ford exec for its car project https://www.engadget.com/the-morning-after-apple-longtime-ford-exec-car-project-111341777.html?src=rss The Morning After Apple may have hired a longtime Ford exec for its car projectI thought Apple s car project had gone a little quiet but it s still a thing according to Bloomberg The company has reportedly hired a longtime Ford engineer and executive to work on its car thought experiment once called Project Titan Desi Ujkashevic had been with the automaker since and was Ford s global director of automotive safety engineering Naturally that means we ve chewed over her work history and LinkedIn page noting she s worked on Ford s electric vehicles and regulatory issues ーexpertise Apple will love There have been rumors about Apple s work on autonomous vehicles since but there have been more setbacks than announcements Doug Field who apparently led Project Titan left Apple to rejoin Ford last September Are they just swapping execs ーMat Smith nbsp The biggest stories you might have missedRivian will receive up to billion in state incentives to build Georgia production facilityBlizzard gives sneak peek of new mobile game Warcraft Arclight Rumble Twitter Circle test limits tweets to close friendsYouTube Go will no longer be available starting this AugustInstagram is testing even more recommendations in the main feedRazer s Blade is the first laptop with a Hz OLED screenLiterally the nicest screen you ll see RAZERRazer is updating its Blade laptop with an option for what it says is the first Hz OLED laptop display You ll get the high responsiveness for an edge in multiplayer games but you ll still have a color accurate p panel percent of the DCI P space with deep contrast You ll need deep pockets The upgraded Blade will arrive before the end of the year for Continue reading Paramount debuts in the UK and Ireland on June ndIt has nearly million subscribers Paramount s streaming service will arrive in the UK and Ireland on June nd South Korea will also have access sometime in June For everywhere else you ll have to wait until the second half of The company announced it added million new Paramount subscribers in the first quarter of putting the platform now at almost million customers Despite Halo Continue reading Ubisoft Montreal takes over work on Prince of Persia remakeThe game was supposed to come out this year but…UbisoftWork on Prince of Persia The Sands of Time Remake hasn t gone as smoothly as Ubisoft hoped The company has now put its Montreal studio in charge of the project taking it away from Ubisoft s Pune and Mumbai studios Ubisoft Montreal was quot the very birthplace of the epic Sands of Time trilogy quot the developers wrote in a message to fans The original was released in which was a reboot of well s Prince of Persia In the original when you died you stayed dead Continue reading The best travel gear for graduatesHook them up with the latest gadgets before their next trip Peak DesignWhile this guide is for graduates planning trips post college I think a lot of us are thinking of going somewhere as travel restrictions relax and we all start to feel more comfortable with the idea of long distance travel Here are some travel essentials to help you stay connected ーand have more fun ーon the road Continue reading 2022-05-04 11:13:41
海外TECH CodeProject Latest Articles A Polynomials Math Parser in VB.NET https://www.codeproject.com/Articles/5328919/A-Polynomials-Math-Parser-in-VB-NET evaluator 2022-05-04 11:04:00
海外TECH WIRED Europe’s New Law Will Force Secretive TikTok to Open Up https://www.wired.com/story/tiktok-transparency-dsa-europe facebook 2022-05-04 11:39:41
海外ニュース Japan Times latest articles Russia bars entry to Kishida and Cabinet ministers https://www.japantimes.co.jp/news/2022/05/04/national/politics-diplomacy/russia-ban-kishida-officials/ Russia bars entry to Kishida and Cabinet ministersRussia s Foreign Ministry on Wednesday announced sanctions against Japanese officials journalists and professors for engaging in what it called unacceptable rhetoric against Moscow 2022-05-04 20:11:24
ニュース BBC News - Home Mali nonuplets in perfect health on first birthday - father https://www.bbc.co.uk/news/world-africa-61318427?at_medium=RSS&at_campaign=KARANGA birthday 2022-05-04 11:12:36
ニュース BBC News - Home Britain's Got Talent star Jonathan Goodwin paralysed https://www.bbc.co.uk/news/uk-wales-61314239?at_medium=RSS&at_campaign=KARANGA goodwin 2022-05-04 11:40:26
ニュース BBC News - Home Boohoo hit as shoppers return more clothes than before Covid https://www.bbc.co.uk/news/business-61318087?at_medium=RSS&at_campaign=KARANGA brand 2022-05-04 11:45:31
ニュース BBC News - Home Toddlers & Tiaras and viral star Kailia Posey dies at 16 https://www.bbc.co.uk/news/entertainment-arts-61318668?at_medium=RSS&at_campaign=KARANGA cheeky 2022-05-04 11:17:20
ニュース BBC News - Home Ukraine war: Why Russian oil is so sticky for Germany https://www.bbc.co.uk/news/world-europe-61318690?at_medium=RSS&at_campaign=KARANGA schwedt 2022-05-04 11:46:55
ニュース BBC News - Home Ukraine war in maps: Tracking the Russian invasion https://www.bbc.co.uk/news/world-europe-60506682?at_medium=RSS&at_campaign=KARANGA ukrainian 2022-05-04 11:43:37
サブカルネタ ラーブロ 名寄市 ラーメン 次郎 しょうゆ篇 http://ra-blog.net/modules/rssc/single_feed.php?fid=198839 久しぶり 2022-05-04 12:35:25
北海道 北海道新聞 こども歌舞伎、熱演で観客魅了 3年ぶり、石川・小松市で https://www.hokkaido-np.co.jp/article/677164/ 安宅の関 2022-05-04 20:20:37
北海道 北海道新聞 中国空母で艦載機が発着 沖縄南方の太平洋 https://www.hokkaido-np.co.jp/article/677169/ 沖大東島 2022-05-04 20:15:33
北海道 北海道新聞 インド中央銀、4・4%に利上げ インフレのリスク懸念 https://www.hokkaido-np.co.jp/article/677171/ 金融政策 2022-05-04 20:14:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

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

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