text:
---
layout: post
title: Mastering User Interface Design A Step by Step Introduction to Wireframes
subtitle: From Concept to Creation, A Guide to UI Design and Wireframing Techniques
tags:
  [
       business analysis,
       project management,
  ]
image: /assets/img/diary.png
bigimg: /assets/img/back.gif
thumbnail-img: /assets/img/diary.png
share-img: /assets/img/diary.png
cover-img: /assets/img/cover.jpg
---

User Interface (UI) design plays a pivotal role in creating engaging and intuitive digital experiences. It involves designing the visual elements and interactive components that users interact with when using a website, application, or software. A crucial step in the UI design process is the creation of wireframes. Wireframes serve as the blueprint for UI design, providing a visual representation of the layout and functionality of a digital product. In this blog post, we will delve into the world of UI design and explore the importance of wireframes in the design process.

_Quick Link to Specific Topic:_

- [Importance of User Interface (UI) Design in Software Systems:](#importance-of-user-interface-ui-design-in-software-systems)
  - [Enhanced User Experience:](#enhanced-user-experience)
  - [Increased User Engagement:](#increased-user-engagement)
  - [Improved Usability:](#improved-usability)
- [What is User Interface (UI) Design:](#what-is-user-interface-ui-design)
- [Role of Wireframes in the Design Process](#role-of-wireframes-in-the-design-process)
- [Understanding UI Controls](#understanding-ui-controls)
  - [What is UI controls:](#what-is-ui-controls)
    - [Buttons:](#buttons)
    - [Text Inputs:](#text-inputs)
    - [Dropdowns and Select Boxes:](#dropdowns-and-select-boxes)
    - [Checkboxes and Radio Buttons:](#checkboxes-and-radio-buttons)
  - [Sliders and Range Inputs:](#sliders-and-range-inputs)
    - [Icons and Images:](#icons-and-images)
- [Understanding UI Design Pattern:](#understanding-ui-design-pattern)
  - [Navigation Patterns:](#navigation-patterns)
  - [Card Design Patterns:](#card-design-patterns)
  - [Modal Patterns:](#modal-patterns)
  - [Form Design Patterns:](#form-design-patterns)
  - [Feedback and Notification Patterns:](#feedback-and-notification-patterns)
  - [Microinteractions:](#microinteractions)
- [Design Principles for Effective UI](#design-principles-for-effective-ui)
  - [Simplicity:](#simplicity)
  - [Consistency:](#consistency)
  - [Visual Hierarchy:](#visual-hierarchy)
  - [User Feedback:](#user-feedback)
  - [Accessibility:](#accessibility)
  - [User Testing:](#user-testing)
- [Creating Wireframes: Tools and Techniques](#creating-wireframes-tools-and-techniques)
- [Design Templates and Guidelines](#design-templates-and-guidelines)
- [Integration of UI Design and Software Requirements](#integration-of-ui-design-and-software-requirements)
- [Effective Communication and Collaboration for Successful UI Implementation](#effective-communication-and-collaboration-for-successful-ui-implementation)
- [About Content Creator:](#about-content-creator)
- [All Posts on Project Management:](#all-posts-on-project-management)

# Importance of User Interface (UI) Design in Software Systems:
User interface design is a critical aspect of software development as it directly impacts user engagement, satisfaction, and overall business success. A well-designed UI can provide the following benefits:

## Enhanced User Experience:
A thoughtfully designed UI ensures that users can easily navigate the software, complete tasks efficiently, and achieve their goals without frustration. This positive experience fosters user loyalty and encourages repeat usage.

## Increased User Engagement:
Engaging UI designs capture users' attention, stimulate their interest, and encourage exploration of different features and functionalities. It helps in creating a lasting impression and differentiating the software from competitors.

## Improved Usability:
A well-designed UI simplifies complex workflows, reduces cognitive load, and enhances usability. Intuitive navigation, clear visual cues, and logical information architecture contribute to a seamless user experience.

# What is User Interface (UI) Design:

User Interface (UI) design encompasses the creation of interfaces that enable users to interact with digital products effectively. It involves the careful selection of visual elements, such as colors, typography, and icons, as well as the arrangement of interactive components, such as buttons, forms, and navigation menus. The ultimate goal of UI design is to enhance the user experience and make the interaction with the product intuitive, enjoyable, and efficient.

# Role of Wireframes in the Design Process

Wireframes are the backbone of the UI design process. They serve as a visual representation of the skeletal structure and layout of a digital product. Wireframes are created before the actual design and development stages, providing a simplified and uncluttered representation of the interface's key elements and their relationships.

The primary purpose of wireframes is to communicate the overall structure and functionality of the user interface. They allow designers, developers, and stakeholders to align their vision, iterate on design concepts, and identify potential usability issues early in the process. By focusing on the layout and functionality rather than visual aesthetics, wireframes enable efficient collaboration and save time and effort during the design and development phases.

# Understanding UI Controls

UI controls play a crucial role in user interface design as they enable effective interaction between users and software systems. Proper understanding and utilization of UI controls can significantly enhance the user experience and overall engagement.

## What is UI controls:
UI controls, also referred to as user interface elements or widgets, are visual and interactive components that allow users to perform actions, input data, and navigate through software interfaces. They encompass a variety of elements such as buttons, text fields, dropdown menus, checkboxes, sliders, and more. Let's explore various UI controls and provide insights into the best practices for building captivating and user-friendly software systems.

### Buttons:
Buttons are one of the most commonly used UI controls, serving as a primary element for user interaction. They trigger actions and provide clear visual cues to guide users. To optimize their effectiveness, consider the following best practices:

- **Use descriptive labels:** Clearly label buttons to convey their purpose and provide clarity to users.
- **Consistent styling:** Maintain a consistent visual style for buttons throughout the software system to ensure familiarity and ease of use.
- **Proper placement:** Position buttons intuitively, making them easily accessible and visible when users need to interact with them.

### Text Inputs:
Text inputs enable users to provide textual information. Whether it's a login form, search field, or data entry, text inputs need careful attention for an engaging UI. Follow these best practices:

- **Placeholder text:** Use helpful placeholder text to provide examples or instructions, guiding users on the expected input format.
- **Validation and feedback:** Implement real-time validation and provide clear feedback to users if their input is incorrect or incomplete.
- **Accessibility:** Ensure text inputs are accessible to users of all abilities, including proper labeling and support for assistive technologies.

### Dropdowns and Select Boxes:
Dropdowns and select boxes are effective UI controls for presenting a set of options to users. When using these controls, consider the following best practices:

- **Default selection:** Set a meaningful default option, which can save users time and effort.
- **Limited options:** Keep the list of options concise and relevant, avoiding overwhelming users with excessive choices.
- **Clear labeling:** Clearly label the dropdowns or select boxes to indicate their purpose and the available options.

### Checkboxes and Radio Buttons:
Checkboxes and radio buttons are useful for enabling users to make selections from a set of options. To optimize their usage, adhere to these best practices:

- **Group related options:** Organize checkboxes and radio buttons into logical groups, making it easier for users to understand their choices.
- **Preselect defaults:** Preselect the most commonly chosen options to expedite the selection process.
- **Visual clarity:** Use clear labels and appropriate spacing to avoid confusion and ensure the checkboxes and radio buttons are visually distinct.

## Sliders and Range Inputs:
Sliders and range inputs allow users to select values within a defined range. To create engaging and user-friendly sliders, follow these best practices:
- **Clearly defined range:** Clearly indicate the minimum and maximum values of the range to avoid ambiguity.
- **Feedback:** Provide visual feedback, such as dynamically updating a value or displaying a tooltip, to enhance the user's understanding of their selection.
- **Responsive design:** Ensure the sliders and range inputs are responsive and work well across different devices and screen sizes.

### Icons and Images:
Icons and images are powerful visual elements that enhance the overall UI experience. Consider these best practices when incorporating icons and images:

- **Purposeful usage:** Use icons and images only when they provide meaningful context or aid understanding.
- **Consistency:** Maintain consistency in style, size, and alignment of icons and images throughout the software system.
- **Optimize image size:** Compress images to reduce load times and improve overall performance.

# Understanding UI Design Pattern:

UI patterns are standardized design solutions that have been proven effective in addressing specific user interface challenges. These patterns are established conventions that users are already familiar with, making it easier for them to comprehend and navigate digital products. Examples of commonly used UI patterns include navigation menus, carousels, tabs, modals, and more. By leveraging these patterns, designers can create consistent and predictable user experiences. Let's dive into the world of UI design patterns and discover how to build captivating and user-friendly software systems.

## Navigation Patterns:
Navigation patterns are essential for helping users navigate through your software system seamlessly. Consider the following best practices:

- **Top Navigation Bar:** Utilize a top navigation bar to provide a clear and consistent navigation mechanism across your software system, enabling users to access different sections easily.
- **Sidebar Menu:** Implement a sidebar menu to display hierarchical navigation options, allowing users to explore different levels of content and functionality.
- **Breadcrumbs:** Incorporate breadcrumbs to show users their current location within your software system's hierarchy, enabling easy backward navigation.

## Card Design Patterns:
Card-based designs have gained popularity due to their versatility and visual appeal. Follow these best practices when implementing card design patterns:
- **Clear Card Hierarchy:** Use different card sizes, colors, and typography to establish a clear visual hierarchy, guiding users' attention to important information.
- **Consistent Card Layout:** Maintain a consistent layout within cards, ensuring that elements such as titles, images, and descriptions are consistently positioned and styled.
- **Responsive Card Design:** Ensure that your card-based design adapts well to different screen sizes and devices, providing an optimal user experience across platforms.

## Modal Patterns:
Modal patterns are effective for displaying contextual information or capturing user input without disrupting the main flow. Incorporate these best practices:

- **Clear Purpose and CTA:** Clearly communicate the purpose of the modal and provide a prominent call-to-action (CTA) to guide users' actions.
- **Dimmed Background:** Dim the background content when the modal is active to provide visual focus and indicate that the main interface is temporarily disabled.
- **Close and Cancel Options:** Offer intuitive ways to close the modal, such as a close button or the ability to click outside the modal area, to ensure ease of use.

## Form Design Patterns:
Forms are crucial for capturing user input, and optimizing their design can significantly enhance the user experience. Consider the following best practices:
- **Clear Labeling:** Clearly label form fields to provide context and guide users on the required input.
- **Validation and Error Handling:** Implement real-time validation and provide clear error messages to assist users in correcting any invalid inputs.
- **Progressive Disclosure:** Use progressive disclosure techniques, such as collapsible sections or conditional fields, to present complex forms in a manageable and user-friendly manner.

## Feedback and Notification Patterns:
Feedback and notification patterns help users stay informed about their actions and system status. Incorporate these best practices:

- **Toast Notifications:** Utilize toast notifications to provide unobtrusive feedback on user actions or system updates, ensuring they are easily dismissible.
- **Loading Indicators:** Display loading indicators to inform users of ongoing processes, preventing confusion and ensuring transparency.
- **Error Messages:** Provide clear and specific error messages when users encounter issues, helping them understand the problem and suggesting possible solutions.

## Microinteractions:
Microinteractions are small, subtle animations or responses that provide feedback and delight users. Follow these best practices:
- **Purposeful Animations:** Use animations sparingly and purposefully to enhance usability, guide user actions, or provide visual feedback.
- **Smooth Transitions:** Ensure that animations and transitions are smooth and fluid to create a polished and engaging user experience.
- **Delightful Feedback:** Add delightful microinteractions, such as subtle hover effects or satisfying button clicks, to make interactions more enjoyable.

By implementing navigation patterns, card design patterns, modal patterns, form design patterns, feedback and notification patterns, and microinteractions, developers can create visually appealing interfaces that enhance the overall user experience.

# Design Principles for Effective UI

To create effective UI designs, it is essential to adhere to design principles that prioritize usability and user-centricity. Some key principles include:

## Simplicity:
Simplicity is the cornerstone of a successful user interface. Keeping your design simple and clutter-free helps users navigate your software system with ease. Consider the following best practices:

- **Minimalistic approach:** Strive for a clean and uncluttered design by removing unnecessary elements and focusing on the core functionality.
- **Consistent layout:** Maintain a consistent layout throughout your software system, ensuring that elements are logically arranged and easily discoverable.
- **Clear hierarchy:** Use visual cues such as size, color, and typography to establish a clear hierarchy of information, guiding users' attention to key elements.

## Consistency:
Consistency is key to providing a cohesive user experience across your software system. When your design is consistent, users can easily learn and navigate through different sections. Follow these best practices:
- **Visual consistency:** Use consistent colors, typography, icons, and button styles throughout your software system.
- **Interaction patterns:** Maintain consistent interaction patterns, such as how buttons and links behave, to avoid confusion and improve learnability.
- **Language and terminology:** Use consistent terminology and language across your software system, ensuring that labels and instructions are clear and easily understood.

## Visual Hierarchy:
Visual hierarchy helps users understand the importance and relationship between different elements within your software system. Implement these best practices to establish a clear visual hierarchy:
- **Size and placement:** Use larger sizes and prominent placements for important elements, guiding users' attention to key areas of the interface.
- **Contrast and color:** Utilize contrast and color to create visual distinctions between different elements, highlighting important information.
- **Typography:** Use different font sizes, weights, and styles to differentiate headings, subheadings, and body text, aiding readability and comprehension.

## User Feedback:
Providing timely and meaningful feedback to users enhances their experience and builds engagement. Incorporate these best practices for effective user feedback:

- **Responsive interfaces:** Ensure that your software system responds promptly to user actions, providing visual feedback such as button state changes or loading indicators.
- **Error handling:** Clearly communicate errors to users with informative messages and suggestions for resolution.
- **Progress indicators:** When tasks require time, provide progress indicators to keep users informed about the status and duration of the process.

## Accessibility:
Designing for accessibility is crucial to ensure that your software system can be used by individuals of all abilities. Follow these best practices for an inclusive design:

- **Proper color contrast:** Ensure that text and graphical elements have sufficient contrast for readability, especially for users with visual impairments.
- **Keyboard accessibility:** Ensure that all functionality can be accessed and operated using a keyboard alone, enabling users who rely on assistive technologies.
- **Alternative text:** Provide descriptive alternative text for images, enabling users with visual impairments to understand the content.

## User Testing:
User testing is an essential practice for validating your design decisions and identifying areas for improvement. Consider these best practices for effective user testing:
- **Early involvement:** Involve users in the design process from an early stage to gather valuable feedback and insights.
- **Clear objectives:** Define specific objectives for user testing sessions to focus on the areas you want to evaluate or improve.
- **Iterative testing:** Conduct multiple rounds of testing and incorporate user feedback into your design, refining and optimizing the user experience.

# Creating Wireframes: Tools and Techniques

Wireframes can be created using various tools, each offering different functionalities and flexibility. Some popular wireframe creation tools include:

**Sketch:** A powerful vector-based design tool that allows for easy creation of wireframes and prototypes.
**Adobe XD:** A comprehensive design and prototyping tool with a user-friendly interface and robust wireframing capabilities.
**Balsamiq:** A tool specifically designed for creating low-fidelity wireframes quickly and efficiently.
**Figma:** A collaborative design tool that enables real-time collaboration and provides extensive wireframing features.

The process of wireframe development typically involves the following steps:

**Define objectives and target audience:** Understand the project goals and the needs and expectations of the target users.
**Create a basic layout:** Establish the overall structure and hierarchy of the user interface.
**Add UI controls and content:** Place UI controls, such as buttons and forms, and populate the wireframe with relevant content.
**Test and iterate:** Validate the wireframe by testing it with users and iterating based on their feedback.
**Finalize and annotate:** Refine the wireframe and add annotations to provide clarity and context for developers.

Best practices for creating wireframes include keeping them simple, focusing on functionality rather than aesthetics, and involving stakeholders and users throughout the process to gather valuable insights and feedback.

# Design Templates and Guidelines

Utilizing pre-designed UI templates can significantly speed up the wireframing process. Many design resources offer pre-made templates that can be customized to suit specific project requirements. These templates provide a starting point and ensure consistency across different screens and interactions.

Following industry-standard design guidelines, such as Apple's Human Interface Guidelines or Google's Material Design guidelines, can also be beneficial. These guidelines provide design principles, patterns, and best practices that have been tested and proven in real-world applications, helping designers create interfaces that align with user expectations.

# Integration of UI Design and Software Requirements

A successful UI design process involves close collaboration between UI designers, business analysts, and project managers. UI designers need to understand the software requirements and user stories to ensure that the design aligns with the intended functionality. Collaborative discussions, workshops, and iterative feedback loops between the design and development teams are crucial for achieving a seamless integration of UI design and software requirements.

# Effective Communication and Collaboration for Successful UI Implementation

Effective communication and collaboration play a vital role in the successful implementation of UI design. Regular meetings, feedback sessions, and documentation are essential to ensure that all stakeholders are aligned on the design vision, requirements, and expectations. Clear communication channels and a collaborative mindset foster an environment where ideas can be shared, evaluated, and refined to create a compelling user interface.

Mastering user interface design requires a solid understanding of the principles, tools, and techniques involved. Wireframes serve as a critical component in the UI design process, providing a visual representation of the interface structure and functionality. By understanding UI controls, leveraging UI patterns, and adhering to design principles, designers can create engaging and user-centric interfaces. Utilizing wireframe creation tools, templates, and industry-standard guidelines streamlines the design process, while effective communication and collaboration ensure a successful UI implementation. Embrace the knowledge gained from this introduction, and apply UI design principles and wireframing techniques to create exceptional digital experiences.

Remember, user interface design is a continuous learning process, and staying updated with the latest trends and technologies is key to delivering outstanding UI designs that meet user expectations and create lasting impressions.

**[⬆ back to top](#definition-and-importance-of-ui-design)**

----------------------------------------------------------------------
----------------------------------------------------------------------

Enjoyed this post!

[![" Thank you!

----------------------------------------------------------------------
----------------------------------------------------------------------

# About Content Creator:

Hi, This is **Rafayet Hossain**

A Seasoned Business Systems Analyst, Project Manager, and SQA Engineer with experience in driving digital changes within organizations. I specialize in understanding business needs and developing software solutions to improve processes and drive growth. I am skilled in managing projects, analyzing data, and ensuring quality in the final product. I am passionate about using my expertise to help organizations reach their goals and succeed. Let's work together to improve your business and drive success.

👉 Contact me for any inquiries or projects :

[![Linkedin](https://img.shields.io/badge/-LinkedIn-blue?style=flat&logo=Linkedin&logoColor=white)](https://www.linkedin.com/in/rafayethossain/)
<EMAIL_ADDRESS>

----------------------------------------------------------------------
----------------------------------------------------------------------

# All Posts on Project Management:

Click on any of the desired links to directly access the information.

- [x]  [**The Basics of Project Management**](https://rafayethossain.github.io/2022-10-10-Project-Management-Beginner's-Guide/)
- [x]  [**How to Transition from Business Analysis to a Project Management Career**](https://rafayethossain.github.io/2022-10-15-Transition-from-Business-Analysis-to-a-Project-Manager/)
- [x]  [**Project Initiation Activities as a Business Analyst**](https://rafayethossain.github.io/2019-02-07-Project-Initiation-Business-Analysis-Activities/)
- [x]  [**How to Manage Your Project Stakeholder Using RACI Matrix**](https://rafayethossain.github.io/2019-02-27-Stakeholder-Management-Business-Analyst/)
- [x]  [**Change Control Process in SDLC**](https://rafayethossain.github.io/2019-07-07-Change-Control-Process-in-SDLC/)
- [x]  [**Agile Scrum: A Comprehensive Guide to Mastering the Framework**](https://rafayethossain.github.io/2022-11-11-Agile-Scrum-in-a-Nutshell/)
-  [x]  [**Agile vs. Waterfall - Which Project Management Methodology is Right for You?**](https://rafayethossain.github.io/2022-11-28-Agile-vs-Waterfall-Choosing-the-Right-Methodology-for-Your-Project/)
-  [x]  [**Achieving Project Success with DMAIC Methodology - A Beginner's Guide**](https://rafayethossain.github.io/2022-12-01-Achieving-Project-Success-with-DMAIC-Methodology/)
-  [x]  [**Understanding Project Scope and Requirements A Guide for Project Managers**](https://rafayethossain.github.io/2022-12-12-Understanding-Project-Scope-and-Requirements/)
-  [x]  [**5 Tips for Creating a Project Management Plan That Works**](https://rafayethossain.github.io/2022-12-14-Tips-for-Creating-a-Project-Management-Plan-that-Works/)
-  [x]  [**How to Use SWOT Analysis to Drive Project Success**](https://rafayethossain.github.io/2022-12-15-How-to-Conduct-a-SWOT-Analysis-for-Your-Project/)
-  [x]  [**A Step-by-Step Guide to Developing Your First Project Charter**](https://rafayethossain.github.io/2022-12-17-A-Step-by-Step-Guide-to-Developing-Your-First-Project-Charter/)
-  [x]  [**Mastering the Art of Project Scheduling as a Beginner**](https://rafayethossain.github.io/2023-01-05-How-to-Develop-a-Project-Schedule-for-as-a-Beginner/)
-  [x]  [**A Beginner’s Guide to Developing and Managing an Effective Project Budget**](https://rafayethossain.github.io/2023-01-10-How-to-Develop-and-Manage-a-Project-Budget-for-as-a-Beginner/)
-  [x]  [**Learn How to Proactively Manage Risks to Keep Your Project on Track**](https://rafayethossain.github.io/2023-01-12-How-to-Identify-and-Manage-Project-Risk-as-a-Beginner/)
-  [x]  [**5 Key Metrics for Evaluating Project Success as a Beginner Project Manager**](https://rafayethossain.github.io/2023-01-14-How-to-Evaluate-Project-Sucess-as-a-Beginner/)
-  [x]  [**Prepare a Effective Communication Strategy**](https://rafayethossain.github.io/2023-01-18-Effective-Communcation-Strategies-for-Project-Manage-and-Business-Analyst/)
-  [x]  [**Overcoming the Top Challenges Faced as a Beginner Project Manager**](https://rafayethossain.github.io/2023-01-22-Top-Challenges-Faced-by-a-Beginner-Project-Manager/)
-  [x]  [**The Power of Collaboration Between Business Analysts and Project Managers**](https://rafayethossain.github.io/2023-01-24-The-Benefits-of-Collboration-Between-Business-Analyst-and-Project-Manager/)
-  [x]  [**Why Quality Assurance is Critical for Successful Business Analysis and Project Management**](https://rafayethossain.github.io/2023-01-28-The-Importance-of-Quality-Assurance-in-Business-Analysis-and-Project-Management/)
-  [x]  [**How Data Analysis Drives Business Analysis and Project Management**](https://rafayethossain.github.io/2023-01-30-The-Role-of-Data-Analysis-in-Business-Analysis-and-Project-Management/)

![Diary](/assets/img/diary.png "Diary")


text:
---
title: scm-trac-plugin
date: 2014-05-21T16:35:37+00:00
author: Sebastian Sdorra
slug: /plugins/scm-trac-plugin/
categories:
  - plugins
  - issue-tracker-plugins

---
The new [scm-trac-plugin](https://bitbucket.org/sdorra/scm-trac-plugin) is now available over the SCM-Manager plugin center. It integrates the issue tracker of Trac to SCM-Manager. The plugin requires version 1.33 or newer of SCM-Manager.

license: MIT

repository: dhuchthausen/website

branch_name: refs/heads/master

extension: md

gha_license_id: MIT

license_type: permissive

repo_name: dhuchthausen/website


text:
#Guidelines for Naming Convention for Consistency across Models

I figured it would be good to have a file where we explicitly declare all of the notation we use throughout our code and future write-ups in terms of what variable names signify. This is always one of the more confusing parts of computational neuroscience packages in general, so hopefully this will improve user experience.

If anyone thinks that there is a better naming convention, feel free to directly modify this .md

For each new model we make lets add it to this .md. Here is the current status:

##XOR on Two Inputs:
	Two input neurons,  A    and B
	Two output neurons, SAME and DIFF

	X and Y are random variables that can each be either A or B
	SAME fires if X xor Y == 1
	DIFF fires if X xor Y == 0

	There is an initial input_wait time interval.
	Afterwards an interval is either STIMULUS
	for a set time stim_dur or mem_gap, respectively.

	Timeline: input_wait | stim_dur | mem_gap | stim_dur | out_gap
	Input:<PHONE_NUMBER> | XXXXXXXX | 0000000 | YYYYYYYY | 0000000
	Output:   	          ****** Masked ******			 | ZZZZZZZ
	----------------------------seq_dur---------------------------

##Flip Flop Test by Inputs:
	Two input neurons,  A  and B
	Two output neurons, A' and B'

	There is an initial input_wait time interval.
	Afterwards an interval is either STIMULUS or QUIET
	for a set time stim_dur or quiet_dur, respectively.

	Timeline: input_wait | stim_dur | quiet_gap | stim_dur | quiet_gap  ...
	Input:<PHONE_NUMBER> | XXXXXXXX | 000000000 | YYYYYYYY | 000000000  ...
	Output:   	   ** Masked ** 	| XXXXXXXXX | *Masked* | YYYYYYYYY  ...
	-----------------------------------seq_dur-------------------------------

	This is repeated n_rounds times.

##Flip Flop Test by Magnitude
	One input neuron,  firing either HI or LO
	One output neuron, firing either HI or LO

	Everything is as in the prior case, with X and Y random variables representing either HI or LO.

repository: ABAtanasov/KerasCog

gha_language: Python

repo_name: ABAtanasov/KerasCog


text:
# geo-import

## usage
i wouldn't

## what
import
* geojson
* kmz
* kml
* shp

into soda-fountain

## setup

### use the correct node version

Ensure that you have the correct version of Node.js, specified at `.node-version`, installed.

Use `n` or `nvm` to make this easy. `bin/start.sh` will automatically do this step for you.

### install dependencies

linux
```
  make
```

mac
  * el capitan, run `make`
  * earlier OSX versions don't have the correct version of clang. Either update xcode (??) or add this [workaround](https://github.com/Homebrew/homebrew/issues/40653)

this also runs a postinstall script to install mapbox/node-srs,
which is built from source in a sibling repo and symlinked here

Note that `make clean` doesn't remove the dependency directory. If you run dependency resolution with the wrong version of node, you will need to `make clean && rm -r node_modules`, change node versions, and then `make` again.

### other services
because this does imports, you need [import-status-service](https://github.com/socrata/import-status-service) and ISS consumer running

you will also need AMQ running

## developing
to compile to es5, run
```
make
```
then run the development configuration using
```
SOCRATA_LOCAL_USER=<username> SOCRATA_LOCAL_PASS=<password> GEO_IMPORT_ENV=dev node lib/index.js
```
(where the username and password are for a Superadmin-enabled user account in Core Server)

To run it as es5

you will need core and the soda2 stack running

## testing

do a single, full test run with `make test`

`./test.sh` will watch your tests and re-run the tests tagged as unit tests. If you want your tests to be run continuously, they need to be in the `test/unit` directory

Smoke tests are tests on real datasets that will take considerably longer to run, so you don't
want to be running them when developing. If you want to add a smoke test, add it to the `test/smoke` directory.

## using
Imports and replaces are passed on AMQ from core to geo-import

* we define `shapeblob` as one of {shape archive, kmz, kml, geojson}
* Content-Types
  * KML content-type must be application/vnd.google-earth.kml+xml
  * KMZ content-type must be application/vnd.google-earth.kmz
  * geoJSON content-type must be application/json
  * shapefile content-type must be application/zip

| Method | Endpoint   | Payload | Content-Type | Description              | Response |
| ------ | ---------- | ------- | ------------ |  ----------------------- | -------- |
| `GET`  | `/version` | `none`  | `anything `  | get the service version  | version as json |
| `POST` | `/summary` | `shapeblob` | must correspond to payload | create a summary of the blob | summary as json |
| `GET`  | `/heapdump`| `none` | `anything` | get a heap dump of the service | a heap dump to load into the chrome profiler |
## tasks

### translations
run `make translations` to get a `translations/en.yml` file. You can use this yaml in the rails frontend for i18n. This generates javascript style templates - because we'll probably be doing error handling in the react importer

repository: socrata-platform/geo-import

branch_name: refs/heads/main

gha_language: JavaScript

repo_name: socrata-platform/geo-import


text:
# Roulette

A simple roulette game created in Java.

## Getting Started

Download Ready to Program Java and open Roulette.java

### Prerequisites

* The most recent version of the [Java Development Kit (JDK)](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
* [Ready to Program Java IDE](http://compsci.ca/holtsoft/)

## Built With

* [Java](https://docs.oracle.com/javase/8/docs/) - The language used
* [Ready To Program](http://compsci.ca/holtsoft/) - The "IDE" needed

## Authors

* **Surya Krishnan** [Github](https://github.com/krsh2001)

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

repository: surya-krishnan/Roulette

repo_name: surya-krishnan/Roulette


text:
True enjoyment in life comes from many sources, but because we spend so much of our time engaged in it, it's only sensible that a fair portion of our pleasure come from work.
For a long time I've been interested in finding ways to enjoy work more fully. There are some conflicting explanations. One common line is that the kinds of things we enjoy are innate. Perhaps, but there are lots of people who develop an interest in something that they hadn't been predisposed to, after spending some time learning it. Maybe then the answer lies with a conflicting popular explanation: you enjoy things that you are good at. Once you gain mastery at something, the theory goes, then you start to get pleasure from it.

What makes some work addictive and gratifying, and other work boring?

Thinking about this led me to a concept called "Flow". Specifically to this Ted talk:

In it, Cziscentmihalyi describes something called an "autotalic personality" - someone who can find enjoyment from nearly anything. An autotalic personality knows how to turn any task, even one as mundane as doing laundry, into something that is intrinsically rewarding.

A series of habits

gha_language: HTML


text:
# colony-bot

> Use Colony on GitHub

## Setup

```sh
# Install dependencies
npm install

# Run typescript
npm run build

# Run the bot
npm start
```

## Contributing

If you have suggestions for how colony-bot could be improved, or want to report a bug, open an issue! We'd love all and any contributions.

For more, check out the [Contributing Guide](CONTRIBUTING.md).

## License

[ISC](LICENSE)

license: ISC

repository: sprusr/colony-bot

repo_name: sprusr/colony-bot


text:
WellRESTed
==========

WellRESTed provides classes to help you create RESTful APIs and work with HTTP requests and responses.

Requirements
------------

- PHP 5.3
- [Composer](http://getcomposer.org/) for autoloading
- [PHP cURL](http://php.net/manual/en/book.curl.php) for making requests

Install
-------

Add an entry for "pjdietz/wellrested" to your composer.json file's **require** property. If you are not already using Composer, create a file in your project called **composer.json** with the following content:

```json
{
    "require": {
        "pjdietz/wellrested": "1.*"
    }
}
```

Use Composer to download and install WellRESTed. Run these commands from the directory containing the **composer.json** file.

```bash
$ curl -s https://getcomposer.org/installer | php
$ php composer.phar install
```

You can now use WellRESTed by including the **autoload.php** file generated by Composer. `vendor/autoload.php`

Examples
--------

### Routing

WellRESTed's primary goal is to facilitate mapping of URIs to classes that will provide or accept representations. To do this, create a Router instance and load it up with some Routes. Each Route is simply a mapping of a URI pattern to a class name. The class name represents the Handler class which the router will dispatch at the time it receives a request for the given URI. The handlers are never loaded unless they are needed.

Here's an example of a Router that will handle two URIs:

```php
// Build the router.
$myRouter = new Router();
$myRouter->addRoute(Route::newFromUriTemplate('/things/', 'ThingCollectionHandler'));
$myRouter->addRoute(Route::newFromUriTemplate('/things/{id}', 'ThingItemHandler'));

// Determine and output the response.
$response = $myRouter->getResponse();
$response->respond();
```

When you create your Handler subclass, you will provide a method for each HTTP verb you would like the endpoint to support. For example, if `/things/` should support `GET`, you would override the `get()` method. For `POST`, `post()`, etc.

If your endpoint should reject particular verbs, no worries. The Handler base class defines the default verb-handling methods to respond with a **405 Method Not Allowed** status.

Here's a simple Handler that matches the first endpoint, `/things/`.

```php
class ThingCollectionHandler extends \pjdietz\WellRESTed\Handler
{
    protected function get()
    {
        // Read some things from the database, cache, whatever.
        // ...read this into the variable $data

        // Set the values for the instance's response member. This is what the
        // Router will eventually use to output a response to the client.
        $this->response->setStatusCode(200);
        $this->response->setHeader('Content-Type', 'application/json');
        $this->response->setBody(json_encode($data));
    }

    protected function post()
    {
        // Read from the instance's request member and store a new Thing.
        // ...

        // Build a response to send to the client.
        $this->response->setStatusCode(201);
        $this->response->setBody('You added a thing!');
    }
}
```

This Handler works with the second endpoint, `/things/{id}`. The pattern for this endpoint has the variable `{id}` in it. The Handler can access path variables through its `args` member, which is an associative array of variables from the URI.

```php
class ThingItemHandler extends \pjdietz\WellRESTed\Handler
{
    protected function get()
    {
        // Lookup a Thing ($thing) based on $this->args['id']
        // ...

        if ($thing) {
            // The Thing exists! Let's output a representation.
            $this->response->setStatusCode(200);
            $this->response->setHeader('Content-Type', 'application/json');
            $this->response->setBody(json_encode($thing));
        } else {
            // The ID did not match anything.
            $this->response->setStatusCode(404);
            $this->response->setHeader('Content-Type', 'text/plain');
            $this->response->setBody('No thing with id ' . $this->args['id']);
        }
    }
}
```

As of version 1.3.0, you can have a Router dispatch other Routers. This is useful for breaking your endpoints into smaller route tables. Here's an example:

```php
/**
 * Top-level router that dispatches all traffic to /cat/... to CatRouter and all
 * traffic to /dog/... to DogRouter.
 */
class TopRouter extends \pjdietz\WellRESTed\Router
{
    public function __construct()
    {
        $this->addRoute(new Route('/^\/cat\//', 'CatRouter'));
        $this->addRoute(new Route('/^\/dog\//', 'DogRouter'));
    }
}
```

### Requests and Responses

You've already seen a Response in use in the examples above. You can also use Responses outside of Handlers. Let's take a look at creating a new Response, setting a header, supplying the body, and outputting.

```php
$resp = new \pjdietz\WellRESTed\Response();
$resp->setStatusCode(200);
$resp->setHeader('Content-type', 'text/plain');
$resp->setBody('Hello world!');
$resp->respond();
exit;
```

The Request class goes hand-in-hand with the Response class. Again, this is used in the Handler class to read the information from the request being handled. From outside the context of a Handler, you can also use the Request class to read info for the request sent to the server.

```php
// Call the static method getRequest() to get a reference to the Request
// singleton that represents the request made to the server.
$rqst = \pjdietz\WellRESTed\Request::getRequest();

if ($rqst->getMethod() === 'PUT') {
    $obj = json_decode($rqst->getBody());
    // Do something with the JSON sent as the message body.
    // ...
}
```

The Request class can also make a request to another server and provide the response as a Response object. (This feature requires [PHP cURL](http://php.net/manual/en/book.curl.php).)

```php
// Prepare a request.
$rqst = new \pjdietz\WellRESTed\Request();
$rqst->setUri('http://my.api.local/resources/');
$rqst->setMethod('POST');
$rqst->setBody(json_encode($newResource));

// Make the request.
$resp = $rqst->request();

// Read the response.
if ($resp->getStatusCode() === 201) {
    // The new resource was created.
    $createdResource = json_decode($resp->getBody());
}
```

### Routing from a Handler

One more fun thing you can do with WellRESTed is use your API from inside your API. WellRESTed makes this easy because each dispatched Handler or Router keeps a reference to the top-level Router.

Suppose you have an endpoint that needs to look up information using another endpoint. Now that you've seen that you can create and work with your own requests and responses, we'll look at how to use them in the context of a handler.

```php
class NestedHandler extends \pjdietz\WellRESTed\Handler
{
    protected function get()
    {
        // To build this response, we need some of the info from the /things/ representation.
        // Create a Request instance to query this API.
        $rqst = new Request();
        $rqst->setPath('/things/');

        // Use this handler's reference to the router that dispatched it.
        $router = $this->getRouter();

        // Pass the request for /things/ to the router to get a response.
        $resp = $router->getResponse($rqst);

        // Read the status code, headers, body, etc. on the response.
        // ...
    }
}
```

More Examples
---------------

For more examples, see the project [pjdietz/wellrested-samples](https://github.com/pjdietz/wellrested-samples).

Copyright and License
---------------------
Copyright © 2013 by PJ Dietz
Licensed under the [MIT license](http://opensource.org/licenses/MIT)

repository: martinsv/wellrested

repo_name: martinsv/wellrested


text:
Binairo Solver
==============

This Maven project solves Binary puzzles (Binairo puzzles). Binairo puzzles are variations
on the well-known Sudoku puzzles, that use only the numbers 0 and 1.

The source code is licensed under the terms of a BSD license. See the LICENSE
file for details.

Binary Puzzle Rules
-------------------
These are the rules as given on [BinaryPuzzle.com](http://binarypuzzle.com):

1. Each box should contain a zero or a one.
2. No more than two similar numbers next to or below each other are allowed.
3. Each row and each column should contain an equal number of zeros and ones.
4. Each row is unique and each column is unique.

repository: ptrckkrmr/BinairoSolver

repo_name: ptrckkrmr/BinairoSolver


text:
# pyFixerio
*A Python wrapper for fixer.io API endpoints.*

This wrapper only uses the free version of the API, but delivers similar functionality
to paid versions. Namely, the wrapper deals with fixer.io's restrictions on:

    - Base currency is only allowed to be 'EUR'
    - No access to the time series API

#### Basic usage

```python
>>> from pyfixerio.pyfixerio import Fixerio

>>> fx = Fixerio('ACCESS_KEY')

>>> fx.current('EURUSD')

### {'EURUSD', 1.1423}

>>> fx.historical('USDGBP', '2019-01-05')

### {'2019-01-05': {'USDGBP': 0.8432'}}

```

#### TODO:

[ ] Validate access key

[ ] When converting / dividing to find base rate - round currency decimal places

[ ] Implement creation of new account for new api key (?)

[ ]Implement option to choose free api as default


text:
# PgNio

PgNio is an asynchronous PostgreSQL client for Java and the JVM. It was built to solve both simple and advanced Postgres
needs without being too opinionated or inflexible. Since all protocol features are supported callers can take advanced
approaches to problems.

[![Javadocs](http://javadoc.io/badge/com.github.cretz.pgnio/pgnio-driver.svg)](http://javadoc.io/doc/com.github.cretz.pgnio/pgnio-driver)
(`protected` visibility excluded)

### Features/Goals

* Java 8+
* Simple and small codebase, no dependencies
* NIO and SSL
* Notification support
* `COPY` support
* Advanced prepared and bound query support including max-rows and suspension
* Flexible server communication - control when/how data is sent/received, support all protocol features
* Extensible - almost everything can be extended
* Low level - can be the base of higher-level Postgres libraries (such as the upcoming async JDBC API or combined with
  other reactive libs)
* Extensible yet not embedded/forced parameter and row data serialization from/to Java types
* Support for date, geom, network, money, hstore, etc data types

### Install

This is deployed to Maven Central. In maven project:

```xml
<dependency>
    <groupId>com.github.cretz.pgnio</groupId>
    <artifactId>pgnio-driver</artifactId>
    <version>0.2.0</version>
</dependency>
```

Or in Gradle:

```
compile 'com.github.cretz.pgnio:pgnio-driver:0.2.0'
```

### How To

Below are simple examples on how to use the client library. The library makes heavy use of composition with
`CompletableFuture` values which is why some of the code appears quite functional and non-ergonomic. All top-level
classes in the library are in the `pgnio` package. While there are synchronous `get` invocations in these examples, in
normal use developers might not want to block for a result.

#### Create and use a single connection

To connect to a database, a `Config` instance is needed. It's a simple class with already-defaulted public fields that
can be set directly. Each field also has a corresponding builder method to set its value and return back the `Config`
instance. Here is a simple config:

```java
Config conf = new Config().hostname("myhost").username("myuser").password("mypass");
```

See the `Config` Javadoc for more details on the values. Besides common values, developers are encouraged to set timeout
values that are used for reading/writing from/to the server.

A connection is first connected via the `Connection.init` static method which accepts a `Config`. It is then
authenticated by calling auth on the resulting opened connection:

```java
Connection.init(conf).thenCompose(conn -> conn.auth()).thenCompose(conn -> /* do stuff */);
```

Note, this example does not block for response or close the connection but normal code would. A shortcut for this is to
just call `Connection.authed`.

Once the connection is done, just call `terminate` or pass a future to `terminated`:

```java
Connection.authed(conf).thenCompose(conn -> conn.terminated(/* do stuff returning future */)).get();
```

This example does block using `get` at the end. It also calls `terminated` to close the connection after stuff is done.
Here is an example of fetching a simple string from a query:

```java
List<QueryMessage.Row> rows = Connection.authed(conf).thenCompose(conn ->
    conn.terminated(conn.simpleQueryRows("SELECT current_database() AS database_name"))).get();
System.out.println("Current DB: " + RowReader.DEFAULT.get(rows.get(0), "database_name", String.class));
```

`RowReader` is covered later.

#### Create and use a connection pool

A `ConnectionPool` can be created with a `Config` like a connection and has a `withConnection` method that helps make
sure connections can be reused:

```java
ConnectionPool pool = new ConnectionPool(conf);
List<QueryMessage.Row> rows = pool.withConnection(conn ->
    conn.simpleQueryRows("SELECT current_database() AS database_name")).get();
System.out.println("Current DB: " + RowReader.DEFAULT.get(rows.get(0), "database_name", String.class));
```

The `Config`'s `poolSize` determines the fixed pool size. While not set by default, developers are encouraged to set
`Config.poolValidationQuery` to something like `SELECT 1` to make sure borrowed connections are always valid. A
`ConnectionPool` should be closed after use. For the rest of these examples, the `pool` variable above will be reused.

#### Execute simple queries

To execute a simple query and retrieve the query result connection state, use `simpleQuery`. This usage requires that
you mark the result `done`. There are convenience methods to do this automatically and return values. They are
`simpleQueryExec` for discarding the result, `simpleQueryRowCount` to get the returned/affected row count, and
`simpleQueryRows` to get the row list:

```java
pool.withConnection(c ->
    c.simpleQueryExec("CREATE TEMP TABLE foo (bar VARCHAR(100))").
        // The result is just of type java.lang.Void anyways, so ignore it
        thenCompose(__ -> c.simpleQueryRowCount("INSERT INTO foo VALUES ('test1'), ('test2')")).
        // The result is an integer, so this outputs "Rows: 2"
        thenAccept(rowCount -> System.out.println("Rows: " + rowCount)).
        // Now select em all
        thenCompose(__ -> c.simpleQueryRows("SELECT * FROM foo")).
        // Show the strings
        thenAccept(rows ->
            System.out.println("Rows: " + rows.stream().
                map(row -> RowReader.DEFAULT.get(row, "bar", String.class)).collect(Collectors.joining(", ")))
        )
).get();
```

#### Reading row values

Rows are returned as `QueryMessage.Row` objects. These objects include metadata about the columns and the two
dimensional byte array, with a byte array for each column. Instead of putting the logic to convert from byte arrays
inside the row class, PgNio offers a `RowReader` class for reading row data. The class may be manually instantiated
with custom converters, but most common uses will use the `RowReader.DEFAULT` singleton:

```java
pool.withConnection(c ->
    c.simpleQueryRows("SELECT 'test' AS first_row, 12, '{5, 6}'::integer[]").
        thenAccept(rows -> {
            // Pass in the row, column name, and type to fetch
            System.out.println("Col 1: " + RowReader.DEFAULT.get(rows.get(0), "first_row", String.class));
            // Can also pass in the zero-based column index
            System.out.println("Col 2: " + RowReader.DEFAULT.get(rows.get(0), 1, Integer.class));
            // Even works with arrays
            System.out.println("Col 3: " + Arrays.toString(RowReader.DEFAULT.get(rows.get(0), 2, int[].class)));
        })
).get();
```

See the Javadoc for more information on custom column value converters. See the [Data Types](#data-types) section below
for more information on supported data types.

#### Execute queries with parameters

In the [PostgreSQL protocol](https://www.postgresql.org/docs/current/static/protocol.html), there are two ways to submit
queries. One is the simple query form which issues a query and gets row metadata and row data. These are the calls
prefixed with "simple". The other way is the "advanced" or "prepared" approach which separates the steps to parse the
query, bind parameters, describe the result, and execute the query. The "simple" approach can be seen as just combining
those 4 steps together in one call on the server side. PgNio offers separate calls for each of these steps allowing the
caller to choose when/how they are called. There are also "prepared" convenience methods analogous to the "simple"
convenience methods which invoke all of these steps internally:

```java
pool.withConnection(c ->
    // Ask for a series from 1 through a parameter (4 in this case)
    c.preparedQueryRows("SELECT * FROM generate_series(1, $1)", 4).
        // Will be a count of 4
        thenAccept(rows -> System.out.println("Row count: " + rows.size()))
).get();
```

Internally, PgNio uses a `ParamWriter` instance (configured with a default via `Config.paramWriter`) to convert from
Java types to PostgreSQL parameters. See the [Data Types](#data-types) for more information on suggested data types for
certain parameter types.

#### Reuse prepared queries

The prepared queries above are "unnamed" (internally they use an empty string as the name) which means they can't easily
be reused. PgNio supports named prepared queries which are stored for the life of the connection or until closed. Unlike
unnamed prepared queries, there aren't convenience methods to create a named query, but convenience methods can be used
for binding, executing, and retrieving rows:

```java
pool.withConnection(c ->
    c.simpleQueryExec("CREATE TEMP TABLE foo (bar VARCHAR(100))").
        thenCompose(__ -> c.prepareReusable("myquery", "INSERT INTO foo VALUES ($1)")).
        // We would use bindDescribeExecuteAndDone if this were a select
        thenCompose(prepared -> prepared.bindExecuteAndDone("test1")).
        thenCompose(result -> result.done()).
        // Count will be 1
        thenCompose(__ -> c.simpleQueryRows("SELECT COUNT(1) FROM foo")).
        thenAccept(rows ->
            System.out.println("Count: " + RowReader.DEFAULT.get(rows.get(0), 0, Long.class))).
        // Reuse the query
        thenCompose(__ -> c.reusePrepared("myquery")).
        thenCompose(prepared -> prepared.bindExecuteAndDone("test2")).
        thenCompose(result -> result.done()).
        // Count will be 2
        thenCompose(__ -> c.simpleQueryRows("SELECT COUNT(1) FROM foo")).
        thenAccept(rows ->
            System.out.println("Count: " + RowReader.DEFAULT.get(rows.get(0), 0, Long.class))).
        // Try to close the statement regardless of error
        handle((__, ex) ->
            c.reusePrepared("myquery").
                thenCompose(prepared -> prepared.closeStatement()).
                thenCompose(prepared -> prepared.done()).
                thenCompose(result -> result.done()).
                thenAccept(___ -> { if (ex != null) throw new RuntimeException(ex); })).
        thenCompose(Function.identity())
).get();
```

Note, "life of the connection" means as long as the socket is open to the server. So when using a connection pool,
developers should always close their prepared statements or they will remain open as long as the connection does.

#### Use transactions

The regular "ready for query" connection state is the `QueryReadyConnection.AutoCommit` class which automatically
commits everything. Running `beginTransaction` on it returns a `QueryReadyConnection.InTransaction` class which won't
return back to auto commit mode until `commitTransaction` or `rollbackTransaction` is executed. Example:

```java
pool.withConnection(c ->
    c.simpleQueryExec("CREATE TEMP TABLE foo (bar VARCHAR(100))").
        // Start the transaction
        thenCompose(__ -> c.beginTransaction()).
        // Insert a value
        thenCompose(txn -> txn.simpleQueryExec("INSERT INTO foo VALUES ('test')").thenApply(__ -> txn)).
        // Count should be 1
        thenCompose(txn ->
            txn.simpleQueryRows("SELECT COUNT(1) FROM foo").thenApply(rows -> {
                System.out.println("Count: " + RowReader.DEFAULT.get(rows.get(0), 0, Long.class));
                return txn;
            })).
        // Roll it back
        thenCompose(txn -> txn.rollbackTransaction()).
        // Count should be 0
        thenCompose(conn -> conn.simpleQueryRows("SELECT COUNT(1) FROM foo")).
        thenAccept(rows ->
            System.out.println("Count: " + RowReader.DEFAULT.get(rows.get(0), 0, Long.class)))
).get();
```

Transactions can also be nested which is internally supported via savepoints.

#### Listen for notifications

PostgreSQL has `LISTEN`/`NOTIFY` support which allows pub/sub. PgNio allows subscription to these messages on a per
connection basis. Once subscribed to the messages, it must be read from the server side. This will happen during normal
query operations since a notification is sent along with other messages. But if not querying, developers need to wait
while reading for a message, which can be done via `unsolicitedMessageTick` and a timeout.

```java
// Create a listener
CompletableFuture listener = pool.withConnection(c -> {
    // Subscribe to the notification
    c.notifications().subscribe(notification -> {
        System.out.println("Got: " + notification.payload);
        // This function requires a future result so it can continue on its way.
        // Here we just return a completed nothing, but developers could listen for another message if they wanted.
        return CompletableFuture.completedFuture(null);
    });
    // Let PostgreSQL know we're listening
    return c.simpleQueryExec("LISTEN my_notifications").
        // Wait for 30 seconds for a single message.
        // To listen for more messages, we'd have to call this again.
        thenCompose(__ -> c.unsolicitedMessageTick(30, TimeUnit.SECONDS));
});

// Send a notification
pool.withConnection(c -> c.simpleQueryExec("NOTIFY my_notifications, 'test1'")).get();

// Wait for listener to end
listener.get();
```

In addition to notifications, developers can also listen for notices and server parameter/option changes (e.g. time zone
change). Note, when a connection is returned to a pool, all of its subscriptions are cleared. Same thing when a
connection is terminated. Therefore, developers who want to listen to notifications for a longer period should consider
creating a longer lived connection or just never giving the connection back to the pool.

#### Copy to a table

PostgreSQL supports a fast insert mode called a [COPY](https://www.postgresql.org/docs/current/static/sql-copy.html) and
PgNio supports it. Here's how to insert some CSV values:

```java
pool.withConnection(c ->
    c.simpleQueryExec("CREATE TEMP TABLE foo (bar VARCHAR(100), baz integer)").
        // Begin copy
        thenCompose(__ -> c.simpleCopyIn("COPY foo FROM STDIN CSV")).
        thenCompose(copy -> copy.sendData("test1,123\n".getBytes(StandardCharsets.UTF_8))).
        thenCompose(copy -> copy.sendData("test2,456\n".getBytes(StandardCharsets.UTF_8))).
        thenCompose(copy -> copy.done()).
        // Count should be 2
        thenCompose(__ -> c.simpleQueryRows("SELECT COUNT(1) FROM foo")).
        thenAccept(rows ->
            System.out.println("Count: " + RowReader.DEFAULT.get(rows.get(0), 0, Long.class)))
).get();
```

There are other formats including the default text format. `ParamWriter` can be used to help with this.

#### Copy from a table

Copying can also occur when reading out from a table:

```java
pool.withConnection(c ->
    c.simpleQueryExec("CREATE TEMP TABLE foo (bar VARCHAR(100), baz integer);" +
            "INSERT INTO foo VALUES ('test1', 123), ('test2', 456)").
        thenCompose(__ -> c.simpleCopyOut("COPY foo TO STDOUT CSV")).
        thenCompose(copy -> {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            return copy.
                receiveEachData(b -> {
                    try { bytes.write(b); }
                    catch (IOException e) { throw new RuntimeException(e); }
                }).
                thenAccept(__ ->
                    System.out.println("Got:\n" + new String(bytes.toByteArray(), StandardCharsets.UTF_8))).
                thenCompose(__ -> copy.done());
        })
).get();
```

#### Cancelling a query

In PostgreSQL, a long-running query cannot simply be cancelled within the same connection. Instead, a separate
connection must be created solely to cancel using the original connection's process ID and secret key:

```java
// We'll just set the process ID and secret key into an int array
CompletableFuture<int[]> processIdAndSecretKey = new CompletableFuture<>();

// Run a query for 10 seconds
CompletableFuture longQuery = pool.withConnection(c -> {
    // Set the process ID and secret key of this connection
    processIdAndSecretKey.complete(new int[] { c.getProcessId(), c.getSecretKey() });
    // Wait 10 seconds
    return c.simpleQueryExec("SELECT pg_sleep(10)");
});

// Kill that query
processIdAndSecretKey.thenCompose(idAndKey ->
    Connection.init(conf).thenCompose(c -> c.cancelOther(idAndKey[0], idAndKey[1]))).get();

// This will throw an exception since it was cancelled
longQuery.get();
```

Note, the newly created connection doesn't have to be explicitly closed/terminated because it is implied with
`cancelOther`.

#### More...

Many more cases are not covered here but can be learned from the code or test cases including:

* Advanced handling of query results including asking for one row at a time, skipping results, etc
* Fetching a maximum bound-query row set then fetching more
* Nested transactions
* Fetching results from multiple queries
* Using `flush` instead of `done` on prepared/bound queries
* Describing prepared statements to get parameter requirements
* Custom `Converters` for `RowReader` and/or `ParamWriter`
* `Notice` use and subscription
* `SSL` including use of custom `SSLContext`s to validate keys

### Data types

Below is a table of PostgreSQL types and their suggested Java data type. Some Java types can be used for multiple
PostgreSQL types and some PostgreSQL types can be represented by multiple Java types. These are listed in the order
they appear in the [PostgreSQL data type documentation](https://www.postgresql.org/docs/current/static/datatype.html)

| PostgreSQL Type | Java Type
| --- | --- |
| `smallint` | `java.lang.Short` |
| `integer` | `java.lang.Integer` |
| `bigint` | `java.lang.Long` |
| `decimal` | `java.lang.BigDecimal`1 |
| `numeric` | `java.lang.BigDecimal`1 |
| `real` | `java.lang.Float` |
| `double precision` | `java.lang.Double` |
| `smallserial` | `java.lang.Short` |
| `serial` | `java.lang.Integer` |
| `bigserial` | `java.lang.Long` |
| `money` | `pgnio.DataType.Money` |
| `varchar(n)` | `java.lang.String` |
| `char(n)` | `java.lang.String` |
| `text` | `java.lang.String` |
| `bytea` | `byte[]` |
| `timestamp without time zone` | `java.time.LocalDateTime` |
| `timestamp with time zone` | `java.time.OffsetDateTime` |
| `date` | `java.time.LocalDate` |
| `time without time zone` | `java.time.LocalTime` |
| `time with time zone` | `java.time.OffsetTime` |
| `interval` | `pgnio.DataType.Interval` |
| `boolean` | `java.lang.Boolean` |
| enumerated types | `java.lang.String` |
| `point` | `pgnio.DataType.Point` |
| `line` | `pgnio.DataType.Line` |
| `lseg` | `pgnio.DataType.LineSegment` |
| `box` | `pgnio.DataType.Box` |
| `path` | `pgnio.DataType.Path` |
| `polygon` | `pgnio.DataType.Polygon` |
| `circle` | `pgnio.DataType.Circle` |
| `inet` | `pgnio.DataType.Inet` |
| `cidr` | `pgnio.DataType.Inet` |
| `macaddr` | `pgnio.DataType.MacAddr` |
| `macaddr8` | `pgnio.DataType.MacAddr` |
| `bit(n)` | `java.lang.String` |
| `bit varying(n)` | `java.lang.String` |
| `tsvector` | `java.lang.String` |
| `tsquery` | `java.lang.String` |
| `uuid` | `java.util.UUID` |
| `xml` | `java.lang.String` |
| `json` | `java.lang.String` |
| `jsonb` | `java.lang.String` |
| arrays | arrays |
| `hstore` | `java.util.Map<String, String>` |
| all other types | `java.lang.String` |

Notes:

1. If `decimal` or `numeric` are expected to ever be NaN or infinity, users might prefer to deserialize to `String`
   first before converting to `BigDecimal`. Otherwise an exception occurs. For parameters that need to be NaN or
   infinity, consider using a float or double.

### FAQ

#### Why was this built?

My company needs a non-blocking PostgreSQL Java driver that is simple and yet can be used for advanced items. The other
ones carry unnecessary dependencies, are opinionated on what they make visible, aren't very configurable with
serialization, don't allow flexible use of the protocol, don't support all PostgreSQL features, and/or are
unmaintained (I've opened issues or made PRs on some of them). Granted there is no guarantee that this one will be
maintained forever either.

As mentioned in the features/goals section, this library is simple, extensible, and both low-level + high-level.
Serialization concerns are separated from protocol use. I also wanted to build this in preparation for the upcoming
async JDBC API and to develop a deep understanding of the PostgreSQL protocol.

#### Is "asynchronous" or "non-blocking" really better?

No. Sometimes it is when you don't want to use a thread per connection though internally NIO leverages thread
groups/pools. Also, since PostgreSQL's protocol doesn't support multiplexing a single connection there is even less
benefit than there might be with other protocols. Having said that, rarely is it worse and this library could easily be
used in a higher-level, synchronous, blocking application or library.

#### Why aren't there built-in conversions for lists, sets, etc?

In order to make this library simple, only the practical converters are included. Those collections can easily be
derived from arrays and/or custom converters can easily be written to build them.

#### Why don't the conversions support `Type` lookups instead of `Class` lookups?

For the `RowReader`, the `get` accepts a `Class` instead of a `Type`. There was no need using the current converters
to support generic types, but this may change in the future.

#### Why don't the conversions look up by implemented interface instead of just superclass?

For the current set of converters, simply traversing the class hierarchy to find a suitable conversion was good enough.
If there is a need for a converter for an interface, this could be supported in the future.

#### Why can't reading an `hstore` into a `Map` use the key and value types?

This library only supports `hstore` converting to a `Map<String, String>`. One might assume that, like arrays, it should
allow map values of other types that recursively does conversions on them. But PostgreSQL doesn't tell you the value
types of `hstore`. It was decided to perform the simple conversion. There is a `RowReader.get` call that accepts a
string if the caller wants to convert further, but it was decided that this library would not do it for them.

#### What about binary formatted parameters and results?

PostgreSQL has two formats in the protocol for parameters and results: binary and text. Right now, PgNio only supports
the text format (the default). The text format sends everything as normal strings and is portable across PostgreSQL
versions. This is usually good enough for almost all purposes. However, as more use cases for binary formatting come
about, it very well might be implemented in the library. In the meantime, the library is built to be extensible enough
that `ParamWriter`s and `RowReader`s operate purely on bytes and anyone can write binary formatters. Also, all protocol
calls that support specifying text or binary format are exposed to let the caller choose if they want.

### Development

#### Style

PgNio gladly accepts pull requests. In general the style is two-space indent, 120-char line max, and try to be clean
with line wrapping ideally with punctuation at the end of the line instead of the start. Since this is also a library
that can be used as a basis for others, we prefer to set the visibility protected instead of private or package-private
for anything that could have any value to anyone. We prefer fields over getters, nested classes over a bunch of files, simpler code over longer code, and clarity over confusion.

The [checker framework](https://checkerframework.org/) is used mainly to check nullability. This is preferred over
runtime checks for this library. Sometimes the initialization constraints get in the way, so feel free to mark code
`@SuppressWarnings("initialization")`.

#### Building

The project can be built with Gradle. Unlike other projects, PgNio does not bundle a Gradle wrapper script with the
repository. Simply download Gradle to `some/path` and run:

    some/path/bin/gradle --no-daemon :driver:assemble

Granted `--no-daemon` is just a choice that some choose to not keep a running Java process in the background, but it
will be a slower build. Also, the [checker framework](https://checkerframework.org/)'s annotation processor slows down
compilation quite a bit.

#### Testing

The unit tests are more like integration tests in that they actually run a PostgreSQL instance as an
[embedded PostgreSQL server](https://github.com/yandex-qatools/postgresql-embedded/). It will automatically download
itself and create directories as needed in `~/.embedpostgresql`. To run all tests, simply:

    some/path/bin/gradle --no-daemon :driver:test

By default it chooses the latest PostgreSQL version configured in the library (`10.2` as of this writing). A different
version can be used by setting the version number that appears in the
[download link](https://www.enterprisedb.com/download-postgresql-binaries) as the system property
`pgnio.postgres.version`. It is usually just the version with `-1` appended. So to test against `9.6.7`:

    some/path/bin/gradle --no-daemon :driver:test -Dpgnio.postgres.version=9.6.7-1

Note, on Windows sometimes the process remains open or there are other oddities. Developers may have to kill the
processes themselves and/or make sure the data files at `~/.embedpostgresql/data` are actually deleted (that is
the `C:\Users\username\.embedpostgresql\data` directory).

#### Using Latest Master

For updates that may not have been released into a numbered version, developers can use
[JitPack](https://jitpack.io/#cretz/pgnio/master-SNAPSHOT). Essentially this means using the JitPack resolver in the
build tool, and setting a dependency on the group `com.github.cretz`, name `pgnio`, and version `master-SNAPSHOT`.

#### Java 9+

When using Java 9 or newer to compile, the checker framework
[cannot perform checks](https://github.com/typetools/checker-framework/issues/1224) so it is disabled. For this reason,
developers ar encouraged to use Java 8 when compiling the `driver` project.

#### ADBA Support

**NOTE: Work on ADBA support has been suspended. See [this issue](https://github.com/cretz/pgnio/issues/8) for more
info.**

Asynchronous database access support (a.k.a. ADBA, JDBC-Next, async JDBC, java.sql2, etc) is currently in development
in the `adba` subproject which uses Java 9. This means that Java 9+ must be used to compile it which, as mentioned
above, disables checker framework checks.

ADBA support requires the ADBA source which is available from the
[OpenJDK sandbox](http://hg.openjdk.java.net/jdk/sandbox/file/9d3b0eb749a9/src/jdk.incubator.adba) as of this writing.
Developers have to compile it to use it; [here](https://gist.github.com/cretz/fb21718d2456fe5d581c9d536c011d99) is a
`build.gradle` script that will build the ADBA JAR when `assemble` is run. Once the JAR is available, the full path to
the JAR must be set as the `adba.jar.path` system property when running the `adba` build in this project. E.g.:

    some/path/bin/gradle --no-daemon :adba:assemble -Dadba.jar.path=/full/path/to/jdk.incubator.adba.jar

Or if you are using an IDE such as IntelliJ this can be set as a Gradle option in the settings.

### TODO

* Streaming/logical replication
* Support other authentication options

repository: wiltonlazary/pgnio

repo_name: wiltonlazary/pgnio


text:
---
title: Faster builds, please
date: 2021-11-25

categories:
    - changelog

tags:
    - self-hosted
    - static-site
---

It's been only a couple of days since I've [started again][started-again] and
more things have changed over here. I've quickly discovered, after half a dozen
deploys, about some of the inconveniences of Cloudflare Pages that people
didn't seem to care enough to talk about. Here's what I've noticed:

1. __The worker startup is painfully slow__. Every time a new change hits
   GitHub, a new build is triggered on Pages and so a new worker must be
   started to actually build and release the website into the internet. And for
   some unknown reason, the startup process alone was taking half of the
   average needed time -- 5 to 6 minutes to run the entire pipeline and half of
   it was just to spin-up the VM (or container, I don't know). And this
   behaviour happened consistently.

1. __The installation of dependencies are mandatory__. If pages detects a
   manifest file -- `Pipfile`, `package.json`, `Gemfile` etc -- it __will__
   install of it's dependencies. You simply cannot skip this. This might not
   sound that bad, but...

1. __Cloudflare Pages don't cache your build__. No, I'm not talking about
   Cloudflare's CDN. I'm talking about all the node modules and other stuff
   generated at build time. Again, this might not sound that bad, but jekyll
   for instance relies on Ruby gems that binds to C code, which of course are
   system / arch-dependent and must be compiled every time. Having the option
   to specify a list of directories that must be cached between executions
   would greatly improve the build speed.

## So??

Yes, a 5 minutes pipeline is not a lot, but it felt wasteful, so I did some
changes...

1. __The build is now being made on Github Actions__ and the modules / packages
   / libs are now cacheable. The first run took 5 minutes just to install and
   compile all the dependencies; the subsequent ones, only 4 seconds. An entire
   build pipeline takes no more than a minute now.

1. The builded files -- HTML pages and stylesheets -- have their own place now:
   a [separate git repository][sep-git-repo].

1. __This site is not on Cloudflare Pages anymore__.

The pipeline is a little more complex, but more faster (on average, 2 minutes
from `git push` to a new site version be live on the internet). A `git commit`
triggers the GitHub Action that builds the site and commits to the other
repository, which in turn triggers [Render][render] -- I've talked about this
guy last post. Render can do it's job in a little more than a minute -- here's
what a build outlook looks like:

```verilog
Nov 25 12:19:40 AM  ==> Cloning from https://github.com/caian-org/caian.org-dist...
Nov 25 12:19:41 AM  ==> Checking out commit 081d48b in branch master
Nov 25 12:19:54 AM  ==> Downloading cache...
Nov 25 12:19:57 AM  ==> Downloaded 5.0MB in 1s. Extraction took 1s.
Nov 25 12:20:06 AM  ==> Using Python version: 3.7.10
Nov 25 12:20:10 AM  ==> Empty build command; skipping build
Nov 25 12:20:25 AM  ==> Uploading build...
Nov 25 12:20:52 AM  ==> Your site is live 🎉
```

## Where will you be next month?

I don't plan to leave Render this soon, but I'll not make any promises. If I
could strip down one more build minute by going somewhere else, I would. For
now I'm overall happy with this new format / build process.

[started-again]: /blog/2021/11/06/starting-again.html
[sep-git-repo]: https://github.com/caian-org/caian.org-dist
[render]: https://render.com

gha_language: SCSS


text:
---
layout: post
title: "Creating Javascript Objects: new vs {}"
date: 2013-01-02 08:15
comments: true
categories: [javascript]
---

Recently I had a discussion with someone about creating javascript objects.

There are two main ways of doing this:

```javascript
 // Method 1 - Using the new operator
 var obj1 = new Object();

 // Method 2 - Using the literal syntax
 var obj = {};
```

Now, most likely, you use the literal syntax. It is the standard that you will find
out in the wild most of the time. And this is the method I use.

I started using the literal syntax way-back-when to save keystrokes.
At some point I was told that it was faster so I continued to use it.
But I've never confirmed that it is actually faster.

So is it really faster or is this just one of those old wise tales?

Let's ask our dear friend [jsperf](http://jsperf.com) and see what we can find.

And I'm back :)

Ok, based on using ``new object()`` and ``{}`` for object instantiation here are the results:

{% img /images/posts/object-testcase.png %}
{% img /images/posts/object-results.png %}

Wow I didn't think it would be that much of a difference! Clearly the object literal is the way to go
since it's significantly faster.

I am only testing on the V8 javascript engine so maybe this won't apply to other browsers.
I tried looking at the V8 source to see if I could'nt quickly find out exactly why this is happening
but with no luck.
My guess is that the constructor call is being executed for ``new`` and not for ``{}``
as an optimization trick for V8. When I have a more time I'd like to venture into the V8 source
and see what's going on. So if I find something I'll post it here.

From these results we can at least justifiably tell people that ``{}`` is not only easier on the eyes
but also easier on the old processor.

repository: craigerm/blog-sources

extension: markdown

repo_name: craigerm/blog-sources


text:
---
layout: post
title: LC 712. Minimum ASCII Delete Sum for Two Strings
categories: [medium, dynamic programming]
author: Sarthak Sehgal
---
# Example
```
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
```

# Solution
Recommended reading: [LC 1143. Longest Common Subsequence](https://sarthak-sehgal.github.io/leetcode101/lc1143/)

The question is pretty similar to the famous DP question, [longest common subsequence](https://sarthak-sehgal.github.io/leetcode101/lc1143/) and can be solved with slight modification. Instead of finding the longest common subsequence, we need to find the most "affordable" common subsequence of the two strings. The more the value of ASCII chars we have to delete, the less affordable is the common subsequence. Consider this example:
```
String 1: abcdef
String 2: defabc
These strings have two common subsequences of length 3 - "abc" and "def" but "def" is more affordable because we then have to only delete 2 a, 2 b and 2 c resulting in lower ASCII value of deleted characters.
```

So our aim is to find the longest common affordable subsequence. Define dp[i][j] as cost of string s1[0..i-1] and s2[0..j-1] where cost is the minimum sum of ASCII value of characters you'll have to remove to make these strings equal (i.e. sum of value of ASCII characters not in the longest common affordable substring). When s1[i-1] = s2[j-1], dp[i][j] is simply equal to dp[i-1][j-1] since we do not need to remove any character. But when s1[i-1] != s2[j-1], `dp[i][j] = min(dp[i-1][j] + s1[i-1], dp[i][j-1]+s2[j-1]);` as we can delete s1[i-1] or s2[j-1]. The idea is similar to [LC 1143. Longest Common Subsequence](https://sarthak-sehgal.github.io/leetcode101/lc1143/).

```
// Here dp[i][j] represents the characters we'll have to delete in the longest common affordable subsequence:
//    ""   e   a   t
// "" -    e   ea  eat
// s  s    se  sea seat
// e  se   s   se  set
// a  sea  sa  s   st

int minimumDeleteSum(string s1, string s2) {
    int len1=s1.length(), len2 = s2.length();
    vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));

    for (int i=1; i<=len1; i++)
        dp[i][0] = dp[i-1][0] + s1[i-1];

    for (int j=1; j<=len2; j++)
        dp[0][j] = dp[0][j-1] + s2[j-1];

    for (int i=1; i<=len1; i++) {
        for (int j=1; j<=len2; j++) {
            if (s1[i-1] == s2[j-1])
                dp[i][j] = dp[i-1][j-1];
            else
                dp[i][j] = min(dp[i-1][j] + s1[i-1], dp[i][j-1]+s2[j-1]);
        }
    }

    return dp[len1][len2];
}
```
Time complexity: O(len1 * len2)<br>
Space complexity: O(len1 * len2)


text:
# This is [fine-rest](https://www.npmjs.com/package/fine-rest)

#### A fine way to define REST server-side routes in Meteor.
##### Make your Meteor app's data accessible over HTTP. Integrate your Meteor backend into a native mobile app or just query your data over HTTP from any client.
---
Install fine-rest in your Meteor project via npm:

```bash
$ meteor npm install --save fine-rest
```

Now use fine-rest in project like so:

```javascript
import { JsonRoutes } from 'fine-rest';
```

A Meteor example application using fine-rest:

### [Meteor Web API Example](https://github.com/aadamsx/meteor-web-app-test)

---

### This package was formally the following Meteor packages, their functionality now rolled into one fine NPM package:

### [json-routes](#json-routes-1)
### [authenticate-user-by-token](#authenticate-user-by-token-1)
### [rest-accounts-password](#rest-accounts-password-1)
### [rest-bearer-token-parser](#rest-bearer-token-parser-1)
### [rest-json-error-handler](#rest-json-error-handler-1)

...
### [Change Log](#change-log-1)

---

# json-routes

A bare-bones way to define server-side JSON API endpoints, without
any extra functionality. Based on [connect-route].

### Example

```js
JsonRoutes.add("get", "/posts/:id", function (req, res, next) {
  var id = req.params.id;

  JsonRoutes.sendResult(res, {
    data: Posts.findOne(id)
  });
});
```

## API

### JsonRoutes.add(method, path, handler)

Add a server-side route that returns JSON.

- `method` - The HTTP method that this route should accept: `"get"`, `"post"`,
  etc. See the full list [here][connect-route L4]. The method name is
  case-insensitive, so `'get'` and `'GET'` are both acceptable.
- `path` - The path, possibly with parameters prefixed with a `:`. See the
  example.
- `handler(request, response, next)` - A handler function for this route.
  `request` is a Node request object, `response` is a Node response object,
  `next` is a callback to call to let the next middleware handle this route. You
  don't need to use this normally.

### JsonRoutes.sendResult(response, options)

Return data fom a route.

- `response` - Required. The Node response object you got as an argument to your handler function.
- `options.code` - Optional. The status code to send. `200` for OK, `500` for internal error, etc. Default is 200.
- `options.headers` - Optional. Dictionary of headers to send back.
- `options.data` - Optional. The data you want to send back. This is serialized to JSON with content type `application/json`. If `undefined`, there will be no response body.

## Errors

We recommend that you simply throw an Error or Meteor.Error from your handler function. You can then attach error handling middleware that converts those errors to JSON and sends the response. Here's how to do it with our default error middleware:

```js
JsonRoutes.ErrorMiddleware.use(
  '/widgets',
  RestMiddleware.handleErrorAsJson
);

JsonRoutes.add('get', 'widgets', function () {
  var error = new Meteor.Error('not-found', 'Not Found');
  error.statusCode = 404;
  throw error;
});
```

### JsonRoutes.setResponseHeaders(headerObj)

Set the default headers used by `JsonRoutes.sendResult` for the response. Default value is:

```js
{
  "Cache-Control": "no-store",
  "Pragma": "no-cache"
}
```

You can pass additional headers directly to `JsonRoutes.sendResult`

## Adding Middleware

If you want to insert connect middleware and ensure that it runs before your
REST route is hit, use `JsonRoutes.Middleware`.

```js
JsonRoutes.Middleware.use(function (req, res, next) {
  console.log(req.body);
  next();
});
```

## Creating Middleware Packages

Once you've created an awesome piece of reusable middleware and you're ready to
share it with the world, you should make it a Meteor package so it can be easily
configured in any JSON Routes API. There are only two requirements.
Actually, they're just very strong recommendations. Nothing will explode if you
don't follow these guidelines, but doing so should promote a much cleaner
middleware ecosystem.

Each middleware package should define a single middleware function and add it
to `RestMiddleware` namespace:

```js
RestMiddleware.someMiddlewareFunc = function (req, res, next) {
  // Do some awesome middleware stuff here
};

RestMiddleware.someMiddlewareErrorFunc = function (err, req, res, next) {
  // Do some awesome middleware error handling here
};
```

Alternatively, you could publish a pure NodeJS middleware package to NPM, and you will be able to require it and use it in your Meteor package or app.

### Auth Middleware

- By convention, any middleware you create that parses the request to find an authentication token should then save that token on `req.authToken`. See `rest-bearer-token-parser` for an example.
- By convention, any middleware you create that determines a user ID should save that ID on `req.userId`. See `authenticate-user-by-token` for an example.

---

# authenticate-user-by-token
Middleware for validating a Meteor.user's login token

## Middleware Name

This middleware can be accessed as:

**`JsonRoutes.Middleware.authenticateMeteorUserByToken`**

### Request Properties Required

- `request.authToken`
  - _String_
  - A valid login token for a `Meteor.user` account (requires `accounts-base`)

### Request Properties Modified

- `request.userId`
  - _String_
  - If the `request.authToken` is found in a user account, sets this to the ID of the authenticated user. Otherwise, `null`.

## Usage

Simply add this layer of middleware after any token parsing middleware, and voila!

For example:

```js
JsonRoutes.Middleware.use('/auth', JsonRoutes.Middleware.parseBearerToken);
JsonRoutes.Middleware.use('/auth', JsonRoutes.Middleware.authenticateMeteorUserByToken);

JsonRoutes.add('GET', 'auth/test', function (request, response) {
  // The authenticated user's ID will be set by this middleware
  var userId = request.userId;
});
```

---

# rest-accounts-password

## Log in and register password accounts over HTTP

If you have `accounts-password` in your app, and you want to be able to use it over HTTP, this is the package for you. Call these APIs to get an access token, and pass that token to API methods you defined with [`json-routes`](#json-routes-1) to call methods and publications that require login.

Make sure to serve your app over HTTPS if you are using this for login, otherwise people can hijack your passwords. Try the [`force-ssl` package](https://atmospherejs.com/meteor/force-ssl).

### POST /users/login, POST /users/register, POST /users/token-login

The login and registration endpoints take the same inputs. Pass an object with the following properties:

- `username`
- `email`
- `password`
- `dbId`

`password` is required, and you must have at least one of `username` or `email`.  dbId is optional and for multi-database scenarios.

The token-login endpoint only requires a token and optionally a Database ID.

- `dbId`
- `loginToken`

#### Responses

Both login and registration have the same response format.

```js
// successful response, with HTTP code 200
{
  token: "string",
  tokenExpires: "ISO encoded date string",
  id: "user id"
}

// error response, with HTTP code 500
{
  error: "error-code",
  reason: "Human readable error string"
}
```

### Authentication

After adding this package, API endpoints accept a standard bearer token header (Based on [RFC 6750](http://tools.ietf.org/html/rfc6750#section-2.1) and [OAuth Bearer](http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#authz-header)).

```http
Authorization: Bearer <token>
```

Here is how you could use Meteor's `http` package to call a method as a logged in user. Inside the method, the current user can be accessed the exact same way as in a normal method call, through `this.userId`.

```js
HTTP.post("/methods/return-five-auth", {
  headers: { Authorization: "Bearer " + token }
}, function (err, res) {
  console.log(res.data); // 5
});
```

---

# rest-bearer-token-parser

Middleware for parsing a standard bearer token from an HTTP request

### Middleware Name

This middleware can be accessed as:

**`JsonRoutes.Middleware.parseBearerToken`**

### Request Properties Required

- None

### Request Properties Modified

- `request.authToken`
  - _String_
  - The parsed bearer token, or `null` if none is found

## Usage

Accepts tokens passed via the standard header or URL query parameter (whichever is found first, in that order).

The header signature is: `Authorization: Bearer <token>`

The query signature is: `?access_token=<token>`

---

## rest-json-error-handler

Middleware for converting thrown Meteor.Errors to JSON and sending the response.

## Usage

Handle errors from all routes:

```js
JsonRoutes.ErrorMiddleware.use(RestMiddleware.handleErrorAsJson);
```

Handle errors from one route:

```js
JsonRoutes.ErrorMiddleware.use(
  '/handle-error',
  RestMiddleware.handleErrorAsJson
);
```

## Example

```js
JsonRoutes.ErrorMiddleware.use(
  '/handle-error',
  RestMiddleware.handleErrorAsJson
);

JsonRoutes.add('get', 'handle-error', function () {
  var error = new Meteor.Error('not-found', 'Not Found');
  error.statusCode = 404;
  throw error;
});
```

---

# Change Log

#### 2.0.0

- Added ability to log in with token at ```/users/token-login```.
- Pass in an optional Database ID for multi database scenarios to ```/users/login```.
- The log in option ```/users/login``` now has the option to pass in a Database ID for multi database scenarios.
- Use the setting.json file in your root project to specify your database ID.

#### 1.0.0 - 1.0.12

- Refactored code and converted over `JsonRoutes` & related packages to NPM fine-rest

repository: aadamsx/fine-rest

repo_name: aadamsx/fine-rest


text:
# aspnetcore-httpclientextensions

[![CircleCI](https://circleci.com/gh/bolorundurowb/aspnetcore-httpclientextensions.svg?style=svg)](https://circleci.com/gh/bolorundurowb/aspnetcore-httpclientextensions)

## About ASP.NET Core HttpClient Extensions

Adds extension methods that allow you pass strongly typed objects as parameters to the `HttpClient` instance.

## Usage

To make use of this library, add it to your project from Nuget using any of the following methods.

```bash
PM> Install-Package AspNet.Http.Extensions
```

or

```bash
dotnet add package AspNet.Http.Extensions
```

or

```bash
paket add AspNet.Http.Extensions
```

Add the appropriate namespace to your class

```csharp
using AspNet.Http.Extensions;
```

Create an instance of `HttpClient`

```csharp
var client = new HttpClient();
```

Create an instance of your payload class

```csharp
var payload = new Foo { Name = "Bar" };
```

Make your HTTP request

```csharp
var response = client.PostAsJsonAsync('url', payload);
```

## Other methods

the library also provides two other extension methods; `PutAsJsonAsync` and `ReadAsJsonAsync`.

gha_language: C#


text:
# regexparam [![Build Status](https://travis-ci.org/lukeed/regexparam.svg?branch=master)](https://travis-ci.org/lukeed/regexparam)

> A tiny (299B) utility that converts route patterns into RegExp. Limited alternative to [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp) 🙇

With `regexparam`, you may turn a pathing string (eg, `/users/:id`) into a regular expression.

An object with shape of `{ keys, pattern }` is returned, where `pattern` is the `RegExp` and `keys` is an array of your parameter name(s) in the order that they appeared.

Unlike [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp), this module does not create a `keys` dictionary, nor mutate an existing variable. Also, this only ships a parser, which only accept strings. Simiarly, and most importantly, `regexparam` **only** handles basic pathing operators:

* Static (`/foo`, `/foo/bar`)
* Parameter (`/:title`, `/books/:title`, `/books/:genre/:title`)
* Optional Parameters (`/:title?`, `/books/:title?`, `/books/:genre/:title?`)
* Wildcards (`*`, `/books/*`, `/books/:genre/*`)

Lastly, please note that while this route-parser is not slow, you should use [`matchit`](https://github.com/lukeed/matchit#benchmarks) or [`trouter`](https://github.com/lukeed/trouter) if performance is of critical importance. This is epsecially true for backend/server scenarios!

This module exposes two module definitions:

* **ES Module**: `dist/regexparam.es.js`
* **CommonJS**: `dist/regexparam.js`

## Install

```
$ npm install --save regexparam
```

## Usage

```js
const regexparam = require('regexparam');

let foo = regexparam('users/*');
// foo.keys => ['wild']
// foo.pattern => /^\/users\/(.*)(?:\/)?\/?$/i

let bar = regexparam('/books/:genre/:title?')
// bar.keys => ['genre', 'title']
// bar.pattern => /^\/books\/([^\/]+?)(?:\/([^\/]+?))?(?:\/)?\/?$/i

bar.pattern.test('/books/horror'); //=> true
bar.pattern.test('/books/horror/goosebumps'); //=> true

// Example param-assignment
function exec(path, result) {
  let i=0, out={};
  let matches = result.pattern.exec(path);
  while (i < result.keys.length) {
    out[ result.keys[i] ] = matches[++i] || null;
  }
  return out;
}

exec('/books/horror', bar);
//=> { genre:'horror', title:null }

exec('/books/horror/goosebumps', bar);
//=> { genre:'horror', title:'goosebumps' }
```

> **Important:** When matching/testing against a generated RegExp, your path **must** begin with a leading slash (`"/"`)!

## API

### regexparam(str)

Returns: `Object`

#### str

Type: `String`

The route/pathing string to convert.

> **Note:** It does not matter if your `str` begins with a `/` -- it will be added if missing.

## License

MIT © [Luke Edwards](https://lukeed.com)

repository: malbernaz/regexparam

repo_name: malbernaz/regexparam