- Mar 2022
-
developer.squareup.com developer.squareup.com
-
store.steampowered.com store.steampowered.com
-
War im Weihnachtskalender bei Chip. Habe selten so ein Schwachsinn gesehen. Ich weiß nicht was die Entwickler sich dabei denken. Man läuft einfach nur hin und her. Auch wenn es kostenlos war, die Zeit hätte ich mir sparen können.
-
-
whiteestate.org whiteestate.org
-
Some workers need to give up the slow methods of work which prevail, and to learn to be prompt. Promptness is necessary, as well as diligence. If we wish to accomplish the work according to the will of God, it must be done in an expeditious manner, but not without thought and care.
.
-
There should be regular hours for rising, for family worship, for meals, and for work. And it is a religious duty ... to maintain this by precept ... by a firm example. Many squander the most precious hours of the morning hoping that they can terminate the work thus neglected during the hours which should be devoted to sleep. Godliness, health, success, everything suffers from this lack of true religious system....
.
-
The work of God must not be done by fits and starts. It will not be placed on vantage ground by following a sudden impulse. On the contrary, it is positively necessary to follow the good work patiently, day by day, progressing in our ways and methods. One should get up at a regular hour. If during the day the work is neglected, and the following night is spent in making up for lost time, the morrow and following day will show, as a result, a wearied brain and a general fatigue which constitute positive violations of the law of life and health.
.
-
God has entrusted His sacred work to human beings, and He asks that they shall do it carefully.... They press too many things into their life, postpone until tomorrow that which demands their attention today, and much time is lost in painfully picking up the lost stitches. Men and women can reach a higher degree of usefulness than to carry with them through life an unsettled state of mind. They can improve the defective traits of their character contracted in their younger years. Like Paul, they can labor to reach a much higher degree of perfection.
.
-
-
store.steampowered.com store.steampowered.com
-
4. it will say winenr no matter what, but the color of the winner text will simblize who won. all the dots will also turn that color.
.
-
-
www.imdb.com www.imdb.com
-
The majority of self-help material is little more than inconsequential banal garbage that provides light titillation to its gullible consumers. The Secret, however, is far more insidious. The implicit messages are actually quite reckless and extremely inappropriate. At one point, one of the 'experts' claims that being involved in a car crash is merely a result of your thought patterns and it could have been avoided with more positive thinking. Seriously, he actually said that. How does an incest survivor process this kind of information? Given the type of vulnerable people that will be drawn to a documentary like this, it is actually pretty disgusting to hear such idiotic comments.
.
-
At times it is actually quite hard to discern whether this is just satire, but sadly it is not.
.
-
One of the single worst pieces of television ever made. Every piece of human garbage associated with this repulsive bilge deserves to be publicly shamed.
.
-
-
github.com github.com
-
Gutentag::ActiveRecord.call self
first time I've seen this API in Ruby
Most would just do include Gutentag::ActiveRecord. or acts_as_taggable
-
-
stackoverflow.com stackoverflow.com
-
You could also check if Time.now > @user.last_active+10.minutes before updating to make sure that you aren't constantly writing to the db
efficiency compromise
-
-
discord.com discord.com
-
or the endangerment of public health
unless preventing people from freely discussing/sharing about what information/treatments they believe is effective/helpful for public health ... is actually more harmful to public health than allowing them to freely post.
Tags
Annotators
URL
-
-
dba.stackexchange.com dba.stackexchange.com
-
ARRAY( SELECT DISTINCT ... FROM unnest(arr) )
-
And that can all can be written with CROSS JOIN LATERAL which is much cleaner, SELECT ARRAY( SELECT DISTINCT e FROM ( VALUES ('foo', 'bar', 'foo', 'baz' ) ) AS t(a,b,c,d) CROSS JOIN LATERAL unnest(ARRAY[a,b,c,d]) AS a(e) -- ORDER BY e; -- if you want it sorted );
-
-
riseup.net riseup.net
-
share.riseup.net — file upload (pastebin and imagebin).
-
- Feb 2022
-
ruby-doc.org ruby-doc.org
-
-
There are two pairs of methods for sending/receiving messages: Object#send and ::receive for when the sender knows the receiver (push); Ractor.yield and Ractor#take for when the receiver knows the sender (pull);
-
-
www.instructables.com www.instructables.com
-
When i started using body wash I hit the jackpot. I use a 3 to 1 ratio of water to body wash and get fantastic results with an occasional clog
.
-
it kinda works, but obviously, never as good as the original foaming soap. The reason for that is, the foaming soap has a slightly different formula than regular soap. Specifically, it has more foaming ingredients (like sodium lauryl sulfate / sodium laureth sulfate) and less actual "soap".
.
-
The sad part of it all is that the manufacturers have found yet another way to rip off the consumer. They put one fourth the amount of soap in three fourths H20, change the dispenser slightly and then charge 4 times as much for the finished product. You do the math,
.
-
-
www.jacobsen.no www.jacobsen.no
-
Hence an email address/mailbox/addr-spec is "local-part@domain"; "local-part" is composed of one or more of 'word' and periods; "word" can be an "atom" which can include anything except "specials", control characters or blank/space; and specials (the *only* printable ASCII characters [other than space, if you call space "printable"] *excluded* from being a valid "local-part") are: ()<>@,;:\".[] Therefore by the official standard for email on the internet, the plus sign is as much a legal character in the local-part of an email address as "a" or "_" or "-" or most any other symbol you see on the main part of a standard keyboard.
-
There's a common design flaw on many many websites that require an email address to register; most recently I came across this bug on CNet's download.com site: for some reason they don't accept me when I try to register an email address containing a "+", and they then send me back saying my address is invalid. It isn't!
-
"+" is a completely valid character in an email address; as defined by the internet messaging standard published in 1982(!) RFC 822 (page 8 & 9)... Any website claiming anything else is wrong by definition, plus they are prohibiting me and many fellow anti-spam activists from tracking where inbound spam comes from:
-
-
people.cs.rutgers.edu people.cs.rutgers.edu
-
Screening is a useful way of avoiding spam and/or other unwanted correspondence.
-
Filing is the simplest application to take advantage of plus signs.
-
The "+tag" portion of the email address can then be used both for filing mail and for screening it.
-
-
github.com github.com
-
The current behaviour is definitely broken (at least in my mind). I don't think I'd consider it a feature just because it's been around a while.
-
Given that 5.2 and 6.0 now have this current (broken?) behavior, I wonder if this behavior will now be considered as breaking change.
-
we often work hard to make symbols and strings interchangeable in contexts where it makes sense
-
-
medium.com medium.com
-
-
lateral (select pledged / fx_rate as pledged_usd) pu, lateral (select pledged_usd / backers_count as avg_pledge_usd) apu, lateral (select goal / fx_rate as goal_usd) gu, lateral (select goal_usd - pledged_usd as usd_from_goal) ufg, lateral (select (deadline - launched_at)/86400.00 as duration) dr
-
-
sunfox.org sunfox.org
-
Comment[:article_id].in(Arel.sql(articles_sql))
-
Query values including NULLs Because .where.not can be counter-intuitive regarding NULL values, you can use is_distinct_from to include them. User.where(User[:active].is_distinct_from(true))
-
User.order(User[:email].desc.nulls_last)
-
User.order( Arel::Nodes::Case .new(User[:role]) .when("admin").then(1) .when("editor").then(2) )
-
User.distinct.pluck(User[:created_at].extract("year"))
-
space = Arel.sql("' '") User.pluck(User[:first_name].concat(space).concat(User[:last_name]))
-
User.where(User[:email].matches("%@example.org")) # => SELECT "users".* FROM "users" WHERE "users"."email" ILIKE '%@example.org'
-
User.where(User[:email].lower.eq(email.downcase)) # => SELECT "users".* FROM "users" WHERE LOWER("users"."email") = 'user@example.org'
-
class ApplicationRecord < ActiveRecord::Base def self.[](attribute) arel_table[attribute] end end
-
-
itectec.com itectec.com
-
It's safe to use CROSS JOIN LATERAL (or just , LATERAL) here, because the array constructor always returns a row. Else, if a lateral subquery could come up empty (no row), you would use LEFT JOIN LATERAL (...) ON true to avoid losing rows.
.
-
-
www.postgresql.org www.postgresql.org
-
Although COALESCE, GREATEST, and LEAST are syntactically similar to functions, they are not ordinary functions
-
-
stackoverflow.com stackoverflow.com
-
You can use to_char to convert the timestamp using appropriate format mask: COALESCE(to_char(timestamp_type, 'YYYY-MM-DD'), varchar_col)
-
But it's MUCH better to not rely on datestyle settings for converting date-times to/from text.
-
-
underpassapp.com underpassapp.com
-
underpassapp.com underpassapp.com
-
StopTheMadness is a web browser extension that stops web sites from making your browser harder to use
-
"The good news is that you can wrest control of your browser back from these malicious, control-freak sites."
-
unfortunately only iOS and Mac
see instead: - https://addons.mozilla.org/en-US/firefox/addon/enable-selection/?utm_source=addons.mozilla.org&utm_medium=referral&utm_content=search
-
-
-
Dispatch a custom event. This differs from Svelte's component event system, because these events require a DOM element as a target, can bubble (and do by default), and are cancelable with event.preventDefault(). All SMUI events are dispatched with this instead of Svelte's createEventDispatcher.
-
In addition, a component that uses Svelte's built in event forwarding system cannot allow event listeners on the "capture" phase of the event lifecycle. It also cannot allow events to be cancelable with the browser's built in preventDefault function.
-
This is especially useful for UI library components, as it is generally unknown which events will be required from them for all desired use cases. For example, if a Button component only forwards a click event, then no use case that requires the mouseover or the keypress event can be used with it.
-
-
naturalselections.substack.com naturalselections.substack.com
-
-
This thing has struck a nerve here. Literally overnight millions of people are talking about real things again. But in such an abrupt way, it's odd, like they were suddenly turned on after having been flash frozen for the last two years.
.
-
-
support.google.com support.google.com
-
I want to filter emails to exclude starred message threads. Even a simple "-is:starred" or "-has:yellow-star" does not work.
limitation
-
-
standforhealthfreedom.com standforhealthfreedom.com
-
unix.stackexchange.com unix.stackexchange.com
-
dmsetup remove /dev/dm-5
.
-
udisksctl unlock -b /dev/sdg1
.
-
-
steamcommunity.com steamcommunity.com
-
blog.saeloun.com blog.saeloun.com
-
class Note < ApplicationRecord delegated_type :authorable, types: %w[ Customer Employee ] end
-
-
Checkout this PR to know more about this feature.
typo
-
-
github.com github.com
-
-
The existence of polymorphic associations does not allow the database to enforce referential integrity, however, because no foreign keys can be defined.
-
Good point. In my example, cardinalities would be fundamentally different: an Entry could have_many :messages and have_many :comments. In the original example, a Message could have_many :entries, etc. In either case, there's no way to enforce the cardinalities at the database level (not that I'm aware of).
-
@entry = Entry.create! entryable: Spot.new(params.require(:spot).permit(:address)) redirect_to @entry # Redirects to e.g. /spots/47, with 47 being the newly created Entry id.
-
Delegated types newly introduced here looks like a Class Table Inheritance (CTI).
-
I did a spike to come up with a PoC for introducing this into the codebase of a product that I'm working on (matteeyah/respondo#225) by monkey-patching ActiveRecord with delegated types. It's amazing how can a small code change in ActiveRecord facilitate a big change in the domain model.
-
I just thought that if there was any time to improve the naming it would be now, before rolling it out to thousands of devs/projects. I don't think of that as bikeshedding, personally.
-
I think I might inadvertently have shared plans for a bike shed and opened the floor to which color it should be painted. My sincerest apologies
-
That was my initial reaction too. I think because we are used to talking about delegating behavior, whereas this is delegating subtyping. Or in other words, delegating the ability to be extended with specialized behavior.
we're used to "delegating" meaning...
-
Is the name "delegated type" up for review? I don't see any delegation happening in the code. It looks more like a "subtype", or "secondary type", or something like that.
-
From the text as it is currently written, though, it is not entirely clear what the advantage would be of this new technique vs. using plain composition.
That's not clear to me either
Tags
- delegation (programming)
- easier to figure out now than later after people are using it
- relational database design
- ActiveRecord: associations: delegated_type
- bikeshedding
- annotation meta: may need new tag
- Rails
- polymorphism
- new feature
- I agree
- referential integrity
- naming: the importance of good names
Annotators
URL
-
-
martinfowler.com martinfowler.com
-
A very visible aspect of the object-relational mismatch is the fact that relational databases don't support inheritance. You want database structures that map clearly to the objects and allow links anywhere in the inheritance structure. Class Table Inheritance supports this by using one database table per class in the inheritance structure.
-
-
github.com github.com
Tags
Annotators
URL
-
-
github.com github.com
-
Another strategy is reinforcement learning (aka. constraint learning), as used in some AI systems.
-
has the operator return its first defined argument, then pass over the next defined one in case of a dead-end, in a depth-first selection algorithm.
-
The evaluation may result in the discovery of dead ends, in which case it must "switch" to a previous branching point and start over with a different alternative.
-
They allow for writing nondeterministic programs which contain various alternatives for the program flow.
-
Ambiguous functions
-
-
You may want to jump straight to the Examples section if formal stuff annoys you.
formal stuff annoys you
prefer practical vs. prefer theoretical/academic
-
A continuation is like a savepoint, representing "what's left to run" at a given time.
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
I tested it, and it indeed works, but I don't want to depend on a to-be-removed feature.
-
I am using them in a real life application. I am calculating the available tables for a full calendar with many time slots and with respect to many configurable business rules for restaurants. Using callcc this feature got blazingly fast and very nicely readable. Also we use it to optimise table arrangements with respect to complex restaurant business rules (even something like: Guest A doesn't like to sit near Guest B). Please just have a look at these resources: https://github.com/chikamichi/amb/tree/master/examples http://web.archive.org/web/20151116124853/http://liufengyun.chaos-lab.com/prog/2013/10/23/continuation-in-ruby.html Please help me to keep Guest A away from Guest B. Bad things might happen.
-
"Context" manipulation is one of big topic and there are many related terminologies (academic, language/implementation specific, promotion terminologies). In fact, there is confusing. In few minutes I remember the following related words and it is good CS exam to describe each :p Thread (Ruby) Green thread (CS terminology) Native thread (CS terminology) Non-preemptive thread (CS terminology) Preemptive thread (CS terminology) Fiber (Ruby/using resume/yield) Fiber (Ruby/using transfer) Fiber (Win32API) Generator (Python/JavaScript) Generator (Ruby) Continuation (CS terminology/Ruby, Scheme, ...) Partial continuation (CS terminology/ functional lang.) Exception handling (many languages) Coroutine (CS terminology/ALGOL) Semi-coroutine (CS terminology) Process (Unix/Ruby) Process (Erlang/Elixir) setjmp/longjmp (C) makecontext/swapcontext (POSIX) Task (...)
-
Using callcc this feature got blazingly fast and very nicely readable.
Tags
- deprecated with no replacement
- deprecated
- programming languages: learning/understanding the subtleties
- programming: fibers
- continuations
- nuance
- Ruby
- computer science
- what is the difference/distinction?
- ruby: fibers
- ruby: continuations
- readability
- control flow
- control (programming)
- subtle distinction
- context
Annotators
URL
-
-
ruby-doc.com ruby-doc.com
-
This (somewhat contrived) example allows the inner loop to abandon processing early: callcc {|cont| for i in 0..4 print "\n#{i}: " for j in i*5...(i+1)*5 cont.call() if j == 17 printf "%3d", j end end }
-
-
www.yld.io www.yld.io
-
For example, did you known React has nothing to do with reactive programming?
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
-
Ruby should not completely ignore blocks. const_set :Example, Class.new do p "Hello, world" end # Doesn't print anything, generate any warning nor error. To minimize any impact, Ruby should issue a warning, and in future version could even raise an error. Even unused variables provide warnings in verbose mode, and they have their use. I can't think of a case where passing a block to a builtin method that doesn't accept a block is not a programming error though.
But since it can't be fixed generally, then just add a check in each core method that doesn't accept block, update its def to include a check.
Where I've been bitten by this was some Enumerable method that I assumed took a block. I think it was
first { cond }, and I assumed it worked the same asdetect { cond } -
The remaining problem should be how to declare Ruby-define methods to be 'non-block taking'. Under the current language spec, absence of '& argument' may or may not mean the method would take a block.
-
-
thoughtbot.com thoughtbot.com
-
This solution can hide a bad user experience. We’re not making any DOM changes on AJAX success, meaning Capybara can’t automatically detect when the AJAX completes. If Capybara can’t see it, neither can our users. Depending on your application, this might be OK.
.
-
-
guides.rubyonrails.org guides.rubyonrails.org
-
As of Rails 7.0+, Active Record has an option for handling associations that would perform a join across multiple databases.
impressive
-
-
guides.rubyonrails.org guides.rubyonrails.org
-
You can also use silence_redefinition_of_method if you need to define the replacement method yourself (because you're using delegate, for example).
-
-
guides.rubyonrails.org guides.rubyonrails.org
-
You need to balance several factors: the need for new features, the increasing difficulty of finding support for old code, and your available time and skills, to name a few.
-
-
bugs.ruby-lang.org bugs.ruby-lang.org
-
I am open to discussion but I don't want to jump on the conclusion.
-
The biggest reason is that we still have several options, so I didn't want to restrict the future possibility.
-
Shouldn't the #descendants method be the reverse of #ancestors?
-
-
api.rubyonrails.org api.rubyonrails.org
-
stackoverflow.com stackoverflow.com
-
personally, i think this is useful when you have objects which are not stored in database, as shown in the database, e.g. temperature, gps location, balance, etc. You might ask then why those are not stored in the database? In the database we only store a value, but if we want to attach useful, relevant methods to that value,
-
-
github.com github.com
-
composed_of attr, :class_name => 'AddressableRecord::Address', :converter => :convert, :allow_nil => true,
-
-
en.wikipedia.org en.wikipedia.org
-
In computer science, a value object is a small object that represents a simple entity whose equality is not based on identity: i.e. two value objects are equal when they have the same value, not necessarily being the same object.
Tags
Annotators
URL
-
-
github.com github.com
-
There is nothing stopping you from creating store objects which scrapes XE for the current rates or just returns rand(2):
-
-
github.com github.com
-
For example the german city munich in german München .. both save a city-model with a name translated all app-locales.
doesn't seem all that useful if that's all it does
most place names would be the same in any language
-
-
-
belongs_to :city
-
-
github.com github.com
-
belongs_to :zipcode
-
-
github.com github.com
-
-
Country State (belongs to country) City (belongs to State) Neighborhood (belongs to city)
-
Address (Belongs to Neighborhood and City, because neighborhood is not required)
-
-
github.com github.com
-
biggs is a small ruby gem/rails plugin for formatting postal addresses from over 60 countries.
-
-
-
-
By default the wizard will render a view with the same name as the step. So for our controller AfterSignupController with a view path of /views/after_signup/ if call the :confirm_password step, our wizard will render /views/after_signup/confirm_password.html.erb
-
To send someone to the first step in this wizard we can direct them to after_signup_path(:confirm_password)
-
steps :confirm_password, :confirm_profile, :find_friends
-
Note that render_wizard does attempt to save the passed object. This means that in the above example, the object will be saved twice. This will cause any callbacks to run twice also. If this is undesirable for your use case, then calling assign_attributes (which does not save the object) instead of update might work better.
acceptable
-
-
-
Notice: Another method for partial validations, which might be considered more flexible by some users (allowing for easy validation testing inside model tests), was described by Josh McArthur here.
I liked the linked-to solution
-
The best way to build an object incrementally with validations is to save the state of our product in the database and use conditional validation. To do this we're going to add a status field to our Product class.
.
-
-
people want to have an object, lets call it a Product that they want to create in several different steps
-
-
www.joshmcarthur.com www.joshmcarthur.com
-
-
This action will work a little differently from a normal create action that you might be used to, as it doesn’t strictly need a new action - we won’t be saving this Pet model with any data - just putting it in the database so that our StepsController can access that.
-
Remember, our wizard controller is responsible for showing and updating steps, but our top-level controller is still responsible for managing our Pet models.
-
-
github.com github.com
-
and calls .unarchived and .archived appropriately when passed an ActiveRecord relation.
-
acts_as_tokened Quickly adds rails 5 has_secure_token to your model, along with some Post.find() enhancements to work with tokens instead of IDs.
-
include Effective::CrudController
-
# All queries and objects will be built with this scope resource_scope -> { current_user.posts } # Similar to above, with block syntax resource_scope do Post.active.where(user: current_user) end
-
Loads an appropriate @posts or @post type instance variable.
-
Replaces your Rails controllers, views and forms with meta programming. Considers routes.rb, ability.rb, current_user and does the right thing.
-
The goal of this gem is to reduce the amount of code that needs to be written when developing a ruby on rails website.
Tags
- reduce the amount of boilerplate/duplication
- convention
- inherited_resources (Rails)
- metaprogramming
- MVC (model–view–controller)
- ambitious goal
- ActiveRecord: default scopes
- alternative to mainstream way
- similar to:
- ActiveRecord extensions
- ActiveRecord: archiving
- convention over configuration
- rails
Annotators
URL
-
-
github.com github.com
-
enumerate_by :alpha_2_code
-
-
github.com github.com
-
Note that this is a reference implementation and, most likely, should be modified for your own usage.
-
-
github.com github.com
-
[:state, :zip]
presumably this groups them together more indivisibly, perhaps so they'll show up as a single line, for example?
-
-
www.ruby-toolbox.com www.ruby-toolbox.com
-
www.codeandeffect.com www.codeandeffect.com
-
github.com github.com
-
alias_method :normalize_whitespace_with_warning, :normalize_whitespace def normalize_whitespace(*args) silence_warnings do normalize_whitespace_with_warning(*args) end end
suppress warnings
-
-
thoughtbot.com thoughtbot.com
-
Since factory_bot_rails automatically loads factory definitions as your application loads, writing a definition like this would cause another Daniel to get added to your database every time you start the server or open a console. I like Daniels and all, but there is a limit.
-
-
github.com github.com
-
As a workaround, you can use setters in every affected reactive block instead of direct assignment. let localForm = {}; const setLocalForm = (data) => { localForm = data; }; $: setLocalForm({...$formData});
Tags
Annotators
URL
-
-
github.com github.com
-
Even though not all code smells indicate real problems (think fluent interfaces)
-
-
stackoverflow.com stackoverflow.com
-
At this point I would call into question the job of Event to both be responsible for managing what gets charged and how something should be charged. I would probably investigate moving those to external service classes to keep charging responsibilities out of a simple event object.
-
-
stackoverflow.com stackoverflow.com
-
however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.
seems reasonable
-
Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference. Really - there isn't all that much to it, just different words for the same thing.
-
'method' is the object-oriented word for 'function'. That's pretty much all there is to it (ie., no real difference).
-
a function is a mathematical construct. I would say all methods are functions but not all functions are methods
theory
-
Coming from a functional programming background, I feel there is a profound distinction between function and method. Mainly methods have side effects, and that functions should be pure thus giving a rather nice property of referential transparency
-
I agree it might be nice if "function" and "method" meant what you wanted them to, but your definitions do not reflect some very common uses of those terms.
-
-
blog.qualys.com blog.qualys.com
-
Unfortunately, if the number of command-line arguments argc is 0 – which means if the argument list argv that we pass to execve() is empty, i.e. {NULL} – then argv[0] is NULL. This is the argument list’s terminator.
subtle bug
-
-
- Jan 2022
-
www.ruby-lang.org www.ruby-lang.org
-
Ruby 2.6 introduces an initial implementation of a JIT (Just-In-Time) compiler. The JIT compiler aims to improve the performance of Ruby programs. Unlike traditional JIT compilers which operate in-process, Ruby’s JIT compiler writes out C code to disk and spawns a common C compiler to generate native code. For more details about it, see the MJIT organization by Vladimir Makarov.
-
-
forums.civfanatics.com forums.civfanatics.com
-
For example, if you pre-build a swordman, a spearman and an horseman in 4 cities, you can produce a total of 12 units in 3 turns. This make you save a lot of gold in units maintenance for a good amount of turns.
-
-
steamcommunity.com steamcommunity.com
-
I just didn't realize the harbor needed to be in the capital as well since it says that it creates a city connection with the capital, and doesn't mention that your capital needs one too. I just figured I could get away without one
-
-
unix.stackexchange.com unix.stackexchange.com
-
tr '\n' '\\n' would change newlines to backslashes (and then there's an extra n in the second set). sed 's/\n/\\n/g won't work because sed doesn't load the line-terminating newline into the buffer, but handles it internally.
-
-
stackoverflow.com stackoverflow.com
-
-
This proposal is deeply flawed and would have far-reaching consequences if implemented. In #31148 I proposed a strategy to address the same pain points in a correct, more generic way. Regardless of whether my approach is taken or not, async handling of promises is a core feature that simply cannot be deprecated, and we should remove the erroneous deprecation accordingly.
-
NODE_OPTIONS=--unhandled-rejections=none node
-
-
-
There are other pjax implementations floating around, but most of them are jQuery-based or overengineered. Hence simple-pjax.
Tags
Annotators
URL
-
-
javascript.info javascript.info
-
As said in the chapter, there’s an "implicit try..catch" around the function code. So all synchronous errors are handled. But here the error is generated not while the executor is running, but later. So the promise can’t handle it.
-
new Promise(function(resolve, reject) { setTimeout(() => { throw new Error("Whoops!"); }, 1000); }).catch(alert);
-
-
github.com github.com
-
You cannot try/catch the reactive statement ($: has no effect outside of the top-level) window.onerror does not catch it window.onunhandledrejection does not catch it
.
-
The best you can do is try/catch inside a function that is reactively called, but my goal is to have a global exception handler to handle all exceptions that I did not expect...
-
-
-
It's vanilla JS, doesn't bind you to specifc syntax and that's the main reason why I like svelte that it doesn't try to sandbox you into framework constraints.
-
const originalUnhandledRejection = window.onunhandledrejection; window.onunhandledrejection = (e) => { console.log('we got exception, but the app has crashed', e); // or do Sentry.captureException(e); originalUnhandledRejection(e); }
-
If at least one component has smallest unhandled error, the whole app will crash and users will not know what to do and developers will not know such an error occurred.
-
When an error is thrown inside a Promise it looks like Firefox still calls window.onerror, but Chrome swallows the error silently.
-
Maybe once the core onError lifecycle is implemented (if maintainers decide to go that way) everyone will discover you're right and an implementation will be built in. I think that's probably what's going to happen. But until real life has proved it, it's usually best to go for the smallest most broadly applicable solution. I can definitely imagine <svelte:error> eventually being a thing, but it's a pretty dramatic change compared to an added importable function.
-
Having a consistent and predictable pattern is key to the elegance.
-
I think the issue is that it's not totally perfect. It doesn't define what should happen in parent components, it's not as flexible as onError and it doesn't allow you (for instance) to nest a svelte:head inside, or decide what to do with the rest of the rendering. What do you do with <div>My component</div> in your example? What about changing the <title>? I assume you can inspect the error...does <svelte:error> allow specifying which error types to expect?
-
That's like the example i wrote, and i think it's very ugly. It's annoying when frameworks are very elegant in demos and presentations but then that elegance disappear when you have to write real world code.
-
An annoying thing about frameworks is when they get too opinonated, which is, in my view, a problem React has.
-
const unsubscribe = errorStore.subscribe(value => { if (!value) { return } error = value errorStore.set() })
-
-
blog.atomist.com blog.atomist.com
-
So it is safe to use an async function as the callback argument to setTimer and setInterval. You just need toBe sure to wrap any operations that can throw an exception in a try/catch block andBe aware that the timer will not await on the promise returned by your async function
-
My gut told me calling an async function from the setTimeout callback was a bad thing. Since the setTimeout machinery ignores the return value of the function, there is no way it was awaiting on it. This means that there will be an unhandled promise. An unhandled promise could mean problems if the function called in the callback takes a long time to complete or throws an error.
-
The callback executed by setTimeout is not expected to return anything, it just ignores the returned value. Since once you enter the promise/async world in JavaScript you cannot escape, I was left to wonder what happens when the setTimeout callback returns a promise?
-
-
stackoverflow.com stackoverflow.com
-
test2 being marked async does wrap your return value in a new promise:
-
const rejectedP = Promise.reject('-'); const finallyP = rejectedP.finally(); const result1 = rejectedP; const result2 = new Promise(resolve => { const rejectedP = Promise.reject('-'); const finallyP = rejectedP.finally(); resolve(rejectedP); }); we can see that the first snippet creates two promises (result1 and rejectedP being the same) while the second snippet creates three promises. All of these promises are rejected, but the rejectedP rejection is handled by the callbacks attached to it, both through ….finally() and resolve(…) (which internally does ….then(resolve, reject)). finallyP is the promise whose rejection is not handled in the both examples. In the second example, result2 is a promise distinct from rejectedP that is also not handled, causing the second event.
-
-
stackoverflow.com stackoverflow.com
-
You basically did var a = promise.then(…); var b = promise.catch(…); creating a branch in the chain. If promise is getting rejected now, the catch callback will be called and b will be a fulfilled promise just fine, but the a promise is getting rejected too and nobody handles that. Instead, you should use both arguments of then and write Requirement.create({id: id, data: req.body.data, deleted: false}) .then(requirement => { res.json(requirement); }, reason => { let err = {'error': reason}; res.json(err); });
-
-
stackoverflow.com stackoverflow.com
-
Updates/edits based on comments should preferably be reflected in the question itself. This way other readers don't have to weed out the whole comment section. You find the edit option under the question.
-
-
-
Just "ignoring" a Promise result if it is not longer needed is an antipattern in my opinion.
-
Moving forward I'd rather see {#await} being removed than adding more {#await}. But that's just from my experience and I'm sure there are use-cases for it.
-
I personally abstract everything away into stores. Stores are amazing. With everything I mean things like fetch, Worker or WebSocket.
-
Another limitation is that you are forced into the syntax of the {#await} block. What I mean by that is that for example you can't add a loading class to a parent. You can only render stuff for the loading state in the given block. Nowhere else.
-
export const fibonacci = function (n, initialData) { return readable( { loading: true, error: null, data: initialData, }, (set) => { let controller = new AbortController(); (async () => { try { let result = await fibonacciWorker.calculate(n, { signal: controller.signal }); set({ loading: false, error: null, data: result, }); } catch (err) { // Ignore AbortErrors, they're not unexpected but a feature. // In case of abortion we just keep the loading state because another request is on its way anyway. if (err.name !== 'AbortError') { set({ loading: false, error: err, data: initialData, }); } } })(); return () => { controller.abort(); }; } ); };
-
<script> import { fibonacci } from './math.js'; $: result = fibonacci(n, 0); </script> <input type=number bind:value={n}> <p>The {n}th Fibonacci number is {$result.data}</p> {#if $result.loading} <p>Show a spinner, add class or whatever you need.</p> <p>You are not limited to the syntax of an #await block. You are free to do whatever you want.</p> {/if}
-
Once you've written the imperative library/util code once, your components are super slim and completely reactive/declarative. Wow.
-
Yes I love stores.
-
No need to debounce fetch (terrible UX), just fire them away
-
-
stackoverflow.com stackoverflow.com
-
export const load: Load = async ({ page, session }) => { if (!isPublic(page.path) && !isAuthenticated(session)) { console.log('Unauthorized access to private page'); return { redirect: '/', status: 302 }; } else { console.log('Auth OK'); } return {}; };
-
That whole setup works. If the user logs out, I can just write an empty JWT cookie and clear the $session.jwt value, redirect back to the home page, done.
-
In hooks.js I have a handle function that basically does request.locals.jwt = cookies.jwt, and then a getSession function that returns { jwt: locals.jwt }
-