AWS |
AWS Open Source Blog |
New cluster-mode support in redis-py |
https://aws.amazon.com/blogs/opensource/new-cluster-mode-support-in-redis-py/
|
New cluster mode support in redis pyWhat is Redis Redis is an incredibly popular open source BSD licensed in memory data store generally used as a database cache or message broker Redis is regularly touted by developers as the most loved database and you ve used Redis when on Twitter GitHub Instagram Airbnb and many other products Redis Clusters enable you to scale … |
2022-01-11 15:42:02 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
【Jython】AutoCloseable / Closeable 実装オブジェクトに with 文を使うには |
https://qiita.com/k650250/items/b3c90dd875008ec0ac76
|
【Jython】AutoCloseableCloseable実装オブジェクトにwith文を使うにはtrywithresource文とwith文Javaにはtrywithresource文があり、これを、インターフェースAutoCloseable又はインタフェースCloseableを実装したクラスをインスタンス化したオブジェクト以下、AutoCloseableCloseable実装オブジェクトが使用すると、ブロック終了時又は例外発生時に於いて、自動的にそのオブジェクトのcloseメソッドが呼び出され、クローズ処理が為される。 |
2022-01-12 00:54:06 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
OpenCVで取得した画素値を、既存のfloat型DataFrameに.iloc結合すると値が変わった |
https://qiita.com/Esp-v2/items/d09c10d90d367bf92dd6
|
OpenCVで取得した画素値を、既存のfloat型DataFrameにiloc結合すると値が変わった発生した問題numpyfloat型DataFrameにOpenCVで取得した画素値をilocで結合したところ、全く異なる値が記録されました。 |
2022-01-12 00:49:22 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
tensorflow-datasets の celeb_a が読めない件 |
https://qiita.com/takkeybook/items/358e57f0706367e83be6
|
個々の画像ファイルを読むcelebaのホームページからzip書庫ファイルになった画像ファイル一式とAnnoフォルダに入っているlistattrcelebatxtを適当な場所にダウンロードしてきて、ToppaDさんの『CelebAデータがtensorflowdatasetsから読み込めないので画像をローカルに落として取り込む』に従えば学習用に読み込むことができます。 |
2022-01-12 00:47:28 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
LSTM セル数・ユニット数について |
https://teratail.com/questions/377711?rss=all
|
LSTMセル数・ユニット数について前提・実現したいことTensorFlownbspTensorFlowampKeras対応nbspプログラミング実装ハンドブックPで質問があります。 |
2022-01-12 00:58:44 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
swift × firebaseを使ってフォローしたユーザーの投稿をタイムラインで見れるようにしたい! |
https://teratail.com/questions/377710?rss=all
|
swift×firebaseを使ってフォローしたユーザーの投稿をタイムラインで見れるようにしたいgtnbspここに言語nbspボールドテキストhttpを入力ヘディングのテキストここに質問の内容を詳しく書いてください。 |
2022-01-12 00:57:35 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
pgui.locateOnScreen("")を実行するとエラーが発生 |
https://teratail.com/questions/377709?rss=all
|
pguilocateOnScreenquotquotを実行するとエラーが発生前提・実現したいことpguilocateOnScreenquotquotを実行しようとするとエラーが発生してしまします。 |
2022-01-12 00:43:12 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
エラーCS1503:引数1:「メソッドグループ」から「アクション」に変換できません |
https://teratail.com/questions/377708?rss=all
|
エラーCS引数「メソッドグループ」から「アクション」に変換できません中学一年生です、このエラーを教えていただいたら助かります。 |
2022-01-12 00:41:38 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Rails環境構築で[ERROR] --initialize specified but the data directory has files in it. Aborting. |
https://teratail.com/questions/377707?rss=all
|
Rails環境構築でERRORinitializespecifiedbutthedatadirectoryhasfilesinitAbortingERRORinitializespecifiedbutthedatadirectoryhasfilesinitAborting代表的なのは上記のエラーです。 |
2022-01-12 00:36:21 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
ターミナルでApplicationsの中身を確認できません。 |
https://teratail.com/questions/377706?rss=all
|
application |
2022-01-12 00:12:25 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
サイトの幅を小さくした時の表示が明らかにおかしい |
https://teratail.com/questions/377705?rss=all
|
サイトの幅を小さくした時の表示が明らかにおかしい自分は現在、模写コーディングのに取り組んでいるのですが、レスポンシブ化の部分で詰まってしまいました。 |
2022-01-12 00:09:08 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
【CircleCI】bundle installされない場合の対処方法 |
https://qiita.com/Hyzsa/items/0b48405aed62b8f65ff5
|
引用元とのことだったので、configymlで指定しているDockerイメージを下記のように修正したら解決しました。 |
2022-01-12 00:47:15 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
crontab×ruby 備忘録 |
https://qiita.com/shelisuke/items/dc320631f13ab4ed5a65
|
crontab×ruby備忘録経緯crontabでrubyのスクリプトを動かすことに苦戦したので、忘れないようにメモ。 |
2022-01-12 00:06:54 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
SAP認定Scale-Out構成-AWS |
https://qiita.com/j-dai/items/3f6b35da95ef1f851493
|
SAP認定ScaleOut構成AWSAWSにデプロイするSAPScaleOut認定構成はピックアップしました。 |
2022-01-12 00:24:50 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
【CircleCI】bundle installされない場合の対処方法 |
https://qiita.com/Hyzsa/items/0b48405aed62b8f65ff5
|
引用元とのことだったので、configymlで指定しているDockerイメージを下記のように修正したら解決しました。 |
2022-01-12 00:47:15 |
海外TECH |
MakeUseOf |
The 9 Best Free Font Websites for Free Fonts Online |
https://www.makeuseof.com/tag/free-fonts-sites-where-find-them/
|
creative |
2022-01-11 15:46:43 |
海外TECH |
MakeUseOf |
5 Reasons Why Reddit Is the Best Social Media Platform Around |
https://www.makeuseof.com/reasons-reddit-best-social-media-platform/
|
reddit |
2022-01-11 15:16:56 |
海外TECH |
DEV Community |
Custom Reack Hooks: useAudio |
https://dev.to/iamludal/custom-reack-hooks-useaudio-565j
|
Custom Reack Hooks useAudioIn the last episode of the Custom React Hooks series we ve discovered the useNetworkState hook to simplify the user s network state management Today we ll explore another useful custom hook useAudio Ready Let s go MotivationImplementationUsageConclusionSupport Me MotivationWhy would you ever need such a hook We ll I ll give you two examples The first one is my personal website iamludal fr I swear this is not self promotion built with React which top navigation bar contains a button to switch between light and dark theme Actually if you turn up the sound a little bit you might hear a switch sound This sound comes from this custom hook The second example is the Typospeed game not self promotion either where you can hear sounds when removing a word actually Typospeed was built with Svelte but you get the idea In both examples we need to play some sounds and we don t want to repeat ourselves by manually instantiating a new audio settings its volume its playback rate const Home gt const audio useRef new Audio switch mp useEffect gt audio current playbackRate audio current volume return lt button onClick audio current play gt Play Sound lt button gt We don t want write all this code every time we need to use audio sounds Also we have to use the useRef hook in this situation and keep track of its current value in order to not recreate the audio instance at each component re render That being said we now have a sufficient reason to implement our new custom hook Let s get our hands dirty ImplementationAs we said in the previous part we don t want to repeat ourselves and this is the major goal of custom hooks Therefore our function will take optional parameters for our audio instance which can be either static or dynamic corresponding to additional options const audio useAudio switch mp volume Also we don t want to bother with the current property we have to extract this logic inside the new hook This way we will be able to interact with the audio instance directly audio play audio pause Hence the skeleton will look like this const useAudio src gt const audio useRef new Audio src return audio current This is the first and basic version of the hook If you don t need to have additional options you re ready to go But we will add another parameter to this hook an options object Each time a given property of that object changes we have to update our instance This way the options can be updated dynamically from outside ーwith another hook such as useState The final hook implementation now looks like this const useAudio src volume playbackRate gt const audio useRef new Audio src useEffect gt audio current volume volume volume useEffect gt audio current playbackRate playbackRate playbackRate return audio current ️If you need any other options feel free to add them depending on your needs For instance you could add an array parameter for the play method in order to only play a specific part of the audio particularly useful when you have one audio file with multiple sounds which is a technique used by some games Our hook is now ready to be used UsageBack to our first example the code can now be simplified as follows const Home gt const audio useAudio switch mp volume playbackRate return lt button onClick audio play gt Play Sound lt button gt We ve abstracted out all the logic inside this new hook which leads to a simpler cleaner and more readable code ConclusionI hope this hook will be useful to you for your projects If you have any questions feel free to ask them in the comments section With that being said thank you for reading me and I ll see you next time for a new custom hook Source code available on CodeSanbox Support MeIf you wish to support me you can click the following link to buy me a coffee which I will then probably turn into a new custom hook |
2022-01-11 15:44:59 |
海外TECH |
DEV Community |
Paracetamol.js💊| #3: ¿Qué imprime este código? |
https://dev.to/duxtech/paracetamoljs-2-que-imprime-este-codigo-3cfc
|
Paracetamol js ¿Quéimprime este código ¿Quécrees que imprime el siguiente código const frutas Mango Manzana Naranja Pera const pera frutas console log pera a Uncaught TypeError cannot read propertyb TypeError null is not an object evaluating c Naranjad PeraTe dejo la solución en el primer comentario |
2022-01-11 15:33:33 |
海外TECH |
DEV Community |
Creating an Asteroid Map with a NASA API |
https://dev.to/flippedcoding/creating-an-asteroid-map-with-a-nasa-api-4afc
|
Creating an Asteroid Map with a NASA APIThere are a lot of cool APIs out there that let you work with interesting datasets If you are interested in space at all then the NASA APIs might be something you want to check out In this post we ll use one of the NASA APIs to create an asteroid map This will give us a representation of how many asteroids came close to hitting the Earth and how big they were We ll save these images to Cloudinary so we can review them later Initial setupThere are a few things we need to have in place before starting on the code First you ll need an API key for the NASA Asteroids NeoWs API we ll be using You can get a free one here It ll send the API key to the email you enter Next you ll need a Cloudinary account to store the asteroid map images that you can reference later You can sign up for a free account here We ll be working with a local Postgres database so if you don t have that installed you can download it here Now that we have all of these things set up we can start working on the app Generate a new Redwood projectIn a terminal run the following command yarn create redwood app asteroid mapThis will create a lot of new files and directories for you Our focus will be in the web and api folders The web folder is where we ll write all fo the front end code in React The api folder is where we ll handle the Postgres connection and the GraphQL back end Create the database schema and connectionWe ll start by connecting to the database and setting up our schema First open the env file in the root of the project You ll see a commented out line that defines the DATABASE URL Uncomment that line and update it to match your local connection string That might look similar to this DATABASE URL postgres postgres admin localhost asteroidsYou won t need to create a new database manually When we run the first migration the asteroids database will be created for you Now we can write the schema for the database In the api gt db folder open schema prisma Redwood uses Prisma to handle the database operations This file is where we use the connection string and write the schema for all of our tables Update the provider value from sqlite to postgresql This tells Primsa we re working with a Postgres instance You can see where the connection string is being read from the DATABASE URL value we set earlier Next you can delete the example model and replace it with the following model Map id Int id default autoincrement name String startDate DateTime endDate DateTime mapUrl String This model represents the data we ll store in the database The NASA API returns asteroid information based on the dates we submit so we re storing those to know which dates correspond to the asteroid maps Running a database migrationSince we have the schema in place for the table we ll save the asteroid maps to let s go ahead and run a database migration In your terminal run the following command yarn redwood prisma migrate devThis will create the database if needed and then add the Map table to it Make the GraphQL types and resolversThat s all we need to do on the database side of this app Now we can turn to the GraphQL server Redwood s CLI has a lot of commands that do some heavy lifting for us We re going to generate the types and resolvers for our back end with this command yarn redwood generate sdl crud mapThis will generate several files for us that handle all of the CRUD functionality for our maps The only things we need to add are the types for the data we get from the NASA API and a resolver to fetch that data Adding the asteroid data typesIn the api gt src gt graphql directory open the newly generated maps sdl ts file This already has the type definitions for the CRUD queries and mutations we might use to update the database Now we ll add the type to define the data we ll get from the API the input type to send to the API and the query we can use to return the data Right below the Map type add this code type Asteroid missDistance String estimatedDiameter String input AsteroidInput startDate Date endDate Date viewDate Date type Query asteroids input AsteroidInput Asteroid requireAuth maps Map requireAuth map id Int Map requireAuth That will give us access to the query and what it needs Let s go define the resolver to fetch this data Calling the NASA API through a resolverThis is one of the cool things about GraphQL You can call another API in a resolver and the data gets sent through the same endpoint as if it were hitting your own database In api gt src gt services gt maps open the maps js file This has the CRUD resolvers created from that CLI command we ran earlier Below all of these add the following resolver to fetch the asteroid data export const asteroids input gt return fetch input startDate toISOString split T amp end date input endDate toISOString split T amp api key your api key really goes here then response gt return response json then rawData gt const data rawData near earth objects input viewDate toISOString split T const asteroids data map value gt return missDistance value close approach data miss distance kilometers estimatedDiameter value estimated diameter kilometers estimated diameter max return asteroids This resolver takes the input we pass to it and makes this request to the API Like with many API requests we have to send the inputs in a particular format That s why we re splitting the date string the way we are GraphQL passes the date in a format the NASA API doesn t like Then we get the data from the response and check out the asteroids that were close by on the viewDate we pass in This date can be any time between the start and end dates We take the data returned from the API and extract the values we need and that s what we pass in a successful response That s everything for the back end We have all of the types and resolvers we need to get the asteroid data and save things to the database We can turn our attention to the front end where we ll wrap things up Building the user interfaceLet s jump right in There s one package that we need to install in order to save the asteroid maps we create In your terminal go to the web directory and run yarn add html to imageThis will allow us to capture an image of the asteroid map really quickly We can use the Redwood CLI to generate the asteroid map page for us So in your terminal go back to the root of the project and run the following command yarn redwood generate page asteroidThis will update the Routes tsx file to have this new path and it generates a few files for us in web gt src gt pages gt AsteroidPage The file we will work in is AsteroidPage tsx Open this file and delete all of the existing import statements and replace them with these import useQuery useMutation from redwoodjs web import useState useRef from react import toPng from html to image After these imports we can add the GraphQL query to get our asteroid data and the mutation to save the map to the Cloudinary and the database const CREATE MAP MUTATION gql mutation CreateMapMutation input CreateMapInput createMap input input id const GET ASTEROIDS gql query GetAsteroids input AsteroidInput asteroids input input missDistance estimatedDiameter Adding states and using hooks in the componentWith all of the imports and GraphQL definitions in place let s start working inside the AsteroidPage component You can delete everything out of the component because we ll be writing a lot of different code We ll start by adding the states and other hooks we need for the component const createMap useMutation CREATE MAP MUTATION const canvasRef useRef null const startDate setStartDate useState const endDate setEndDate useState const viewDate setViewDate useState const loading data useQuery GET ASTEROIDS variables input startDate startDate endDate endDate viewDate viewDate First we create the method that does the mutation to add new records to the database Then we set the canvas ref that will hold the image of the asteroid map Next we set a few different date states These will let us adjust what s in the map we save and what we see in the app Then there s the data fetch query This calls that resolver we made to get the asteroid data from the NASA API We pass in the input in the shape we defined in the types on the back end These values come from the states so whenever the state values change we can get a new asteroid map Having a loading stateYou ll notice that we have a loading value from the useQuery call This tells us if the data is still being fetched It s important to have some kind of element that tells the user a page is loading This also prevents the app from crashing when the data isn t available yet So below the data query add this code if loading return lt div gt Loading lt div gt This just renders a loading message on the page The elements that get renderedNow that we have the data coming in let s write the return statement for what should render on the page Below the loading state check add the following code and we ll go through it return lt gt lt h gt AsteroidPage lt h gt lt form onSubmit submit gt lt div gt lt label htmlFor mapName gt Map Name lt label gt lt input type text name mapName gt lt div gt lt div gt lt label htmlFor startDate gt Start Date lt label gt lt input type date name startDate gt lt div gt lt div gt lt label htmlFor endDate gt End Date lt label gt lt input type date name endDate gt lt div gt lt div gt lt label htmlFor viewDate gt View Date lt label gt lt input type date name viewDate gt lt div gt lt button type submit gt Save Asteroid Map lt button gt lt form gt lt button type button onClick makeAsteroidMap gt View Map lt button gt lt canvas id asteroidMap ref canvasRef height width gt lt canvas gt lt gt There s not as much going on as it might seem We have a form that has a few input elements for the name we want to give an asteroid map and the dates we need to get the data and image This form has a submit button that fetches new asteroid data based on our inputs and saves a new map There s another button that lets us view the asteroid map in the canvas element below it The canvas element is what we target in the useRef hook above The form and view map buttons have functions that we need to write If you want to look at the app so far run yarn redwood dev in your terminal You should see something like this The submit functionWe ll add this function right below the loading state check This will get the form data update the date states take a snapshot of the asteroid map in the canvas upload it to Cloudinary and then make a new database record async function submit e e preventDefault const mapName e currentTarget mapName value const startDate e currentTarget startDate value const endDate e currentTarget endDate value const viewDate e currentTarget viewDate value setStartDate startDate setEndDate endDate setViewDate viewDate if canvasRef current null return const dataUrl await toPng canvasRef current cacheBust true const uploadApi cloudName image upload const formData new FormData formData append file dataUrl formData append upload preset upload preset value const cloudinaryRes await fetch uploadApi method POST body formData const input name mapName startDate new Date startDate endDate new Date endDate mapUrl cloudinaryRes url createMap variables input You ll need to get your cloudName and upload preset value from your Cloudinary console The only function left to write is the one to draw the asteroid map on the canvas Drawing the asteroid mapThis will create a different sized circle at various distances from the left side of the page to show how close they were to Earth and how big they were function makeAsteroidMap if canvasRef current getContext let ctx canvasRef current getContext d data asteroids forEach asteroid gt const scaledDistance asteroid missDistance const scaledSize asteroid estimatedDiameter let circle new PathD circle arc scaledDistance scaledDistance scaledSize Math PI ctx fill circle The scaling here isn t based on anything in particular so feel free to play around with the math Now if you run the app and click the View Map button you ll see something like this If you update the dates you can view a different map and save it to the database That s all of the code for this app Now you can see how close we almost came to an asteroid event every day Finished codeYou can take a look at the complete project in the asteroid map folder of this repo Or you can take a look at the front end in this Code Sandbox You ll have to update some values to match yours in order for this to work ConclusionWorking with external APIs is something we commonly do and GraphQL is one of the ways we can centralize all of the APIs we call Using this as a tool to make visual representations of how close we came to being hit by asteroids every day is just a fun way to use that functionality |
2022-01-11 15:25:24 |
海外TECH |
DEV Community |
Popup Subscription Form using CSS & JavaScript |
https://dev.to/elinabey/popup-subscription-form-using-css-javascript-364f
|
Popup Subscription Form using CSS amp JavaScriptCreate Popup Subscription Form Having a mailing list of subscribed users is very important to get your users back to your website Usually people come to your website read the post and move on If you post new content on your website they may not return So having a list of subscribed users actually helps when the user preferably visits your blog on your website we pop up a model subscription form on the window screen by clicking on subscribe button Create Popup Subscription FormOne thing to hold in mind throughout this method is not to make multiple popups in which case the user may get furious and leave your blog without reading it thoroughly Let s start First you need to create index html style css and Javascript files or you can add CSS and js code in the HTML file as well HTML Code lt script src gt lt script gt lt div class container gt lt a class button popup button href gt Open Model lt a gt lt div gt lt div class wrapper gt lt div class popup box gt lt h gt SIGN UP amp GET OFF lt h gt lt p gt Subscribe to our newsletters now and stay up to date with new collections lt p gt lt a class close button popup close href gt x lt a gt lt div class form group gt lt form method post gt lt input type email name useremail id required placeholder Please Enter your email gt lt button type submit id subscribe gt SUBSCRIBE lt button gt lt form gt lt div gt lt div gt lt div gt CSS Style import url Sans italic body font family Open Sans line height background bff subscribe background ddd padding px px px px margin px border none cursor pointer border radius px input width height px background color eee border none padding left px outline none font weight position relative border radius px container width px margin px auto text align center h margin bottom px font size px color fff important h font size px color fff p font size px color fff button margin top px padding display inline block webkit transition all linear s transition all linear s border radius px background fff font size px font weight bold text decoration none text transform uppercase color button hover opacity wrapper width height display none position absolute top px left px content background rgba popup box width px padding px transform translate scale position absolute top left box shadow px px px rgba border radius px text align center popup box h color aaa popup box h color popup box close button width px height px display inline block position absolute top px right px webkit transition all ease s transition all ease s border radius px background bff font weight bold text decoration none color fff line height popup box close button hover webkit transform rotate deg transform rotate deg transform in transform out display block webkit transition all ease s transition all ease s transform in webkit transform translate scale transform translate scale transform out webkit transform translate scale transform translate scale Javascript document ready function popup button click function e wrapper fadeIn popup box removeClass transform out addClass transform in e preventDefault popup close click function e wrapper fadeOut popup box removeClass transform in addClass transform out e preventDefault I shared this post from Popup Subscription Form using CSS amp Javascript you can read in detail from there To see live demo CodepenI hope this post supported you learn how to create subscription popup model to your website If you have any questions or suggestions please discuss below |
2022-01-11 15:11:25 |
海外TECH |
DEV Community |
Angular Material Menu: Nested Menu using Dynamic Data |
https://dev.to/shhdharmen/angular-material-menu-nested-menu-using-dynamic-data-1nfm
|
Angular Material Menu Nested Menu using Dynamic DataThe Angular Material Menu is a floating panel containing a list of options In this tutorial we will learn how we can create nested menus from dynamic data We will first learn the basics of Angular Material Menu and how to render a nested menu with a static HTML template Then we will understand why and what changes are needed to dynamically render nested menus from data Angular Material Menu lt mat menu gt is a floating panel containing a list of options By itself the lt mat menu gt element does not render anything The menu is attached to and opened via application of the matMenuTriggerFor directive lt button mat button matMenuTriggerFor menu gt Menu lt button gt lt mat menu menu matMenu gt lt button mat menu item gt Item lt button gt lt button mat menu item gt Item lt button gt lt mat menu gt Static Nested MenuTo render a nested menu with static data or simply from HTML template we will have to define the root menu and sub menus in addition to setting the matMenuTriggerFor on the mat menu item that should trigger the sub menu lt button mat button matMenuTriggerFor animals gt Animal index lt button gt lt mat menu animals matMenu gt lt button mat menu item matMenuTriggerFor vertebrates gt Vertebrates lt button gt lt mat menu gt lt mat menu vertebrates matMenu gt lt button mat menu item matMenuTriggerFor fish gt Fishes lt button gt lt button mat menu item gt Amphibians lt button gt lt button mat menu item gt Reptiles lt button gt lt button mat menu item gt Birds lt button gt lt button mat menu item gt Mammals lt button gt lt mat menu gt lt mat menu fish matMenu gt lt button mat menu item gt Baikal oilfish lt button gt lt button mat menu item gt Bala shark lt button gt lt button mat menu item gt Ballan wrasse lt button gt lt button mat menu item gt Bamboo shark lt button gt lt button mat menu item gt Banded killifish lt button gt lt mat menu gt And the output will be like below Dynamic Nested MenuBuilding a menu from dynamic data is often needed especially in business or enterprise applications For example loading features based on logged in user s permissions The data may come from a REST API We will take an example where items and their children are loaded from a database And we will render a nested menu for each item which has children DatabaseFor the database we are going to assume the following service You can connect the actual REST API with this service too import Injectable from angular core import delay of from rxjs Injectable providedIn root export class DynamicDatabase dataMap new Map lt string string gt Fruits Apple Orange Banana Vegetables Tomato Potato Onion Apple Fuji Macintosh Onion Yellow White Purple Macintosh Yellow White Purple rootLevelNodes string Fruits Vegetables getChildren node string adding delay to mock a REST API call return of this dataMap get node pipe delay isExpandable node string boolean return this dataMap has node Above service s code is simple dataMap represents data this could be the actual databaserootLevelNodes represents first nodes to rendergetChildren will return the items for a particular node We will use this to render sub menu itemsisExpandable will return whether there are any children We will use this to identify whether a sub menu is needed Nested MenuNow understand that we can t simply follow the standard HTML template of MatMenu for dynamic data Below are the reasons We can t load the lt mat menu gt until we know that item has childrenWe can t attach matMenuTrigger to mat menu item until lt mat menu gt is loaded in the DOMSo to handle the above problems we will follow the below approach in respective order Read node from node listCheck if any node is expandableIf yes then create a sub menu lt mat menu gt with loader and attach it with matMenuTrigger in the rendered node s mat menu itemOnce the user clicks node get and render child nodes in sub menuFor sub menu s child nodes again follow the same approach and start from step If no then simply create node s mat menu item Root ComponentTo achieve the above approach we will create a app menu component and use it in app root lt src app app component html gt lt app menu trigger Food data initialData isRootNode true gt lt app menu gt src app app component tsimport Component from angular core import DynamicDatabase from dynamic database service Component selector app root templateUrl app component html export class AppComponent title mat menu dynamic data initialData string constructor private database DynamicDatabase this initialData this database rootLevelNodes slice We are reading rootLevelNodes and passing it as data in app menu Menu ComponentFor the menu initially we want to show a button which will trigger a menu lt src app menu menu component html gt lt button mat button matMenuTriggerFor menu gt trigger lt button gt lt mat menu menu matMenu gt lt button mat menu item ngFor let node of data gt node lt button gt lt mat menu gt And the class looks like this src app menu menu component tsexport class MenuComponent Input data string Input trigger Trigger Input isRootNode false RecursionNow to render a nested menu we will just need to handle recursion in this code And generate the same DOM structure for each nested menu So first we will change the code inside lt mat menu gt lt src app menu menu component html gt lt button mat button matMenuTriggerFor menu gt trigger lt button gt lt mat menu menu matMenu gt lt ng container ngFor let node of data let i index gt lt button mat menu item gt lt app menu trigger node ngIf isExpandable node else menuItem gt lt app menu gt lt button gt lt ng template menuItem gt lt button mat menu item gt node lt button gt lt ng template gt lt ng container gt lt mat menu gt Now inside the menu we are checking for each node if the isExpandable method returns true we are rendering app menu again inside it isExpandable method will simply call isExpandable from the DynamicDatabase service src app menu menu component ts export class MenuComponent isExpandable node string boolean return this database isExpandable node Let s look at the output Notice that text is also hoverable inside mat menu item That s because of the mat button When app menu is rendered inside we will have to change the directive of the button from mat button to mat menu item let s do that lt src app menu menu component html gt lt button ngIf isRootNode mat button matMenuTriggerFor menu gt trigger lt button gt lt button ngIf isRootNode mat menu item matMenuTriggerFor menu gt trigger lt button gt lt mat menu menu matMenu gt lt ng container ngFor let node of data let i index gt lt button mat menu item gt lt app menu trigger node ngIf isExpandable node else menuItem gt lt app menu gt lt button gt lt ng template menuItem gt lt button mat menu item gt node lt button gt lt ng template gt lt ng container gt lt mat menu gt Let s look at the output now It s rendering the root items fine now but the sub menu is blank Let s add data in it DataWe want to load the data once the menu is rendered and opened So we will use the menuOpened event to load the data menuOpened emits the event when the associated menu is opened We only want to load the data for non root items because for root items data is coming from the parent component lt src app menu menu component html gt lt button ngIf isRootNode mat button matMenuTriggerFor menu gt trigger lt button gt lt button ngIf isRootNode mat menu item matMenuTriggerFor menu menuOpened getData trigger gt trigger lt button gt lt rest remains same gt Let s create a getData method in menu component ts src app menu menu component ts export class MenuComponent isLoading false dataLoaded false getData node string if this dataLoaded this isLoading true this database getChildren node subscribe d gt this data d slice this isLoading false this dataLoaded true With getData we are creating more flags isLoading Indicates if data is being fetcheddataLoaded Indicates if data is already loaded and prevents further fetchingLet s look at the output now Notice that data is getting loaded after a particular time that s because we have added a delay in DynamicDatabase getChildren to simulate an API call And it s not fetching the data again if it s already loaded and in that case menu items are rendered instantly LoaderThe last thing remaining is to show a loader when data is getting fetched We already have isLoading flag let s use that to show lt mat spinner gt lt src app menu menu component html gt lt rest remains same gt lt mat menu menu matMenu gt lt button mat menu item ngIf isLoading style display flex justify content center align items center gt lt mat spinner mode indeterminate diameter gt lt mat spinner gt lt button gt lt ng container ngFor let node of data let i index gt lt rest remains same gt lt ng container gt lt mat menu gt Notice that I have added some inline styles so that lt mat spinner gt is displayed in the center of mat menu item Let s look at the output now SummaryWe started with a simple example of a menu where we rendered nested menus using static HTML template Then we understood the need for dynamic data in nested menus and the problems to achieve dynamicity with the simple HTML template We then created a app menu component First we loaded a menu with root items provided as data input from the parent component Then we handled recursion rendering app menu inside app menu based on isExpandable flag Next we implemented fetching data based on menuOpened event and finally we displayed a loader while fetching the data All the above code is available on GitHub repo mat menu dynamic data |
2022-01-11 15:07:14 |
Apple |
AppleInsider - Frontpage News |
Apple iCloud Mail, Photos, and more are again 'slow or unavailable' |
https://appleinsider.com/articles/22/01/11/apple-icloud-mail-photos-and-more-are-again-slow-or-unavailable?utm_medium=rss
|
Apple iCloud Mail Photos and more are again x slow or unavailable x For the second day in a row Apple s iCloud services have been hit by an outage that sees very many of them either running slowly or not being available at all On Monday Apple acknowledged that multiple iCloud services were running slowly or not at all but implemented fixes that appeared to return them to normal On Tuesday however it admitted that very many were again affected All current issues were originally acknowledged by Apple at a m Eastern on January Some of them are listed as affecting some users and potentially being slow or unavailable Read more |
2022-01-11 15:58:36 |
Apple |
AppleInsider - Frontpage News |
Apple VR, iPhone 14, and iMessage controversy - An exclusive interview with Rene Ritchie |
https://appleinsider.com/articles/22/01/11/apple-vr-iphone-14-and-imessage-controversy---an-exclusive-interview-with-rene-ritchie?utm_medium=rss
|
Apple VR iPhone and iMessage controversy An exclusive interview with Rene RitchieOn this special episode of the AppleInsider podcast we interview Apple pundit Rene Ritchie and discuss the Apple VR headset what he hopes to see in future versions of iPhone and whether iMessage lock in is Apple s problem Rene Ritchie has been covering Apple since and is now an independent journalist creating in depth videos on YouTube We kick off the show discussing how Apple could differentiate its VR headset from competitors while leveraging services like Fitness and Apple Arcade Lossless audio could be coming to the next version of AirPods Pro but would require new wireless technologies to provide enough bandwidth We discuss future audio technologies and whether Apple would still support Bluetooth wireless in AirPods Read more |
2022-01-11 15:20:47 |
海外TECH |
Engadget |
Instagram is exploring a customizable profile grid |
https://www.engadget.com/instagram-reorder-profile-grid-test-153412873.html?src=rss
|
Instagram is exploring a customizable profile gridYour Instagram profile s grid might soon be more than just a snapshot of your most recent posts Leaker Alessandro Paluzzi has discovered that Instagram has been developing an quot edit grid quot feature that would let you reorder the posts in your profile This could help musicians or stores using multi post collages to plug their latest work but it might also be helpful if you want to highlight an important post or prioritize your favorites We ve asked Instagram for comment It s not clear if the social network plans to test or widely distribute the feature It wouldn t be surprising if the customizable profile grid became a mainstay though Instagram has spent more and more of its time courting businesses and shops and the option to rearrange the grid might attract companies wanting to fine tune their public image This might also help if you re an artist or photo enthusiast hoping to showcase your best shots regardless of how old they might be Instagram is working on the ability to edit the profile grid allowing you to rearrange posts in any order you like pic twitter com fjmkJDjeーAlessandro Paluzzi alexa January |
2022-01-11 15:34:12 |
海外TECH |
Engadget |
Maserati will field a Formula E team in 2023 |
https://www.engadget.com/maserati-formula-e-2023-gen3-151809581.html?src=rss
|
Maserati will field a Formula E team in Some Italian flair is coming to the Formula E grid Maserati plans to field a team in the electric motor racing series in becoming the first brand from the country to do so The automaker is returning to single seater competition for the first time in more than six decades Maserati ran a successful Formula team in the s and its two seater MC took titles in the FIA GT sports car series between and Maserati plans to take what it learns on Formula E tracks and feed that back into its Folgore EV lineup “Beyond this piece of history Maserati Formula E will be our technological laboratory to accelerate the development of high efficiency electrified powertrains and intelligent software for our road sports cars quot Stellantis Motorsport senior VP Jean Marc Finot said The automaker will enter Formula E as the series shifts to the Gen car its lightest and fastest vehicle to date Formula E and the Federation Internationale de l Automobile FIA said the Gen will be the planet s most efficient race car They claim the EV will produce at least percent of energy used in a race via regenerative braking |
2022-01-11 15:18:09 |
海外TECH |
Network World |
Weekly internet health check, US and worldwide |
https://www.networkworld.com/article/3534130/covid-19-weekly-health-check-of-isps-cloud-providers-and-conferencing-services.html#tk.rss_all
|
Weekly internet health check US and worldwide The reliability of services delivered by ISPs cloud providers and conferencing services a k a unified communications as a service UCaaS is an indication of how well served businesses are via the internet ThousandEyes is monitoring how these providers are handling the performance challenges they face It will provide Network World a roundup of interesting events of the week in the delivery of these services and Network World will provide a summary here Stop back next week for another update and see more details here Get regularly scheduled insights by signing up for Network World newsletters To read this article in full please click here |
2022-01-11 15:50:00 |
金融 |
RSS FILE - 日本証券業協会 |
J-IRISS |
https://www.jsda.or.jp/anshin/j-iriss/index.html
|
iriss |
2022-01-11 15:10:00 |
金融 |
金融庁ホームページ |
アクセスFSA第221号を公表しました。 |
https://www.fsa.go.jp/access/index.html
|
アクセス |
2022-01-11 17:00:00 |
金融 |
金融庁ホームページ |
金融審議会「資金決済ワーキング・グループ」報告書について公表しました。 |
https://www.fsa.go.jp/singi/singi_kinyu/tosin/20220111.html
|
金融審議会 |
2022-01-11 17:00:00 |
金融 |
金融庁ホームページ |
「デジタル・分散型金融への対応のあり方等に関する研究会」(第4回)議事録について公表しました。 |
https://www.fsa.go.jp/singi/digital/gijiroku/20211101.html
|
Detail Nothing |
2022-01-11 17:00:00 |
ニュース |
BBC News - Home |
Fans to return to Scottish stadiums next week |
https://www.bbc.co.uk/news/uk-scotland-scotland-politics-59953823?at_medium=RSS&at_campaign=KARANGA
|
football |
2022-01-11 15:12:54 |
ニュース |
BBC News - Home |
Andrew Gosden: Two men arrested for trafficking and kidnap |
https://www.bbc.co.uk/news/uk-england-south-yorkshire-59952786?at_medium=RSS&at_campaign=KARANGA
|
london |
2022-01-11 15:21:40 |
ニュース |
BBC News - Home |
Schools struggle amid Covid as one in 12 teachers off |
https://www.bbc.co.uk/news/education-59950903?at_medium=RSS&at_campaign=KARANGA
|
absence |
2022-01-11 15:13:28 |
ニュース |
BBC News - Home |
Vicar of Dibley actor Gary Waldhorn dies |
https://www.bbc.co.uk/news/entertainment-arts-59950298?at_medium=RSS&at_campaign=KARANGA
|
french |
2022-01-11 15:37:08 |
ニュース |
BBC News - Home |
'This is the Ashes' - O'Sullivan outclasses Lisowski and will meet Aussie Robertson in last eight |
https://www.bbc.co.uk/sport/snooker/59955170?at_medium=RSS&at_campaign=KARANGA
|
x This is the Ashes x O x Sullivan outclasses Lisowski and will meet Aussie Robertson in last eightRecord seven time champion Ronnie O Sullivan outclasses Jack Lisowski to reach the quarter finals of the Masters at Alexandra Palace |
2022-01-11 15:36:07 |
ニュース |
BBC News - Home |
What are the new Covid rules for the UK? |
https://www.bbc.co.uk/news/explainers-52530518?at_medium=RSS&at_campaign=KARANGA
|
events |
2022-01-11 15:03:02 |
ニュース |
BBC News - Home |
Covid passports: Where do I need a pass and how do I get one? |
https://www.bbc.co.uk/news/explainers-55718553?at_medium=RSS&at_campaign=KARANGA
|
outdoor |
2022-01-11 15:10:17 |
サブカルネタ |
ラーブロ |
らぁめん 鴇@藤沢(神奈川県) 「醤油、ほか」 |
http://ra-blog.net/modules/rssc/single_feed.php?fid=195477
|
神奈川県 |
2022-01-11 15:01:14 |
北海道 |
北海道新聞 |
荒天で運休や欠航、12日も交通障害や高潮に警戒 |
https://www.hokkaido-np.co.jp/article/632282/
|
交通障害 |
2022-01-12 00:06:22 |
北海道 |
北海道新聞 |
3回目接種、一般も前倒し 12歳未満3月にも 首相表明 |
https://www.hokkaido-np.co.jp/article/632187/
|
岸田文雄 |
2022-01-12 00:00:39 |
コメント
コメントを投稿