python |
Pythonタグが付けられた新着投稿 - Qiita |
rosメッセージをjsonに変換する |
https://qiita.com/hoshianaaa/items/7c016da85ed9df99dfec
|
roslibjs |
2022-08-27 16:25:39 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
google colaboratoryでcondaコマンドを使い仮想環境をactivateする方法 |
https://qiita.com/MILKTEA_af/items/6209f5497fb5b0a1f298
|
pylinuxxshminicondadownlo |
2022-08-27 16:17:42 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
javaScriptでTabキーに制限を加えたい |
https://qiita.com/d-tsuchi/items/3fba75651d09ab4c858a
|
javascript |
2022-08-27 16:54:18 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
OTP(One-Time-Password)発行管理アプリを作った |
https://qiita.com/poruruba/items/df2b39344cfbc461f815
|
otponetimepassword |
2022-08-27 16:09:41 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
rootユーザー以外でCost Explorerを見たい |
https://qiita.com/AWS11/items/ecf7b2417c5e319b6ce6
|
costexplorer |
2022-08-27 16:13:29 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
React + Rails + AWS Fargate の構成を実現したい - 07 バックエンドのCI導入(GitHub Actions) |
https://qiita.com/memomaruRey/items/3895c5ddf5735dcd6ecc
|
httpsqii |
2022-08-27 16:06:58 |
海外TECH |
DEV Community |
The Modern Refresher to React Development in 2022 |
https://dev.to/eludadev/the-modern-refresher-to-react-development-in-2022-8ai
|
The Modern Refresher to React Development in There s no denying that React is the most popular web framework out there This fact is even proven by StackOverFlow s recent survey polling thousands of developers Having already covered Vue development in our prior article in this series comparing web frameworks it s only fair to give React an equal chance by showing off its features and community made treasures And while React is backed by multi trillion dollar company it s open source community is still one of the key factors in its large success In this article we ll go through the React development process for beginners and developers who just need a quick refresher We ll build a website for publicly sharing short messages called “ithink It s like Twitter but with no accounts and you can t delete what you post ithink corp react Official implementation of ithink made in React and powered by Cyclic ithink powered by CyclicRun it on your own machine npm installnpm dev View on GitHub First we need an APIIf you play around with the CodePen above you ll quickly realize that the database is not fake We actually have a back end side of our application it handles the storing and retrieving of simple text data It s also built on Amazon s S object storage service ithink corp api Official API for ithink powered by Cyclic The Official ithink API built on Cyclic shThis is an example REST API designed to be deployed on Cyclic shUsageLearn how to use the ithink API using the curl command List all itemscurl H Content Type application json Create a new itemcurl data text Say something nice H Content Type application json View on GitHubA developer would normally spend hours and hours setting up a database like this and it s not free either Luckily for us we get a free instance of the AWS S Storage when we use Cyclic No credit card is required How do we create a new React project A beginner shouldn t have to create anything from scratch That s a fact and the React community recognizes it so much that they built a completely interactive program that helps newcomers setup their projects without much hassle It s called create react app and it uses Babel and webpack under the hood but you don t need to know anything about them But I d be irresponsible if I told you that you ll never encounter these two programs so I recommend saving these articles about webpack and Babel Read them when you re ready It s finally time to use this magical software Make sure that you have NodeJS and NPM installed on your machine then launch your terminal and run the following command in your preferred directory npx create react app my appcd my appnpm startIf you re not using Linux or MacOS for programming check out this cheat sheet covering our commands counter parts in Windows Don t worry if it takes unusually long for these commands to execute They may take longer to run if you have a slower internet connection Please give it some time as you only need to run it once per project When these commands finally cease to run a new tab will automatically open in your current web browser While not much the source code behind it is critical to the development that we re gonna do in this article Regardless of what starter is given to us when we run create react app the first step is to actually erase all of it Yes you heard me correctly we re gonna erase almost all of what this magical program does But don t fret the part that we re gonna delete is not the useful part of the React template so go ahead and run this command rm src r erase all files in the src foldertouch src index js create a new file called index js in the src folderWe already did too much change but we can go a step further and craft our own folders A good folder structure is key to a well organized and future proof project There are many not so well agreed on candidates out there but we re gonna go simple and create only two new directories mkdir src components src utils create two directories in the src folderAs their name suggests components like the pop up modal will go into the components folder and useful functions like a function to post data to the server will go into the utils sibling Another step that we would do in this stage is to set up TailwindCSS and FontAwesome as they re used in this project These packages both contain detailed guides that will help you set them up for yourself This is just another consequence of the wide popularity of React No beginner tutorial covers this but there s a little secret in programming that you should start practicing as soon as possible It s the use of linters programs that enforce style guides in your code and catch bugs before they happen I recommend using eslint the most popular linter in the JavaScript world Setting it up is easy as covering in the linked guide How do we deploy a React project to the Internet It s hard enough to create an entire application in one s local computer it s its own industry with the name “Frontend Development A frontend developer should not have to worry about the intricacies behind servers and deployment Lucky for us Cyclic gives us the ability to deploy React applications to the cloud for free by just clicking one button and adding one script to our application With Cyclic s React starter we know to add the following script to the root of our project server jsconst express require express const path require path const app express This configures static hosting for files in public that have the extensions listed in the array var options dotfiles ignore etag false extensions htm html css js ico jpg jpeg png svg index index html maxAge m redirect false app use express static build options const port process env PORT app listen port gt console log React app listening at http localhost port It s also important to add the following changes to the package json file scripts start react scripts start start node server js dev react scripts start With that done all it takes to launch our app to the world wide web is creating a Cyclic account and clicking the DEPLOY button Trust me it s so satisfying seeing it do all the work for you And you can even choose your own free subdomain afterwards How do we create a component in React As it currently stands our app is not functional This stems from the fact that the index js script is still empty and that s because we just created it Let s learn a new fact about React each application must have one main component It s like the lt body gt element where all the content is held React places the insides of the main component inside a top level root element as you can see in the following image As you might have guessed we create this main component inside the index js file It might sound scary to create something from scratch…But it s not because it always resembles the following template The importsimport React from react import ReactDOM from react dom client The componentclass App extends React Component The JavaScript Logic constructor props super props The HTML Markup Notice how we use className instead of class this is important read this render return lt div gt lt header className gt lt h gt ithink lt h gt lt button gt New lt button gt lt header gt lt div gt Injecting the component inside the root elementconst root ReactDOM createRoot document getElementById root root render lt App gt Hold on Those are a lot of new things that you may have never seen before First of all there s the presence of imports and classes Please make sure that your understanding of these two concepts is rock solid before continuing with this article But there s one other thing that still stands out and it s surely new to all beginner React developers It s the “weird mix of JavaScript code and HTML markup This odd format is called JSX the Java Script Ex tension All you need to know about it for now is that it makes the inclusion of HTML markup inside JavaScript code okay It doesn t always work With JSX this is not okay render lt article gt lt article gt lt article gt lt article gt But this is render lt div gt lt article gt lt article gt lt article gt lt article gt lt div gt Lesson learned always wrap your HTML markup around one and only one element How do we listen to click events in React We all know how to attach buttons to logic using pure JavaScript code but the same task is done quite differently and quite more simply as you ll see in React We re gonna be using the onClick attribute and while it s already available in pure JavaScript its usage is quite more common in React class App extends React Component render return lt div gt lt button onClick this toggleModal gt New lt button gt lt div gt With one simple attribute we re able to call any method defined on the component It s recommended to define component methods in the following manner class App extends React Component Bad toggleModal do stuff Okay toggleModal gt do stuff Long story short the first style would prohibit your method from accessing the this keyword which you would need to alter other parts of the component On the other hand the second method is fine and you should make it a habit to define class methods in that style How do we create a toggle in React Almost every user interface component has one or more toggles in it and our pop up modal is no different With a Boolean toggle we can dictate if the modal is either open or closed Thankfully creating toggles is no hassle at all Variables that control the UI are all collectively called the state and our modal toggle is clearly one of them The state is anything from data displayed in the application to user input to toggles that can do pretty much everything When a state variable changes the component is quickly and efficiently refreshed Creating stateful variables is also the easiest thing in the world class App extends React Component constructor props super props this state isModalOpen false Toggles wouldn t be very interesting if we couldn t actually toggle them This logic falls into the component method that we created earlier Unfortunately mutating stateful variables is quite counter intuitive toggleModal gt Wrong this state isModalOpen true Correct this setState isModalOpen true How do we create multiple components in React Aside from the main component applications are composed of a ton of UI parts that must all be organized in an effective fashion We created the components folder for this reason it s time to finally put it to use I m also gonna introduce to you a new template for creating components in React and it s the simplest one Instead of classes which we may not all be comfortable with we re gonna use functions which we definitely all have used enough times before that we could even write them with our eyes closed Please make sure that you re fluent with JavaScript exports before following with this article components modal jsexport function NewModal props notice the use of htmlFor instead of for read this to understand why return lt div gt lt dialog open gt lt main gt lt form method dialog gt lt label htmlFor content gt Content lt label gt lt textarea id content autoFocus gt lt textarea gt lt div gt lt button value cancel gt Cancel lt button gt lt button value default gt Post lt button gt lt div gt lt form gt lt main gt lt footer gt lt p gt Whatever you write will become public lt p gt lt footer gt lt dialog gt lt div gt And while our component is now almost done it won t magically appear in our application One more step that we must take is to import the modal into the main component It s easy to do and very similar to native HTML elements import Modal from components modal class App extends React Component render return lt div gt lt Modal gt lt div gt We also can t forget about the toggle logic that we just implemented in the last section of this article so we must put it to use It s easy to tell React to conditionally show an element based on a Boolean state variable The syntax that I m about to introduce is quite new and it s special to JSX this state isModalOpen amp amp lt Modal gt The double brackets are key to combining JavaScript logic with HTML markup They can contain almost anything from calculations to String manipulations and even lists of HTML elements as we ll soon see in this guide Hello Hello World This neat feature of JSX is called interpolation and we can even combine it with JavaScript s logical AND operator amp amp to conditionally display HTML markup depending on a variety of possibilities false amp amp lt div gt lt div gt will NEVER display true amp amp lt div gt lt div gt will ALWAYS display condition amp amp lt div gt lt div gt will ONLY display if condition is TRUE How do we submit data to the server with a React component After having already covered the process of listening to click events it s no surprise that form submission won t be much of a hassle at all I will therefore quickly cover it right now And please notice how we don t have to use the this keyword anymore with function based components export function NewModal props async function onSubmit e e preventDefault TODO submit data to the server return lt div gt lt form onSubmit onSubmit gt lt form gt lt div gt But while this is all fun and games for us it s still critical to pose the following question how do we get the input s value in React To answer this seemingly easy question I have to introduce you to React Hooks the most important concepts in modern development And while they re a bit beyond the scope of this tutorial we re gonna use a handy hook to create state variables for function based components import useState from react export function NewModal props const message setMessage useState return lt textarea value message onChange event gt setMessage event target value gt That s surprising simply With the useState hook we re able to both access the stateful variable message and mutate it using its setMessage sibling With these two gems we used JSX interpolation to set the value of the text area and respond to change events by updating the state Expect to see this pattern again and again in React applications import postMessage from utils server it s now easy to post data to the server async function onSubmit e e preventDefault await postMessage message We still can t actually submit data to our server without writing a script to do that job As a utility function we re gonna put this logic inside a new file named server js in the utils directory There s nothing new here just an ordinary data fetch function to communicate with our server utils server jsexport async function postMessage message await fetch method post headers Content Type application json body JSON stringify text message How do we close a modal when clicked outside in React One feature that we see again and again in websites is the ability to close pop ups by tapping anywhere outside their area This is clearly positive for the user experience of our application so it s not crazy that we re gonna be adding it even in this high level tutorial Thankfully we don t have to do much code ourselves thanks to the great React community Being such an important feature experienced developers have already implemented it and shipped it along with dozens of other small utilities as hooks yes hooks are marking their presence once again I told you that they re very important concepts It s all packaged in a nifty library called react use import useRef from react import useClickAway from react use export function NewModal props const containerRef useRef null useClickAway containerRef gt props onClose return lt div gt lt dialog ref containerRef gt lt dialog gt lt div gt Notice how we re also making use of yet another hook useRef It s one of the most popular hooks out there because its function is one that s very important The useRef hook gives us access to the DOM using it is as simple as adding a ref attribute to the desired HTML element as you can see in the code snippet above How do we display a list of items in React Good news We re done with the modal component But we re still missing one major part of our application the list of messages Not much is new here so let s just create a new component file named message list js in the components directory as usual index jsimport MessageList from components message list render return lt div gt lt main gt lt MessageList gt lt main gt lt div gt components message list jsexport function MessageList props if props messages Display list of messages return lt div gt lt div gt else Display loading skeleton return lt div gt lt div gt As you can see we re using an if condition to decide which UI to display If data is loaded we re gonna return a list showing all of it Otherwise we re gonna show a loading skeleton Of course none of these things is currently being shown That s because I have to introduce you to a new concept in React Remember JSX interpolation There s something very interesting we can do with this magical feature It s possible to use the Array map method to return a dynamic list of HTML elements lt div gt props messages map message gt lt p key message gt message lt p gt lt div gt Isn t that so amazing We can do the same thing to display the loading skeleton lt div gt Array from Array keys map number gt lt div key number gt lt div gt lt div gt Notice the use of the key property in both examples It s important to include it when using this interpolation feature as it helps React keep track of the list of elements It s critical that these keys are all unique How do we load a list of data from the server with a React component While we already built the messages listing component it still doesn t display any data and it s stuck in the loading state Obviously we haven t made any effort to actually load messages from the server yet Thankfully this is not very different from former server function that we just implemented class App extends React Component constructor props super props this state messages null As soon as the main component is created we wish to load data from the server There s no immediately obvious way of implementing this logic because you still don t know about lifecycle hooks With these magical devices we re able to run whatever logic we want at important times in a component s “lifecycle class App extends React Component componentDidMount load items With the compnentDidMount lifecycle hook we re able to run whatever we want when the component is finally rendered which is exactly what we were looking for With that done we re left with the task of filling the messages stateful variable with data from the server import getMessages from utils server class App extends React Component componentDidMount const messages await getMessages this setState messages messages Of course we cannot dismiss the logic that actually retrieves data from the server utils server jsexport async function getMessages const res await fetch headers Content Type application json const items await res json return items map item gt message item ConclusionAnd voila our application is done just like that The React development process is definitely a unique one and you can immediately tell many differences from the VueJS process that we covered in our last article We covered many features of React Creating new projects with create react app listening to and handling events hooks and the react use library custom components JSX interpolation stateful variables dynamic lists DOM refs And while we just scraped the surface of what React is capable of we still got a good idea of what the React development process is like and that s enough to help us choose the best framework for our purposes |
2022-08-27 07:46:49 |
海外TECH |
DEV Community |
With this macOS app, declutter your workspace and organize it in 1-click |
https://dev.to/pradeepb28_/with-this-macos-app-declutter-your-workspace-and-organize-it-in-1-click-30nh
|
With this macOS app declutter your workspace and organize it in clickProblemDesktop clutter is a serious problem on macOS It s so bad that we ve all accepted it as the norm Having so many windows amp apps open make it impossible to navigate amp get your work done SolutionSpaces for macOS ーIn one click you can clutter free and organize your workspace for any situation Checkout more use cases here Spaces for macOSand many more features available…Use “Spaces as WorkspaceUse “Spaces as LauncherRaycast IntegrationSupport Spotlight searchSupport Shortcuts appSupport Siri via shortcutsetcTech stackFrontend SwiftBackend SupabaseContinuous updates Firebase with SparkleLearn more here Spaces for macOS |
2022-08-27 07:37:02 |
海外TECH |
DEV Community |
Merge Triplets to Form Target Triplet |
https://dev.to/salahelhossiny/merge-triplets-to-form-target-triplet-3jb6
|
Merge Triplets to Form Target TripletA triplet is an array of three integers You are given a D integer array triplets where triplets i ai bi ci describes the ith triplet You are also given an integer array target x y z that describes the triplet you want to obtain To obtain target you may apply the following operation on triplets any number of times possibly zero Choose two indices indexed i and j i j and update triplets j to become max ai aj max bi bj max ci cj For example if triplets i and triplets j triplets j will be updated to max max max Return true if it is possible to obtain the target triplet x y z as an element of triplets or false otherwise class Solution def mergeTriplets self triplets List List int target List int gt bool good set for t in triplets if t gt target or t gt target or t gt target continue for i v in enumerate t if v target i good add i return len good |
2022-08-27 07:30:52 |
海外TECH |
DEV Community |
9 useful code snippets for everyday JavaScript development || Part 2 |
https://dev.to/swastikyadav/9-useful-code-snippets-for-everyday-javascript-development-part-2-470
|
useful code snippets for everyday JavaScript development Part Hello EveryoneWelcome to this JS code snippets series Thanks a lot for all the love to the st part of this post This is the nd post with JS code snippets that you can use in your everyday JavaScript development Read the first code snippets here Form data to Object This snippet will make your life a lot easier by converting form data into object which you can directly use as payload const formToObject form gt Array from new FormData form reduce acc key value gt acc key value formToObject document querySelector form email test email com name Test Name First use the FormData constructor to convert HTML form into FormData Convert FormData into an Array with Array from Use Array prototype reduce to achieve the desired object from array Generate UUID in browserLet s say you need a unique id key for every item in your list With this snippet you can generate unique id key right in your browser const UUIDGeneratorBrowser gt e e e e e replace g c gt c crypto getRandomValues new UintArray amp gt gt c toString UUIDGeneratorBrowser fcfe bede bed Use Crypto getRandomValues to generate a UUID Use Number prototype toString to convert it to a proper UUID hexadecimal string Check if a string is valid JSON If you have ever accessed an object from localStorage you know that you get a stringified version of that object And now you want to check if that stringified object is valid JSON or not The below snippet will help you exactly with that const isValidJSON str gt try JSON parse str return true catch err return false ExampleisValidJSON name John age trueisValidJSON name John age falseIn the try block we parse the string with JSON Parse method If string in invalid JSON catch block will return false else true Array to CSVYou have an array of data and you want to convert it to CSV so that you can open it on excel or google sheet Well Vanilla JS can do that also for you const arrayToCSV arr delimiter gt arr map row gt row map value gt value join delimiter join n ExamplearrayToCSV one two three four one two n three four The Array map method is used to iterate over each level of the array and join each value with a defined delimiter So that is it for this post If you anyhow liked this post make sure to show your support I also run a weekly newsletter so you can join me there also Thank You |
2022-08-27 07:16:47 |
海外TECH |
DEV Community |
¿Por qué es importante normalizar los conjuntos de datos? |
https://dev.to/christianpaez/por-que-es-importante-normalizar-los-conjuntos-de-datos-1de6
|
¿Por quées importante normalizar los conjuntos de datos La estandarización de datos es una práctica común en la ciencia de datos y el aprendizaje automático ¿Quésignifica realmente y por quées beneficioso DefiniciónEstandarizar un conjunto de datos significa transformar los datos para que tengan una media de y una desviación estándar de Esto se suele hacer restando la media de cada punto de datos y dividiéndola por la desviación estándar Visualmente esto significa convertir un conjunto de datos como este A uno como este Veamos algunas de las ventajas de la normalización PrecisiónLa normalización permite realizar comparaciones más precisas entre los puntos de datos Si dos puntos de datos están en escalas diferentes puede ser difícil saber si son realmente diferentes entre sío si la diferencia se debe sólo a la escala La normalización de los datos elimina este problema Rendimiento de los algoritmos de aprendizaje automáticoOtra razón por la que la estandarización es importante es que puede ayudar a mejorar el rendimiento de los algoritmos de aprendizaje automático Muchos algoritmos de aprendizaje automático se basan en el descenso de gradiente y requieren que todas las características estén en una escala similar para funcionar correctamente Si las características no están estandarizadas el algoritmo puede tener dificultades para converger en una solución Evitar los valores atípicosPor último la estandarización también puede ayudar a reducir la cantidad de ruido en los datos Si hay muchos valores atípicos en los datos pueden tener un impacto significativo en los resultados de cualquier análisis que se realice Estandarizar los datos puede ayudar a filtrar parte del ruido y hacer que los resultados sean más fiables Esperamos que este artículo le haya proporcionado algunas ideas sobre el popular concepto de estandarización de los conjuntos de datos en la ciencia de los datos y sus muchas ventajas Mira este post en Art Of Code Crédito imagen mbaumi |
2022-08-27 07:01:16 |
海外ニュース |
Japan Times latest articles |
China’s large drills near Taiwan raise alert level for Japan and U.S. |
https://www.japantimes.co.jp/news/2022/08/27/national/china-drills-taiwan-us-japan-threat/
|
China s large drills near Taiwan raise alert level for Japan and U S Experts said that Yonaguni Island in Okinawa Prefecture just km from Taiwan could be covered in any potential Chinese Taiwan lockdown operations aimed at |
2022-08-27 16:42:32 |
海外ニュース |
Japan Times latest articles |
Russia to hand over three bodies found after tour boat sinking to Japan |
https://www.japantimes.co.jp/news/2022/08/27/national/russia-japan-tour-boat-bodies/
|
september |
2022-08-27 16:23:19 |
ニュース |
BBC News - Home |
Uefa confirms Champions League, Europa League and Conference fixtures |
https://www.bbc.co.uk/sport/football/62698956?at_medium=RSS&at_campaign=KARANGA
|
champions |
2022-08-27 07:44:25 |
北海道 |
北海道新聞 |
紋別高、強豪の実力体感 横浜高野球部と練習試合 |
https://www.hokkaido-np.co.jp/article/722710/
|
神奈川県 |
2022-08-27 16:10:00 |
北海道 |
北海道新聞 |
IAEA、現地入り調整急ぐ ザポロジエ原発、実現へ障害 |
https://www.hokkaido-np.co.jp/article/722709/
|
事務局長 |
2022-08-27 16:22:00 |
北海道 |
北海道新聞 |
和歌山・高野山駅で一日駅長体験 ケーブルカー巻き上げ機を見学 |
https://www.hokkaido-np.co.jp/article/722705/
|
高野山駅 |
2022-08-27 16:07:18 |
北海道 |
北海道新聞 |
生活保護費見直し、秋から本格化 5年に1度、級地含め年内決定へ |
https://www.hokkaido-np.co.jp/article/722708/
|
厚生労働省 |
2022-08-27 16:22:00 |
北海道 |
北海道新聞 |
「戦争の犠牲者はいつも市民」 旧ソ連の北方四島侵攻77年 記憶たどる元島民たち |
https://www.hokkaido-np.co.jp/article/722707/
|
世界大戦 |
2022-08-27 16:15:00 |
北海道 |
北海道新聞 |
米FRB、景気下押しを容認 物価抑制優先、NY株が急落 |
https://www.hokkaido-np.co.jp/article/722706/
|
米連邦準備制度理事会 |
2022-08-27 16:05:00 |
ビジネス |
東洋経済オンライン |
アリストテレスとプラトンは一体何が違ったのか 両極端な2つの人間のあり方を体現している | リーダーシップ・教養・資格・スキル | 東洋経済オンライン |
https://toyokeizai.net/articles/-/614128?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
大学入学資格 |
2022-08-27 17:00:00 |
コメント
コメントを投稿