投稿時間:2022-03-20 21:26:26 RSSフィード2022-03-20 21:00 分まとめ(30件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita Pythonによる移動通信シミュレーション 受信電力の変動 https://qiita.com/epppJones/items/c4994ff47be02a29abef 2022-03-20 20:53:21
python Pythonタグが付けられた新着投稿 - Qiita [GCP] CloudFunctionsを使って指定日にLINE送信する仕組みを作ってみた [無料] https://qiita.com/tsutome_engineer/items/f557436360e9cdcd81cb トリガー設定適当な関数名をつけて、トリガーに先ほど作成したPubSubを設定します。 2022-03-20 20:15:24
python Pythonタグが付けられた新着投稿 - Qiita 【完全無料】Microsoftのデータサイエンス初心者向けコースをやってみるDay2チャレンジ:非構造データを扱う。 https://qiita.com/keiji_dl/items/700a734757aaf6b2d8ba COVID国別感染者の集計構造化されたデータCOVID論文の解析非構造データ利用するライブラリの概要pandaspandasライブラリでは、リレーショナルテーブルに類似した、いわゆるDataframeを操作することができます。 2022-03-20 20:11:26
js JavaScriptタグが付けられた新着投稿 - Qiita ドットインストールでJavaScript基礎文法編をやってみた https://qiita.com/Masaru_Tech/items/0ea2b3dc6d718b2a1a51 ドットインストールでJavaScript基礎文法編をやってみたドットインストールJavaScript基礎文法編です要点だけまとめてみたので、後で振り返り用としておきますJavaScriptを書いてみようConsoleの開き方GoogleChrome︙➜その他のツール➜デベロッパーツール➜下のウィンドウのコンソールボタンコンソール画面にエラーメッセージ出てるんだがソースマップうんちゃらかんちゃらだったので調べて無効にしたら出なくなったのでとりあえずはOKということで・・・しょーもないかもしれないけど、エラーに対応出来た感じがエンジニアぽい感じ参考にさせて頂いたgtSourceMapソースマップエラーの対処法usestrict厳密なエラーチェックをするためのもの書いておくとエラーが発見しやすくなるので、必ず書いておくJSファイルの記述場所書く場所としては、HTMLファイル内に書くor外部ファイルに書く基本的には後者の外部ファイルに書いて呼び出すのが良さそうltscriptsrcファイルの場所を指定gtltscriptgtltbodygtbodyの閉じタグの前にスクリプトタグを置こうエラーメッセージに慣れようコンソールに出たエラーメッセージは重要なヒントになるmainjsと書いてあればmainjsファイルの行目がおかしいんだなと分かるDeepLも上手く活用していこうバックスラッシュの使い方文字列の中でorを表示したい場合例itsmeもしくはitsmen改行例itsnmetタブ例itstmevarは使わない定数gtconst変数gtlet変数を使った計算は省略出来る型について学ぼうnulltypeofで調べた時にnullがobjectと出るのはJSの有名なバグ文字列と数値について数字からなる文字列と数字の演算は可能で、その場合、数字からなる文字列も数値に変換されるただ、足し算だけは例外で、文字列と数値の間に演算子を用いた場合は文字列の連結のための演算子として扱われる真偽値比較演算子を含まない単一の値も真偽値で評価出来るfalseltnullundefined空文字列falsetrueltそれ以外条件分岐を学ぼうif文trueの場合iffalseの場合else条件がつ以上に分岐する場合はelseifnifとelseの間条件演算子条件式trueの処理falseの処理短く書ける利点の一方で、場合によってはコードが読みにくくなるという欠点があるよく出てくる表現なので理解はしておくべきだが、読みやすさとのバランスを考えて使う必要がある論理演算子ampampなおかつANDもしくはORではないNOTifに続く条件を論理演算子で繋ぐswitchを使った条件式が多く並ぶような条件式の時に使えるswitch比較したい値casebreakncaseがつ以上の時はcasenどれにも当てはまらない時の処理はdefaultbreakcaseの最後はではなく条件の繰り返し処理for文カウンターの変数名はiが慣習的に良く使われる再代入するのでletを使うテンプレートリテラル文字列の中で定数を使用する場合に使うconsoleloghelloiの中はバッククォートと波括弧が使われるiは、変数iにを足してくださいねという処理インクリメントと言う逆はデクリメントwhile文指定した条件が満たしている間、特定の処理を繰り返す最初から条件を満たしていないが、値を表示して欲しい時dowhileを使うcontinuebreakforやwhile文で特定の回だけスキップしたい時continue特定の回で処理を終了させる時breakの倍数の時をスキップしたいなどの時の演算子例の倍数の時にスキップしたいgti変数iをで割った余りがgtの倍数gtgtgt関数を使って処理をまとめてみよう関数似たような処理を何度も書かなくて済むfunction書き方宣言gtfunction関数名処理呼び出す時gt関数名いくつか呼び出した処理を変えたいといった時は呼び出した関数名ltの内を変更出来る実引数その場合、宣言時のfunction関数名ltの内に変数を入れる仮引数の中をテンプレートリテラルを使って処理を記述する関数を呼び出す時に値を渡さなかった場合のデフォルト値を変数に指定出来るfunction変数名関数名としておくと関数名を呼び出した時にこちらで何も引数を渡さないと関数名の値が使われる関数式上記は関数宣言と言い、その他に関数式という書き方もある書き方は定数に関数を代入するといった書き方になる注意点としては代入する形になるので、の最後にはを付け忘れない事アロー関数関数式を更に短く書く書き方const定数引数gt引数の処理returnreturnを使うと、関数内で処理をした結果を「戻り値」として返す事が出来るnote本来returnを使わず処理を行った場合consolelogそのまま終了となるしかし、returnを使う事で処理を行った結果を値として返せるので、その値を使ってさらに別の処理を続ける事ができる例abcとdefがAとBとして結果が出る更にABの処理をしたい時などに利用出来るということスコープスコープとは、有効範囲という意味ブロック条件式の外で定数を宣言した場合、この定数は全ての範囲で有効で、このようなスコープをグローバルスコープと呼ぶ同じ定数を別の場面で使いたい場合はブロックに囲ってあげる必要があるブロックはの範囲ということなので、基本的に書いたコードはブロックで囲ってスコープを分けるという習慣を付けておくといいかもしれない所感HTMLCSSとは違って目に見えない部分の処理という部分でまた難しいなぁと感じました。 2022-03-20 20:21:59
Docker dockerタグが付けられた新着投稿 - Qiita Docker for windowsを使わずにWSL2でDockerを使用する https://qiita.com/tlasu/items/2f406d61b38743378244 2022-03-20 20:29:31
GCP gcpタグが付けられた新着投稿 - Qiita [GCP] CloudFunctionsを使って指定日にLINE送信する仕組みを作ってみた [無料] https://qiita.com/tsutome_engineer/items/f557436360e9cdcd81cb トリガー設定適当な関数名をつけて、トリガーに先ほど作成したPubSubを設定します。 2022-03-20 20:15:24
技術ブログ Developers.IO システム内部音声でMacOS上の画面録画方法 https://dev.classmethod.jp/articles/macos_screen_recording_with_internal_audio/ macos 2022-03-20 11:12:41
海外TECH DEV Community Building REST APIs in Golang go-gin with persistence database Postgres https://dev.to/ramu_mangalarapu/building-rest-apis-in-golang-go-gin-with-persistence-database-postgres-4616 Building REST APIs in Golang go gin with persistence database PostgresLet s build REST APIs in Go using Gin web framework I will adding authentication docker image and sample deployment in Google cloud in next coming articles We are going to build APIs around Albums that I took from go dev but I will extend by using the Postgres database So this will have persistent data storage Usually when we are working with web frameworks they usually contains all the required components to build full application without importing any other extra library See hereWe will be having routing JSON XML parsers we could say famous data interchange format parsers validations sanitizations of input data HTTP clients to make call to external APIs database drivers things that makes response writing easy to server ORMs object relational mapper Security measures such as CSRF XSS SQL Injections logging etc which are required to build application easily Just imagine we do not have fully tested router functionality and in case if want to build router from scratch it is really hard for normal developer to build and maintain all the times All the libraries frameworks and SDKs provide abstraction for us to build application easily We only need to worry about what is our business logic In fact there are even Go libraries that generated REST APIs skelton for us Awesome right Yes it is it is happening and it will continue to happen that we do not bother to write code for common web application items such as authentication authorization input validations response generation unit testing integration testing logging middleware take any functionality you wanted to have there will be multiple libraries and APIs this could be SaaS companies which provide enterprise level things which makes things easy for us I think we are going beyond our current topic all I am sharing here is basic example of building REST APIs which has persistent memory with Postgres Server Let s initialize go module to create to rest apis go mod init example com web servicesFirst of all we need to connect to database I am keeping all the files in same main package as this is simple one but usually we should divide into packages there are no official project layout for Go but usually developers follow things like handlers config services apis domain etc like that but there are like golang project layoutpostgressql sqlCREATE TABLE IF NOT EXISTS artist id SERIAL PRIMARY KEY name VARCHAR NOT NULL this is name of the Author title VARCHAR UNIQUE NOT NULL price VARCHAR NOT NULL SELECT id name title price FROM artist LIMIT OFFSET UPDATE artist SET name nae title tle price WHERE id SELECT FROM artist SELECT FROM artist WHERE id DELETE FROM artist WHERE id INSERT INTO artist name title price VALUES name title price ON CONFLICT DO NOTHING database gopackage mainimport database sql fmt log github com lib pq Env holds database connection to Postgrestype Env struct DB sql DB database variables usually we should get them from env like os Getenv variableName const host localhost port user postgres password root dbname artists ConnectDB tries to connect DB and on succcesful it returns DB connection string and nil error otherwise return empty DB and the corresponding error func ConnectDB sql DB error connString fmt Sprintf host s port d user s password s dbname s sslmode disable host port user password dbname db err sql Open postgres connString if err nil log Printf failed to connect to database v err return amp sql DB err return db nil main gopackage mainimport log github com gin gonic gin func main connect to DB first env new Env var err error env DB err ConnectDB if err nil log Fatalf failed to start the server v err router gin Default router GET albums id env GetAlbumByID router GET albums env GetAlbums router POST albums env PostAlbum router PUT albums env UpdateAlbum router DELETE albums id env DeleteAlbumByID router Run localhost handler gopackage main This is to ensure we do not overload the server when we have millions of rowsvar recordFetchLimit testing purposealbum get gopackage mainimport database sql fmt log net http strconv github com gin gonic gin github com lib pq GetAlbumByID locates the album whose ID value matches the id parameter sent by the client then returns that album as a response func env Env GetAlbumByID c gin Context id err strconv Atoi c Param id if err nil e fmt Sprintf received invalid id path param which is not string v c Param id log Println e makeGinResponse c http StatusNotFound e return var name title string var price float q SELECT FROM artist WHERE id row env DB QueryRow q id err row Scan amp id amp name amp title amp price switch err case sql ErrNoRows log Printf no rows are present for alubum with id d id makeGinResponse c http StatusBadRequest err Error case nil log Printf we are able to fetch album with given id d id c JSON http StatusOK NewAlbum id title name price default e fmt Sprintf error v occurred while reading the databse for Album record with id d err id log Println e makeGinResponse c http StatusInternalServerError err Error GetAlbums responds with the list of all albums as JSON func env Env GetAlbums c gin Context Note pagnination can be impleted in may ways but I am following one of the way if you feel this is confusing please read medium article that I have added below For this page and perPage isseus front end engineers can take care of it by escaping and sanitization of query params Please see Please see page c Query page AKA limit in SQL terms if page e missing query param page log Println e makeGinResponse c http StatusNotFound e return perPage c Query perPage AKA limit in SQL terms if perPage e missing query param perPage log Println e makeGinResponse c http StatusNotFound e return limit err strconv Atoi page if err nil e fmt Sprintf received invalid page query param which is not integer v page log Println e makeGinResponse c http StatusBadRequest e return if limit gt recordFetchLimit Seems some bad user or front end developer playing with query params e fmt Sprintf we agreed to fetch less than d records but we received request for d recordFetchLimit limit log Println e makeGinResponse c http StatusBadRequest e return offset err strconv Atoi perPage if err nil e fmt Sprintf received invalid offset query param which is not integer v page log Println e makeGinResponse c http StatusBadRequest e return anyway let s check if offset is a negative value if offset lt e offset query param cannot be negative log Println e makeGinResponse c http StatusBadRequest e return q SELECT id name title price FROM artist LIMIT OFFSET rows err env DB Query q limit offset switch err case sql ErrNoRows defer rows Close e no rows records found in artist table to read log Println e makeGinResponse c http StatusBadRequest e case nil defer rows Close a make Album var rowsReadErr bool for rows Next var id int var name title string var price float err rows Scan amp id amp name amp title amp price if err nil log Printf error occurred while reading the database rows v err rowsReadErr true break a append a NewAlbum id title name price if rowsReadErr log Println we are not able to fetch few records let s return the read rows at least log Printf we are able to fetch albums for requested limit d and offest d limit offset c JSON http StatusOK a default defer rows Close this should not happen e some internal database server error log Println e makeGinResponse c http StatusInternalServerError e album post gopackage mainimport log net http github com gin gonic gin github com lib pq PostAlbums adds an album from JSON received in the request body func env Env PostAlbum c gin Context Call BindJSON to bind the received JSON to newAlbum var newAlbum Album if err c BindJSON amp newAlbum err nil log Printf invalid JSON body v err makeGinResponse c http StatusNotFound err Error return q INSERT INTO artist name title price VALUES ON CONFLICT DO NOTHING result err env DB Exec q newAlbum Artist newAlbum Title newAlbum Price if err nil log Printf error occurred while inserting new record into artist table v err makeGinResponse c http StatusInternalServerError err Error return checking the number of rows affected n err result RowsAffected if err nil log Printf error occurred while checking the returned result from database after insertion v err makeGinResponse c http StatusInternalServerError err Error return if no record was inserted let us say client has failed if n e could not insert the record please try again after sometime log Println e makeGinResponse c http StatusInternalServerError e return NOTE Here I wanted to return the location for newly created Album but this pq library does not support LastInsertionID functionality m successfully created the record log Println m makeGinResponse c http StatusOK m album put gopackage mainimport fmt log net http github com gin gonic gin github com lib pq UpdateAlbum updates the Album with the given details if record found func env Env UpdateAlbum c gin Context Call BindJSON to bind the received JSON to toBeUpdatedAlbum var toBeUpdatedAlbum Album if err c BindJSON amp toBeUpdatedAlbum err nil e fmt Sprintf invalid JSON body v err log Println e makeGinResponse c http StatusBadRequest e return q UPDATE artist SET name title price WHERE id result err env DB Exec q toBeUpdatedAlbum Artist toBeUpdatedAlbum Title toBeUpdatedAlbum Price toBeUpdatedAlbum ID if err nil e fmt Sprintf error v occurred while updating artist record with id d err toBeUpdatedAlbum ID log Println e makeGinResponse c http StatusInternalServerError e return checking the number of rows affected n err result RowsAffected if err nil e fmt Sprintf error occurred while checking the returned result from database after updation v err log Println e makeGinResponse c http StatusInternalServerError e if no record was updated let us say client has failed if n e could not update the record please try again after sometime log Println e makeGinResponse c http StatusInternalServerError e return m successfully updated the record log Println m makeGinResponse c http StatusOK m album delete gopackage mainimport fmt log net http strconv github com gin gonic gin github com lib pq DeleteAlbumByID locates the album whose ID value matches the id parameter sent by the client then returns that corresponding message func env Env DeleteAlbumByID c gin Context id err strconv Atoi c Param id if err nil e fmt Sprintf received invalid id path param which is not string v c Param id log Println e makeGinResponse c http StatusNotFound e return q DELETE FROM artist WHERE id result err env DB Exec q id if err nil e fmt Sprintf error occurred while deleting artist record with id d and error is v id err log Println e makeGinResponse c http StatusInternalServerError e return checking the number of rows affected n err result RowsAffected if err nil e fmt Sprintf error occurred while checking the returned result from database after deletion v err log Println e makeGinResponse c http StatusInternalServerError e return if no record was deleted let us inform that there might be no records to delete for this given album ID if n e could not delete the record there might be no records for the given ID log Println e makeGinResponse c http StatusBadRequest e return m successfully deleted the record log Println m makeGinResponse c http StatusOK m We can add business object in domain gopackage main Album holds of few important details about it type Album struct ID int json id omitempty Title string json title Artist string json artist Price float json price NewAlbum is Album constructor func NewAlbum id int title artist string price float Album return Album id title artist price There are certain things in application we repeat again may be we can make one function DRY principal add it in the utils gopackage mainimport github com gin gonic gin func makeGinResponse c gin Context statusCode int value string c JSON statusCode gin H message value statusCode statusCode In case if you want try to just take all the codes and copy it run go mod download or go mod tidy to get go sum and go mod files I have tested them fully please find Postman collectionpostmainCollection json info postman id bfde a c bd ecfbcd name Learning schema item name Get Albums request method GET header url raw localhost albums page amp perPage host localhost port path albums query key page value key perPage value response name Get Albums By ID request method GET header url raw localhost albums host localhost port path albums response name Post Album request method POST header body mode raw raw r n id r n title newTitle r n artist dfjkfdkj r n price r n options raw language json url raw localhost albums host localhost port path albums response name Update Album request method PUT header body mode raw raw r n id r n title dddf r n artist r n price r n options raw language json url raw localhost albums host localhost port path albums response name Delete Album by ID request method DELETE header url raw localhost albums host localhost port path albums response More sharing of learnings to come Happy unlearn learn relearn Thank you 2022-03-20 11:20:24
海外TECH DEV Community Amazon S3 Storage Classes https://dev.to/aws-builders/amazon-s3-storage-classes-2328 Amazon S Storage ClassesAmazon S offers a range of storage classes for the objects that you store  You choose a class depending on your use case scenario and performance access requirements All storage classes offer high durability Amazon S Storage ClassesS StandardS Intelligent Tiering S Standard IAS GlacierS Glacier Deep ArchieveFor performance sensitive use cases that require millisecond access time and frequently accessed dataS Standard ーThe default storage class If you don t specify the storage class when you upload an object Amazon S assigns the S Standard storage class Storage class for automatically optimizing data with changing or unknown access patternsS Intelligent Tiering is an Amazon S storage class designed to optimize storage costs by automatically moving data to the most cost effective access tier without performance impact or operational overhead Storage classes for infrequently accessed objectsThe S Standard IA and S One Zone IA storage classes are designed for long lived and infrequently accessed data IA stands for infrequent access  S Standard IA ーAmazon S stores the object data redundantly across multiple geographically separated Availability ZonesS One Zone IA ーAmazon S stores the object data in only one Availability Zone which makes it less expensive than S Standard IA However the data is not resilient to the physical loss of the Availability ZoneStorage classes for archiving objectsThe S Glacier and S Glacier Deep Archive storage classes are designed for low cost data archiving S Glacier ーUse for archives where portions of the data might need to be retrieved in minutes Data stored in the S Glacier storage class has a minimum storage duration period of days and can be accessed in as little as minutes using expedited retrieval S Glacier Deep Archive ーUse for archiving data that rarely needs to be accessed Data stored in the S Glacier Deep Archive storage class has a minimum storage duration period of days and a default retrieval time of hours  S Storage Classes Use CasesS Standard Frequently accessed data ad hoc needs short term requirement lt days S Standard IA Requires long term storage for production data with low cost and immediate access for occasssional requestsS One Zone IA  Copy of backup data required in a separate region with minimal access latencyS Glacier Deep Archive  Lowest cost required for long term archival of data for compliance purposesS Lifecycle ManagementAn S Lifecycle configuration is an XML file that consists of a set of rules with predefined actions  transition or expiration action  that you want Amazon S to perform on objects during their lifetime There are two types of actionTransition actions Define when object transition to another storage classExpiration actions Define when objects expire deleted by S S Lifecycle Management Supported Transitions S ReplicationAmazon Simple Storage Service S Replication is an elastic fully managed low cost feature that replicates objects between buckets NB Bucket versioning must have been enabledCross Region Replication CRR Amazon S Cross Region Replication CRR you can replicate objects and their respective metadata and object tags into other AWS Regions for reduced latency compliance security disaster recovery Same Region Replication SRR Amazon S Same Region Replication SRR is an S feature that automatically replicates data between buckets within the same AWS Region for aggregation of logs replication between multiple accounts and data sovereignity S EncryptionServer Side Encryption with S Managed Keys SSE S Unique Object KeysMaster KeyAES Server Side Encryption with AWS KMS Managed Keys SSE KMS KMS Managed KeysCustomer Master KeysCMK can be customer generatedServer Side Encryption With Client Provided Keys SSE C Client Managed KeysNot Stored On AWSClient Side EncryptionClient Managed KeysNot Stored on AWSYou can use AWS KMS CMKS Default EncryptionDefault encryption can be set that all new objects are encrypted when stored in a bucketObjects are encrypted using Server Side EncryptionThere is no change of encryption states of objects that existed in bucket before default encryption was enabledNB Amazon S encrypts object before saving to disk and decrypts them when downloaded S Event Notifications Sends notifications when an event happens in your bucketDestinations include Amazon Simple Notification ServiceAmazon Simple Queue Service SQS queuesAWS LambdaS Select amp Glacier SelectS Select and Glacier Select SQL expression to retrieve individual file from zip archive Server Access LoggingProvides detailed records Logs of request made to Amazon S bucketDetails Include Requester Bucket Name Request Time Request Action Response Status and Error Code If Applicable Must specify a separate bucket as destinationMust grant write permission to Amazon S Log delivery group on destination bucketNB Disabled by defaultRequester PaysRequester Pays feature in Amazon S that allows bucket owners to pass the request and data transfer costs to users who download the data  NB  The bucket owner always pays the cost of storing data Doesn t support Anonymous request BitTorrent and SOAP requestsObject Lock Object Lock can help prevent objects from being deleted or overwritten for a fixed amount of time or indefinitely You can use Object Lock to help meet regulatory requirements that require write once read many  WORM model or to simply add another layer of protection against object changes and deletion NB Versioning must be enabled    This action is permanent Cross Origin Resource Sharing CORS Allows request from an origin to another originOrigin is defined by DNS name  protocol and portEnabled through Access Control Allow OriginAccess Control Allow MethodsAccess Control Allow HeadersNB Rules are defined and added using JSON files in Amazon S 2022-03-20 11:17:04
海外TECH DEV Community Loading external configurations via http using APP_INITIALIZER https://dev.to/ayyash/loading-external-configurations-via-http-using-appinitializer-34i7 Loading external configurations via http using APP INITIALIZERGiven that title I don t think I need to explain So let s get on with it Fetching Configuration from serverEnvironment variables pollute the compiled source code which does not allow for multiple server deployments External configuration allows multiple custom configuration for the same source code The downside is you have to maintain them manually Let s begin by creating the config json file with some keys The full project is on StackBlitz API apiRoot http localhost netlify functions MyKey MyValue The end result in some component is to be able to get the configuration as a property of a service or as a static member Componentconstructor private configService ConfigService ngOnInit void const myValue this configService Config MyKey or const myStaticValue ConfigService Config MyKey APP INITIALZER tokenIn AppModule refer to mysterious three tokens post NgModule imports BrowserModule HttpClientModule CommonModule declarations AppComponent HelloComponent bootstrap AppComponent providers TODO create ConfigService and configFactory provide APP INITIALIZER useFactory configFactory multi true deps ConfigService export class AppModule In a service file for ConfigService export const configFactory config ConfigService gt Observable lt boolean gt gt return gt config loadAppConfig Injectable providedIn root export class ConfigService constructor private http HttpClient retursn observable right now just http get loadAppConfig Observable lt boolean gt return this http get environment configUrl pipe map response gt do something to reflect into local model this CreateConfig response return true catchError error gt if in error set default fall back from environment this CreateConfig defaultConfig return of false The evironment configUrl in development would be the local file ore remote server Later will be elaborating more on strategy of how to handle the config file and location The Config model export interface IConfig API apiRoot string MyKey string The private method to cast configuration should also return default configuration in case of failure The extra configuration though does not have to match IConfig The default fallback config import environment from enviornments dev env export const Config API apiRoot environment apiRoot MyKey default value ExtraKeys wont harm Back to the service the CreateConfig should only try to cast then set to a public property This later is going to fail But let s go on export class ConfigService constructor private http HttpClient private createConfig config any IConfig cast all keys as are const config lt IConfig gt config return config public property public Config IConfig loadAppConfig Observable lt boolean gt return this http get environment configUrl pipe map response gt set to public property this Config this createConfig response return true catchError error gt if in error return set fall back from Config this Config Config return of false The curious case of Router InitializationThe Router Module uses APP INITIALIZE as referenced in master branch of Angular and initialization functions are run in parallel according to source code Without digging deeper into navigation options it is already an open wound that needs to be patched The sequence of events cannot be guaranteed in a module that uses both configuration and Route modules One is going to happen before the other Route guards and resolves are one example of routing happening sooner than initialization response The extreme case I reached after multiple trials The external configuration is remote thus a bit slower than localRouting option InitialNavigation is set to enabledBlocking according to Angular docs this is required for SSR A word of caution leaving the InitialNavigation to its default enableNonBlocking will produce unexpected results in the resolve service Filtering out unready configuration to avoid fallback values the benefit of non blocking is nullified Read the code comments as you go along So let s create an app routing module and add a router resolve with these extreme conditions the routing moduleconst routes Routes path project component ProjectComponent resolve add a project resolve ready ProjectResolve NgModule imports RouterModule forRoot routes enableBlocking for SSR but also enabledNonBlocking is not as good as it sounds in this setup initialNavigation enabledBlocking exports RouterModule export class AppRoutingModule Import the AppRoutingModule into root AppModule add a project component and let s create the project resolve that returns a Boolean Injectable providedIn root export class ProjectResolve implements Resolve lt boolean gt inject the service constructor private configService ConfigService resolve route ActivatedRouteSnapshot state RouterStateSnapshot Observable lt boolean gt log the value of the configuration here if this is too soon the result is undefined console log on resolve this configService Config return of true Running this on Stackblitz and loading the app on project consoles undefined Which means the initial Route Resolve was faster than getting http config result The solution to that if we see it backwards should be like this wait till this configService Config is readyThat translates to RxJS observable So let me head to ConfigService and create an observable of an internal subject much like RxJS state management config serviceexport class ConfigService constructor private http HttpClient keep track of config initialize with fall back Config private config new BehaviorSubject lt IConfig gt Config as IConfig config Observable lt IConfig gt this config asObservable private createConfig config any IConfig cast all keys as are const config lt IConfig gt config return config loadAppConfig Observable lt boolean gt return this http get environment configUrl pipe map response gt const config this createConfig response here next this config next config return true catchError error gt if in error return set fall back from Config this config next Config console log error return of false In the resolve service watching updates is not good enough we need to signal end of stream to return and move on RxJS take is usually recommended but before we take we need to filter out configuration that is not ready yet otherwise that would be the fallback one This is why enableNonBlocking is useless in this setup I hope I m clear if not let me know in the comments and I will try to clear that out in resolve need to take and return This is he first attempt return this configService config pipe take map n gt if n MyKey default the first one will actually be the fallback return false return true attempt two filter before you takereturn this configService config pipe filter n gt n somevalue to distinguish remote config take map n gt if n MyKey default return false it will be true for sure return true last attempt two in one return this configService config pipe first n gt n somevalue to distinguish remote config map n gt always same value return true isServed is my new configuration property to distinguish remote configuration from fallback one It s just a Boolean set to true in remote config config json isServed true API apiRoot http localhost server app MyKey MyValue Add it to the config model and to the default Config config model export interface IConfig isServed boolean API apiRoot string MyKey string the default Config with isServed falseexport const Config isServed false API apiRoot environment apiRoot MyKey default value ExtraKeys wont harm The project resolve is ready Injectable providedIn root export class ProjectResolve implements Resolve lt boolean gt constructor private configService ConfigService resolve route ActivatedRouteSnapshot state RouterStateSnapshot Observable lt boolean gt watch it until it s served return this configService config pipe first n gt n isServed map n gt true The observable in the current setup shall produce two values the first is isServed set to false To read the configuration in a component Component template Project page with resolve lt p gt config async json lt p gt changeDetection ChangeDetectionStrategy OnPush export class ProjectComponent implements OnInit config Observable lt IConfig gt constructor private configService ConfigService ngOnInit void this config this configService config A final touch to garnish for off the track usage we add static getter that returns the value of the configuration config service make a static memberprivate static config IConfig and a static getter with fallbackstatic get Config IConfig return this config Config private createConfig config any IConfig const config lt IConfig gt config set static member ConfigService config config return config This can be used directly for example in template ConfigService Config isServed PitfallsIf the remote configuration does not have all keys expected they will be overwritten to null To overcome extend the configuration via shallow cloning private createConfig config any IConfig shallow extension of fallback const config Config lt IConfig gt config ConfigService config config return config The default Config may be mistaken for ConfigService Config if ever used the default fallback value is in place To fix that a separation between the general Config and remote Config fallback may be needed or a little bit of attention If the config file needed in Route Resolve or Guard fails to be served we re blocked Placing the config file on the same server or a combination of RxJS operators are possible solutions The url of the config file cannot be part of the configuration keys Remember to filter out config url in your HTTP interceptor if you prefix urls with a value fed by configuration Where to place the config fileThe benefit aspired for is to have a production specific configurations for every deployed version ready to be adjusted for whatever prompt reason As much as you would like to believe that touching production is taboo there shall be times when the kitchen is on fire The question is where to place configuration during development Remote server Can be an inhouse local server or a staging server Mock server a nodejs local server that you run before starting Angular On a root folder e g configs served via angular json assetsWherever you decide to place your configuration remember to update respective environments add this to assets in angular json assets glob json input configs output localdata now every configs json will be accessed in dev env as localdata json Inline SSR and other issuesThere is another way to load configuration without HTTP and that is to inject the JS file in the header of the index file To accomplish that come back next week Thank you for tuning in Let me know in the comments if I pressed any wrong buttons This configuration setup is part of the Cricket Seed ResourcesGithub Issue Guards and Resolvers don t wait for APP INITIALIZERUsing absolute URLs for HTTP data requests on the serverRxJS TakeStackblitz 2022-03-20 11:13:08
海外TECH DEV Community LetsDefend SOC143 - Password Stealer Detected https://dev.to/yusiber/letsdefend-soc143-password-stealer-detected-5de LetsDefend SOC Password Stealer DetectedMerhabalar bu yazımızda LetDefend platformu üzerinde bulunan SOC Password Stealer Detected isimli event ID si olan davayıele alacağız LetsDefend platformundan ve mavi takım operasyonlarıbakımından yararlarından daha önceki yazıda bahsetmiştik Hemen davayıüstlenerek başlayalım Genel itibariyle bir bakacak olursak Olay April p m tarihinde gerçekleşmiş nolu IP adresinden bill microsoft com kullanıcısından ellie letsdefend io isimli kullanıcıya gönderilen bir mail içeriyor Cihaz eylemi kabul edilirken mailin içeriği ve konusu belirtilmemişbizden araştırmamız beklenmiş Öncelikle bilgi olarak bize sunulan IP adresini farklıplatformlarda aratıp bilgi edinmeye çalışıyoruz Cisco Talos AbuseIPDB vb çeşitli platformalarda arattık Edindiğimiz bilgilere göre IP Çin çıkışlı Beijing merkezli bir providera ait Şimdi ise LetsDefend platformunda bulunan mailbox bölümüne geçişyapıyoruz ve mail hareketliliğini araştırmaya başlıyoruz Mailbox gt Inbox sekmesinde source olan bill microsoft com u veyahutta tarihi filtreleyip maili kontrol ediyoruz Mail içeriğini inceleyecek olursak herhangi bir metin veya başlık belirtilmeden yalnızca bir zip dosyayıyla karşılaşıyoruz Karşılaştığımız bu zip dosyasınıHybrid Analysis VirusTotal gibi platformlarda araştırıp Zararlıherhangi bir şey içeriyor mu Daha önceki kayıtlarda zararlıbir durumla karşılaşılmışmı gibi sorulara yanıt arıyoruz VirusTotal platformunda arattığımızda farklıaramanın sadece tanesinde şüpheli olduğuna kanaat getirildiğini görüyoruz Hybrid Analysis de arattığımızda ise malicious olarak bildirilen durumlarla karşılaşıyoruz Bu durumlarıdetaylıincelediğimiz vakit içinde barındırdığıdosyanın malware olarak bildirildiğini görüyoruz Tüm bu riskleri göz önünde bulundurarak zip dosyasınısanal makinemiz olan Kali Linux a indirip inceliyoruz İndirip bize verilen infected parolasıyla birlikte dosyayıdışarıçıkarıyoruz ardından zip dosyasından çıkan HTML dosyasınıkontrol etmek üzere VirusTotal ve Hybrid Analysis e başvuruyoruz Dosyayıkontrol edebilmek için mdsum yardımıile dosyamısın MD ınıbuluyoruz Yukarıda görüldüğüüzere HTML dosyamız farklıplatformlarda ağırlıklıolarak malicious olarak bildirilmiş Hybrid Analysis de detaylıolarak incelediğimizde alınan ekran görüntülerinde bir login paneli olduğunu görüyoruz ve phishingden şüpheleniyoruz Bu şüphelerimizi doğrulamak için bize güvenli ortam sağlayan any run platformu üzerinde HTML dosyasınıaçıyoruz Dosyayıaçtıktan sonra gerçekten de görüldüğüüzere bizi bir login ekranıkarşıladı Login ekranında rastgele bir parola giriyoruz ve bizi tecyardit com URL sine yönlendirdiğini görüyoruz URL yi VirusTotal de aratmamızın ardından pek çok kez malicious ve phishin olduğuna kanaat getirildiğini görüyoruz Login ekranından aldığıparola bilgisini ilettiği uçnoktada saklayıp kişisel bilgileri çalan bir çeşit phishing saldırısıolduğunu anlıyoruz Hatta bu seferki kurban direkt kendi adına uygulanan bir spear phishing saldırısıile karşıkarşıya Herşeyin ardından edindiğimiz bu bilgilerin ışığında davayısonlandırmak üzere playbooku açıyoruz İlk soruya dosya bir URL içerdiği için evet yanıtınıveriyoruz İkinci soruda VirusTotal Hybrid Analysis vb sitelerde aratıp malicious durumlarla karşılaştığımız için malicious yanıtınıveriyoruz Mail teslim edildiği için delivered işaretliyoruz Elde ettiğimiz verileri girmemiz için bize verilen bölümüdolduruyoruz ve playbooku tamamlıyoruz Yorumumuzu yapıp davayıbaşarılıbir şekilde kapatıyoruz 2022-03-20 11:09:49
海外ニュース Japan Times latest articles Cabinet support rate rises to 60% on Kishida’s response to war in Ukraine, poll says https://www.japantimes.co.jp/news/2022/03/20/national/politics-diplomacy/japan-kishida-cabinet-survey-ukraine/ Cabinet support rate rises to on Kishida s response to war in Ukraine poll saysNearly of respondents support Japan s sanctions on Russia over its invasion of Ukraine a Kyodo News survey showed Sunday 2022-03-20 20:19:39
ニュース BBC News - Home I will help with costs where I can, says Chancellor Rishi Sunak https://www.bbc.co.uk/news/uk-politics-60812549?at_medium=RSS&at_campaign=KARANGA faces 2022-03-20 11:56:49
ニュース BBC News - Home P&O Ferries' sackings were appalling, says Sunak https://www.bbc.co.uk/news/business-60812328?at_medium=RSS&at_campaign=KARANGA chancellor 2022-03-20 11:50:57
ニュース BBC News - Home Wirral marshland fire may have been started deliberately https://www.bbc.co.uk/news/uk-england-merseyside-60809416?at_medium=RSS&at_campaign=KARANGA peninsula 2022-03-20 11:57:03
ニュース BBC News - Home Great Britain's Scott wins 3,000m bronze at World Athletics Indoor Championships https://www.bbc.co.uk/sport/athletics/60810210?at_medium=RSS&at_campaign=KARANGA Great Britain x s Scott wins m bronze at World Athletics Indoor ChampionshipsMarc Scott claims Great Britain s first medal at the World Athletics Indoor Championships in Belgrade with bronze in the men s m 2022-03-20 11:56:56
サブカルネタ ラーブロ 浅草醤油らーめん きび太郎(TX浅草)/醤油らーめん味玉入り(こってり)+豚飯 http://ra-blog.net/modules/rssc/single_feed.php?fid=197411 浅草醤油らーめんきび太郎TX浅草醤油らーめん味玉入りこってり豚飯さて、時間は巻き戻って約年前の月の初旬。 2022-03-20 11:18:28
北海道 北海道新聞 道東中心に大雪 JR111本運休、道道通行止めも https://www.hokkaido-np.co.jp/article/659228/ 通行止め 2022-03-20 20:32:00
北海道 北海道新聞 仏大統領の支持率42%に上昇 コロナ対応の20年4月以来 https://www.hokkaido-np.co.jp/article/659226/ 日付 2022-03-20 20:27:00
北海道 北海道新聞 米石油・ガス採掘大手がロシア事業停止 新規開発に影響も https://www.hokkaido-np.co.jp/article/659225/ 事業停止 2022-03-20 20:23:00
北海道 北海道新聞 「ホームで胴上げを」 イーグルス連勝にファン歓喜 アジアリーグプレーオフ https://www.hokkaido-np.co.jp/article/659224/ 連勝 2022-03-20 20:18:00
北海道 北海道新聞 胆振管内106人、日高管内2人感染 新型コロナ https://www.hokkaido-np.co.jp/article/659223/ 新型コロナウイルス 2022-03-20 20:16:00
北海道 北海道新聞 渡辺棋王、自己最多10連覇 将棋、タイトル通算30期に https://www.hokkaido-np.co.jp/article/659220/ 永瀬拓矢 2022-03-20 20:08:00
北海道 北海道新聞 国内、3万9659人コロナ感染 死者は66人 https://www.hokkaido-np.co.jp/article/659219/ 新型コロナウイルス 2022-03-20 20:07:00
北海道 北海道新聞 新庄監督、オープン戦で攻守に手応え「いい感じ」 https://www.hokkaido-np.co.jp/article/659216/ 取り組み 2022-03-20 20:07:00
北海道 北海道新聞 ハンドボール、北国銀行が最多の8連覇 男子は豊田合成V https://www.hokkaido-np.co.jp/article/659215/ 北国銀行 2022-03-20 20:07:07
北海道 北海道新聞 高校柔道で顕徳、姥らが優勝 全国選手権第1日 https://www.hokkaido-np.co.jp/article/659214/ 日本武道館 2022-03-20 20:08:05
ビジネス 東洋経済オンライン 「ドラえもん」が50年以上愛され続ける納得理由 藤子・F・不二雄と立川談志、その意外な共通点 | リーダーシップ・教養・資格・スキル | 東洋経済オンライン https://toyokeizai.net/articles/-/536823?utm_source=rss&utm_medium=http&utm_campaign=link_back 東洋経済オンライン 2022-03-20 20:30:00
海外TECH reddit Russia’s elite wants to eliminate Putin, they have already chosen a successor - Intelligence https://www.reddit.com/r/worldnews/comments/tiizbt/russias_elite_wants_to_eliminate_putin_they_have/ Russia s elite wants to eliminate Putin they have already chosen a successor Intelligence submitted by u manticor to r worldnews link comments 2022-03-20 11:24:31
海外TECH reddit 推し店員のいるサイゼリヤに今週も行っちゃうぞーって連休前は思ってたけどいざ連休に入ったら何もする気が起きない。 https://www.reddit.com/r/newsokunomoral/comments/tiisqv/推し店員のいるサイゼリヤに今週も行っちゃうぞーって連休前は思ってたけどいざ連休に入ったら何もする気が/ ewsokunomorallinkcomments 2022-03-20 11:12:17

コメント

このブログの人気の投稿

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

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

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)