99 Matching Annotations
  1. Mar 2024
    1. When you need to publish multiple packages and want to avoid your contributors having to open PRs on many separate repositories whenever they want to make a change.
    2. when projects want to keep strict boundaries within their code and avoid becoming an entangled monolith. This is for example the case for Yarn itself, or many enterprise codebases.
  2. Jan 2024
    1. Instance methods Instances of Models are documents. Documents have many of their own built-in instance methods. We may also define our own custom document instance methods. // define a schema const animalSchema = new Schema({ name: String, type: String }, { // Assign a function to the "methods" object of our animalSchema through schema options. // By following this approach, there is no need to create a separate TS type to define the type of the instance functions. methods: { findSimilarTypes(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); } } }); // Or, assign a function to the "methods" object of our animalSchema animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); }; Now all of our animal instances have a findSimilarTypes method available to them. const Animal = mongoose.model('Animal', animalSchema); const dog = new Animal({ type: 'dog' }); dog.findSimilarTypes((err, dogs) => { console.log(dogs); // woof }); Overwriting a default mongoose document method may lead to unpredictable results. See this for more details. The example above uses the Schema.methods object directly to save an instance method. You can also use the Schema.method() helper as described here. Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work.

      Certainly! Let's break down the provided code snippets:

      1. What is it and why is it used?

      In Mongoose, a schema is a blueprint for defining the structure of documents within a collection. When you define a schema, you can also attach methods to it. These methods become instance methods, meaning they are available on the individual documents (instances) created from that schema.

      Instance methods are useful for encapsulating functionality related to a specific document or model instance. They allow you to define custom behavior that can be executed on a specific document. In the given example, the findSimilarTypes method is added to instances of the Animal model, making it easy to find other animals of the same type.

      2. Syntax:

      Using methods object directly in the schema options:

      javascript const animalSchema = new Schema( { name: String, type: String }, { methods: { findSimilarTypes(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); } } } );

      Using methods object directly in the schema:

      javascript animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); };

      Using Schema.method() helper:

      javascript animalSchema.method('findSimilarTypes', function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); });

      3. Explanation in Simple Words with Examples:

      Why it's Used:

      Imagine you have a collection of animals in your database, and you want to find other animals of the same type. Instead of writing the same logic repeatedly, you can define a method that can be called on each animal instance to find similar types. This helps in keeping your code DRY (Don't Repeat Yourself) and makes it easier to maintain.

      Example:

      ```javascript const mongoose = require('mongoose'); const { Schema } = mongoose;

      // Define a schema with a custom instance method const animalSchema = new Schema({ name: String, type: String });

      // Add a custom instance method to find similar types animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); };

      // Create the Animal model using the schema const Animal = mongoose.model('Animal', animalSchema);

      // Create an instance of Animal const dog = new Animal({ type: 'dog', name: 'Buddy' });

      // Use the custom method to find similar types dog.findSimilarTypes((err, similarAnimals) => { console.log(similarAnimals); }); ```

      In this example, findSimilarTypes is a custom instance method added to the Animal schema. When you create an instance of the Animal model (e.g., a dog), you can then call findSimilarTypes on that instance to find other animals with the same type. The method uses the this.type property, which refers to the type of the current animal instance. This allows you to easily reuse the logic for finding similar types across different instances of the Animal model.

      Certainly! Let's go through each part and explain it in simple terms: ### 1. `this` in Mongoose: - **What is `this`?** In JavaScript, `this` refers to the current context or object. In Mongoose, particularly within methods and middleware functions, `this` represents the instance (document) the function is currently operating on. - **Why is it used?** `this` is used to access and modify the properties of the current document. For example, in a Mongoose method, `this` allows you to refer to the fields of the specific document the method is called on. ### 2. Example: Let's use the `userSchema.pre("save", ...)`, which is a Mongoose middleware, as an example: ```javascript userSchema.pre("save", async function (next) { if (!this.isModified("password")) { next(); } else { this.password = await bcrypt.hash(this.password, 10); next(); } }); ``` - **Explanation in Simple Words:** - Imagine you have a system where users can sign up and set their password. - Before saving a new user to the database, you want to ensure that the password is securely encrypted (hashed) using a library like `bcrypt`. - The `userSchema.pre("save", ...)` is a special function that runs automatically before saving a user to the database. - In this function: - `this.isModified("password")`: Checks if the password field of the current user has been changed. - If the password is not modified, it means the user is not updating their password, so it just moves on to the next operation (saving the user). - If the password is modified, it means a new password is set or the existing one is changed. In this case, it uses `bcrypt.hash` to encrypt (hash) the password before saving it to the database. - The use of `this` here is crucial because it allows you to refer to the specific user document that's being saved. It ensures that the correct password is hashed for the current user being processed. In summary, `this` in Mongoose is a way to refer to the current document or instance, and it's commonly used to access and modify the properties of that document, especially in middleware functions like the one demonstrated here for password encryption before saving to the database.

    Tags

    Annotators

    URL

    1. It's also common to want to compute the transitive closure of these relations, for instance, in listing all the issues that are, transitively, duped to the current one to hunt for information about how to reproduce them.
    2. Purpose of the relations should be to allow advanced analysis, visualization and planning by third-party tools or extensions/plugins, while keeping Gitlab's issues simple and easy to use.
  3. Dec 2023
  4. Sep 2023
    1. Recent work has revealed several new and significant aspects of the dynamics of theory change. First, statistical information, information about the probabilistic contingencies between events, plays a particularly important role in theory-formation both in science and in childhood. In the last fifteen years we’ve discovered the power of early statistical learning.

      The data of the past is congruent with the current psychological trends that face the education system of today. Developmentalists have charted how children construct and revise intuitive theories. In turn, a variety of theories have developed because of the greater use of statistical information that supports probabilistic contingencies that help to better inform us of causal models and their distinctive cognitive functions. These studies investigate the physical, psychological, and social domains. In the case of intuitive psychology, or "theory of mind," developmentalism has traced a progression from an early understanding of emotion and action to an understanding of intentions and simple aspects of perception, to an understanding of knowledge vs. ignorance, and finally to a representational and then an interpretive theory of mind.

      The mechanisms by which life evolved—from chemical beginnings to cognizing human beings—are central to understanding the psychological basis of learning. We are the product of an evolutionary process and it is the mechanisms inherent in this process that offer the most probable explanations to how we think and learn.

      Bada, & Olusegun, S. (2015). Constructivism Learning Theory : A Paradigm for Teaching and Learning.

  5. Aug 2023
    1. async vs. sync depends exactly on what you are doing in what context. If this is in a network service, you need async. For a command line utility, sync is the appropriate paradigm in most simple cases, but just knee-jerk saying "async is better" is not correct. My snippet is based on the OP snippet for context.
  6. May 2023
    1. human values and ethics, rather than solely pursuing technological progress.

      I ask whether technology is classic Pandora's Box--once the attitude is out, you cannot re-box it. Or at least we haven't figured out a way.

      Once this margin has been populated with annotations I want to redo the prompt to include them as an alternative point of view in the dialogue.

  7. Nov 2022
    1. It can be useful to use with keywords argument, which required symbol keys.
    1. For example, if I make an application (Client) that allows a user (Resource Owner) to make notes and save them as a repo in their GitHub account (Resource Server), then my application will need to access their GitHub data. It's not secure for the user to directly supply their GitHub username and password to my application and grant full access to the entire account. Instead, using OAuth 2.0, they can go through an authorization flow that will grant limited access to some resources based on a scope, and I will never have access to any other data or their password.
  8. Sep 2022
    1. Consumers can use the status member to determine what the original status code used by the generator was, in cases where it has been changed (e.g., by an intermediary or cache), and when message bodies persist without HTTP information. Generic HTTP software will still use the HTTP status code.
  9. Aug 2022
    1. The instructions here for "Postman Collection" might be useful on the portal, but are they too complex? Is there anything we can do (such as purchase a Postman team license) to streamline this part of the work? Ask the ProServ Team.

    1. Beyond memory leaks, it's also really useful to be able to re-run a test many times to help with tracking down intermittence failure and race conditions.
  10. May 2022
    1. The shared context worked though thanks! RSpec.shared_context "perform_enqueued_jobs" do around(:each) { |example| perform_enqueued_jobs { example.run } } end RSpec.configure do |config| config.include_context "perform_enqueued_jobs" end

      use case for around

    1. 1/ It fits into existing spec based testing infrastructure nicely, including running on travis, code coverage using SimpleCov, switching between generating a profile (RubyProf), a benchmark (Benchmark::IPS) or normal test run. 2/ Some of my benchmarks do have expect clauses to validate that things are working before invoking the benchmark.

      Answering the question:

      I don't understand the point of putting it in a spec. What does that gain you over using benchmark-ips the normal way?

    2. I just wanted to mention there was, IMHO, a valid use case for this. It helps add to the validity of the ticket and the design of the feature.
  11. Apr 2022
    1. Let's imagine your project talks to databases, supports several, and has adapters for each one of them. Those adapters may have top-level require calls that load their respective drivers: # my_gem/db_adapters/postgresql.rb require "pg" but you don't want your users to install them all, only the one they are going to use.
    2. There are project layouts that put implementation files and test files together.
    3. Let's suppose that your gem decorates something in Kernel:
    1. if Rails.application.config.reloading_enabled? Rails.autoloaders.main.on_unload("Country") do |klass, _abspath| klass.expire_redis_cache end end
    2. If your application decorates classes or modules from an engine,
    3. Some projects want something like app/api/base.rb to define API::Base, and add app to the autoload paths to accomplish that.
    4. By default, app/models/concerns belongs to the autoload paths and therefore it is assumed to be a root directory. So, by default, app/models/concerns/foo.rb should define Foo, not Concerns::Foo.
    1. I am not looking for model based after commits on update/create/etc, I want to be able to dynamically define a block that will be executed only if the current (top-most) transaction passes:
    2. This would work if your transaction only wraps a single model's save operation. I need to wrap at least Node + Version + Attachment

      looking for a callback that you can register to happen after current transaction is committed, not just after_commit of model -- though actually, that might fire precisely when current transaction is committed, too (except that it might only get triggered for nested transactions, not the top-most transaction), so it could maybe go there ... but I think the problem is just that it doesn't belong there, because it's not specific to the model...

      I guess the OP said it best:

      I am not looking for model based after commits on update/create/etc, I want to be able to dynamically define a block that will be executed only if the current (top-most) transaction passes:

    1. You want the front page to show a few hundred posts along with the top three comments on each post. You’re planning on being very popular, so the front page will need to be very fast. How do you fetch that data efficiently from postgresql using Activerecord?
    2. Making one Comment query per Post is too expensive; it’s N+1 queries (one to fetch the posts, N to fetch the comments). You could use includes to preload all the comments for all the posts, but that requires hydrating hundreds of thousands of records, even though you only need a few hundred for your front page. What you want is some kind of GROUP BY with a LIMIT on each group — but that doesn’t exist, either in Activerecord nor even in postgres. Postgres has a different solution for this problem: the LATERAL JOIN.
    1. Let's say the user is in the process of selecting some files. The names don't indicate anything. So she has to listen and select.
    1. When a web page is viewed on a screen with a large physical size (assuming a maximised browser window), the author might wish to include some less relevant parts surrounding the critical part of the image. When the same web page is viewed on a screen with a small physical size, the author might wish to show only the critical part of the image.
  12. Mar 2022
    1. This has cropped up in particular when trying to create a copy of a store object when the store changes (which is a common use case with forms where you don't want to mutate the global store until the form is saved).

      Exactly! This is more or less the same kind of use case I tend to have: intentionally having/wanting a stale/out-of-date copy of a (reactive) object.

    1. This is particularly useful in cases where you want to separate your data migrations from your schema migrations or where you have multiple steps in your migration process that must have other steps invoked throughout.
    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.
  13. Feb 2022
    1. 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.
  14. Jan 2022
    1. My case is that I have a component which takes an object as a prop. As the user changes the object's values, they can either Save or Cancel. So in the component I have two variables: value and valueUnsaved. It's similar to the example on my comment above. To avoid mutating the original object directly, I assign valueUnsaved as a deep clone of value. If value is changed outside of the component, valueUnsaved should be updated.
    1. Thunderbird provides the ability to archive messages - that is, to move them from the default folders to archive folders without deleting the messages altogether. This makes it easy to organize archives or move them to a backup device, and keep the Inbox clean. Messages can only be archived manually, not automatically.
  15. Nov 2021
  16. Oct 2021
    1. This function allows you to modify (or replace) a fetch request for an external resource that happens inside a load function that runs on the server (or during pre-rendering). For example, your load function might make a request to a public URL like https://api.yourapp.com when the user performs a client-side navigation to the respective page, but during SSR it might make sense to hit the API directly (bypassing whatever proxies and load balancers sit between it and the public internet).
  17. Sep 2021
    1. One good use for /dev/tty is if you're trying to call an editor in a pipeline (e.g., with xargs). Since the standard input of xargs is some list of files rather than your terminal, just doing, e.g., | xargs emacs will screw up your terminal. Instead you can use | xargs sh -c 'emacs "$@" </dev/tty' emacs to connect the editor to your terminal even though the input of xargs is coming from elsewhere.
  18. Jul 2021
  19. Jun 2021
    1. for cpp_file in *.cpp; do gcc -c $$cpp_file & done; wait This gives much finer control than make -j.
    2. There is one very important reason for enabling job control to be useful inside scripts: the side-effect it has of placing background processes in their own process groups. This makes it much, much easier to send signels to them and their children with one simple command: kill -<signal> -$pgid. All other ways of dealing with signaling entire trees of processes either involve elaborate (sometimes even recursive) functions, which are often bugnests, or risk killing the parent in the process (no pun intended).
    1. These tests should only be used when: the functionality/component being tested is small the internal state of the objects/database needs to be tested it cannot be tested at a lower level
    1. Thanks, this was just what I was looking for! This is a perfect appropriate use of instance_eval. I do not understand the nay-sayers. If you already have your array in a variable, then sure, a.reduce(:+) / a.size.to_f is pretty reasonable. But if you want to "in line" find the mean of an array literal or an array that is returned from a function/expression — without duplicating the entire expression ([0,4,8].reduce(:+) / [0,4,8].length.to_f, for example, is abhorrent) or being required to assign to a local, then instance_eval option is a beautiful, elegant, idiomatic solution!!
    2. instance_eval is analogous to using tap, yield_self, … when you are dealing with a chain of method calls: do use it whenever it's appropriate and helpful! And in this case, I absolutely believe that it is.
    3. instance_eval lets you run the code while only specifying a once, so it can be chained with other commands. I.e. random_average = Array.new(10) { rand(10) }.instance_eval { reduce(:+) / size.to_f } instead of random = Array.new(10) { rand(10) }; random_average = random.reduce(:+) / random.size
  20. May 2021
    1. also it's can be helpful for geo deploying when your browser should get access to closest API by GeoDNS but server part can touch neighborhood server or same server.

      "geo deploy"

    1. Make it easier to manage people and control visibility. Give people different permissions depending on their group membership.
    2. Organize large projects. For large projects, subgroups makes it potentially easier to separate permissions on parts of the source code.
  21. Apr 2021
    1. With Stack Overflow for Teams being a flexible platform, we’ve seen customers use it for a wide variety of use cases: A platform to help onboard new employees A self-serve help center to reduce support tickets Collaboration and documentation to drive innersource initiatives Breaking down silos and driving org wide transformation like cloud migration efforts A direct customer support platform Enable people who are working towards a common goal, whether a startup or a side project, to develop a collective knowledge base
  22. Mar 2021
    1. Application: 3-D Shape RegistrationAn important problem in model-based recognition is to find the transformation of a set of datapoints that yields the best match of these points against a shape model. The process is oftenreferred to asdata registration. The data points are typically measured on a real object by rangesensors, touch sensors, etc., and given in Cartesian coordinates. The quality of a match is oftendescribed as the total squared distance from the data pointsto the model. When multiple shapemodels are possible, the one that results in the least total distance is then recognized as the shapeof the object.Quaternions are very effective in solving the above least-squares-based registration problem.
    1. There is obvious connections between the flow paths of a use case and its test cases. Deriving functional test cases from a use case through its scenarios (running instances of a use case) is straightforward.
    2. With content based upon an action or event flow structure, a model of well-written use cases also serves as an excellent groundwork and valuable guidelines for the design of test cases
  23. Feb 2021
    1. ActiveInteraction also supports merging errors. This is useful if you want to delegate validation to some other object. For example, if you have an interaction that updates a record, you might want that record to validate itself. By using the #merge! helper on errors, you can do exactly that.
    1. think about them as a text/markup equivalent to the way a video or another media file would be embedded
    2. but I wouldn't use a frameset for anything but a manual since it no longer exists in html5. Example: Game maker manual
  24. Jan 2021
    1. toppings on a spreadsheet sundae.🍨🍦

      One of my fav toppings is to use Google Forms. Sheets is integrated completely there. In fact this is practically my only use case for google sheets so I am grateful for discussion of add-ons and other uses.

    2. I use sheets for organizing lists of people, topics and grades, as well as managing budgets, ideas and plans.

      Use case #1. How might I use it? How might others use it?

    1. Maybe $$slots like $$props? My use case is that I'd like to wrap a slot's content in an element that applies styling that I'd like absent without the slotted content. Something like this: {#if $$slots.description} <div class="description"> <slot name="description"></slot> </div> {/if}
    1. If components gain the slot attribute, then it would be possible to implement the proposed behavior of <svelte:fragment /> by creating a component that has a default slot with out any wrappers. However, I think it's still a good idea to add <svelte:fragment /> so everyone who encounters this common use case doesn't have to come up with their own slightly different solutions.
    1. I want to make some add-ons or wrappers on components e.g BigButton.svelte <script> import Button from './Button.svelte' </script> <Button fz="16" h="64" {...$$props}> <slot slot="prepend" name="prepend" /> <slot /> <slot slot="append" name="append" /> </Button>
  25. Oct 2020
    1. Looks like the problem is that debounce defaults to waiting for 0 ms ... which is completely useless!

      It would be (and is) way to easy to omit the 2nd parameter to https://lodash.com/docs/4.17.15#debounce.

      Why is that an optional param with a default value?? It should be required!

      There must be some application where a delay of 0 is useless. https://www.geeksforgeeks.org/lodash-_-debounce-method/ alludes to / implies there may be a use:

      When the wait time is 0 and the leading option is false, then the func call is deferred until to the next tick.

      But I don't know what that use case is. For the use case / application of debouncing user input (where each character of input is delayed by at least 10 ms -- probably > 100 ms -- a delay of 0 seems utterly useless.

    1. trusktr herman willems • 2 years ago Haha. Maybe React should focus on a template-string syntax and follow standards (and provide options for pre-compiling in Webpack, etc).

      Well anywho, there's other projects now like hyperHTML, lit-html, etc, plus some really fast ones: https://www.stefankrause.ne...

      React seems a little old now (and the new Hooks API is also resource heavy).

      • Share ›  Michael Calkins trusktr • 4 years ago • edited That's a micro optimization. There isn't a big enough difference to matter unless you are building a game or something extraordinarily odd.

      • Share › −  trusktr Michael Calkins • 2 years ago True, it matters if you're re-rendering the template at 60fps (f.e. for animations, or for games). If you're just changing views one time (f.e. a URL route change), then 100ms won't hurt at all.

  26. Aug 2020
    1. More information about limitations and exceptions to copyright

      Under more information about limitations and exceptions to copyright add section titled Case Studies: Case studies provide valuable information relating to the state of affairs in various countries, as well as the opposing views when debating copyright issues.

      • South Africa: a case study of politics and the global economics of limitations and exceptions to copyright. The current debate in South Africa regarding proposed amendments to the Copyright Bill allows showcases the different sides of the debate, and how legal frameworks, e.g. the Constitution of the Republic of South Africa also informs decision making.
      1. US Government Threatening To Kill Free Trade With South Africa After Hollywood Complained It Was Adopting American Fair Use Principles, by Mike Masnick, 4 November 2019.
      2. South Africa’s Copyright Amendment Bill – one year on, by Denise Nicholson, 30 March 2020. This work is licensed under a Creative Commons Attribution 4.0 International License.
      3. South Africa’s Copyright Amendment Bill Returned to Parliament for Further Consideration, Mike Palmedo, 22 June 2020. This work is licensed under a Creative Commons Attribution 4.0 International License.
      4. See the light and pass the Copyright Amendment Bill, by Mugwena Maluleke, Tebogo Sithathu, Jack Devnarain, Tusi Fokane, Ben Cashdan and Jace Nair, 24 June 2020. © Mail & Guardian Online.
      5. South African President’s Reservations to Copyright Bill Not Supported by Law, by Sean Flynn, 13 July 2020. This work is licensed under a Creative Commons Attribution 4.0 International License.

      For a comprehensive list of materials relating to the South African Copyright Amendment Bill processes, see Copyright and Related Issues: USTR GSP trade threats re: Bill, list compiled and amended by Denis Nicholson

  27. Jul 2020
    1. Matz, alas, I cannot offer one. You see, Ruby--coding generally--is just a hobby for me. I spend a fair bit of time answering Ruby questions on SO and would have reached for this method on many occasions had it been available. Perhaps readers with development experience (everybody but me?) could reflect on whether this method would have been useful in projects they've worked on.
  28. Nov 2019
  29. Jun 2019
  30. Feb 2016
    1. Searches for tortoise food web and area meteorological data in the region at the DataONE portal. Searches for land-use histories, especially for former grazing lands. Searches for co-locality data for other animal species as possible signals for other ecological changes in the region.