python |
Pythonタグが付けられた新着投稿 - Qiita |
pythonの`next`関数は、iteratorから次の要素を取得してくれるものでした |
https://qiita.com/seigot/items/1a6baa5e43882083dcdc
|
|
2022-02-13 22:55:18 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
SMTPLIBを使ったGmailの送信サンプルコード |
https://qiita.com/Maruchin/items/c4b6cb7635b74def03cf
|
SMTPLIBを使ったGmailの送信サンプルコードSMTPLIBを使ったGmailの送信サンプルコードです。 |
2022-02-13 22:23:21 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
PyOCRを使ったOCRのサンプルコード |
https://qiita.com/Maruchin/items/1526bdf8460e2a3c6ebc
|
PyOCRを使ったOCRのサンプルコードPyOCRを使ったOCRのサンプルコードです。 |
2022-02-13 22:21:01 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
ReportLabのチートシート |
https://qiita.com/Maruchin/items/dce50cebac7134b57df2
|
ReportLab の チートシート ReportLab の チートシート の チートシート です 。 |
2022-02-13 22:19:08 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
PyPDF2のチートシート |
https://qiita.com/Maruchin/items/e78aaf02df0a02f34094
|
PyPDF の チートシート PyPDF の チートシート です 。 |
2022-02-13 22:16:59 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Beautiful Soupを使ったWebスクレイビングのサンプルコード(気象情報をcsvにエクスポート) |
https://qiita.com/Maruchin/items/dca4b5580c71746a3553
|
BeautifulSoupを使ったWebスクレイビングのサンプルコード気象情報をcsvにエクスポートBeautifulSoupを使ったWebスクレイビングのサンプルコード気象情報をcsvにエクスポートです。 |
2022-02-13 22:15:08 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Seleniumを使ったWebスクレイビングのサンプルコード(Google検索結果をcsvにエクスポート) |
https://qiita.com/Maruchin/items/73215b6080643f1f8da3
|
Seleniumを使ったWebスクレイビングのサンプルコードGoogle検索結果をcsvにエクスポートSeleniumを使ったWebスクレイビングのサンプルコードGoogle検索結果をcsvにエクスポートです。 |
2022-02-13 22:11:40 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
MeCabを使ったキーワード抽出のサンプルコード |
https://qiita.com/Maruchin/items/cc25b6219f02559153cb
|
MeCabを使ったキーワード抽出のサンプルコードMeCabを使ったキーワード抽出のサンプルコードです。 |
2022-02-13 22:08:17 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Python-Docxのチートシート |
https://qiita.com/Maruchin/items/373274b7ba18670fae99
|
PythonDocx の チートシート PythonDocx の チートシート を まとめ て み た 。 |
2022-02-13 22:04:50 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
ViteでビルドしたOpenLayersで地理院地図を表示する |
https://qiita.com/naoele/items/5cdb92687a10a379016c
|
OpenLayersを実行して地図を表示GitBashやコマンドプロンプトで以下のコマンドで作成されたアプリケーションの名前のディレクトリへ移動し開発サーバを起動します。 |
2022-02-13 22:34:25 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
【AWSコスト削減の道 for ステージング環境】 Fargate編 |
https://qiita.com/H_broth/items/59f3abc891dcf474cb1c
|
|
2022-02-13 22:33:39 |
GCP |
gcpタグが付けられた新着投稿 - Qiita |
Google Cloud 認定 Professional Cloud Architect 本番レベル問題 Part9 25~27問目(概要欄に問題集のリンクあり) |
https://qiita.com/clouds-starter/items/c6b51f967033ecb7d84b
|
最小限のコストで低遅延を実現すること重複したクレジットカードを識別でき、平文のカード番号を保存しないこと年回の鍵のローテーションに対応していることトークン化サービスには、どのようなストレージアプローチを採用すべきでしょうか。 |
2022-02-13 22:16:53 |
海外TECH |
MakeUseOf |
8 Common Scrum Interview Questions and How to Answer Them |
https://www.makeuseof.com/scrum-interview-questions-how-to-answer/
|
scrum |
2022-02-13 13:30:12 |
海外TECH |
DEV Community |
GitHub Repositories to Crush any Programming Interview! |
https://dev.to/genicsblog/github-repositories-to-crush-any-programming-interview-5f8f
|
GitHub Repositories to Crush any Programming Interview Programming Interviews may be frustrating and tough If you have any phobia regarding programming interviews have no fear because this articles is for you Pro tip Save time by listening to the audio version of this article at Genics BlogToday I ll be disclosing some repositories you can visit to ace in any programming interviews These were rated based on popularity usability and reliability Coding Interview UniversityThis repository helps students prepare for companies like Amazon Microsoft Apple etc Some of the key features are This is my multi month study plan to become a software engineer for a large company If you missed out on getting a degree in computer science this will catch you up and save four years of your life Note this is a study plan for software engineering not web development Large software companies like Google Amazon Facebook and Microsoft view software engineering as different from web development The repository carefully differentiate between the topics into Planning Topic and optional topics to cover to get a edge over others It s a long plan It may take you months However if you are familiar with a lot of this already it will take you a lot less time Tech Interview HandbookIt has curated interview preparation materials for busy engineers Some of the key elements are There are free and curated technical interview preparation materials for busy engineers brought to you by the author of the Blind list Besides the usual algorithm questions it includes Best practice questions for coding interviews How to prepare for coding interviews Straight to the point Do s and Don ts Algorithm tips categorized by topic and many more This repository has practical content that covers all phases of a technical interview from applying for a job to passing the interviews to offer negotiation Technically competent candidates might still find the non technical content helpful The key to succeeding in technical interviews is consistent practice It doesn t bore you with too many words and keeps everything to the point The difference between this repository and others is that many existing interview repositories contain mainly links to external resources whereas this repository contains top quality curated content directly for your consumption Javascript Interview QuestionsThis repo contains a huge list of JavaScripts Interview Questions Some of the main features are Take this JavaScript Projects course to go from a JavaScript beginner to confidently building your own projects Take this coding interview bootcamp if you re serious about getting hired and don t have a CS degree Take this Advanced JavaScript Course to learn advanced JS concepts and become a top JS developer You can download the PDF and Epub version of this repository JavaScript AlgorithmsIt has JavaScript based examples of many popular algorithms and data structures explained Some of the key features are Each algorithm and data structure has its own separate README with related explanations and links for further reading including ones to YouTube videos The beginners and advanced are separated by using symbols B and A respectively This repository has a seperate content for each topic in a systematic way How Web WorksIt helps to learn What happens behind the scenes when we type a URL in a browser Let s look at some of the features If you wonder what happens behind the scenes when we type google com in a browser then you definitely need to check this out This repository goes through a lot of minute details This repository covers stuffs like DNS lookup Opening of a socket TLS handshake HTTP Server Request Handle The browser s high level structure and many more This repository doesn t waste much time and directly dives into the topic InterviewThis repo contains everything you need to prepare for your technical interview Some features include Lists of books to learn algorithms List of websites to practice coding Guides you may need It also contains list of book specifically for job interviews and needs of industries System Design PrimerIt helps to learn how to design large scale systems Preparation for the system design interview Some features like Learning how to design scalable systems will help to become a better engineer System design is a broad topic There is a vast amount of resources scattered throughout the web on system design principles This repo is an organized collection of resources to help you learn how to build systems at scale This is a continually updated open source project In addition to coding interviews system design is a required component of the technical interview process at many tech companies Practice common system design interview questions and compare your results with sample solutions discussions code and diagrams Also contains additional for interview preparation How to secure anythingThis repo contains everything you need to learn on security engineering Like Its lessons are not just applicable to computer security This repository aims to document a process for securing anything whether it s a medieval castle an art museum or a computer network Even you can contribute for this article GanqqwertyThis repo has essential JavaScript Questions to prepare for interview Some features include This book s goal is to help javascript frontend developers prepare for technical job interviews through a collection of carefully compiled questions You can even get this in paperback format This repository is still getting updated so for early access you can visit this repository JavaScript QuestionIt is a long list of advance JavaScript questions and their explanations Some of the key features are From basic to advanced test how well you know JavaScript refresh your knowledge a bit or prepare for your coding interview This repository gets updated daily so new questions are added every day The questions also come with explanation along with answers The repository covers almost every single type of question one can expect in an interview Thank you for reading I write blogs on programming web development and current technology trend If you find this article interesting do share it with others and comment your thoughts Follow me on twitter Until We Meet Again Arindol Sarkar |
2022-02-13 13:45:16 |
海外TECH |
DEV Community |
Como usar uma classe Fixture com xUnit |
https://dev.to/fernandoandrade/como-usar-uma-classe-fixture-com-xunit-58jc
|
Como usar uma classe Fixture com xUnitOi pessoal tudo certo Gostaria de compartilhar uma dica que acho interessante para quem escreve testes utilizando o xUnit que éo uso de Fixture Para quem estáiniciando nessa jornada de testes unitários assim como eu énormal escrevemos dessa forma Fact public void TesteAreaDoQuadrado Area area new int result area Quadrado Assert Equal result Fact public void TesteAreaDoTriangulo Area area new int result area Triangulo Assert Equal result Fact public void TesteAreaDoRetangulo Area area new int result area Retangulo Assert Equal result O que énormal no início mas podemos que notar que para cada teste estamos instanciando a classe Area repetidamente para podermos utilizar os métodos nos casos de teste isso significa que toda vez que um de nossos testes na mesma classe precisa ser executado uma nova instância dessa classe écriada e ter uma Fixture resolve essa necessidade Fixture éuma classe que compartilha todos os métodos de teste nessa classe vocêpode configurar tudo que for necessário assim evitamos de instanciar classes para cada teste individual e melhorando o tempo de execução dos testes Criando a FixtureDentro da classe de teste criamos uma outra classe no meu caso AreaFixture que iráter como propriedade a classe Area jásendo instanciada public class AreaFixture public Area Area gt new Após isso para compartilhar essa instância entre todos os nossos testes adicionamos uma interface para nossa classe de teste usando o IClasseFixture a interface IClasseFixture espera receber a uma classe Fixture nesse caso a AreaFixture public class AreasTest IClassFixture lt AreaFixture gt Ultimo passo évia injeção de dependência adicionamos ao construtor da classe AreaTest a classe AreaFixturepublic class AreasTest IClassFixture lt AreaFixture gt private readonly AreaFixture areaFixture public AreasTest AreaFixture areaFixture areaFixture areaFixture Agora quando o xUnit executar os testes iráser criado uma instância apenas e todos os nossos testes agora possuem acesso aos métodos da classe Area atráves do campo areaFixture Area Fact public void TesteAreaDoQuadrado Area area areaFixture Area int result area Quadrado Assert Equal result Fact public void TesteAreaDoTriangulo Area area areaFixture Area int result area Triangulo Assert Equal result Fact public void TesteAreaDoRetangulo Area area areaFixture Area int result area Retangulo Assert Equal result Código no completo |
2022-02-13 13:40:22 |
海外TECH |
DEV Community |
Starter template with Vite and TypeScript for front-end projects |
https://dev.to/tim_yone/starter-template-with-vite-and-typescript-for-front-end-projects-4055
|
Starter template with Vite and TypeScript for front end projects Starter template with Vite and TypeScript for front end projectsI ve created a starter template which is named VITAM for front end development This template focuses on building a static website and suits small to medium projects like a landing page and a corporate website Check out VITAMVITAM provides some features to increase productivity for front end developers You can get these benefits and features from VITAM Fast HMR with VitePWA supportQuick local serverCompressing image assetsBreaking HTML smaller files with HandlebarsReferring to Enduring CSSOut of the box useful JavaScript librariesOut of the box useful SCSS functions and MixinsChecking TypeScript with ESLintHTML Validation with HTML validateTransforming styles with PostCSSBuilt in test runner with Jest Requirements to use VITAMBefore you start using VITAM make sure you do these following tasks Install Node js Node v Install YarnHere is recommeded tools but they are not necessary Visual Studio CodeGitHub Creating a repository from a templateYou can directly generate a new repository from VITAM s repository Please click Use this template Creating a repository from a template Clone your projectClone the repository you generated from VITAM git clone Install packagesInstall all dependencies for a project with bellow command yarn install Start developmentRun a build command after installed packages yarn buildAnd then run a start command yarn startThat s all to do before you start project Let s enjoy development Template s detailI ve written down below the infomation you should know to use VITAM HTMLYou can handle bundling multiple HTML files with vite plugin handlebars Make sure Handlebars Context as you need If you want to use multiple partial files Add your partial files into the partials folder src partialsYou can call partial files directly by other templates like this example gt header lt main gt lt h gt Welcome to VITAM Docs lt h gt lt p gt VITAM is a front end template with Vite for static websites lt p gt lt main gt gt footer site config ts manages the site s basic information You have to edit site config ts when you create a new page const pagesData sample index html locale siteData locale title Smaple Page siteData siteName description This is a sample page siteData description url siteData url sampple ogpImage siteData ogpImage ogType article fbAppId siteData fbAppId fbAdmins siteData fbAdmins twitterCard siteData twitterCard twitterSite siteData twitterSite Sass Dart Sass You can manage style sheets logically with Sass I ve already defined some functions and Mixins Check out these files before you get started with your project src scss foundation functions scsssrc scss foundation mixins scssLearn Sass CSS ArchitectureVITAM gives you CSS architecture which is Enduring CSS standardly but it s not necessary architecture in all projects I recommend you introduce the best architecture in each project Learn CSS ArchitectureLearn Enduring CSS TypeScriptVITAM supports TypeScript It s easy to import ts files You can customize TypeScript s options with tsconfig json at any time I ve already defined some utility functions Check out these files before you get started with your project src ts utils tspostInstall command will help you to install typings in this project Jest is built in in this project You can run Jest from the command line Learn TypeScriptLearn Jest PWAVite Plugin PWA supports making your website faster Edit vite config ts if you would like to customize settings for PWA You can generate icons for PWA with Favicon Generator Note Please replace some asset files for PWA with your project s files Learn PWA GitHub ActionsIf you use GitHub in your project you can take advantage of GitHub Actions to automate your development workflows Check out this file before you get started with your project github workflows project ci yml ConclusionI added some useful libraries and utility functions into VITAM to improve your development efficiency I hope you take advatage of them Check out VITAM |
2022-02-13 13:24:30 |
海外TECH |
DEV Community |
Interface vs Type in Typescript |
https://dev.to/ridhoanshory/interface-vs-type-in-typescript-4ca0
|
Interface vs Type in TypescriptMy personal convention which I describe below is this Always prefer interface over type When to use type Use type when defining an alias for primitive types string boolean number bigint symbol etc Use type when defining tuple typesUse type when defining function typesUse type when defining a unionUse type when trying to overload functions in object types via compositionUse type when needing to take advantage of mapped typesAdditions Generic TransformationsUse the type when you are transforming multiple types into a single generic type Example type Nullable lt T gt T null undefinedtype NonNull lt T gt T extends null undefined never TType AliasingWe can use the type for creating the aliases for long or complicated types that are hard to read as well as inconvenient to type again and again Example type Primitive number string boolean null undefinedCreating an alias like this makes the code more concise and readable Type CapturingUse the type to capture the type of an object when the type is unknown Example const orange color Orange vitamin C type Fruit typeof orangelet apple FruitHere we get the unknown type of orange call it a Fruit and then use the Fruit to create a new type safe object apple When to use interface Use interface for all object types where using type is not required see above Use interface when you want to take advantage of declaration merging Additions PolymorphismAn interface is a contract to implement a shape of the data Use the interface to make it clear that it is intended to be implemented and used as a contract about how the object will be used Example interface Bird size number fly void sleep void class Hummingbird implements Bird class Bellbird implements Bird Though you can use the type to achieve this the Typescript is seen more as an object oriented language and the interface has a special place in object oriented languages It s easier to read the code with interface when you are working in a team environment or contributing to the open source community It s easy on the new programmers coming from the other object oriented languages too The official Typescript documentation also says we recommend using an interface over a type alias when possible This also suggests that the type is more intended for creating type aliases than creating the types themselves Declaration MergingYou can use the declaration merging feature of the interface for adding new properties and methods to an already declared interface This is useful for the ambient type declarations of third party libraries When some declarations are missing for a third party library you can declare the interface again with the same name and add new properties and methods Example We can extend the above Bird interface to include new declarations interface Bird color string eat void That s it It s easier to remember when to use what than getting lost in subtle differences between the two PS According to TypeScript handbook the answer is Almost all features of an interface are available in type The key distinction is that a type cannot be re opened to add new properties vs an interface which is always extendable |
2022-02-13 13:17:02 |
Apple |
AppleInsider - Frontpage News |
Arm IPO endangered by China unit's legal issues |
https://appleinsider.com/articles/22/02/13/arm-ipo-endangered-by-china-units-legal-issues?utm_medium=rss
|
Arm IPO endangered by China unit x s legal issuesArms plan for an IPO may already be in trouble before it s even started as a long running dispute with its division in China could endanger Softbank s offloading of the chip firm Following the failure of a billion acquisition of Arm by Nvidia owner Softbank intends to spin it off as an independent entity and list it on the New York Stock Exchange later in However problems relating to its unit in China could derail the potential IPO Management issues with its Chinese division including legal activity and a lack of transparency are causing friction that could put off investors reports the Financial Times Read more |
2022-02-13 13:25:04 |
ニュース |
BBC News - Home |
Ukraine tensions: US defends evacuating embassy as Zelensky urges calm |
https://www.bbc.co.uk/news/world-europe-60365017?at_medium=RSS&at_campaign=KARANGA
|
antony |
2022-02-13 13:07:06 |
ニュース |
BBC News - Home |
Humza Yousaf: Scotland should not be forced into Covid easing |
https://www.bbc.co.uk/news/uk-scotland-60366858?at_medium=RSS&at_campaign=KARANGA
|
england |
2022-02-13 13:20:51 |
ニュース |
BBC News - Home |
NHS hospital doctor arrested on suspicion of sexual assault |
https://www.bbc.co.uk/news/uk-england-stoke-staffordshire-60366949?at_medium=RSS&at_campaign=KARANGA
|
trent |
2022-02-13 13:12:07 |
北海道 |
北海道新聞 |
メダル二つ目にっこり 小林陵侑に「銀」授与 |
https://www.hokkaido-np.co.jp/article/645237/
|
小林陵侑 |
2022-02-13 22:02:00 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
ステンレス板の欠陥分類 |
https://qiita.com/daityan_freedom/items/d09a7be9fdae2341fdcc
|
・進め方手順データを調整無しで分類し精度の高い分類方法Bestを選定手順データクレンジングを行い、手順のBestの方法で分類手順手順で最も精度の高い分類方法でハイパーパラメータチューニングを行う開発環境GoogleColaboratoryPytonNumpyPandasseabornsklearnLightGBM学習モデルの構築今回検証する機械学習モデル分類手法は下記で行う。 |
2022-02-14 00:15:35 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
Rails7のapiモードでGraphQLを使ってみた |
https://qiita.com/nakazawaken1/items/e95b2896e65cd3fda8e5
|
RailsのapiモードでGraphQLを使ってみた目的RailsでGraphQLを使うときはどんな感じに書くのかを確認する必要なものDocker今回使用バージョンDockerversionbuildeedVSCodeRemoteDevelpment拡張機能を使用今回使用バージョンVersionブラウザ今回はChromeバージョンOfficialBuildを使用開発環境構築VSCodeを起動してDockerfileを作成し仮想環境を起動するVSCodeで開発用の空フォルダを開くここではdevrailsgraphqlとするRuby環境のDokerfileを作成するdevrailsgraphsqlDockerfileFROMrubyVSCodeのコマンドReopeninContainerでFromDockerfileから仮想環境に切り替えるrailsインストール用のGemfileを作成するGemfilesourcegemrailsVSCodeのterminalを開きgemをインストールするterminalbundleinstallrubyとrailsのバージョン確認terminalrubyv実行結果rubyprevisionfbdfdxlinuxterminalrailsv実行結果Railsrailsプロジェクトを作成terminalrailsnewapiminimal動作確認サーバ起動terminalrailsshttplocalhostにアクセスすればrailsが動作しているのが確認できますGraphQL用のgemを追加terminalbundleaddgraphqlbundleaddgroupdevelopmentgraphiqlsassrails※graphiqlは開発用ツールsassrailsはgraphiql動作に必要graphql関連ファイルの生成terminalrailsggraphqlinstallgraphiqlが動作するよう設定を調整セッション有効化applicationrbに行追加configapplicationrbconfigmiddlewareuseActionDispatchCookiesconfigmiddlewareuseActionDispatchSessionCookieStorerouteに設定を追加routesrbifRailsenvdevelopmentmountGraphiQLRailsEngineatgraphiqlgraphqlpathgraphqlend動作確認railssでサーバを起動してhttplocalhostgraphiqlにアクセステスト用に生成されているクエリを実行GraphQLのクエリ作成今回はイベント予定表のAPIを想定して作ってみますまずイベントの予定を管理するモデルとRESTAPIを生成しますterminalrailsgscaffoldEventtitlestringindexstartatdatetimeindexendatdatetimeplacestringindextagsstringmemotextcanceledbooleanindex生成結果invokeactiverecordcreatedbmigratecreateeventsrbcreateappmodelseventrbinvoketestunitcreatetestmodelseventtestrbcreatetestfixtureseventsymlinvokeresourcerouterouteresourceseventsinvokescaffoldcontrollercreateappcontrollerseventscontrollerrbinvokeresourcerouteinvoketestunitcreatetestcontrollerseventscontrollertestrb次に参加者分を生成しますterminalrailsgscaffoldMembernamestringindexemailstringuniq生成結果invokeactiverecordcreatedbmigratecreatemembersrbcreateappmodelsmemberrbinvoketestunitcreatetestmodelsmembertestrbcreatetestfixturesmembersymlinvokeresourcerouterouteresourcesmembersinvokescaffoldcontrollercreateappcontrollersmemberscontrollerrbinvokeresourcerouteinvoketestunitcreatetestcontrollersmemberscontrollertestrb最後にイベントの参加者分を生成しますterminalrailsgscaffoldEventMembereventreferencesmemberreferencespresentedbooleanindex生成結果invokeactiverecordcreatedbmigratecreateeventmembersrbcreateappmodelseventmemberrbinvoketestunitcreatetestmodelseventmembertestrbcreatetestfixtureseventmembersymlinvokeresourcerouterouteresourceseventmembersinvokescaffoldcontrollercreateappcontrollerseventmemberscontrollerrbinvokeresourcerouteinvoketestunitcreatetestcontrollerseventmemberscontrollertestrbnotnullや既定値を追加設定しますdbmigratecreateeventsrbclassCreateEventsltActiveRecordMigrationdefchangecreatetableeventsdottstringtitlenullfalsetdatetimestartatnullfalsetdatetimeendattstringplacetstringtagsttextmemotbooleancancelednullfalsedefaultfalsettimestampsendaddindexeventstitleaddindexeventsstartataddindexeventsplaceaddindexeventscanceledendenddbmigratecreatemembersrbclassCreateMembersltActiveRecordMigrationdefchangecreatetablemembersdottstringnamenullfalsetstringemailnullfalsettimestampsendaddindexmembersnameaddindexmembersemailuniquetrueendenddbmigratecreateeventmembersrbclassCreateEventMembersltActiveRecordMigrationdefchangecreatetableeventmembersdottreferencesmembernullfalseforeignkeytruetbooleanpresentednullfalsedefaultfalsettimestampsendaddindexeventmemberspresentedendendmigrationを実行しますterminalrailsdbmigrate実行結果CreateEventsmigratingcreatetableeventsgtsaddindexeventstitlegtsaddindexeventsstartatgtsaddindexeventsplacegtsaddindexeventscanceledgtsCreateEventsmigratedsCreateMembersmigratingcreatetablemembersgtsaddindexmembersnamegtsaddindexmembersemailuniquegttruegtsCreateMembersmigratedsCreateEventMembersmigratingcreatetableeventmembersgtsaddindexeventmemberspresentedgtsCreateEventMembersmigratedsGraphQL用の型を生成terminalrailsggraphqlobjectEvent実行結果createappgraphqltypeseventtyperb以下のようにeventsテーブルから情報を取得して自動生成できていますねappgraphqltypeseventtyperbfrozenstringliteraltruemoduleTypesclassEventTypeltTypesBaseObjectfieldidIDnullfalsefieldtitleStringnullfalsefieldstartatGraphQLTypesISODateTimenullfalsefieldendatGraphQLTypesISODateTimefieldplaceStringfieldtagsStringfieldmemoStringfieldcanceledBooleannullfalsefieldcreatedatGraphQLTypesISODateTimenullfalsefieldupdatedatGraphQLTypesISODateTimenullfalseendend同じようにmembereventmemberの分も生成します。 |
2022-02-14 00:07:53 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
【個人的メモ】 EC2からSageMakerを扱う |
https://qiita.com/now-hr/items/50153afd75a57a6ebf7b
|
|
2022-02-14 00:37:44 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
ローカル環境で開発するときに、MySQL を Docker で動かしてみる |
https://qiita.com/sugimount-a/items/a13ae09627309a05728e
|
DockerでMySQLを動かすECRPublicで公開されているDockerImageを使って、ローカル上でMySQLを動かします。 |
2022-02-14 00:59:55 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
Rails7のapiモードでGraphQLを使ってみた |
https://qiita.com/nakazawaken1/items/e95b2896e65cd3fda8e5
|
RailsのapiモードでGraphQLを使ってみた目的RailsでGraphQLを使うときはどんな感じに書くのかを確認する必要なものDocker今回使用バージョンDockerversionbuildeedVSCodeRemoteDevelpment拡張機能を使用今回使用バージョンVersionブラウザ今回はChromeバージョンOfficialBuildを使用開発環境構築VSCodeを起動してDockerfileを作成し仮想環境を起動するVSCodeで開発用の空フォルダを開くここではdevrailsgraphqlとするRuby環境のDokerfileを作成するdevrailsgraphsqlDockerfileFROMrubyVSCodeのコマンドReopeninContainerでFromDockerfileから仮想環境に切り替えるrailsインストール用のGemfileを作成するGemfilesourcegemrailsVSCodeのterminalを開きgemをインストールするterminalbundleinstallrubyとrailsのバージョン確認terminalrubyv実行結果rubyprevisionfbdfdxlinuxterminalrailsv実行結果Railsrailsプロジェクトを作成terminalrailsnewapiminimal動作確認サーバ起動terminalrailsshttplocalhostにアクセスすればrailsが動作しているのが確認できますGraphQL用のgemを追加terminalbundleaddgraphqlbundleaddgroupdevelopmentgraphiqlsassrails※graphiqlは開発用ツールsassrailsはgraphiql動作に必要graphql関連ファイルの生成terminalrailsggraphqlinstallgraphiqlが動作するよう設定を調整セッション有効化applicationrbに行追加configapplicationrbconfigmiddlewareuseActionDispatchCookiesconfigmiddlewareuseActionDispatchSessionCookieStorerouteに設定を追加routesrbifRailsenvdevelopmentmountGraphiQLRailsEngineatgraphiqlgraphqlpathgraphqlend動作確認railssでサーバを起動してhttplocalhostgraphiqlにアクセステスト用に生成されているクエリを実行GraphQLのクエリ作成今回はイベント予定表のAPIを想定して作ってみますまずイベントの予定を管理するモデルとRESTAPIを生成しますterminalrailsgscaffoldEventtitlestringindexstartatdatetimeindexendatdatetimeplacestringindextagsstringmemotextcanceledbooleanindex生成結果invokeactiverecordcreatedbmigratecreateeventsrbcreateappmodelseventrbinvoketestunitcreatetestmodelseventtestrbcreatetestfixtureseventsymlinvokeresourcerouterouteresourceseventsinvokescaffoldcontrollercreateappcontrollerseventscontrollerrbinvokeresourcerouteinvoketestunitcreatetestcontrollerseventscontrollertestrb次に参加者分を生成しますterminalrailsgscaffoldMembernamestringindexemailstringuniq生成結果invokeactiverecordcreatedbmigratecreatemembersrbcreateappmodelsmemberrbinvoketestunitcreatetestmodelsmembertestrbcreatetestfixturesmembersymlinvokeresourcerouterouteresourcesmembersinvokescaffoldcontrollercreateappcontrollersmemberscontrollerrbinvokeresourcerouteinvoketestunitcreatetestcontrollersmemberscontrollertestrb最後にイベントの参加者分を生成しますterminalrailsgscaffoldEventMembereventreferencesmemberreferencespresentedbooleanindex生成結果invokeactiverecordcreatedbmigratecreateeventmembersrbcreateappmodelseventmemberrbinvoketestunitcreatetestmodelseventmembertestrbcreatetestfixtureseventmembersymlinvokeresourcerouterouteresourceseventmembersinvokescaffoldcontrollercreateappcontrollerseventmemberscontrollerrbinvokeresourcerouteinvoketestunitcreatetestcontrollerseventmemberscontrollertestrbnotnullや既定値を追加設定しますdbmigratecreateeventsrbclassCreateEventsltActiveRecordMigrationdefchangecreatetableeventsdottstringtitlenullfalsetdatetimestartatnullfalsetdatetimeendattstringplacetstringtagsttextmemotbooleancancelednullfalsedefaultfalsettimestampsendaddindexeventstitleaddindexeventsstartataddindexeventsplaceaddindexeventscanceledendenddbmigratecreatemembersrbclassCreateMembersltActiveRecordMigrationdefchangecreatetablemembersdottstringnamenullfalsetstringemailnullfalsettimestampsendaddindexmembersnameaddindexmembersemailuniquetrueendenddbmigratecreateeventmembersrbclassCreateEventMembersltActiveRecordMigrationdefchangecreatetableeventmembersdottreferencesmembernullfalseforeignkeytruetbooleanpresentednullfalsedefaultfalsettimestampsendaddindexeventmemberspresentedendendmigrationを実行しますterminalrailsdbmigrate実行結果CreateEventsmigratingcreatetableeventsgtsaddindexeventstitlegtsaddindexeventsstartatgtsaddindexeventsplacegtsaddindexeventscanceledgtsCreateEventsmigratedsCreateMembersmigratingcreatetablemembersgtsaddindexmembersnamegtsaddindexmembersemailuniquegttruegtsCreateMembersmigratedsCreateEventMembersmigratingcreatetableeventmembersgtsaddindexeventmemberspresentedgtsCreateEventMembersmigratedsGraphQL用の型を生成terminalrailsggraphqlobjectEvent実行結果createappgraphqltypeseventtyperb以下のようにeventsテーブルから情報を取得して自動生成できていますねappgraphqltypeseventtyperbfrozenstringliteraltruemoduleTypesclassEventTypeltTypesBaseObjectfieldidIDnullfalsefieldtitleStringnullfalsefieldstartatGraphQLTypesISODateTimenullfalsefieldendatGraphQLTypesISODateTimefieldplaceStringfieldtagsStringfieldmemoStringfieldcanceledBooleannullfalsefieldcreatedatGraphQLTypesISODateTimenullfalsefieldupdatedatGraphQLTypesISODateTimenullfalseendend同じようにmembereventmemberの分も生成します。 |
2022-02-14 00:07:53 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
ユニットテストのメソッドのメモ |
https://qiita.com/d_takahashi/items/86eeae0e9ab029543388
|
ユニットテストのメソッドのメモメソッド説明assert式メッセージ式が真ならば成功assertequal変数変数メッセージ変数と変数が等しければ成功assertnotequal変数変数メッセージ変数と変数が等しくなければ成功assertnil変数メッセージ変数がnilならば成功assertnotnil変数メッセージ変数がnilじゃなければ成功assertmatch正規表現文字列メッセージ正規表現に文字列がマッチすれば成功assertnomatch正規表現文字列メッセージ正規表現に文字列がマッチしなければ成功assertraise例外例外例外…ブロックを実行して例外が発生し、その例外がexpectedexceptionklassクラスならば成功assertnothingraised例外例外例外…ブロックを実行して例外がおきなけらば成功assertindeltaexpectedfloatactualfloatdeltamessageflunkメッセージ常に失敗。 |
2022-02-14 00:57:32 |
海外TECH |
MakeUseOf |
5 Tech Habits and Tips That Can Help You Stay Happier |
https://www.makeuseof.com/tech-habits-tips-help-stay-happier/
|
Tech Habits and Tips That Can Help You Stay HappierTechnology can make life easier but it can also open up a world of negativity Here s how to develop healthy tech habits to help you stay happier |
2022-02-13 15:31:12 |
海外TECH |
MakeUseOf |
9 Ways Your WhatsApp Messages Can Be Hacked |
https://www.makeuseof.com/tag/how-whatsapp-messages-can-hacked/
|
whatsapp |
2022-02-13 15:16:49 |
海外TECH |
MakeUseOf |
AirDrop Not Working? Fix It Fast With These 15 Tips |
https://www.makeuseof.com/tag/airdrop-not-working-troubleshoot-file-transfer-woes/
|
airdrop |
2022-02-13 15:16:49 |
海外TECH |
DEV Community |
Tutorial : build your first DAPP with Remix and Etherscan |
https://dev.to/yakult/tutorial-build-your-first-dapp-with-remix-and-etherscan-52kf
|
Tutorial build your first DAPP with Remix and EtherscanIn this tutorial with detailed tasks we will build a DApp semi DApp in this tutorial step by step Task Preparation for buildingTask Learn Remix IDE online smart contract development environmentTask Greeter sol First semi DApp with RemixTask Second semi DApp ERC TokenTask Understanding approve allowance and transferFromTask Deploy to public testnet like RopstenOptional Task deploy and verify on PolygonDApp is a web app with logic in on chain smart contracts which users can access through their wallet Ethereum org explains A decentralized application dapp is an application built on a decentralized network that combines a smart contract and a frontend user interface I have a simple definition of DAPP myself DApp Smart Contract on blockchain User interface web app running on server Wallet in browser and mobile app DAPP Smart Contract Web APP Wallet user controlled I would like to call what we build in these eight step semi DApp as we will focus on smart contracts while relying on Remix Etherscan as user interface We will build web app using React Next js that works with smart contract and wallet such as MetaMask later Prerequisite Knowledge and toolsYou need basic knowledge and tools before we start Knowledge BlockchainEthereumWalletSolidityERC amp ERCTools Remix IDE MetaMask Wallet browser extension Node js yarn TypeScriptOpenZeppelin Solidity library Etherscan block explorerLet s start our journey Task Preparation for buildingWe need tedious preparation to have all the needed tools set MetaMask and accountHardhat local testnetRemix IDE settings Task Install MetaMask and create accountIn this sub task we will install MetaMask create a wallet and write down mnemonics phrase Download and install MetaMask extension from Chrome extension store on your Chrome browser Create a wallet following the instructions of MetaMask with mnemonics written down with pen and paper Get to know the usage of MetaMask switch Network edit Network add account change account You can also use other browsers MetaMask supports such as Firefox Brave and Edge Task Run a local testnet by HardhatWe will use Hardhat which is an Ethereum development environment to run a local testnet You can also use Ganache by truffle To use Hardhat you need to have node js and yarn in your computer STEP make a directory and install hardhat in itmkdir hhproject amp amp cd hhprojectmkdir chain amp amp cd chainyarn add hardhatSTEP create a sample Hardhat projectyarn hardhat choose Create an advanced sample project that uses TypeScriptA hardhat project is created with a sample smart contract Greeter sol that we will use in Task STEP run Harhat Network local testnet in stand alone modeyarn hardhat nodeA local testnet will is running chainId Started HTTP and WebSocket JSON RPC server at It give us accounts each has test ETH Account xffdeaadffceabcfffb ETH Account xcdcacdbeddcc We will organize our project directory as hhproject chain working dir for hardhat webapp working dir for Next js app later Task switch MetaMask network to local testnetPlease make sure Hardhat Network local testnet is still running STEP In MetaMask browser extension click the network selector on the top bar Switch the network from mainnet to localhost STEP Click the Account icon on the topbar and go to Settings Network Choose localhost Note make sure Chain ID is It may be by default Task Add Import account to MetaMaskSTEP Click Account icon in the top bar and choose Import Account Import Account with Private Key of local testnet Account Private Key of Account is Account xffdeaadffceabcfffbPrivate Key xacbecaebaabdffbacbcbedefcaedbffffSTEP Switch to the added Account with address xffdeaadffceabcfffb There is test ETH in it on ethereum local testnet Task Learn Remix IDE online smart contract development environmentWebsite Remix Ethereum IDE Remix IDE is the online development environment for Ethereum Introduction from Remix IDE docs Remix is used for the entire journey of contract development as well as act as a playground for learning and teaching Ethereum Remix IDE is a powerful open source tool that helps you write Solidity contracts straight from the browser Remix IDE has modules for testing debugging and deploying of smart contracts and much more Task Have a look at Remix IDETake a look at the components we will use Editor Open File Explorer of Remix IDE and click a sample smart contract file Storage sol Solidity Compiler where we compile smart contracts Deploy and Run Transactions where we deploy smart contracts and interact with smart contracts Unit Test the plugin for unit test using Solidity If not installed add from plugin button in the bottom left File structure in Remix IDE workspace contracts scripts tests There are several sample smart contracts as well as deploy scripts in JavaScript and Unit Test scripts in Solidity in the default workspace of Remix IDE Task Change Environment to Injected Web in RemixIn this sub task we will change the Environment in Remix Deploy amp Run tab STEP make sure MetaMask network is switched to localhost and switch account to xffdeaadffceabcfffbSTEP change Environment from default Javascript VM London to Injected Web We told Remix IDE to use injected ethereum provider by MetaMask SETP check the account in this tab It should be changed to xff same as MetaMask Task Compile a sample smart contractIt is intuite to compile a smart contract in Remix IDE STEP In the Editor tab select a smart contract such as Storage sol STEP In Solidity Compiler tab compile the selected smart contract Leave the option as default Compiler commit edaLanguage SolidityEVM Version Compiler defaultSTEP Click Compile button The selected smart contract will be compiled Task Run unit testRemix IDE support unit test written in solidity with a plugin STEP In Plugin Manager install Solidity unit testing plugin if it is not installed and activated STEP In Unit Test tab select test Ballot test sol click Run button Note We usually run unit test in Javascript in popular Ethereum development environments such as Truffle and Hardhat So will will skip unit test in this tutorial in the following tasks We call the smart contract development circle Compile Test Deploy and will do deployment in the next sub task Task Deploy to testnet provided by Remix IDERemix IDE also provides a testnet with EVM ethereum virtual machine based on ethereumjs vm EVM implementation github repo link First we will try to deploy a smart contract to JavaScript VM London provided with Remix IDE STEP change environment to JavaScript VM London STEP It provides accounts on the node We will use account xB eddC as the deployer STEP click deploy button Once deployment is completed a transaction receipt will be logged on the Remix IDE console at the bottom right of the screen The deployed contract will be displayed in the left bottom of the screen We can interact with it store a number such as retrieve get Task Deploy to injected testnet provide by MetaMaskIn this sub task we will deploy the sample smart contract to the injected testnet provided by MetaMask It is the local testnet running on HTTP and WebSocket JSON RPC server at STEP In Deploy amp Run tab change the environment to Injected Web STEP check if the account is xf same as the MetaMask STEP click deploy button STEP confirm in the popup of MetaMask The returned receipt of the transaction is status true Transaction mined and execution succeedtransaction hash xbfcfddbdefebccedcccaabccdcfrom xfFdeaadFFceaBcffFbto Storage constructor You can see that the transaction is sent from xfFdeaadFFceaBcffFb Task Interact with the smart contractWe can call functions of smart contract in Remix IDE Deep blue button is read only Orange button is write to change blockchain state which requires user confirmation in wallet Let s interact with the smart contract STEP set number as and click store button This will send a transaction to the blockchain which needs confirmation in MetaMask STEP confirm the transaction STEP click retrieve button retrieve is a read only call which don t need confirmation in MetaMask The result will be displayed on the screen Transaction details of Write send and Read call are logged in the Remix IDE console After you finish Task and Task you are fully prepared for the DApp development journey Task Greeter First semi DApp with RemixIn Task we will begin building our first DAPP using Remix IDE Hardhat local testnet Greeter sol smart contractWe will not build web front end by ourselves in this tutorial Instead we use Remix IDE as web user interface to interact with smart contracts Task Sample contract Greeter sol There is a smart contract Greeter sol in hardhat sample project Create a file contracts Greeter sol in Remix IDE and copy the Greeter sol in the hardhat project directory to it SPDX License Identifier Unlicensepragma solidity import hardhat console sol contract Greeter string private greeting constructor string memory greeting console log Deploying a Greeter with greeting greeting greeting greeting function greet public view returns string memory return greeting function setGreeting string memory greeting public console log Changing greeting from s to s greeting greeting greeting greeting There are also deploy scripts and unit test scripts in hardhat project Task Compile Greeter solSwitch to Solidity Compiler tab in Remix IDE Compile Greeter sol Once it is compiled successfully you will see Compilation Details in Remix IDE We can also copy ABI and Bytecode to view if you are interested in them These files are stored in the contract artifacts directory Task TestWe will skip unit test here Task DeployThere are deployment scripts in Remix IDE which we can use by default We don t need to make any changes Go to Deploy and Run Tab in Remix IDE and deploy Greeter sol STEP make sure Greeter sol has been already compiled successfully STEP make sure MetaMask switched to localhost network and account switched to the related hardhat account STEP make sure Environment change to Injected Web And the Account is the related hardhat account STEP leave Gas Limit and Value as default STEP choose Contract Greeter contract Greeter sol STEP leave deploy variable string greeting to be blank or input any string you like STEP click Deploy Button STEP confirm the transaction in MetaMask Popup STEP check deploy receipt in Remix IDE console status true Transaction mined and execution succeedfrom xfFdeaadFFceaBcffFbto Greeter constructor gas gastransaction cost gas input x decoded input string greeting My first DAPP Task Interact with the deployed smart contractSTEP get initial greet by click greet Deep Blue button which is set in the deployment process STEP setGreeting to My first Dapp and confirm in MetaMask popup STEP get greet again It should be My first Dapp We just finished our first DAPP In the next task we will write an ERC token smart contract using solidity library OpenZeppelin Task Second semi DApp ERC TokenThe most common use case of DAPP is based on tokens ERC ERC ERC on ethereum as assets We will not write a token smart contract from scratch Instead we will inherit from verified and popular solidity library OpenZeppelin The best practice of token smart contract development is using verified one in contrast to reinventing the wheel Task ERC using OpenZeppelinWrite an ERC token ClassToken symbol CLT in contracts ClassToken sol SPDX License Identifier Unlicensepragma solidity import contract ClassToken is ERC constructor ERC ClassToken CLT mint msg sender e Please note that we import OpenZeppelin from GitHub files To write smart contract in local development environments like Hardhat or Truffle we install OpenZeppelin and import like this import openzeppelin contracts token ERC ERC sol Information about this ERC token Name and symbol ClassToken CLTDecimals InitialSupply CLT mint to deployer msg sender Task CompileCompile ClassToken sol in Compile Tab Task TestWe skip unit test here Task DeployIn Deploy and Run Tab deploy to local testnet Click Deploy Button The deployed smart contract is showing on the left panel Click to show the functions we can call and send These are standard interface of ERC FUNCTIONSname symbol decimals totalSupply balanceOf account transfer recipient amount allowance owner spender approve spender amount Task Read token informationThere are several read only function of ERC Standard token smart contract decimals name ClassTokensymbol CLTinitialSupply which means CLT token We can query token balance of a address by calling balanceOf input xfFdeaadFFceaBcffFb output which means CLT token Task Send token by calling transferClick the arrow of transfer button enter inputs input recipient xcdcacdbeddcc Account input amount CLT Confirm the transaction in MetaMask popup After success the receipt of the transaction will be displayed on Remix IDE console Get the balance of CLT of addresses xcdcacdbeddcc CLT xfFdeaadFFceaBcffFb CLT The PrivateKey of xcdcacdbeddcc Account is xcefaafdcedaecafbbd You can add this account and token to MetaMask to interact with ERC smart contract using MetaMask Task Add token to MetaMaskMetaMask can t show ClassToken CLT on assets list automatically We need to add using contract address token address You can click import tokens to add We will input the token smart contract address xCfEdAccAaeeCEDFfBFc Please input the address of your deployed ClassToken We can see the balance of CLT now We can send CLT to others using MetaMask We also import Account to MetaMask and transfer its CLT to others Tips reset MetaMask account nounceWhen we try with localhost and MataMask for several times we can mess the nounce transaction count Sometimes we can t send transactions When encountering this problem we need to reset MetaMask account nounce as following STEP Go to Setting gt AdvancedSTEP Reset AccountExplanation in the setting Resetting your account will clear your transaction history This will not change the balances in your accounts or require you to re enter your Secret Recovery Phrase Task Understanding approve allowance and transferFrom Task Understanding transferFromThere is an ingenious design in ERC token standard approvetransferFromallowanceWhat can we do with it we can grant another person an amount of token he can use by sending approve he can use it by sending transferFrom we can check the allowance calling allowance There are also two helpers decreaceAllowance and increaseAllowance in OpenZeppelin ERC implementation The definition of TransferFrom is transferFrom address sender address recipient uint amount Let s play with this approve transferFrom design try approve and transferFromWe will use accounts Account The private key of Account is Account xcdcacdbeddccPrivate Key xcefaafdcedaecafbbdAccount xCCdDdBafabddedFABCPrivate Key xdeafaabfebfcecafcfbacdabaSTEP import Account and to MetaMaskSTEP MetaMask in Account approve Account with CLT Send approve spender xcdcacdbeddcc Account amount CLT amount is uint with decimals STEP check allowance Call allowance owner xfFdeaadFFceaBcffFb Account spender xcdcacdbeddcc Account result is CLT STEP switch to Account STEP MetaMask in Account Account send TransferFrom to sends token from Account to Account sender xfFdeaadFFceaBcffFb Account recipient xCCdDdBafabddedFABC Account amount CLT STEP check allowance again The result is CLT STEP switch to Account in MetaMaskSTEP set allowance to approve called by Account spender xcdcacdbeddcc Account amount STEP check allowance Call allowance owner xfFdeaadFFceaBcffFb Account spender xcdcacdbeddcc Account The result will be A security notice from OpenZeppelin docs you should know Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering One possible solution to mitigate this race condition is to first reduce the spender s allowance to and set the desired value afterwards issuecomment In the next tasks we will deploy ClassToken to public testnet like Ropsten Rinkeby etc You can also try to deploy it to polygon BSC and other EVM compatible chain as well as Ls like Optimism and Arbitrum Task Deploy to public testnet like RopstenTo deploy smart contract to Ropsten test network you need Ropsten test ETH in wallet You can get from faucet Etherscan provide a block explorer for Ropsten Task Compile Test DeployDeploy smart contract to Ropsten testnet in steps STEP switch MetaMask to Ropsten network and switch to your own account Note don t use account provide by Hardhat testnet Account are default accounts generated by Hardhat and many people know their private key STEP Get test ETH Ropsten testnet at faucet for your account You will need test ETH to pay gas fee STEP In Remix IDE Deploy amp Run Tab make sure that the environment is Injected Web connecting to network Ropsten network STEP Click Deploy Button and confirm in MetaMask popup The deployment to public testnet may take one or two minutes STEP Once the smart contract is deployed successfully you can view the transaction details at block explorer Task Interact with contract in RemixWe can interact from Remix IDE just like Task Read token information transfer tokenadd token to MetaMask and transfer between accounts You can view transactions on Task Verify contract on Etherscan API key needed We can interact with a smart contract directly when it is verified on Etherscan In Task and we will verify our smart contract on and interact with it STEP create an account at Etherscan ioSTEP get API key at STEP In Remix IDE Plugin Manager search and add Etherscan Contract Verification STEP In Etherscan Contract Verification plugin input etherscan API key STEP Verify contract Waiting for the verification to be completed Please note that Verify means two things We will publish the source code on etherscan The code is verified the same as the compiled and deployed code Task Interact with contract on EtherscanWhen verified successfully we can interact with smart at STEP click Code button You can read the open source code STEP click Read Contract button We can call read only functions of this ERC smart contract STEP click Write Contract button STEP connect to Web Before we can call state change functions of the contract we need to connect to Web first Connect to MetaMask in the popup STEP click transfer input variable and confirm in the MetaMask popup To deploy smart contract and verify it on Ethereum mainnet is almost the same In the next optional task we will deploy and verify contract on Polygon The process is a little different Optional Task deploy and verify on PolygonWe will try to deploy to Polygon mainnet in Task You need MATIC token on Polygon network to pay for gas fee You can add Polygon Mainnet to your MetaMask using Chainlist org Optional Task Deploy contract to Polygon mainnet MATIC needed To deploy contract to Polygon mainnet is almost the same as to Ropsten testnet Switch MetaMask network to Polygon MainnetDeploy in Environment Injected Web Connect to Custom network It may take a few minutes View contract at block explorer polygonscan com is also built by the Etherscan team Optional Task Verify contract on Polygonscan website There is no handy plugin to verify contract on Polygonscan com We can do it manually STEP Create an account at polygonscan comSTEP Search by the deployed contract address and go to contract page STEP Click Contract tab on that page There is only ByteCode in it Click the Verify and Publish link to verify STEP Fill out the form to verify contract Compile Type choose Solidity Single File Compiler Version choose the same one as that in Remix IDE compiler TabWe need some help to make our smart contract into a single file as we inherit ClassToken from OpenZeppelin ERC contract There is Remix IDE plugin Flattener we can use here STEP Backup ClassToken sol first as flattener will change it STEP In Flattener Plugin click button Flatten contracts ClassToken sol It will make the smart contract which inherits from OpenZeppelin ERC to one file This process is called Flatten STEP paste the flattened contract code to polygonscan explorer verify page STEP wait the verify process to be completed It will take less than a minute Optional Task Interact with contract on Polygonscan block explorerOnce the contract is verified on Polygonscan you can interact with it just like Task After completing these tasks in this tutorial you already know how to compile deploy and interact smart contract with the help of Remix IDE and Etherscan The smart contract Remix IDE Etherscan and MetaMask wallet together are DApp or Semi DApp in this tutorial smart contract on chain web app based on Remix IDE Etherscan MetaMask wallet controlled by user I will publish another two tutorials to build DApp with smart contract and real web front end user interface using Node js ethers js and Web React Then we will have a real DApp instead of a semi DAPP here If you find this tutorial helpful you can find me at Twitter fjun |
2022-02-13 15:20:27 |
海外TECH |
DEV Community |
Running Prisma migrate in an Electron app |
https://dev.to/awohletz/running-prisma-migrate-in-an-electron-app-1ehm
|
Running Prisma migrate in an Electron appI use Prisma Migrate in my Electron app Here s a mechanism to detect when I need to run migrations on app start In main ts I check if the DB needs creation first app run or if it needs a migration let needsMigration const dbExists fs existsSync dbPath if dbExists needsMigration true prisma for whatever reason has trouble if the database file does not exist yet So just touch it here fs closeSync fs openSync dbPath w else try const latest Migration await prisma queryRaw select from prisma migrations order by finished at needsMigration last latest migration name latestMigration catch e log error e needsMigration true Here latestMigration is a hardcoded constant This needs to be updated every time you create a migration export const latestMigration added col index Note that running migrate on an empty merely touched DB file will create the DB tables There s no need to package a hardcoded template database to start with Then I run the migration if needed if needsMigration try const schemaPath path join app getAppPath replace app asar app asar unpacked prisma schema prisma log info Needs a migration Running prisma migrate with schema path schemaPath first create or migrate the database If you were deploying prisma to a cloud service this migrate deploy command you would run as part of your CI CD deployment Since this is an electron app it just needs to run when the production app is started That way if the user updates AriNote and the schema has changed it will transparently migrate their DB await runPrismaCommand command migrate deploy schema schemaPath dbUrl seed log info Seeding await seed prisma catch e log error e process exit else log info Does not need migration seed is just a function that inserts initial data relevant to my app export async function seed prisma PrismaClient await prisma workspace upsert create id default name Default update where id default The source for runPrismaCommand is on this Github thread issuecomment I also recommend checking out Florian s repo here for a starter kit to using Prisma in Electron WorkflowWith this to make a schema modification I follow these steps Edit the schema prisma with the changes to the schema Create the migration with command prisma migrate dev name added col index I m naming it added col index in this particular example since I added a column Update latestMigration constant in the code with the generated migration folder name export const latestMigration added col index Build pack and distribute the app as usual When users update the app the updated code will contain a new latestMigration which will make the app run Prisma Migrate on start because the user s database does not contain that migration in prisma migrations table Prisma Migrate compares the migrations available in the prisma migrations folder to the migrations run in the user s DB It runs the new migration App opens the browser window as usual The user only notices a little slower start time This has the manual step of updating latestMigration but since I rarely create migrations it works well enough To automate it I could probably write some code that looks at the migrations folder in the packed app to see the latest migration file and compare that to the latest migration run in the DB It s actually not necessary to detect whether a migration is needed I could just run migrate on every app start However that adds noticeably to the app startup time |
2022-02-13 15:19:52 |
海外TECH |
DEV Community |
Introduction to python: Getting started with python |
https://dev.to/adachime/introduction-to-python-getting-started-with-python-4pad
|
Introduction to python Getting started with pythonAs a code newbie when someone talks about python the first thing that comes to mind is probably the animal lol well it s not Python is a computer programming language that enables users to build websites analyze data and visualize data It was originally created by Guido van Rossum in and further developed by the python Software Foundation Guido wanted to create a programming language that was that used simple syntax and had code lines that were easy to read he named python python because he wanted a name that was unique and kind of mysterious So why should you want to learn how to code using pythonThere are many reasons why you want to learn pythonIt s highly versatile Python can be used to carry out several functions across many industries Functions such as analyzing data etc It uses simple syntax This makes coding easy to understand and learn It is said that if you can write hello world that you can write any line of code Believe me this is very true print hello world Python has a large and very supportive community where you can ask any confusing question and get answers Communities like stack overflow etc Python is one of the most used programming languages in the world Many big companies use this language companies like google facebook amazon netflix to mention but a few The demand for python and skilled python users is on the increase The career opportunities and salary is also increasing it is used in fields like data science app development web development machine learning etc So where can you learn python from You can learn python from Bootcamps Online courses Courses from udemy coursera codecademy udacity sololearn etc YoutubeOne of the most amazing things is that most these sites offer free courses You can also read blog post on medium hashnode dev to etc they will help a lot Incase you are confused on any syntax you can google it websites like stack overflow geek for geeks wschools will help out Remember google is your friend Thanks for reading |
2022-02-13 15:13:57 |
海外TECH |
DEV Community |
Manage CodeCommit and CodePipeline in Multiple AWS Accounts |
https://dev.to/arshadzackeriya/manage-codecommit-and-codepipeline-in-multiple-aws-accounts-18i5
|
Manage CodeCommit and CodePipeline in Multiple AWS AccountsThis video demonstrate how to setup AWS Codepipelines in multiple AWS accounts with single CodeComit as a Single Source Of Truth Use this repo to access the IAM policy materials used in this demo |
2022-02-13 15:09:10 |
海外TECH |
DEV Community |
Usage of `React.FC` from my experience |
https://dev.to/xenoxdev/usage-of-reactfc-from-my-experience-22n7
|
Usage of React FC from my experienceI have been working with React Typescript setup for a year and a half and if you are someone like me I bet you could have seen or used Typescript interface FC at least once On that note I want to share a few things related to React FC which are purely out of my experience using it Please consider this just as an opinion nothing much and nothing less What is React FC or React FunctionalComponentReact FC is a generic interface for the functional components one of the two ways to write components in React This is not an inbuilt type but comes as a part of the types reactBelow is a general way to write a component that takes children const CardComponentNonFC title children title string children ReactNode gt return lt div className card gt lt h className card title gt title lt h gt lt div className card content gt children lt div gt lt div gt And the same code can be written with React FC in the followingimport React FC from react const CardComponentFC FC lt title string gt title children gt return lt div className card gt lt h className card title gt title lt h gt lt div className card content gt children lt div gt lt div gt How do i use it Cleaner code and Better DX Developer Experience with the default children prop It makes a component container by the behaviour and less mental toll in understanding the code With FCimport React FC from react const Card gt return lt CardComponentFC gt CardComponentFC is defined above lt div gt lt div gt lt CardComponentFC gt same without FCconst CardNonFC gt return lt CardComponentNonFC children lt div gt lt div gt gt For me the first code is much cleaner and easier to understand Second and last reason is the return type restrictions I d like my component to always return an element or null null is mostly the bottom type of my components and I don t like undefined being returned React FC has that check by default to prevent returning undefined import FC from react export const Container FC children gt if children return lt gt children lt gt this would through the error return undefined See the CodeSandbox for the same How do i NOT use it I tried to use it for the default functional exports over the functional expressions I had a hard time with it Let me know if you have solved it If a component that doesn t need to render children It doesn t need to be typed as React FC Now that we know it implies the children prop by default use FC only where it makes sense Not every component need to accommodate the children Generics in React typescript is something I like and has the flexibility React FC doesn t seem to fit well with that SummaryThere are mixed opinions on using it and it was recently removed from the Create React App template There are a few posts suggesting not to use it but from experience you may not have any huge performance implications of not using it There are definitely some limitations disadvantages of using it but I would rather say that depends on the component Not all components need memoisation or hooks similarly not all components need FC If you can draw that thin line you can happily use it References to read more about it originally published at here |
2022-02-13 15:07:19 |
海外TECH |
DEV Community |
Custom element hearts for Valentine's Day |
https://dev.to/tirithen/custom-element-hearts-for-valentines-day-3mmk
|
Custom element hearts for Valentine x s DayTomorrow is valentines day so what could be more fitting than making a custom valentine hearts element for your web page Coding might be for work but sometimes it should just be for fun Lets create a custom element that can be added to a page like this lt DOCTYPE html gt lt html lang en gt lt head gt lt script type module src valentine hearts js gt lt script gt lt head gt lt body gt lt p gt Lorem ipsum dolor sit amet consectetur adipisicing elit lt p gt lt valentine hearts gt lt valentine hearts gt lt body gt lt html gt Time for some fun class ValentineHearts extends HTMLElement shadowRoot constructor super this createShadowRoot createShadowRoot this shadowRoot this attachShadow mode open this shadowRoot innerHTML lt style gt host heart size em heart color red heart speed s pointer events none display block position absolute top left width height z index overflow hidden heart opacity display block width var heart size height var heart size position absolute left calc var heart x offset background var heart color transform rotate deg scale transition top var heart speed linear opacity s ease in out transform s ease in out animation duration s animation iteration count infinite will change top left opacity transform heart before content display block width var heart size height var heart size border radius calc var heart size position absolute top left calc var heart size background var heart color heart after content display block width var heart size height var heart size border radius calc var heart size position absolute top calc var heart size left background var heart color keyframes sway left calc var heart x offset left calc var heart x offset left calc var heart x offset lt style gt connectedCallback setInterval gt this spawnHeart for let i i lt i this spawnHeart this addEventListener resize gt this resize this resize resize this style width window clientWidth px this style height document body clientHeight px spawnHeart const heart document createElement heart heart style top Math round Math random heart style setProperty heart x offset Math random const brightness Math random heart style setProperty heart color rgb Math round brightness Math round brightness this shadowRoot appendChild heart setTimeout gt heart style animationName sway Math random requestAnimationFrame gt heart style top heart style opacity heart style transform rotate deg scale Math random function removeHeart event if event propertyName top heart parentNode removeChild heart heart removeEventListener transitionend removeHeart heart addEventListener transitionend removeHeart customElements define valentine hearts ValentineHearts Happy Valentine s Day |
2022-02-13 15:02:00 |
Apple |
AppleInsider - Frontpage News |
Daily deals Feb 13: $179 Rosetta Stone lifetime access, $495 13-inch Core i5 MacBook Pro, more! |
https://appleinsider.com/articles/22/02/13/daily-deals-feb-13-179-rosetta-stone-lifetime-access-495-13-inch-core-i5-macbook-pro-more?utm_medium=rss
|
Daily deals Feb Rosetta Stone lifetime access inch Core i MacBook Pro more Alongside a Core i Intel inch MacBook Pro and refurbished AirPods for Sunday s best deals include a inch Vizio Smart TV for and Philips Hue smart bulbs for Best Deals for February As we do every day we ve collected some of the best deals we could find on Apple products tech accessories and other items for the AppleInsider audience If an item is out of stock it may still be able to be ordered for delivery at a later date Read more |
2022-02-13 15:08:44 |
海外科学 |
NYT > Science |
Sigal Barsade, 56, Dies; Argued That It’s OK to Show Emotions at Work |
https://www.nytimes.com/2022/02/13/business/sigal-barsade-dead.html
|
leaders |
2022-02-13 15:19:29 |
金融 |
ニュース - 保険市場TIMES |
損保ジャパン、ジオエックス社と保険引受高度化に向けた協業開始 |
https://www.hokende.com/news/blog/entry/2022/02/14/010000
|
損保ジャパン、ジオエックス社と保険引受高度化に向けた協業開始保険引受に建物画像解析AI技術を活用損害保険ジャパン株式会社以下、損保ジャパン、SOMPOホールディングス株式会社、SOMPOリスクマネジメント株式会社は、イスラエルのスタートアップ企業「GeoXInnovations」以下、ジオエックス社と建物画像解析AI技術を活用した保険引受高度化に向け、年月より協業を開始すると発表した。 |
2022-02-14 01:00:00 |
ニュース |
BBC News - Home |
Ukraine tensions: US defends evacuating embassy as Zelensky urges calm |
https://www.bbc.co.uk/news/world-europe-60365017?at_medium=RSS&at_campaign=KARANGA
|
antony |
2022-02-13 15:03:41 |
ニュース |
BBC News - Home |
Russia-Ukraine crisis: Whiff of Munich in the air, says Ben Wallace |
https://www.bbc.co.uk/news/uk-60366088?at_medium=RSS&at_campaign=KARANGA
|
diplomatic |
2022-02-13 15:47:19 |
ニュース |
BBC News - Home |
Canada bridge protesters cleared by police after a week of disruption |
https://www.bbc.co.uk/news/world-us-canada-60368408?at_medium=RSS&at_campaign=KARANGA
|
clear |
2022-02-13 15:15:54 |
ニュース |
BBC News - Home |
Northern Powergrid sorry for Storm Arwen trillion pound compensation error |
https://www.bbc.co.uk/news/uk-england-tyne-60369098?at_medium=RSS&at_campaign=KARANGA
|
arwen |
2022-02-13 15:39:36 |
ニュース |
BBC News - Home |
Swiss approve tobacco ad ban long after neighbours |
https://www.bbc.co.uk/news/world-europe-60333336?at_medium=RSS&at_campaign=KARANGA
|
countries |
2022-02-13 15:37:53 |
ニュース |
BBC News - Home |
Weir scores late stunner as City beat United in Manchester derby |
https://www.bbc.co.uk/sport/football/60276453?at_medium=RSS&at_campaign=KARANGA
|
manchester |
2022-02-13 15:22:01 |
北海道 |
北海道新聞 |
スプリンター押しのけ銀メダル 高木美帆、女子500m |
https://www.hokkaido-np.co.jp/article/645248/
|
高木美帆 |
2022-02-14 00:19:54 |
北海道 |
北海道新聞 |
米国のジャクソンが500m制す スピードスケート女子・13日 |
https://www.hokkaido-np.co.jp/article/645249/
|
女子 |
2022-02-14 00:16:00 |
北海道 |
北海道新聞 |
「買収指摘の理由ない」 自民西田議員、動画で否定 |
https://www.hokkaido-np.co.jp/article/645240/
|
国政選挙 |
2022-02-14 00:16:07 |
北海道 |
北海道新聞 |
銭湯の屋根崩落 女性客がけが 積雪原因か 札幌・手稲区 |
https://www.hokkaido-np.co.jp/article/645243/
|
札幌市手稲区手稲本町 |
2022-02-14 00:14:30 |
北海道 |
北海道新聞 |
サッカー、板倉フル出場 ドイツ2部リーグ |
https://www.hokkaido-np.co.jp/article/645246/
|
板倉 |
2022-02-14 00:10:00 |
コメント
コメントを投稿