投稿時間:2022-02-13 02:16:02 RSSフィード2022-02-13 02:00 分まとめ(20件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita LINE Botで位置情報を活用する https://qiita.com/ryoutarouh9/items/c3863ec05a8a6517f167 2022-02-13 01:50:46
python Pythonタグが付けられた新着投稿 - Qiita requestsとBeautifulSoupを理解する [ 画像の自動収集 ] https://qiita.com/ryoutarouh9/items/b226fa155af3de90c57c 2022-02-13 01:47:39
python Pythonタグが付けられた新着投稿 - Qiita Detectron2ではじめる画像の物体検出とセグメンテーション https://qiita.com/ryoutarouh9/items/ecaf7feef0336a988875 2022-02-13 01:46:37
python Pythonタグが付けられた新着投稿 - Qiita 音声変換の進展(備忘録も兼ねて) https://qiita.com/lefirea/items/780c764be9a730e14967 前々から「LPCという特徴量がフィルタ的な役割でもある」とは聞いてた。 2022-02-13 01:37:05
js JavaScriptタグが付けられた新着投稿 - Qiita 【のこるんvol.4】3タップ完了LINEフォトアルバム #LINEDC #GAS #AppSheet https://qiita.com/okinakamasayoshi/items/f98bc993caf3cefdcfa9 【今回のトライ】GAS部分のコードを書き変え、LINEで画像とコメントを送付すると、すぐに情報が更新され、WEBアプリとして送った写真とコメントをフォトアルバムとして見れる状態にします。 2022-02-13 01:37:14
Ruby Rubyタグが付けられた新着投稿 - Qiita renderにおけるオプション https://qiita.com/wangqijiangjun/items/37a4d6444a8a4e8a1b55 ltpgtcollectionオプションは、部分テンプレート先でeach処理があるときに使えるオプションです。 2022-02-13 01:56:04
Ruby Railsタグが付けられた新着投稿 - Qiita renderにおけるオプション https://qiita.com/wangqijiangjun/items/37a4d6444a8a4e8a1b55 ltpgtcollectionオプションは、部分テンプレート先でeach処理があるときに使えるオプションです。 2022-02-13 01:56:04
Ruby Railsタグが付けられた新着投稿 - Qiita Herokuのコマンド一覧 https://qiita.com/Shoji__y/items/4e1b60c571715d051c63 2022-02-13 01:07:26
海外TECH MakeUseOf Start Improving Your Life With These 8 Self-Help Blogs https://www.makeuseof.com/start-improving-life-self-help-blogs/ emotional 2022-02-12 16:30:23
海外TECH MakeUseOf How to Fix Windows Media Center Errors on Windows https://www.makeuseof.com/windows-fix-windows-media-center-errors/ center 2022-02-12 16:15:12
海外TECH DEV Community Async vs Defer in javascript https://dev.to/iamrishupatel/async-vs-defer-in-javascript-4ohg Async vs Defer in javascript IntroductionHow many times have you added javascript to your HTML like this lt script src path to some javascript gt lt script gt but have you ever pondered how browser handle that line of code Why do we sometimes pass async or defer attributes to the script tag In this article we ll take a look and understand major differences between async and defer attributes and which one is better to use But first let s understand what if we don t use them at all lt script gt tag without async or deferLet s take a look at the following code lt html lang en gt lt head gt lt title gt Async vs Defer lt title gt lt script src path to some javascript gt lt script gt lt head gt lt body gt lt h gt Async vs Defer lt h gt lt body gt lt html gt When the browser runs this file it starts by parsing the HTML line by line In this example as soon as the browser sees the script tag it stops the HTML parsing and starts to fetch the javascript file and it also executes the javascript line by line immediately after it fetches the javascript file During this fetching of the javascript file the HTML parsing is stopped and this delays the content rendering on DOM and eventually slows down the website This is not a good thing because if you are working on a large project then even a delay of say second might lead people to go back from your website and eventually hurt the revenue We can solve this by using async or defer so let s take a look at them Async Attribute lt script async src path to some javascript gt lt script gt When we use the async attribute in a script tag The browser starts by parsing the HTML file and when the browser sees the script tag it starts fetching the javascript in the background while continuing the HTML parsing Once the script is available to be executed then the browser stops the HTML parsing and executes the Javascript file line by line Once the javascript execution finishes the browser continues the HTML parsing Defer Attribute lt script defer src path to some javascript gt lt script gt The defer attribute is quite similar to async The one difference is that the scripts loaded with defer attribute are not executed until HTML parsing is completely finished What that means is browsers start by parsing HTML and fetches the javascript in the background if it encounters any script tags and continues the HTML parsing Javascript is executed only after the HTML is completely parsed Problem with asyncIf multiple scripts are being used in HTML file and some are dependent on others so in order for them to work correctly we need to make sure that the script on which others are dependent are loaded and executed first in the browsers before the script which is dependent on this script The async attribute does not guarantee the order in which different javascript files are executed Let s take an example lt script async src script gt lt script gt lt script async src script depended on script gt lt script gt lt script async src script depended on script above this gt lt script gt If we use async in this case then it does not guarantee that script will be loaded and executed before the script depended on script because these scripts are being fetched in the background and one might be fetched before the others due to any reason like its size or network issue So if script depended on script is fetched first then it will be executed first because when using async attribute browsers execute the javascript immediately after it is available or downloaded in the browsers defer however guarantees that scripts will be executed in the order even if one is available to the browser before the other because all scripts will be executed after the HTML parsing is done ConclusionIf you have multiple scripts that are dependent on each other then use defer as it guarantees the order of execution If you don t want to block the HTML parsing then use deferI personally recommend using defer most of the time I hope you found this interesting and learned something Thank you Per Aspera Ad Astra 2022-02-12 16:14:23
海外TECH DEV Community Add nestjs nx plugin, create server app and core lib https://dev.to/endykaufman/add-nestjs-nx-plugin-create-server-app-and-core-lib-1l3o Add nestjs nx plugin create server app and core lib Install nestjs plugin to nx monoreponpm install D nrwl nestendy endy virtual machine Projects current kaufman bot npm install D nrwl nestadded packages and audited packages in s packages are looking for funding run npm fund for detailsfound vulnerabilities Add nx script to package json scripts nx nx start nx serve build nx build test nx test Create servernpm run nx g nrwl nest app serverendy endy virtual machine Projects current kaufman bot npm run nx g nrwl nest app server gt kaufman bot nx gt nx g nrwl nest app server UPDATE workspace jsonUPDATE nx jsonCREATE jest config jsCREATE jest preset jsUPDATE package jsonUPDATE vscode extensions jsonCREATE apps server src app gitkeepCREATE apps server src assets gitkeepCREATE apps server src environments environment prod tsCREATE apps server src environments environment tsCREATE apps server src main tsCREATE apps server tsconfig app jsonCREATE apps server tsconfig jsonCREATE apps server project jsonCREATE eslintrc jsonCREATE apps server eslintrc jsonCREATE apps server jest config jsCREATE apps server tsconfig spec jsonCREATE apps server src app app controller spec tsCREATE apps server src app app controller tsCREATE apps server src app app module tsCREATE apps server src app app service spec tsCREATE apps server src app app service tsadded packages removed packages changed packages and audited packages in s packages are looking for funding run npm fund for detailsfound vulnerabilitiesup to date audited packages in s packages are looking for funding run npm fund for detailsfound vulnerabilities Create core librarynpm run nx g nrwl nest lib core serverendy endy virtual machine Projects current kaufman bot npm run nx g nrwl nest lib core server gt kaufman bot nx gt nx g nrwl nest lib core server CREATE libs core server README mdCREATE libs core server babelrcCREATE libs core server src index tsCREATE libs core server tsconfig jsonCREATE libs core server tsconfig lib jsonUPDATE tsconfig base jsonCREATE libs core server project jsonUPDATE workspace jsonCREATE libs core server eslintrc jsonCREATE libs core server jest config jsCREATE libs core server tsconfig spec jsonCREATE libs core server src lib core server module ts 2022-02-12 16:10:33
海外TECH DEV Community How to use Asp Net Core DI & Reflection https://dev.to/nikcio/how-to-use-asp-net-core-di-reflection-1fi1 How to use Asp Net Core DI amp ReflectionWhen using Asp Net Core you have access to dependency injection in many cases but how do you go about creating objects in your code using the same dependency injection What is reflection To start we have to know what reflection is and how to use it Reflection is used to create objects dynamically and can be used to create objects in a generic use case You can for example create an object from the assembly qualified name which can be found on any type like this objectType GetType AssemblyQualifiedName When doing reflection you will be using the Activator object To create an object from the assembly qualified name you found above you would use code like this public object GetReflectedObject object objectType var assemblyQualifiedName objectType GetType AssemblyQualifiedName return Activator CreateInstance Type GetType assemblyQualifiedName I take out the assembly qualified name because I want to show how to decouple the creation logic from any type of object This could make it possible to store the assembly qualified names and first later create the objects Adding DI to reflectionTo add dependency injection you will need to use the IServiceProvider which is used to get dependencies from the Asp Net Core IOC container This can be done with a simple constructor injection like this public class Factory private readonly IServiceProvider serviceProvider public Factory IServiceProvider serviceProvider this serviceProvider serviceProvider Then to add dependency injection we first have to locate a constructor before we can create the object instance with Activator CreateInstance To find the constructor in this example we require a specific object type to be the first in the constructor Then we choose the first that matches that description This can be done like so public void GetConstructor object objectType var type objectType GetType var constructors type GetConstructors var constructor constructors FirstOrDefault constructor gt GetFirstParameter constructor typeof Factory private static Type GetFirstParameter ConstructorInfo constructor return constructor GetParameters FirstOrDefault ParameterType We can then check for any other parameters and get them with the service provider and then we have created Asp Net Core DI amp Reflection public object GetReflectedObject object objectType var requiredFactoryObject new Factory serviceProvider var assemblyQualifiedName objectType GetType AssemblyQualifiedName var parameters GetConstructorParameters objectType var injectedParamerters new object requiredFactoryObject Concat GetDIParamters parameters ToArray return Activator CreateInstance Type GetType assemblyQualifiedName injectedParamerters private IEnumerable lt object gt GetDIParamters ParameterInfo parameters return parameters Skip Select parameter gt serviceProvider GetService parameter ParameterType public ParameterInfo GetConstructorParameters object objectType var type objectType GetType var constructors type GetConstructors return constructors FirstOrDefault constructor gt GetFirstParameter constructor typeof Factory GetParameters private static Type GetFirstParameter ConstructorInfo constructor return constructor GetParameters FirstOrDefault ParameterType And with some extra refactoring you can get this generic factory that can then create an object with a required constructor parameter lt summary gt A factory that can create objects with DI lt summary gt public class DependencyReflectorFactory private readonly IServiceProvider serviceProvider private readonly ILogger lt DependencyReflectorFactory gt logger public DependencyReflectorFactory IServiceProvider serviceProvider ILogger lt DependencyReflectorFactory gt logger this serviceProvider serviceProvider this logger logger lt summary gt Gets the reflected type with DI lt summary gt lt typeparam name T gt lt typeparam gt lt param name typeToReflect gt The type to create lt param gt lt param name constructorRequiredParamerters gt The required parameters on the constructor lt param gt lt returns gt lt returns gt public T GetReflectedType lt T gt Type typeToReflect object constructorRequiredParamerters where T class var propertyTypeAssemblyQualifiedName typeToReflect AssemblyQualifiedName var constructors typeToReflect GetConstructors if constructors Length LogConstructorError typeToReflect constructorRequiredParamerters return null var parameters GetConstructor constructors constructorRequiredParamerters GetParameters if parameters null LogConstructorError typeToReflect constructorRequiredParamerters return null object injectedParamerters null if constructorRequiredParamerters null injectedParamerters parameters Select parameter gt serviceProvider GetService parameter ParameterType ToArray else injectedParamerters constructorRequiredParamerters Concat parameters Skip constructorRequiredParamerters Length Select parameter gt serviceProvider GetService parameter ParameterType ToArray return T Activator CreateInstance Type GetType propertyTypeAssemblyQualifiedName injectedParamerters lt summary gt Logs a constructor error lt summary gt lt param name typeToReflect gt lt param gt lt param name constructorRequiredParamerters gt lt param gt private void LogConstructorError Type typeToReflect object constructorRequiredParamerters string constructorNames string Join constructorRequiredParamerters Select item gt item GetType Name string message Unable to create instance of typeToReflect Name Could not find a constructor with constructorNames as first argument s logger LogError message lt summary gt Takes the required paramters from a constructor lt summary gt lt param name constructor gt lt param gt lt param name constructorRequiredParamertersLength gt lt param gt lt returns gt lt returns gt private ParameterInfo TakeConstructorRequiredParamters ConstructorInfo constructor int constructorRequiredParamertersLength var parameters constructor GetParameters if parameters Length lt constructorRequiredParamertersLength return parameters return parameters Take constructorRequiredParamertersLength ToArray lt summary gt Validates the required parameters from a constructor lt summary gt lt param name constructor gt lt param gt lt param name constructorRequiredParameters gt lt param gt lt returns gt lt returns gt private bool ValidateConstructorRequiredParameters ConstructorInfo constructor object constructorRequiredParameters if constructorRequiredParameters null return true var parameters TakeConstructorRequiredParamters constructor constructorRequiredParameters Length for int i i lt parameters Length i var requiredParameter constructorRequiredParameters i GetType if parameters i ParameterType requiredParameter return false return true lt summary gt Gets a constructor lt summary gt lt param name constructors gt lt param gt lt param name constructorRequiredParameters gt lt param gt lt returns gt lt returns gt private ConstructorInfo GetConstructor ConstructorInfo constructors object constructorRequiredParameters return constructors FirstOrDefault constructor gt ValidateConstructorRequiredParameters constructor constructorRequiredParameters This code example was originally from Nikcio UHeadlessOriginal file can be found here 2022-02-12 16:08:46
海外TECH DEV Community Spring Kafka Streams playground with Kotlin - IV https://dev.to/thegroo/spring-kafka-streams-playground-with-kotlin-iv-aea Spring Kafka Streams playground with Kotlin IV ContextThis post is part of a series where we create a simple Kafka Streams Application with Kotlin using Spring boot and Spring Kafka Please check the first part of the tutorial to get started and get further context of what we re building If you want to start from here you can clone the source code for this project git clone git github com mmaia simple spring kafka stream kotlin git and then checkout v git checkout v and follow from there continuing with this post In this post we re going to create our QuoteStream we will process messages from the quote topic and do a join with the GlobalKTable for leverage we created in the previous post we will then do branching and send quotes to three different topics based on it s keys Creating a Quote StreamLet s now create a stream from the stock quotes topic and join with Leverage GlobalKTable we created in the last post we will use a stream join and if there s a Leverage for that specific quote we enrich the quote and publish it to one topic based on it s key This will demonstrate the usage of branching to separate data for post processing which is quite common use case In our sample application we will produce the data to one of three new topics we will produce ant Apple quotes to a topic Google quotes to another topic and all other quotes to the third topic AAPL gt apple stocks topicGOOGL gt google stocks topicAny others gt all other stocks topicIn order to do that our first step is to create those topics using the Admin client Add the following constants to the KafkaCofiguration class const val AAPL STOCKS TOPIC apple stocks topic const val GOOGL STOCKS TOPIC google stocks topic const val ALL OTHER STOCKS TOPIC all other stocks topic Change the appTopics function on the same class to also create those three new topics Beanfun appTopics NewTopics return NewTopics TopicBuilder name STOCK QUOTES TOPIC build TopicBuilder name LEVERAGE PRICES TOPIC compact build TopicBuilder name AAPL STOCKS TOPIC build TopicBuilder name GOOGL STOCKS TOPIC build TopicBuilder name ALL OTHER STOCKS TOPIC build The next time you run the application those new topics will be created using the admin client Let s now add the new schema definition which we will use for those new topics create a new avro schema file under src gt main gt avro called processed quote with the following content namespace com maia springkafkastreamkotlin repository type record name ProcessedQuote fields name symbol type string name tradeValue type double name tradeTime type null long default null name leverage type null double default null Notice that the difference in this case is just a new leverage field which we will use to enrich the incoming quote with the value if they match Build the project so the java code is generate for this new avro schema mvn clean package DskipTests Let s now create a new class on the repository package called QuoteStream we will need a reference to our Leverage GlobalKTable so we use Spring Boot dependency injection Repositoryclass QuoteStream val leveragepriceGKTable GlobalKTable lt String LeveragePrice gt On this class declare a function to process and enrich the quote Beanfun quoteKStream streamsBuilder StreamsBuilder KStream lt String ProcessedQuote gt In this function create a KStream which will process the data from the stock quotes topic do a join with the GlobalKTable we created for leverage and transform in the new Avro Type ProcessedQuote enriching the quotes with leverage if it s available val stream KStream lt String StockQuote gt streamsBuilder stream STOCK QUOTES TOPIC val resStream KStream lt String ProcessedQuote gt stream leftJoin leveragepriceGKTable symbol gt symbol stockQuote leveragePrice gt ProcessedQuote stockQuote symbol stockQuote tradeValue stockQuote tradeTime leveragePrice leverage and to wrap up this function we will tap in the new Stream and based on the Key we will send the message to specific topics and return the new stream so we can re use it later for other operations KafkaStreamBrancher lt String ProcessedQuote gt branch symbolKey gt symbolKey equals APPL ignoreCase true ks gt ks to AAPL STOCKS TOPIC branch symbolKey gt symbolKey equals GOOGL ignoreCase true ks gt ks to GOOGL STOCKS TOPIC defaultBranch ks gt ks to ALL OTHER STOCKS TOPIC onTopOf resStream return resStream If you just want to get your local code to this point without using the presented code you can checkout v git checkout vCool now we can play around a bit with it let s build and run our application make sure your local kafka setup is running mvn clean package DskipTests amp amp mvn spring boot runYou can then send some leverage messages and quote messages using the APIs as we did before in this tutorial And you can check the messages being enriched if the specific quote has a leverage and flowing to the three different topics based on their keys here s some screenshots from the topics I took while playing around with the project using Conduktor The messages seem duplicated on the screenshots but that s because I sent them multiple times with the same values while playing around I also sent a few before sending the respective leverage so you can see what happens and check that the initial ones on the bottom have a null leverage That s it for now Tomorrow I will be publishing part V of this tutorial where we will use grouping counting and calculate volume using Kafka Streams DSL Stay tuned Photo by Nubelson Fernandes on Unsplash 2022-02-12 16:04:45
海外TECH DEV Community SOLID Principles -Object Oriented Programming in PHP https://dev.to/dalelantowork/solid-principles-object-oriented-programming-in-php-3p3e SOLID Principles Object Oriented Programming in PHPSOLID is an acronym for the first five object oriented design OOD principles by Robert C Martin also known as Uncle Bob These principles establish practices that lend to developing software with considerations for maintaining and extending as the project grows Adopting these practices can also contribute to avoiding code smells refactoring code and Agile or Adaptive software development SOLID stands for S Single responsiblity PrincipleO Open closed PrincipleL Liskov Substitution PrincipleI Interface Segregation PrincipleD Dependency Inversion PrincipleNow let s talk about the first one Single Responsibility Principle A Class Should Have One And Only One Responsibility It means that if our class assumes more than one responsibility we will have a high coupling The cause is that our code will be fragile at any changes Suppose we have a User class like the following lt phpclass User private email Getter and setter public function store Store attributes into a database In this case the method store is out of the scope and this responsibility should belong to a class that manages the database The solution here is to create two classes each with proper responsibilities lt phpclass User private email Getter and setter class UserDB public function store User user Store the user into a database Now let s move on to the O in SOLIDOpen closed PrincipleObjects or entities should be open for extension but closed for modification According to this principle a software entity must be easily extensible with new features without having to modify its existing code in use Suppose we have to calculate the total area of some objects and to do that we need an AreaCalculator class that does only a sum of each shape area The issue here is that each shape has a different method to calculate its own area lt phpclass Rectangle public width public height public function construct width height this gt width width this gt height height class Square public length public function construct length this gt length length class AreaCalculator protected shapes public function construct shapes array this gt shapes shapes public function sum area foreach this gt shapes as shape if shape instanceof Square area pow shape gt length else if shape instanceof Rectangle area shape gt width shape gt height return array sum area If we add another shape like a Circle we have to change the AreaCalculator in order to calculate the new shape area and this is not sustainable The solution here is to create a simple Shape interface that has the area method and will be implemented by all other shapes lt phpinterface Shape public function area class Rectangle implements Shape private width private height public function construct width height this gt width width this gt height height public function area return this gt width this gt height class Square implements Shape private length public function construct length this gt length length public function area return pow this gt length class AreaCalculator protected shapes public function construct shapes array this gt shapes shapes public function sum area foreach this gt shapes as shape area shape gt area return array sum area In this way we will use only one method to calculate the sum and if we need to add a new shape it will just implement the Shape interface The third principle in SOLID L stands for Liskov Substition PrincpleLet q x be a property provable about objects of x of type T Then q y should be provable for objects y of type S where S is a subtype of T The principle says that objects must be replaceable by instances of their subtypes without altering the correct functioning of our system I know this is hard to understand so I separated the meaning in parts Child function arguments must match function arguments of parent Child function return type must match parent function return type Child pre conditions cannot be greater than parent function pre conditions Child function post conditions cannot be lesser than parent function post conditions Exceptions thrown by child method must be the same as or inherit from an exception thrown by the parent method To fully understand this here s a scenario Imagine managing two types of coffee machine According to the user plan we will use a basic or a premium coffee machine the only difference is that the premium machine makes a good vanilla coffee plus than the basic machine lt phpinterface CoffeeMachineInterface public function brewCoffee selection class BasicCoffeeMachine implements CoffeeMachineInterface public function brewCoffee selection switch selection case ESPRESSO return this gt brewEspresso default throw new CoffeeException Selection not supported protected function brewEspresso Brew an espresso class PremiumCoffeeMachine extends BasicCoffeeMachine public function brewCoffee selection switch selection case ESPRESSO return this gt brewEspresso case VANILLA return this gt brewVanillaCoffee default throw new CoffeeException Selection not supported protected function brewVanillaCoffee Brew a vanilla coffee function getCoffeeMachine User user switch user gt getPlan case PREMIUM return new PremiumCoffeeMachine case BASIC default return new BasicCoffeeMachine function prepareCoffee User user selection coffeeMachine getCoffeeMachine user return coffeeMachine gt brewCoffee selection The main program behavior must be the same for both machines The fourth principle I stands for Interface Segregation PrincipleA client should never be forced to implement an interface that it doesn t use or clients shouldn t be forced to depend on methods they do not use This principle defines that a class should never implement an interface that does not go to use In that case means that in our implementations we will have methods that don t need The solution is to develop specific interfaces instead of general purpose interfaces Here s a scenario imagine we invent the FutureCar that can both fly and drive… lt phpinterface VehicleInterface public function drive public function fly class FutureCar implements VehicleInterface public function drive echo Driving a future car public function fly echo Flying a future car class Car implements VehicleInterface public function drive echo Driving a car public function fly throw new Exception Not implemented method class Airplane implements VehicleInterface public function drive throw new Exception Not implemented method public function fly echo Flying an airplane The main issue as you can see is that the Car and Airplane have methods that don t use The solution is to split the VehicleInterface into two more specific interfaces that are used only when it s necessary like the following lt phpinterface CarInterface public function drive interface AirplaneInterface public function fly class FutureCar implements CarInterface AirplaneInterface public function drive echo Driving a future car public function fly echo Flying a future car class Car implements CarInterface public function drive echo Driving a car class Airplane implements AirplaneInterface public function fly echo Flying an airplane Last but not the least is D which stands for Dependency Inversion PrincipleEntities must depend on abstractions not on concretions It states that the high level module must not depend on the low level module but they should depend on abstractions This principle means that a particular class should not depend directly on another class but on an abstraction of this class This principle allows for decoupling and more code reusability Let s get the first example of the UserDB class This class could depend on a DB connection lt phpclass UserDB private dbConnection public function construct MySQLConnection dbConnection this gt dbConnection dbConnection public function store User user Store the user into a database In this case the UserDB class depends directly from the MySQL database That means that if we would change the database engine in use we need to rewrite this class and violate the Open Close Principle The solution is to develop an abstraction of database connection lt phpinterface DBConnectionInterface public function connect class MySQLConnection implements DBConnectionInterface public function connect Return the MySQL connection class UserDB private dbConnection public function construct DBConnectionInterface dbConnection this gt dbConnection dbConnection public function store User user Store the user into a database This code establishes that both the high level and low level modules depend on abstraction Hurray We are done with the SOLID Principle of Object Oriented Programming You can use these principles represent the state of the art of the code quality and following them permit you to write software that will be easily extended reusable and refactored Projects that adhere to SOLID principles can be shared with collaborators extended modified tested and refactored with fewer complications 2022-02-12 16:04:40
海外TECH DEV Community Express Error Handling https://dev.to/adidoshi/express-error-handling-7nd Express Error HandlingError Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously Error handling often doesn t get the attention amp prioritization it deserves but it s important to remember all it takes is one unhandled error leak into your user interface to override all the seconds you helped your users save There are so many components involved in a successful functioning web application it is essential to foolproof your application by preparing for all possible errors and exceptions Let s begin then Overview Errors can be divided into two types operational amp programming errors Programming errors are the bugs that occurs from the developers code on the other hand operational error will inevitably happen when users will interact with our web app It may include invalid paths server failing to connect amp invalid user input We should be prepared for these errors in advance by creating a global custom error handling middleware Error middleware Middleware functions in Express come into play after the server receives the request and before the response fires to the client They have access to the request and the response objects They can be used for any data processing database querying making API calls sending the response or calling the next middleware function using the next function Let s take a simple example where the request path doesn t match the defined routes If you try to visit a route other than suppose you will see an error status error Not found otherwise if error not handled it would be in plain html like Creating an error class A common practice is to take the initial Error object and expand on it with our own class class ErrorHandler extends Error constructor message statusCode super message this statusCode statusCode this status statusCode startsWith fail error Error captureStackTrace this this constructor The super function only takes message as an argument because that s what Error takes initially Then we add a statusCode property and a status that derives from statusCode Finally the captureStackTrace line prevents this class from showing up in the stack trace which is part of the console log that shows where in code the error occurred For example with this error class lets rewrite our above code app use req res next gt next new ErrorHandler Can t find req originalUrl on this server Catching Errors in Async FunctionsMostly while developing an API we come around writing async functions for database query sending response Until now we ve used try catch blocks to catch errors in our async await functions to give you an example const createPost async req res gt const desc location pic req body try if desc pic location res status json Please fill all the details else const newPost new Post user req user id desc location img pic const createdPost await newPost save res status json createdPost catch error next error but they make our code look messy The best way to avoid try catch in your node js application is to wrap your function call into a higher order function const catchAsync fn gt return req res next gt fn req res next catch next This is a function catchAsync where I m passing three parametes req res next object which will be passed as standard from our express function here it means we wrap our func call into Promise amp next means that pass it to the next function in the chain Let s wrap our above createPost function into this const createPost catchAsync async req res next gt const desc location pic req body if desc pic location return next new ErrorHandler Fill all the details else const newPost new Post user req user id desc location img pic const createdPost await newPost save res status json createdPost Wohoo Finally we get rid of try catch as now any route function you wrap inside this catchasync that will automatically catch the errors Note We also have an NPM package express async handler which works in a similar way amp inside which we can wrap our route function but understanding how things works behind the scenes will help us a lot Production vs development errors We want to send understandable clean error messages to the user However in development we want as much information as possible We ll access our environment variable and send back responses accordingly Stack trace It is used to trace the active stack frames at a particular instance during the execution of a program The stack trace is useful while debugging code as it shows the exact point that has caused an errorconst sendErrorDev err res gt res status err statusCode json status err status message err message stack err stack const sendErrorProd err res gt res status err statusCode json status err status message err message module exports err req res next gt err statusCode err statusCode err message err message Internal Server Error if process env NODE ENV development sendErrorDev err res else if process env NODE ENV production sendErrorProd err res To explain the main function code it says err statusCode if any or statusCode which is the error caused by the server Further we can also handle mongoose errors which are helpful in case of model properties check if any Mongoose errors can include duplicate key error if err code const message Duplicate Object keys err keyValue entered err new ErrorHandler message Generally when we create express API s we divide our code into a specific structure called Model view controller mvc design pattern which is good practice to have as a developer With this we have middleware s which also include error middleware we talked about That s it hope reading this post made you understand proper error handling practices in nodejs amp you try it in your upcoming projects Thankyou for visiting 2022-02-12 16:04:33
海外TECH DEV Community How to combine and summarize excel/CSV files in Python? https://dev.to/laraneedscoffee/how-to-combine-and-summarize-excelcsv-files-in-python-4581 How to combine and summarize excel CSV files in Python This is the begging of a series to share simple and short lines of code in Python that helped me to automate my work Scenario You have monthly sales reports for the year and your need to put them all in one file to create a yearly report and generate simple statistics How can we do that Prerequisites All files must have the same set of columns same name spelling and number Have all files in one folder All files must have the same extension either xlsx cvs Any version of Python mine is You will need the below libraries glob pandas os Set upFirst install the above libraries if you do not have them installed already You can use the below commands and tweak them depending on the IDE you use I use Spyder Spyder pip install pandas pip install os pip install glob Importing the files Set up the pathpath r C Folder Name Get the list of filesThis will get for us the names of all the excel csv files in the particular folder we specified in the path file list glob glob path xlsx Just change xlsx to csv throughout the code and it will work the same Importing the filesThis is a for loop that will go through each file we got in the file list read it as a data frame and put it inside a list of data frames by appending it to the list excel list for file in file list excelFile pd read excel file excelFile fileName os path basename file excel list append excelFile Merging the files into one Concatenating the files into one data frameexcel merged pd concat excel list ignore index True Export the file to the same pathexcel merged to excel path All Lists xlsx index False Create summary and basic statistsGet all columns in the dataexcel merged columns tolist Generate a general summary of the dataexcel merged describe This will give stats of all numeric columns mean medium STD count max min etc You can use the below to get stats on a certain numeric columnexcel merged column name describe Get stats group by certain monthsummary excel merged groupby Month Sales Value describe summaryThis will show us statistics on sales per month it is a good indicator to see if we have peaks or low sales in certain months Plot the dataf ax plt subplots ax bar x excel merged Month height excel merged Sales color purple ax set title Plot of Sales per Month plt show TroubleshootingIn case a file was missing ensure that the file is in the file list and it has the same extension and is in the folder If you have more columns than the original lists this means there is a file with either extra columns or does not have the same spelling Throughout the codes just change the path from xlsx to csv and it will work the same Well done 2022-02-12 16:03:00
Apple AppleInsider - Frontpage News Satechi 3-in-1 Magnetic Wireless Charging Stand review: difficult to justify the high price https://appleinsider.com/articles/22/02/12/satechi-3-in-1-magnetic-wireless-charging-stand-review-difficult-to-justify-the-high-price?utm_medium=rss Satechi in Magnetic Wireless Charging Stand review difficult to justify the high priceThe Satechi in Magnetic Wireless Charging Stand looks good on your desk or bedside table but while W iPhone charging and weak feeling magnets may not justify its high price the removable Apple Watch charger may be enough to save it The Satechi in Wireless Charging StandSatechi s charging stand can charge your iPhone Apple Watch and AirPods in a single dedicated device However there are a few setbacks when compared to other similar bedside chargers Read more 2022-02-12 16:02:57
海外TECH Engadget Apple reportedly increases pay of many US retail employees https://www.engadget.com/apple-us-retail-employee-compensation-increase-165044322.html?src=rss Apple reportedly increases pay of many US retail employeesApple is reportedly handing out raises to many of its retail employees in the US According to Bloomberg the company has increased the pay of some of its retail workers including sales staff Genius Bar support personnel and senior hourly workers by as much as percent The exact number depends on the store where each employee works and their specific role According to the outlet the hikes don t apply to all employees and nbsp some have only seen their compensation increase by about two percent The pay hikes come in the same week Apple reportedly expanded benefits for all of its US retail employees Per Bloomberg the company will offer both full time and part time staff at all of its stores nationwide increased sick days paid parental leave and more starting April th The moves are a response to a tight labor market Like many other businesses Apple has struggled to recruit and retain hourly workers during the pandemic Staffing shortages due to COVID exposures and infections have led to multiple store closures in recent months Retail staff have also complained of poor working conditions that involve low pay and stressful workloads Over the same time period Apple has recorded multiple record breaking fiscal quarters 2022-02-12 16:50:44
海外TECH Engadget Hitting the Books: How crop diversity became a symbol of Mexican national sovereignty https://www.engadget.com/hitting-the-books-endangered-maize-helen-anne-curry-uc-press-163015768.html?src=rss Hitting the Books How crop diversity became a symbol of Mexican national sovereigntyBeginning in the s Mexico s Green Revolution saw the country s agriculture industrialized on a national scale helping propel a massive decades long economic boom in what has become known as the Mexican Miracle Though the modernization of Mexico s food production helped spur unparalleled market growth these changes also opened the industry s doors to powerful transnational seed companies eroding national control over the genetic diversity of its domestic crops and endangering the livelihoods of Mexico s poorest farmers nbsp In the excerpt below from her new book Endangered Maize Industrial Agriculture and the Crisis of Extinction author and Peter Lipton Lecturer in History of Modern Science and Technology at Cambridge University Helen Anne Curry examines the country s efforts to maintain its cultural and genetic independence in the face of globalized agribusiness UC PressExcerpted from Endangered Maize Industrial Agriculture and the Crisis of Extinction by Helen Anne Curry Published by University of California Press Copyright by Helen Anne Curry All rights reserved Amid the clatter and hum generated by several hundred delegates and observers to the Conference of FAO a member of the Mexican delegation took the floor Participants from member nations had already reviewed the state of global agricultural production assessed and commended ongoing FAO programs agreed on budget appropriations and wrestled over the wording of numerous conference resolutions The Mexican representative opened discussion on yet another draft resolution this one proposing “The Establishment of an International Plant Germplasm Bank Two interlocked elements lie at the resolution s heart a collection of duplicate samples of all the world s major seed collections under the control of the United Nations and a legally binding international agreement that recognized “plant genetic resources as the “patrimony of humanity Together the bank and agreement would ensure the “availability utilization and non discriminatory benefit to all nations of plant varieties in storage and in cultivation across the globe Today international treaties are integral to the conservation and use of crop genetic diversity The Convention on Biological Diversity aims to ensure the sustainable and just use of the world s biodiversity which includes plant genetic resources Meanwhile the International Treaty on Plant Genetic Resources for Food and Agriculture also called the Seed Treaty establishes protocols specific to crop diversity Although it draws much of its power from the Convention on Biological Diversity the roots of the Seed Treaty reach further back to the resolution of the Mexican delegation and beyond Mexico s resolution like today s Seed Treaty offered conservation as a principal motivation It told a story of farmers varieties displaced by breeders products the attrition of genetic diversity and the looming “extinction of material of incalculable value Earlier calls for conservation had sketched the same picture Yet those who prepared and promoted the Mexican proposal mobilized this narrative to different ends They may well have wanted to protect crop diversity Far more important however was the guarantee of access to this diversity once conserved They insisted that a seed bank governed by the United Nations and an international treaty were needed to prevent the “monopolization of plant genetic materials This monopolization came in the form of control by national governments the ultimate decision makers for most existing seed banks It also resulted from possession by transnational corporations By exercising intellectual property protections in crop varieties seed companies could take ownership of these varieties even if they were derived from seeds sourced abroad In other words the survival of a seed sample in a base collection or its duplicate did not mean this sample was available to breeders let alone farmers in its own place of origin Binding international agreements were necessary to ensure access Mexico s intervention at the FAO Conference was just one volley in what would later be called the seed wars a decades long conflict over the granting of property rights in plant varieties and the physical control of seed banks Allusions to endangered crop diversity have been mostly rhetorical flourishes in this debate deployed in defense of other things considered threatened by agricultural changeーnamely peoples and governments across Africa Asia and Latin America in the later twentieth century Seed treaties were meant to protect not seeds but sovereignty Between the late s and the early s in the midst of this struggle over seeds consensus fractured about the loss of crop diversityーor more specifically about the meaning of this loss When experts had gathered at FAO in the s to discuss genetic erosion most saw this as an inevitable consequence of a beneficial transition Wherever farmers opted for breeders lines over their own seeds the value of these so called improved lines was confirmed and agricultural productivity inched forward In the s genetic erosion featured centrally in a very different narrative It was offered as evidence of the misguided ideas and practices driving agricultural development especially the Green Revolution and of the dangers posed by powerful transnational seed companies Corporate greed emerged as a new driver of crop diversity loss The willingness of wealthy countries to sustain this greed through friendly regulations meant both were complicit in undermining the capacities of developing countries to feed themselves The extinction of farmers varieties and landraces was no longer an accepted byproduct of agricultural modernization It was an argument against this development This shift pitted scientists committed to saving crop diversity against activists ostensibly interested in the same thing It brought competing visions of what agriculture could and should be head to head Invocations of the imminent loss of crop diversity the one element everyone seemed able to agree on reached a fever pitch during the seed wars This rhetorical barrage often obscured on the ground realities While FAO delegates government officials NGO activists and prominent scientists waged a war of words in meeting rooms and magazines plant breeders and agronomists tended experimental plots tested genetic combinations and presented farmers with varieties they hoped would be improvements In s Mexico some of these researchers were newly resolved to use Mexican seeds and methods to address the needs of the country s poorest farmers Keeping these individuals their methods and their corn collections in view grounds the seed wars in actual seeds If the Mexican delegation s invocation of crop diversity at FAO in was a rhetorical flourish in a bid to defend national sovereignty the concurrent use of crop diversity by some Mexican breeders was a practical strategy for getting Mexican agriculture out from under the thumb of the United States and transnational agribusinesses On the ground seeds were not ornaments in oratory but the very stuff of sovereignty Inroads for AgribusinessWhile scientists in Mexico searched for novel solutions to the country s rural crises critical assessments of agricultural aid bolstered the case for these alternatives By the mid s studies by economists sociologists and other development experts indicated that the much vaunted Green Revolution had done more harm than help thanks especially to the input and capital intensive model of farming it espoused The first critiques of the Green Revolution followed close on the heels of its initial celebration In the Oxford economist Keith Griffin joined a growing chorus when he cataloged the harms introduced with “high yielding varieties a phrase used to describe types bred to flourish with synthetic fertilizers Their introduction had neither increased income per capita nor solved the problems of hunger and malnutrition according to Griffin They had produced effects however “The new technology has accelerated the development of a market oriented capitalist agriculture It has hastened the demise of subsistence oriented peasant farming It has increased the power of landowners especially the larger ones and this in turn has been associated with a greater polarization of classes and intensified conflict In Griffin thought that the ultimate outcome depended on how governments responded to these changes Five years later he had come to a final determination “The story of the green revolution is a story of a revolution that failed he declared Griffin was a researcher on the project “Social and Economic Implications of the Large Scale Introduction of High Yielding Varieties of Foodgrain Carried out under the auspices of the United Nations Research Institute for Social Development this project enlisted social scientists to document the uptake of new agricultural technologies ーchiefly new crop varieties ーand their social and economic effects across Asia and North Africa Mexico was also included among the project s case studies since organizers pinpointed it as the historical site of the “first experiments in high yielding seeds for modernizing nations An attempt to synthesize a single account from the case studies in the s highlighted the problems arising from the integration of farmers into national and international markets New varieties chemical fertilizers and mechanical equipment demanded that cultivators quot become businessmen competent in market operations and small scale financing and receptive to science generated information quot This was thought to be in marked contrast to their having once been quot artisan cultivators who drew on tradition and locally valid practices quot to sustain their families The fact that only a minority of better off farmers could make such a transition meant that development programs benefited a few at the expense of the many Drawing on her case study of Mexico project contributor Cynthia Hewitt de Alcántara extended this observation about market integration into a reflection on the flow of economic resources around and out of the country ーfrom laborers to landowners from farms to industries from national programs to foreign businesses The reconfiguration of agriculture as what she labeled a quot capitalist enterprise quot had not brought more money to the countryside but instead robbed peasants of what little they had This apparent contradiction in Mexico s agricultural development invited scrutiny from many besides Hewitt The preceding three decades had been characterized by steady economic growth thanks to increased international trade during World War II government policies that encouraged national industry and investments in infrastructure and education This period of the so called Mexican Miracle had also seen a transition from food dependency ーneeding to import grain to feed the nation ーto self sufficiency At this level of abstraction Mexico s prospects for sustaining adequate food and nutrition looked rosy When sociologists and economists delved into specifics however the miracle revealed itself a mirage Investments in agriculture had focused on supplying food to urban workers and developing new products for export State food aid programs too had been oriented to urban labor with set prices that kept food affordable for consumers in the city but made its cultivation unprofitable for farmers in the countryside While well off cultivators in the north of the country benefited from state funded irrigation programs and guaranteed prices poor farmers working small plots without access to state grain purchasers found that they could not sustain their families by selling surplus corn Hewitt estimated that in one third of the Mexican population experienced calorie deficiency A national survey came to similar conclusions calculating that million Mexicans over a quarter of the population suffered from malnutrition The persistence of poverty in Mexico in spite of the country s celebrated economic growth could be traced to the model of development embraced by national leaders since the s Politicians and policy makers had assumed that subsistence farmers could be made irrelevant with their surplus labor absorbed into the growing industrial economy Yet industry had not acted the sponge with the result that this “irrelevant segment of the population had grown while continuing to be neglected by the state The economist David Barkin linked faulty Mexican policies to a more fundamental problem of emulating the market capitalism of its northern neighbor The apparently flourishing Mexican economy had invited the interest of foreign investors in particular US corporations Despite protectionist policies these companies had moved in and national industries had been sold off leaving Mexicans vulnerable to the whims of private capital Agriculture offered a prime example of this pattern By the s US firms dominated across the sector from farm machinery John Deere International Harvester to chemicals Monsanto DuPont American Cyanamid to production and processing United Brands Corn Products to animal feed Ralston Purina Observing this trend another economist pinpointed Mexican agriculture as the place of origin of a “new world wide modernization strategy He traced a path from the interventions of the Rockefeller Foundation to the stimulus these gave to the importation of costly agricultural inputs to the management of Mexican farms by foreign firms Foreign control and deepening ties to international markets affected food self sufficiency It made sense from the perspective of increasing individual profits for large and well financed producers in Mexico to focus on the crops that would bring the best prices These were more likely to be fruits and vegetables for US supermarkets or sorghum to feed cattle than corn or wheat to feed Mexican workers Thanks to these patterns it was possible to see much of Mexican agriculture as an extension of US agribusiness operating chiefly “to exploit Mexican rural labor Mexican land and water resources and Mexican private and public capital for the principal benefit of US entrepreneurs The ultimate outcome of technical assistance to enhance agricultural production ostensibly undertaken for the betterment of Mexican farmers and the Mexican economy was the dominance of transnational companies in that very task for their own aggrandizement This portended ill for Mexico and especially for the poorest Mexicans 2022-02-12 16:30:15

コメント

このブログの人気の投稿

投稿時間: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件)