19,785 Matching Annotations
  1. Mar 2022
    1. The problems with ORMs are numerous, and the above issues only begin to scratch the surface
    2. Object hierarchies are very different from relational hierarchies. Relational hierarchies focus on data and its relationships, whereas objects manage not only data, but also their identity and the behavior centered around that data.
    3. Ruby Object Mapper (rom-rb) is a fast ruby persistence library with the goal of providing powerful object mapping capabilities without limiting the full power of the underlying datastore.
    1. If you need to ensure migrations run in a certain order with regular db:migrate, set up Outrigger.ordered. It can be a hash or a proc that takes a tag; either way it needs to return a sortable value: Outrigger.ordered = { predeploy: -1, postdeploy: 1 } This will run predeploys, untagged migrations (implicitly 0), and then postdeploy migrations.
    2. class PreDeployMigration < ActiveRecord::Migration tag :predeploy end
    3. This is especially useful for zero downtime deploys to Production environments.
    1. The code will work without exception but it doesn’t set correct association, because the defined classes are under namespace AddStatusToUser. This is what happens in reality: role = AddStatusToUser::Role.create!(name: 'admin') AddStatusToUser::User.create!(nick: '@ka8725', role: role)
    1. If the users table is large, running this migration on a live Postgres 9 database will likely cause downtime. Safe PG Migrations hooks into Active Record so that the following gets executed instead: class AddAdminToUsers < ActiveRecord::Migration[5.2] # Do not wrap the migration in a transaction so that locks are held for a shorter time. disable_ddl_transaction! def change # Lower Postgres' lock timeout to avoid statement queueing. Acts like a seatbelt. execute "SET lock_timeout TO '5s'" # The lock_timeout duration is customizable. # Add the column without the default value and the not-null constraint. add_column :users, :admin, :boolean # Set the column's default value. change_column_default :users, :admin, false # Backfill the column in batches. User.in_batches.update_all(admin: false) # Add the not-null constraint. Beforehand, set a short statement timeout so that # Postgres does not spend too much time performing the full table scan to verify # the column contains no nulls. execute "SET statement_timeout TO '5s'" change_column_null :users, :admin, false end end
    1. There are three keys to backfilling safely: batching, throttling, and running it outside a transaction. Use the Rails console or a separate migration with disable_ddl_transaction!.
    2. Active Record creates a transaction around each migration, and backfilling in the same transaction that alters a table keeps the table locked for the duration of the backfill. class AddSomeColumnToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :some_column, :text User.update_all some_column: "default_value" end end
    1. Can you check out whether the polkit permission is even queried by adding a rule /etc/polkit-1/rules.d/10-udisks.rules. polkit.addRule(function(action, subject) { var prefix = "org.freedesktop.udisks"; if (action.id.slice(0, prefix.length) == prefix) polkit.log(action.id); });
    2. echo "TEMP /dev/sdb2 /home/key" >> /etc/crypttab
    3. One of the DEBUG lines near the end of the udiskie output should contain a hint as to why the device was rejected by udiskie.

      .

    4. Let's investigate:

      maintainer willing to help debut

    5. udiskie-mount -v /dev/sdb2 gdbus call --system --dest org.freedesktop.UDisks2 --object-path /org/freedesktop/UDisks2/block_devices/sdb2 --method org.freedesktop.DBus.Properties.GetAll org.freedesktop.UDisks2.Block

      .

    1. No need to construct strings that then need to be deconstructed later.
    2. And events are just data so can process, enrich, filter, aggregate, visualise the data with your own tools.
    3. Because it is cheap to log events, you can freely log plenty.

      .

    4. Event logs are useful, but not as important as process flow (therefore preferable to drop events rather than crashing the process)

      .

    5. I believe we need the break free of these anachronistic designs and use event loggers, not message loggers
    6. In any significant project I worked in the last 15 years, logging text messages resulted in a large amount of strings which was hard to make sense of, thus mostly ignored.

      hard to make sense of, thus mostly ignored

    7. µ/log's idea is to replace the "3 Pillars of Observability" with a more fundamental concept: "the event"

      bold goal

    8. Event-based data is easy to index, search, augment, aggregate and visualise therefore can easily replace traditional logs, metrics and traces.
    1. Modern JavaScript environments will also implement the by ECMA-402 specification, which provides the Intl object
    2. Using Date.parse, or new Date(<string>) has been problematic and implemented inconsistently in the past. The current specification defines parsing a variation of ISO 8601 strings, where date-only forms (like "2020-09-14") are parsed as UTC, instead of local time as they would be by ISO 8601.
    3. not all modern implementations have implemented this specification correctly (e.g., Safari)
    4. You Probably Don't Need Moment.js Anymore You don't (may not) need Moment.js
    5. The Moment team has discussed these issues at length. We recognize that many existing projects may continue to use Moment, but we would like to discourage Moment from being used in new projects going forward. Instead, we would like to recommend alternatives that are excellent choices for use in modern applications today.
    1. The chip was developed as a result of the 1983 video game crash in North America, partially caused by an oversaturated market of console games due to lack of publishing control. Nintendo president Hiroshi Yamauchi said in 1986, "Atari collapsed because they gave too much freedom to third-party developers and the market was swamped with rubbish games."[6] By requiring the presence of the 10NES in a game cartridge, Nintendo prevented third-party developers from producing games without Nintendo's approval, and provided the company with licensing fees
    1. There's an open suggestion at microsoft/TypeScript#13347 to introduce a compiler flag or some other mechanism to more strictly enforce readonly, but it's been around for a long time and it's not clear whether or not this will ever happen.

      may not ever happen...

    1. The cleanest is to give up on readonly properties and instead use some kind of mapping that turns an object into something you really can only read from, via something like getter functions.
    1. Note that this is a breaking API change in the libraries (more information in the README.md). It does not affect the backwards compatibility of the protocol itself.

      annotation meta: may need new tag: backwards compatibility of the protocol backwards compatibility for [libraries that use [it?]]

    2. ambiguous and invisible Unicode characters

      'е' != 'e'

    1. Now if I may ask, if my formatting is happening in multiple places, is this domain logic? I tend to say it is.

      .

    2. One of the toughest decisions that a developer always has to make is to distinguish between domain logic and non-domain logic.

      .

    1. 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.
    1. 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.

      .

    2. 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....

      .

    3. 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.

      .

    4. 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.

      .

    1. 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.

      .

    1. 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.

      .

    2. At times it is actually quite hard to discern whether this is just satire, but sadly it is not.

      .

    3. 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.

      .

    1. Gutentag::ActiveRecord.call self

      first time I've seen this API in Ruby

      Most would just do include Gutentag::ActiveRecord. or acts_as_taggable

    1. 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

    1. 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.

    1. ARRAY( SELECT DISTINCT ... FROM unnest(arr) )
    2. 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 );
    1. share.riseup.net — file upload (pastebin and imagebin).
  2. Feb 2022
    1. 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);
    1. 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

      .

    2. 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".

      .

    3. 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,

      .

    1. 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.
    2. 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!
    3. "+" 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:
    1. 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.
    2. 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.
    3. we often work hard to make symbols and strings interchangeable in contexts where it makes sense
    1. 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
    1. Comment[:article_id].in(Arel.sql(articles_sql))
    2. 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))
    3. User.order(User[:email].desc.nulls_last)
    4. User.order( Arel::Nodes::Case .new(User[:role]) .when("admin").then(1) .when("editor").then(2) )
    5. User.distinct.pluck(User[:created_at].extract("year"))
    6. space = Arel.sql("' '") User.pluck(User[:first_name].concat(space).concat(User[:last_name]))
    7. User.where(User[:email].matches("%@example.org")) # => SELECT "users".* FROM "users" WHERE "users"."email" ILIKE '%@example.org'
    8. User.where(User[:email].lower.eq(email.downcase)) # => SELECT "users".* FROM "users" WHERE LOWER("users"."email") = 'user@example.org'
    9. class ApplicationRecord < ActiveRecord::Base def self.[](attribute) arel_table[attribute] end end
    1. 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.

      .

    1. Although COALESCE, GREATEST, and LEAST are syntactically similar to functions, they are not ordinary functions
    1. You can use to_char to convert the timestamp using appropriate format mask: COALESCE(to_char(timestamp_type, 'YYYY-MM-DD'), varchar_col)
    2. But it's MUCH better to not rely on datestyle settings for converting date-times to/from text.
    1. 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.
    2. 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.
    3. 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.
    1. 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.

      .

    1. I want to filter emails to exclude starred message threads. Even a simple "-is:starred" or "-has:yellow-star" does not work.

      limitation

    1. The existence of polymorphic associations does not allow the database to enforce referential integrity, however, because no foreign keys can be defined.
    2. 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).
    3. @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.
    4. Delegated types newly introduced here looks like a Class Table Inheritance (CTI).
    5. 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.
    6. 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.
    7. 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
    8. 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...

    9. 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.
    10. 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

    1. 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.
    1. Another strategy is reinforcement learning (aka. constraint learning), as used in some AI systems.
    2. 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.
    3. 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.
    4. They allow for writing nondeterministic programs which contain various alternatives for the program flow.
    5. Ambiguous functions
    6. 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

    7. A continuation is like a savepoint, representing "what's left to run" at a given time.
    1. I tested it, and it indeed works, but I don't want to depend on a to-be-removed feature.
    2. 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.
    3. "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 (...)
    4. Using callcc this feature got blazingly fast and very nicely readable.
    1. 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 }
    1. 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 as detect { cond }

    2. 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.
    1. 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.

      .

    1. As of Rails 7.0+, Active Record has an option for handling associations that would perform a join across multiple databases.

      impressive

    1. You can also use silence_redefinition_of_method if you need to define the replacement method yourself (because you're using delegate, for example).
    1. 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.
    1. 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,
    1. 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.
    1. 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

    1. 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
    2. To send someone to the first step in this wizard we can direct them to after_signup_path(:confirm_password)
    3. steps :confirm_password, :confirm_profile, :find_friends
    4. 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

    1. 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

    2. 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.

      .

    3. people want to have an object, lets call it a Product that they want to create in several different steps
    1. 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.
    2. Remember, our wizard controller is responsible for showing and updating steps, but our top-level controller is still responsible for managing our Pet models.
    1. and calls .unarchived and .archived appropriately when passed an ActiveRecord relation.
    2. 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.
    3. include Effective::CrudController
    4. # 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
    5. Loads an appropriate @posts or @post type instance variable.
    6. Replaces your Rails controllers, views and forms with meta programming. Considers routes.rb, ability.rb, current_user and does the right thing.
    7. The goal of this gem is to reduce the amount of code that needs to be written when developing a ruby on rails website.
    1. [:state, :zip]

      presumably this groups them together more indivisibly, perhaps so they'll show up as a single line, for example?