text:
# LogCLI

Go [here](../README.md) to setup Loki

## Install

Install the binary:

```
$ wget https://github.com/grafana/loki/releases/download/v2.7.0/logcli-darwin-amd64.zip
$ unzip logcli-darwin-amd64.zip
$ sudo mv logcli-darwin-amd64 /usr/local/bin/logcli
$ sudo chmod +x /usr/local/bin/logcli
```

Configure the environment:

```
$ export LOKI_ADDR=https://localhost:3100
$ export LOKI_USERNAME=x
$ export LOKI_PASSWORD=x
```

Permamntly configure the environment:

```
$ echo -n "
export LOKI_ADDR=https://localhost:3100
export LOKI_USERNAME=admin
export LOKI_PASSWORD=admin
" >> ~/.bashrc
$ . ~/.bashrc
```

## Discover Labels

```
$ logcli labels
__name__
cluster_name
container_name
environment
job
```

View all the job labels:

```
$ logcli labels job
dev/dockerlogs
prod/dockerlogs
```

## Analyze Labels

```
$ logcli series '{job="dev/dockerlogs"}' --analyze-labels
Total Streams:  5
Unique Labels:  4

Label Name      Unique Values  Found In Streams
container_name  5              5
cluster_name    1              5
environment     1              5
job             1              5
```

## Query

Query by label value:

```
$ logcli query '{job="dev/dockerlogs"}'
```

Query by label value and match filter expression:

```
$ logcli query '{job="dev/dockerlogs"} |= "this string"'
```

Query by label value and dont match filter expression:

```
$ logcli query '{job="dev/dockerlogs"} != "this string"'
```

Query by label value and regex match filter expression:

```
$ logcli query '{job="dev/dockerlogs"} |~ "this string: (true|false)"'
```

Query by label value and dont match regex filter expression:

```
$ logcli query '{job="dev/dockerlogs"} !~ "this string and .+"'
```

Tail:

```
$ logcli query '{job="dev/dockerlogs"}' --tail
```

Since 4h ago:

```
$ logcli query '{job="dev/dockerlogs"}' --since 4h
```

Last 10 lines:

```
$ logcli query '{job="dev/dockerlogs"}' --last 10
```

Piping:

```
$ logcli query '{job="dev/dockerlogs"} |= "error"' | grep -i message
```

Suppress log labels:

```
$ logcli query -q '{job="dev/dockerlogs"}'
```

Change output:

```
$ logcli query -o raw '{job="dev/dockerlogs"}'
```

## More

For more detailed tutorials have a look at my blog at [blog.ruanbekker.com](https://blog.ruanbekker.com/blog/archives/)

repository: ruanbekker/cheatsheets

repo_name: ruanbekker/cheatsheets


text:
# 🏷 ahs - AWS EC2 Hostname Setter

[![PkgGoDev](https://pkg.go.dev/badge/github.com/mvisonneau/ahs)](https://pkg.go.dev/mod/github.com/mvisonneau/ahs)
[![Go Report Card](https://goreportcard.com/badge/github.com/mvisonneau/ahs)](https://goreportcard.com/report/github.com/mvisonneau/ahs)
[![Docker Pulls](https://img.shields.io/docker/pulls/mvisonneau/ahs.svg)](https://hub.docker.com/r/mvisonneau/ahs/)
[![Build Status](https://cloud.drone.io/api/badges/mvisonneau/ahs/status.svg)](https://cloud.drone.io/mvisonneau/ahs)
[![Coverage Status](https://coveralls.io/repos/github/mvisonneau/ahs/badge.svg?branch=master)](https://coveralls.io/github/mvisonneau/ahs?branch=master)

This projects aims to ease the configuration of AWS EC2 instances hostname.
In particular when they are launched as part of ASGs or fleets.

## TL;DR

```bash
# Using instance-id method
~$ ahs instance-id
INFO[2018-07-23T11:56:00Z] Found AZ: 'eu-west-1a'
INFO[2018-07-23T11:56:00Z] Computed region : 'eu-west-1'
INFO[2018-07-23T11:56:00Z] Found instance-id : 'i-096bed3161783f000'
INFO[2018-07-23T11:56:00Z] Querying input-tag 'Name' from EC2 API
INFO[2018-07-23T11:56:00Z] Computing hostname with truncated instance-id
INFO[2018-07-23T11:56:00Z] Computed unique hostname : 'myhostname-096be'
INFO[2018-07-23T11:56:00Z] Setting instance hostname locally
INFO[2018-07-23T11:56:00Z] Setting hostname on configured instance output tag 'Name'

# Using sequential method
~$ ahs sequential
INFO[2018-07-23T11:56:00Z] Found AZ: 'eu-west-1a'
INFO[2018-07-23T11:56:00Z] Computed region : 'eu-west-1'
INFO[2018-07-23T11:56:00Z] Found instance-id : 'i-096bed3161783f000'
INFO[2018-07-23T11:56:00Z] Querying input-tag 'Name' from EC2 API
INFO[2018-07-23T11:56:00Z] Computing a hostname with sequential naming
INFO[2018-07-23T11:56:00Z] Computed unique hostname : 'myhostname-1' - Sequential ID : '1'
INFO[2018-07-23T11:56:00Z] Setting instance hostname locally
INFO[2018-07-23T11:56:00Z] Setting hostname on configured instance output tag 'Name'
INFO[2018-07-23T11:56:00Z] Setting instance sequential id (1) on configured tag 'ahs:instance-id'
```

You can also use a containerized version if you prefer:

```bash
~$ docker run -it --rm --privileged mvisonneau/ahs <instance-id|sequential>
```

## Install

Have a look onto the [latest release page](https://github.com/mvisonneau/ahs/releases/latest) and pick your flavor.

### Go

```bash
~$ go install github.com/mvisonneau/ahs/cmd/ahs@latest
```

### Homebrew

```bash
~$ brew install mvisonneau/tap/ahs
```

### Docker

```bash
~$ docker run -it --rm --privileged mvisonneau/ahs
```

### Binaries, DEB and RPM packages

For the following ones, you need to know which version you want to install, to fetch the latest available :

```bash
~$ export AHS_VERSION=$(curl -s "https://api.github.com/repos/mvisonneau/ahs/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
```

```bash
# Binary (eg: linux/amd64)
~$ wget https://github.com/mvisonneau/ahs/releases/download/${AHS_VERSION}/ahs_${AHS_VERSION}_linux_amd64.tar.gz
~$ tar zxvf ahs_${AHS_VERSION}_linux_amd64.tar.gz -C /usr/local/bin

# DEB package (eg: linux/386)
~$ wget https://github.com/mvisonneau/ahs/releases/download/${AHS_VERSION}/ahs_${AHS_VERSION}_linux_386.deb
~$ dpkg -i ahs_${AHS_VERSION}_linux_386.deb

# RPM package (eg: linux/arm64)
~$ wget https://github.com/mvisonneau/ahs/releases/download/${AHS_VERSION}/ahs_${AHS_VERSION}_linux_arm64.rpm
~$ rpm -ivh ahs_${AHS_VERSION}_linux_arm64.rpm
```

## Usage

```bash
~$ ahs
NAME:
   ahs - Set the hostname of an EC2 instance based on a tag value and the instance-id

USAGE:
   ahs [global options] command [command options] [arguments...]

COMMANDS:
   instance-id  compute a hostname by appending the instance-id to a prefixed/base string
   sequential   compute a sequential hostname based on the number of instances belonging to the same group
   help, h      Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --dry-run              only display what would have been done (default: false) [$AHS_DRY_RUN]
   --help, -h             show help (default: false)
   --input-tag tag        tag to use as input to determine the hostname (default: "Name") [$AHS_INPUT_TAG]
   --log-format format    log format (json,text) (default: "text") [$AHS_LOG_FORMAT]
   --log-level level      log level (debug,info,warn,fatal,panic) (default: "info") [$AHS_LOG_LEVEL]
   --output-tag tag       tag to update with the computed hostname (default: "Name") [$AHS_OUTPUT_TAG]
   --persist-hostname     set /etc/hostname with generated hostname (default: false) [$AHS_PERSIST_HOSTNAME]
   --persist-hosts        assign generated hostname to <IP_ADDRESS> in /etc/hosts (default: false) [$AHS_PERSIST_HOSTS]
   --separator separator  separator to use between tag and id (default: "-") [$AHS_SEPARATOR]
   --version, -v          print the version
```

### InstanceID method

This method basically takes the output of a tag considered as the `base` of the hostname, it appends a separator to it (default to `-`) and finally a truncated value of the instance-id (default to `5 characters`).

```bash
~$ ahs instance-id -h
NAME:
   ahs instance-id - compute a hostname by appending the instance-id to a prefixed/base string

USAGE:
   ahs instance-id [command options]

OPTIONS:
   --length value  length of the id to keep in the hostname (default: 5) [$AHS_INSTANCE_ID_LENGTH]
```

### Sequential method

This method allows you to have sequential hostnames on instances on which you couldn't or haven't configured at the time of provisioning.

```bash
~$ ahs sequential -h
NAME:
   ahs sequential - compute a sequential hostname based on the number of instances belonging to the same group

USAGE:
   ahs sequential [command options]

OPTIONS:
   --instance-group-tag value          tag to use in order to determine which group the instance belongs to (default: "ahs:instance-group") [$AHS_INSTANCE_GROUP_TAG]
   --instance-sequential-id-tag value  tag to which output the computed instance-sequential-id (default: "ahs:instance-id") [$AHS_INSTANCE_SEQUENTIAL_ID_TAG]
   --respect-azs                       if instances are provisioned through an ASG, setting this flag it will get the sequential-ids associated to respective azs (default: false) [$AHS_RESPECT_AZS]
```

## Develop

You can have a look at the [Makefile](/Makefile) in order to see all available options:

```bash
~$ make
all                            Test, builds and ship package for all supported platforms
build                          Build the binaries using local GOOS
clean                          Remove binary if it exists
coverage                       Generates coverage report
coverage-html                  Generates coverage report and displays it in the browser
fmt                            Format source code
help                           Displays this help
install                        Build and install locally the binary (dev purpose)
is-git-dirty                   Tests if git is in a dirty state
lint                           Run all lint related tests upon the codebase
prerelease                     Build & prerelease the binaries (edge)
release                        Build & release the binaries (stable)
setup                          Install required libraries/tools for build tasks
test                           Run the tests against the codebase
```

## Contribute

Contributions are more than welcome! Feel free to submit a [PR](https://github.com/mvisonneau/ahs/pulls).

repository: mvisonneau/ahs

branch_name: refs/heads/main

extension: md

gha_language: Go

license_type: permissive

repo_name: mvisonneau/ahs


text:
# Image Data Set Creator
The application automates the creation of image data set from google image search, basic image preprocessing, and data augmentation.
## Installation

1. Installation of required python libraries

```bash
  pip install opencv-python
  pip install tensorflow
  pip install selenium
  pip install numpy
  pip install beautifulsoup4
  pip install Pillow
  pip install urllib3
  pip install PyQt5

```

2. Download chrome Driver
Download required version of chrome driver from url given below
https://chromedriver.chromium.org/downloads

## Deployment

To run this project run the following command in downloaded directory

```bash
  python ui_design.py
```
check the demo video mentioned below.

## Demo
https://drive.google.com/file/d/14ksN5aqfEFzJJIlkEJ26KYEDJih_FRiR/view?usp=sharing
## License

[MIT](https://choosealicense.com/licenses/mit/)

## Feedback

If you have any feedback, please reach out to us at<EMAIL_ADDRESS>

## Support

For support, email<EMAIL_ADDRESS>

## Authors

- [@nvakhilnair](https://github.com/nvakhilnair)

![Logo](https://cdn1.bbcode0.com/uploads/2021/8/10/e7b5c5b1dc5b9a6f848ee9135f2e000c-full.png)

## 🚀 About Me
- 👋 Hi, I’m @nvakhilnair
- 👀 I’m interested in Data Science,Machine learning, Data Mining, Data Visualization and Programing
- 🌱 I’m currently open to work
- 📫 How to reach me https://www.linkedin.com/in/akhilnvnair

license: MIT

repository: nvakhilnair/Image-Data-Set-Creator

repo_name: nvakhilnair/Image-Data-Set-Creator


text:
# A small tutorial to initiate learning the build toolchain

## Preliminaries

`clang++` and `g++` take individual .cpp files and turn them into .o files. All code in the .cpp
must have _definitions_, but the _implementation_ is not necessary for a successful compile. When
you include a .hpp, the C++ pre-processor simply replaces the #include directive with the content of
that .hpp -- header files are a useful index of definitions, and .cpp files contain implementations.
To produce the final executable, the compiler calls either `ld` or `lld` to link the object files
(.o) together along with any static libraries (.a) and dynamic libraries (.so). To produce .a files,
the compiler calls `ar` to compress .o files together and produce an index for ease of linking. To
produce .so files, the compiler calls `ld` or `lld` with the `-dy` flag. Code is copied out from
static libraries when they are linked into other artifacts, and the produced artifact has no
dependency on the static library; dynamic libraries are loaded at runtime by the dynamic loader, and
the paths to libraries are in `/etc/ld.so.conf.d` (typically `/usr/lib` and `/usr/local/lib` among
others).

## Link Errors, libstdc++, and libc++

Link errors arise when a directory specified in the `-L` flag does not contain the library specified
using the `-l` flag.

    $ ld -lc --verbose
    attempt to open /usr/x86_64-redhat-linux/lib64/libc.so failed
    attempt to open /usr/x86_64-redhat-linux/lib64/libc.a failed
    attempt to open /usr/local/lib64/libc.so failed
    attempt to open /usr/local/lib64/libc.a failed
    attempt to open /lib64/libc.so succeeded
    opened script file /lib64/libc.so
    opened script file /lib64/libc.so
    attempt to open /lib64/libc.so.6 succeeded
    /lib64/libc.so.6
    attempt to open /usr/lib64/libc_nonshared.a succeeded
    attempt to open /lib64/ld-linux-x86-64.so.2 succeeded
    /lib64/ld-linux-x86-64.so.2
    ld-linux-x86-64.so.2 needed by /lib64/libc.so.6
    found ld-linux-x86-64.so.2 at /lib64/ld-linux-x86-64.so.2

So ld found libc, and it was under one of the paths specified in the conf. Notice that libc is
classically a dynamic library, and every single program on the entire system must be compiled
against the same version.

2.  main is a function in the program that's fully defined. The 'T' next to it indicates "text",
    which means that it is _defined_ in str.o (because it was defined in str.c), and therefore does
    not need any further resolution.

3.  `std::__1` symbols, which can be resolved by linking to libc++ from LLVM (not libstdc++ that's
    supplied with gcc). libc++ uses the C++11 "inline namespaces" feature to mangle the standard
    library so that mixing libstdc++ with libc++ would lead to link-time errors instead of runtime
    crashes; libc++ is _not_ binary-compatible with libstdc++.

Okay, so how do we compile str.c using gcc and libc++? First, we produce an object file with the
mangled symbols from including the libc++ headers. Notice how `std::__::placeholders` symbols are
additionally present when we use `-std=c++11`.

    $ g++ -std=c++11 -nostdinc++ -I<prefix>/include/c++/v1 -c str.c
    $ nm -C str.o

Next, we need to invoke `ld` to link str.o with the dynamic library libc++.so:

    $ ld str.o -L<prefix>/lib -dy -lc++

Lots of link errors, but let's look at the prerequisites (undefined symbols) in libc++ first:

    $ nm -uC libc++.so.1.0
          U fprintf@@GLIBC_2.2.5
          ...

Any C++ library has to be built on top of a glibc. Okay, so where can we find these symbols?

    $ ld str.o -L<prefix>/lib -L/lib64 -dy -lc++ -lc

Note that we absolutely need to link libc.so dynamically; static linking will only work with the
special musl library. We still get link errors, but we find out which libraries the symbols are in
are try again:

    $ ld str.o -L/curr/software/llvm/lib -L/lib64 \
        -L/lib/gcc/x86_64-redhat-linux/4.8.2 -dy -lc++ -lc -lpthread -lgcc_s
    ld: warning: cannot find entry symbol _start; defaulting to<PHONE_NUMBER>400950
    str.o: In function `main':
    str.cpp:(.text+0x16): undefined reference to `std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(char const*)'
    str.o: In function `std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> > std::__1::__pad_and_output<char, std::__1::char_traits<char> >(std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> >, char const*, char const*, char const*, std::__1::ios_base&, char)':
    str.cpp:(.text._ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_[_ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_]+0x190): undefined reference to `std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(unsigned long, char)'
    ld: defaultlibs: hidden symbol `_ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEC1EPKc' isn't defined
    ld: final link failed: Bad value

Shouldn't these symbols be present in the text section of libc++? What happened?

    $ nm --defined-only -C libc++.so.1.0 | fgrep 'std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(char const*)'
<PHONE_NUMBER>08f130 t std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(char const*)
<PHONE_NUMBER>08f130 t std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(char const*)

It is indeed present, but the lowercase 't' indicates that it is not visible (exported). Let's see
what `clang` does with `str.cpp`:

   $ clang++ -std=c++11 -c str.cpp -o str.clang.o -stdlib=libc++
   $ nm -C str.clang.o

In the diff, we see:

    - std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(char const*)
    + std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::__init(char const*, unsigned long)

Of course it doesn't use the non-exported symbol! We could choose to fork libcxx and make the
symbols visible.

## `_start`, C runtime objects (crt)

Now that we understand visibility, it's time to invoke `ld`; note that the objects in the C runtime
must be prefixed and suffixed as follows for `_start` and a bunch of other ELF ABI symbols to be
resolved:

    crt1.o
    crti.o
    crtbegin.o
    <main object files>
    crtend.o
    crtn.o

repository: SFU-HiAccel/merlin-compiler

repo_name: SFU-HiAccel/merlin-compiler


text:
# concat-streams
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
[![Build Status](https://travis-ci.org/DavidCai1993/concat-streams.svg?branch=master)](https://travis-ci.org/DavidCai1993/concat-streams)
[![Coverage Status](https://coveralls.io/repos/github/DavidCai1993/concat-streams/badge.svg?branch=master)](https://coveralls.io/github/DavidCai1993/concat-streams?branch=master)

Concat streams by piping and pass the specified events through to the end.

## Installation

```sh
npm install concat-streams
```

## Usage

```js
'use strict'
const concatStream = require('concat-streams')

concatStream([stream1, stream2, stream3], 'error').on('error', console.error)
// Equal to:
// stream1.pipe(stream2)
// stream2.pipe(stream3)
// stream1.on('error', (err) => stream2.emit(err))
// stream2.on('error', (err) => stream3.emit(err))
// stream3.on('error', console.error)
```

## API

### concatStream(streams, event)

  - streams: `Array`<`stream`> an array of streams
  - event: `String` || `Array`<`string`> name of the events you want to pipe through, by default it is `'error'`.

Concat all streams in array by `pipe` and once the `event` occurred in one stream, all streams after will get it. Return the last stream in the array.

branch_name: refs/heads/master


text:
# Choose your own instrument

A playground for learning programming basics while making an instrument

The static version is here: http://theophani.github.io/choose-your-own-instrument/

## Get your own copy to play with

If you don’t have `git` or don’t want to use it:

Download the **raw** versions of [index.html](index.html), [styles.css](styles.css), [script.js](script.js), and [tones.js](tones.js) files and put them in the same folder on your computer.

Or, using `git`:

```
git clone git@github.com:theophani/choose-your-own-instrument.git
```

## Play around to see how things work!

### Options when creating figures

(Tipps auf Deutsch: https://gist.github.com/matthiasr/95bc945d1e5fc52e1b5102de0f77c21b)

Available shapes:
"triangle", "circle", "square", "diamond"

Available colors:
"red", "yellow", "blue", "orange", "green", "purple", "pink", "black"

Available notes:
"c", "c#", "db", "d", "d#", "eb", "e", "f", "f#",
"gb", "g", "g#", "ab", "a", "a#", "bb", "b"

Sharps are denoted with “#”, and flats are denoted with “b”.

### Change the background

On line 28, the background class is set. You can change the background to one of
the available classes: "sky", "sea", "bubble-gum", "fireball", "sunset", "cool-mint", "fuji"

```javascript
    document.body.className = "fuji"
```

### Helper functions

Use the `randomShape` function to choose a random shape.
Use it when adding a figure, like this:

```javascript
  addFigure(randomShape(), "orange", "e")
```

Use the `randomColor` function to choose a random color.
Use it when adding a figure, like this:

```javascript
  addFigure("circle", randomColor(), "g")
```

Use the `randomNote` function to choose a random note.
Use it when adding a figure, like this:

```javascript
  addFigure("diamond", "pink", randomNote())
```

Use the `noteFromNumber` function to get the nth note in the C Major scale.
Integers 0 though 7 are the notes "c" through "g".
This is especially useful when adding a series of figures in a loop, like this:

```javascript
  for (var i = 0; i < 16; i++) {
    addFigure("square", "black", noteFromNumber(i))
  }
```

You can use any integers from -28 to 41 (i.e. across 10 octaves).
Try this:

```javascript
  for (var i = -28; i <= 41; i++) {
    addFigure("diamond", "pink", noteFromNumber(i));
  }
```

### Tempo

To change the tempo of the auto playback, set the variable `bpm` to a number
greater than 0. The default is 300 beats per minute.

```javascript
bpm = 300
```

### Change how the notes sound

You can change how the notes sound by setting `tones.type`, `tones.attack`, and
`tones.release`.

The “type” determines the shape of the sound wave. The default is "sine".
The available types are: "sine", "square", "sawtooth", "triangle"

```javascript
tones.type = "sine"
```

The “attack” determines how intensely the sound starts. The default is 1.
Try other numbers to see how it smooths out the tone.

```javascript
tones.attack = 1
```

The “release” determines how quickly the sound fades out. The default is 100.
Try other numbers to see how it creates clipped or echoey sounds.

```javascript
tones.release = 100
```

Note: When you set these values, they affect all future notes played. That means
you can set these values in the console, as the auto playback is happening, and
change how the notes sound on the fly. Ask a coach to help you!

### Change how figures look

Try this:

```javascript
myFigure = addFigure("star", "yellow", randomNote())
myFigure.style.backgroundImage = "url('http://theophani.github.io/choose-your-own-instrument/swiss-cheese.jpg')"
myFigure.style.width = "500px"
myFigure.style.height = "500px"
```

## The tones library

The tones library is by bit101: https://github.com/bit101/tones

repository: theophani/choose-your-own-instrument

branch_name: refs/heads/gh-pages

gha_language: JavaScript

gha_license_id: MIT

repo_name: theophani/choose-your-own-instrument


text:
---
layout: post
title: "Implementation of the PWM Class for BeagleBone Black"
author: wilmer
categories: [BeagleBone]
tags: [PWM]
image: assets/images/Post21/CoverPost.png
description: "Coding the PWM Class members and methods for the BeagleBone Black"
featured: false
hidden: false
rating: 5
date:   2021-01-11 08:00:00 -0600
---

In this post, I show a PWM C++ class implementation. Remembering the PWM is a technique that lets us emulate an analog signal in a digital pin. This is done by changing the time that a signal is On in a fixed period of time. The ratio between the time ON and OFF is named duty cycle. The more duty cycle, the more is the "analog" average voltage measured on the digital pin.

The BeagleBone has six pins than can be dedicated to do PWM.  These are:

P8_13

P8_19

P9_14

P9_16

P9_21

P9_22

## Coding

The methods coded to the C++ class `PWM` are:
- Private methods:
  - `WriteFile(string, string, int)`
  - `Enable()`
  - `Disable()`

- Public methods:
  - `int GetPeriod()`
  - `int GetDutyCycle()`
  - `int SetPeriod(int)`
  - `int SetDutyCycle(int)`
  - `void Delayms(int)`
  - `int DoUserFunction(callbackType)`
  - `void StopUserFunction()`

The `WriteFile(string, string, int)` method accesses to the file system path that controls the PWM behaviour on the pin at **"/sys/devices/platform/ocp/"**.

The `Enable()` method activates the PWM on the pin setting the enable property to 1 This method is called in the Constructor.

The `Disable()` method deactivates the PWM on the pin setting the enable property to 0. This method is called in the  Destructor.

The `GetPeriod()` method, returns the last set pin's period.

The `GetDutyCycle()` method, returns the last set pin's duty cycle.

The `SetPeriod(int)` method, receives an int number and set the period property of the pin in the sys file system.

The `SetDutyCycle(int)` method, receives an integer number between 0 and 100 and converts it as a percentage of the period before to set the duty_cycle property of the pin in the sys file system. The method checks if the number is less or greater than that range, and set the duty_cycle property as 0 or 100, respectively.

The `DoUserFunction(callbackType)` method, receives a user function thought a function pointer from the main program to do something in background through the execution of a thread.

The `StopUserFunction()` method finishes the execution of the thread called by the user function that should be defined in the previous explained `void DoUserFunction(callbackType)` method.

## Class code

### PWM.h
```cpp
#ifndef PWM_H
#define PWM_H

#include <string>
#include <thread>
#include "RAINBOWCOLORS.h"

/*
  Declare a type for a function pointer
  It is the construct for: using function_type = int (*) ()
    function_type:  the function name
    int: return type
    (*): the dereference operator due to the address of the function name
    (): the arguments of the function, in this case void
  Stores the address of a function
*/
using callbackType = int (*)();

const std::string PWM_PATH ("/sys/devices/platform/ocp/");
const std::string EHRPWM0_PATH = "48300000.epwmss/48300200.pwm/pwm/";
const std::string EHRPWM1_PATH = "48302000.epwmss/48302200.pwm/pwm/";
const std::string EHRPWM2_PATH = "48304000.epwmss/48304200.pwm/pwm/";

/* The pwm class internal number of the pin*/
enum ID {
  P8_13 = 0,
  P8_19 = 1,
  P9_14 = 2,
  P9_16 = 3,
  P9_21 = 4,
  P9_22 = 5,
};

class PWM
{
  private:
    int id; /* The PWM number of the object */
    std::string idMap[6];
    std::string name;   /* The name of the PWM e.g. pwm-6:1 */
    std::string path;   /* The full path to the PWM e.g. /sys/class/pwm/pwm-6:1 */
    int period;
    int dutyCycle;
    int enable;
    bool stopDutyCycleFlag = false;

    std::thread functionThread;

    // Method to write the files
    virtual int WriteFile(std::string, std::string, int);
    // Method to enable the pwm on the pin
    virtual int Enable();
    // Method to enable the pwm on the pin
    virtual int Disable();

  public:

    // Default constructor
    PWM(int id = P8_13, int period = 500000);

    // Interface method to get the period
    virtual int GetPeriod();

    // Interface method to get the duty cycle
    virtual int GetDutyCycle();

    // Interface method to set the period
    virtual int SetPeriod(int);

    // Interface method to set the duty cycle
    virtual int SetDutyCycle(int);

    // Delay method in milliseconds
    virtual void Delayms(int);

    // Method to do execute an user function
    virtual int DoUserFunction(callbackType);

    // Method to stop the user function
    virtual void StopUserFunction();

    // Destructor
    virtual ~PWM();

};
#endif // PWM_H
```

### PWM.cpp
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <chrono> // chrono::milliseconds()
#include <thread> // this_thread::sleep_for()
#include <exception>
#include <mutex>
#include <cstdlib>// system()

#include "PWM.h"

using namespace std;

class CustomException : public exception
{
  private:
    string reason;
  public:
    CustomException (const char* why) : reason (why) {};
    virtual const char* what() const noexcept
    {
      return reason.c_str();
    }
};

// Overload constructor with 2 arguments
PWM::PWM(int pwmPin, int newPeriod)
{
  id = pwmPin;
  period = newPeriod;

  idMap[P8_13] = "P8.13";
  idMap[P8_19] = "P8.19";
  idMap[P9_14] = "P9.14";
  idMap[P9_16] = "P9.16";
  idMap[P9_21] = "P9.21";
  idMap[P9_22] = "P9.22";

  switch (pwmPin)
  {
  case P8_13:
    name = EHRPWM2_PATH + "pwmchip6/pwm-6:1/";
    break;
  case P8_19:
    name = EHRPWM2_PATH + "pwmchip6/pwm-6:0/";
    break;
  case P9_14:
    name = EHRPWM1_PATH + "pwmchip3/pwm-3:0/";
    break;
  case P9_16:
    name = EHRPWM1_PATH + "pwmchip3/pwm-3:1/";
    break;
  case P9_21:
    name = EHRPWM0_PATH + "pwmchip1/pwm-1:1/";
    break;
  case P9_22:
    name = EHRPWM0_PATH + "pwmchip1/pwm-1:0/";
    break;
  default:
    break;
  }

  path = PWM_PATH + name;

  cout  << RainbowText("Trying to enable the PWM pin: ","Pink")
        << RainbowText(idMap[pwmPin], "Pink", "Default", "Bold") << endl;
  string commandString = "config-pin " + idMap[pwmPin] + " pwm";
  const char* command = commandString.c_str();
  system(command);

  // Set the period for the PWM behavior
  SetPeriod(newPeriod);

  // Enabling the PWM behavior on the pin
  Enable();

  cout  << RainbowText("Setting the PWM pin with a period of ", "Pink")
        << RainbowText(to_string(GetPeriod()), "Pink")
        << RainbowText("ns was a success!", "Pink") << endl;
}

/*
    Private method that writes a string value to a file in the path provided
    @param string path: The system path of the file to be modified
    @param string feature: The name of file to be written
    @param int value: The value to be written to in the file
    @return int: 1 written has succeeded
*/
int PWM::WriteFile(string path, string feature, int value)
{
  string fileName = path + feature;

  ofstream file(fileName, ios_base::out);
  if (!file.is_open())
  {
    perror(("Error while opening file: " + fileName).c_str());
    throw CustomException("Error in 'writeFile' method");
  }
  file << value;
  file.close();
  Delayms(10);

  return 1;
}

/*
    Private method to enable the PWM on the pin.
    It is used in the constructor
    @return int: 1 set duty cycle has succeeded / throw an exception if not
*/
int PWM::Enable()
{
    if (WriteFile(path, "enable", 1) == 1)
      return 1;
    else
    {
      perror("Error enabling the PWM on the pin");
      throw CustomException("Error in Enable method");
    }
}

/*
    Private method to disable the PWM on the pin.
    It is used in the constructor
    @return int: 1 set duty cycle has succeeded / throw an exception if not
*/
int PWM::Disable()
{
    if (WriteFile(path, "enable", 0) == 1)
      return 1;
    else
    {
      perror("Error disabling the PWM on the pin");
      throw CustomException("Error in DisablePWM method");
    }
}

/*
    Public method to get the period
    @return int: The pin's period
*/
int PWM::GetPeriod()
{
    return period;
}

/*
    Public method to get the period
    @return int: The pin's duty cycle
*/
int PWM::GetDutyCycle()
{
    return dutyCycle;
}

/*
    Public method to set the period of the PWM
    The chosen period is in nanoseconds
    @param int: The desired period
    @return int: 1 set period has succeeded / throw an exception if not
*/
int PWM::SetPeriod(int newPeriod)
{
    period = newPeriod;
    if (WriteFile(path, "period", period) == 1)
      return 1;
    else
    {
      perror("Error setting the PWM period for the pin");
      throw CustomException("Error in WritePWMPeriod method");
    }
}

/*
    Public method to set the duty cycle of the PWM
    @param int: The desired duty cycle in percentage: 0-100
    @return  int: 1 set duty cycle has succeeded / throw an exception if not
            int: 0 if the user decides to stop this method
*/
int PWM::SetDutyCycle(int newDutyCycle)
{
  while (stopDutyCycleFlag == false)
  {
    if (newDutyCycle >= 0 && newDutyCycle <= 100)
      dutyCycle = static_cast<int>(newDutyCycle / 100.0 * period);
    else if (newDutyCycle < 0)
      dutyCycle = 0;
    else
      dutyCycle = 100;

    if (WriteFile(path, "duty_cycle", dutyCycle) == 1)
      return 1;
    else
    {
      perror("Error setting the PWM duty cycle for the pin");
      throw CustomException("Error in WritePWMDutyCycle method");
    }
  }
  return 0;
}

/*
  Public method to do a delay in milliseconds
  @param int: duration of the delay
*/
void PWM::Delayms(int millisecondsToSleep)
{
  this_thread::sleep_for(chrono::milliseconds(millisecondsToSleep));
}

/*
  Public callback method to do a user customized function when is called
  @param callbackType: user function pointer to execute
  @return int: 1 the user function was called
*/

int PWM::DoUserFunction (callbackType callbackFunction)
{
  string message = "'UserFunction' method has been activated!";
  cout << RainbowText(message, "Orange") << endl;

  functionThread = thread(callbackFunction);

  return 1;
}

/*
    Public method to stop the user function execution
*/
void PWM::StopUserFunction()
{
  stopDutyCycleFlag = true;
}

// Destructor
PWM::~PWM()
{
  if (functionThread.joinable())
    functionThread.join();

  // Turn Off the duty cycle on the pin
  this->SetDutyCycle(0);

  // Disabling the pwm on the pin
  this->Disable();
  this->Delayms(10);
  cout  << RainbowText("Destroying the GPIO_PIN with path: ","Gray")
        << RainbowText(path, "Gray", "Default", "Bold") << endl;
}
```

Se you in the next post.


text:
__Please Note__ : All credit in developing this app goes to ["sandiiarov"](https://github.com/sandiiarov). I have cloned it from [HERE](https://github.com/sandiiarov/drysel-demo-app). In order to install and run, please follow following steps. This app assumes that you already have installed the latest versions of _npm_ and _nodejs_ on your machine.

```sh
$ npm install
```

```sh
$ npm run build
```

```sh
$ npm start
```

"drysel.demoapp" is a front-end only app. It is developed to test and demo various frameworks of the [DrySel](https://github.com/orion-analytics/drysel) project. This web-app has 2 UI pages. First to login with user name = Joe and password = admin. On successful login it shows User Information page, where users can add her demographics information and save it. On saving, the information is displayed in the read-only pan given on the right hand side of the page.


text:
# SPD 2.3 Sample Assingments

- Download [Debugging Exercises](https://github.com/Make-School-Labs/SPD-2.3-Debugging-Steps-Lab) and solve them.

- Improve the code formatting and layout of the following programs according to PEP 8:

```python
# by Kami Bigdely
# docstrings for class

class fighter:
    def __init__(self):
        self.x = 0
        self.y = 0
        self.health = 100
        self.gas = 3
    def set_position(self, x, y):
        self.x = x
        self.y = y
    def render(self):
        print("rendered the fighter")
    def take_damage(self, damage):
        self.health -= damage
        if self.health <= 0:
            print("the figher fell apart!")
    def consume_gas(self):
        if self.gas > 0:
            self.gas -= 1
        else:
            print('out of gas! ')
    def take_gas(self, gas_amound):
        self.gas += gas_amound

f = fighter()
f.set_position(10, 10)
f.consume_gas()
f.take_damage(90)
f.take_damage(40)

```

----------

``` python
# by Kami Bigdely
# Writing docstring for functions and classes.
# reference: https://math.ryerson.ca/~danziger/professor/MTH141/Handouts/projections.pdf
import numpy as np
def proj_u_onto_v(u,v):
    return np.dot(u, v)/np.dot(v, v) * v

force = np.array([1,1])
displacement = np.array([1,0])
proj = proj_u_onto_v(force, displacement)
print(proj[0], proj[1])

```

----------

```python
# by Kami Bigdely
# Indentation
def write_to_db():
   print('person info are written into db.')

def set_person_info(first_name, last_name, gender, date_of_birth, photo, nationality, place_of_birth):
    if not first_name:
      print('first name is empty.')
    if not last_name:
      print('last name is empty.')
    # ...
    write_to_db()

photo_path = "https://en.wikipedia.org/wiki/Tim_Hunt#/media/File:Tim_Hunt_at_UCSF_05_2009_(4).jpg"
set_person_info('Tim', 'Hunt', 'male','19 February 1943', photo_path, 'Uited Kingdom', 'Neston, Cheshire, England')
```

----------

```python
# by Kami Bigdely
# PEP8 - whitespaces and variable names.
# This is a guess game. Guess what number the computer has chosen!
import random
lowerLimit=0
UPPER_limit= 100
randomNumber = random.randint (lowerLimit ,UPPER_limit )
print ('The computer has selected a number between 0 and 100. Use your supernatural superpowers to guess what the number is.')
while True:
    UserGuess = int (input("Enter a number between 0 and 100 (including): "))
    if UserGuess> randomNumber:
        print ("Guess a smaller number.")
    elif UserGuess <randomNumber:
        print ("Guess a larger number.")
    else: #UserGuess == randomNumber:
        print ("You Won!")
        break

```

- Use **Extract method** refactoring technique to improve the following code:

```python
# Adapted from a Java code in the "Refactoring" book by Martin Fowler.
# Code snippet. Not runnable.
def print_owing():
    outstanding = 0.0
    # print banner
    print("*******************")
    print("***Customer owes***")
    print("*******************")
    # calculate outstanding
    for order in orders:
        outstanding += order.get_amount()
    # print details
    print("name: " + name)
    print("amount: " + outstanding)
```

- Use **Replace Temp with Query** refactoring technique to improve the following code:

```python
# Adapted from a Java code in the "Refactoring" book by Martin Fowler.
# Replace temp with query
# Code snippet. Not runnable.
def getPrice():
    base_price = quantity * item_price
    discount_factor = 0
    if (base_price > 1000):
        discount_factor = 0.95
    else:
        discount_factor = 0.98
    return base_price * discount_factor

```

- Use **Introduce Explaining Variable (Extract Variable)** refactoring technique to improve the following code:

```python
# Adapted from a Java code in the "Refactoring" book by Martin Fowler.
# Introduce Explaining variable (aka extract variable)
platform = "mac pro 2018"
browser = 'safari 8.0'
resize = True
def is_initialized():
    return True
def render_banner():
    if ('MAC' in platform.upper() and
    "SAFARI" in browser.upper() and
    is_initialized()):
        print("Yes!")
        # do something

render_banner()

```

- Use **Split Temporary Variable** refactoring technique to improve the following code:

```python
# Adapted from a Java code in the "Refactoring" book by Martin Fowler.
# split temporary variable
width = 5
height = 10
temp = 2 * (height + width)

print(temp)
temp = height * width
print(temp)

```


text:
Amazon Product Advertising Client
================================

## Configure
Add your AWS authentication credentials to `config/config.exs`:

Hex: https://hex.pm/packages/amazon_product_advertising_client

```elixir

  # in your mix.exs
  {:amazon_product_advertising_client, "~> 0.2.1"}

```

```elixir

# in your config/config.exs
config :amazon_product_advertising_client,
  associate_tag: "YourAssociateTag",
  aws_access_key_id: "YourAccessKeyID",
  aws_secret_access_key: "YourSecretAccessKey",
  marketplace_host: "webservices.amazon.ca" # If not specified the default value is webservices.amazon.com

```

## Usage and Examples

Both of the functions return an %HTTPoison.Response{} struct. This Amazon API responds with XML, so you will most likely want
to parse the body using a library such as SweetXml.

### Search
Create a search params struct and execute the search, for example:

```elixir

alias AmazonProductAdvertisingClient.ItemSearch

def search_for_item do
  %ItemSearch{"MaximumPrice": "25", "Keywords": "long sleeve shirt"} |> ItemSearch.execute
end

```

### Lookup
```elixir

alias AmazonProductAdvertisingClient.ItemLookup

# e.g. an ISBN of<PHONE_NUMBER>992
def lookup_book_by_isbn(isbn) do
  %ItemLookup{
      IdType: "ISBN",
      ItemId: isbn,
      SearchIndex: "Books"}
  |> ItemLookup.execute()
end

```

### Lookup and Parse Response
```elixir

# Modules needed.
alias AmazonProductAdvertisingClient.ItemLookup
import SweetXml

# Returns a map with 'title' and 'detail_page_url' keys
def lookup_book_info(isbn) do
  lookup_struct =
    %ItemLookup{
      IdType: "ISBN",
      ItemId: isbn,
      SearchIndex: "Books"}

  case ItemLookup.execute(lookup_struct) do
    {:ok, %HTTPoison.Response{body: body}} ->
      body |> parse_xml_body()
  end

end

# The XML response from Amazon is voluminous. There are many fields to retrieve,
# for this example we pull the book's title and Amazon URL.
def parse_xml_body(body) do
  body
  |> SweetXml.xmap(
    title: ~x"//ItemLookupResponse/Items/Item/ItemAttributes/Title/text()",
    detail_page_url: ~x"//ItemLookupResponse/Items/Item/DetailPageURL/text()",
    )
end

```

gha_language: Elixir


text:
---
title: Telerik.Web.UI.DockMode
description: Telerik.Web.UI.DockMode
slug: Telerik.Web.UI.DockMode
---

# enum Telerik.Web.UI.DockMode

## Inheritance Hierarchy

* *[Telerik.Web.UI.DockMode]({%slug Telerik.Web.UI.DockMode%})*

## Fields

### Floating `1`

The dock is always floating and cannot be docked to a zone.

### Docked `2`

The dock is always docked and cannot be moved outside a zone.

### Default `3`

Default behavior of the RadDock control. It can be moved outside a docking zone or placed inside one

repository: telerik/ajax-docs

gha_language: C#

repo_name: telerik/ajax-docs


text:
---
layout: default
title: Software Development Tools
nav: pages/ch_devtools
---

{{ page.title }}
=============================================

Software Development Tools
--------------------------

The overview for this chapter consists of the following topics:

-   Introduction

-   Chapter Outline

### Introduction

The tools used in-house by software developers at NCBI -- such as debuggers, memory checkers, profilers, etc. are discussed in [C++ Toolkit Confluence](https://confluence.ncbi.nlm.nih.gov/display/CT).

### Chapter Outline

As mentioned above, the tools used in-house by software developers at NCBI -- such as debuggers, memory checkers, profilers, etc. are discussed in [C++ Toolkit Confluence](https://confluence.ncbi.nlm.nih.gov/display/CT).

Section Placeholder
-------------------

This section is only here for technical reasons.

repository: ncbi/cxx-toolkit

gha_language: HTML

gha_license_id: Unlicense

repo_name: ncbi/cxx-toolkit


text:
# Instructions for running the FUCA web application

## Clone repository
Have your computer connected to the Internet.
Open command line interface and navigate to a location where you want to clone this repo.
Clone this repo:
`git clone https://github.com/urosisakovic/FUCA.git`

## Download Miniconda
Follow this [link](https://docs.conda.io/en/latest/miniconda.html) and download Miniconda.

## Created conda environment
Open Conda CLI. Create conda environment for this project:

`conda env create -n fuca python=3.6`

Activate the created environment:
`conda activate fuca`

Every future time you wish to start the project, you will have to activate `fuca` environment as well.

## Install needed Python packages
Navigate to the root of this repo using Conda CLI. Download necessary Python packages:
`pip install -r requirements.txt`

## Start the application
Navigate to the /src subdirectory of this repo using Conda CLI.
Start the project by runnning the python script:
`python run.py`

## Inspect the application in web browser
Open web browser of your choice (Chrome, Firefox, etc.) and visit http://localhost:5000.

repository: urosisakovic/FUCA

gha_language: Python

repo_name: urosisakovic/FUCA


text:
1583\. Count Unhappy Friends

Medium

You are given a list of `preferences` for `n` friends, where `n` is always **even**.

For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from `0` to `n-1`.

All the friends are divided into pairs. The pairings are given in a list `pairs`, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.

However, this pairing may cause some of the friends to be unhappy. A friend `x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is paired with `v` but:

*   `x` prefers `u` over `y`, and
*   `u` prefers `x` over `v`.

Return _the number of unhappy friends_.

**Example 1:**

**Input:** n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]

**Output:** 2

**Explanation:**

Friend 1 is unhappy because:

- 1 is paired with 0 but prefers 3 over 0, and

- 3 prefers 1 over 2.

Friend 3 is unhappy because:

- 3 is paired with 2 but prefers 1 over 2, and

- 1 prefers 3 over 0.

Friends 0 and 2 are happy.

**Example 2:**

**Input:** n = 2, preferences = [[1], [0]], pairs = [[1, 0]]

**Output:** 0

**Explanation:** Both friends 0 and 1 are happy.

**Example 3:**

**Input:** n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]

**Output:** 4

**Constraints:**

*   `2 <= n <= 500`
*   `n` is even.
*   `preferences.length == n`
*   `preferences[i].length == n - 1`
*   `0 <= preferences[i][j] <= n - 1`
*   `preferences[i]` does not contain `i`.
*   All values in `preferences[i]` are unique.
*   `pairs.length == n/2`
*   `pairs[i].length == 2`
*   xi != yi
*   0 <= xi, yi <= n - 1
*   Each person is contained in **exactly one** pair.

repository: javadev/LeetCode-in-Java

gha_language: Java

repo_name: javadev/LeetCode-in-Java


text:
## Usage

Create a `tools.go` file with at least the following content:

```go
//+build tools

package tools

import (
	_ "github.com/fhofherr/toolmgr"
)
```

Add imports for the used tools to the above files as required. Then make
sure to install `toolmgr`:

```sh
export GOBIN="$PWD/bin"
go mod tidy
go install github.com/fhofherr/toolmgr
"$PWD"/bin/toolmgr -bin-dir "$PWD/bin"
```

Whenever you add new tools to `tools.go` be sure to re-execute the above
steps.

### Makefile targets

In many cases it is convenient to use a `Makefile` to make the above
easier. Simply add the following targets to your `Makefile`.

```Makefile
GO ?= go

## Change this to your liking:
TOOLS_BIN_DIR ?= bin
TOOLS_GO := tools.go

.PHONY: tools
tools: $(TOOLS_BIN_DIR)

## Dummy target to allow depending on all tools
$(TOOLS_BIN_DIR): $(TOOLS_BIN_DIR)/toolmgr

$(TOOLS_BIN_DIR)/%: $(TOOLS_GO)
	GOBIN=$(abspath ./$(TOOLS_BIN_DIR)) $(GO) install github.com/fhofherr/toolmgr
	$(TOOLS_BIN_DIR)/toolmgr -bin-dir $(TOOLS_BIN_DIR) -tools-go $(TOOLS_GO)
```

Whenever one of your other `Makefile` targets depends on one or more
tools you can either depend on the `$(TOOLS_BIN_DIR)` target or on
`$(TOOTOOLS_BIN_DIR)/<toolname>`.

## License

Copyright © 2021 Ferdinand Hofherr

Distributed under the MIT License.

repository: fhofherr/toolmgr

repo_name: fhofherr/toolmgr


text:
# YaoTensorNetwork

[![Build Status](https://travis-ci.com/QuantumBFS/YaoTensorNetwork.jl.svg?branch=master)](https://travis-ci.com/QuantumBFS/YaoTensorNetwork.jl)

Converting a Quantum Circuit in<EMAIL_ADDRESS>to a tensor network.

To start, open a Julia REPL and type `]` to enter pkg mode, install dependancies by
```julia
pkg> add Yao LuxurySparse BitBasis DelimitedFiles OMEinsum
pkg> dev YaoExtensions
pkg> dev git@github.com:QuantumBFS/YaoTensorNetwork.jl.git
```

If the second line does not work, please try clone and `pkg> dev .` at top level folder.

## Learn by Example
```julia
julia> using Yao, YaoExtensions, YaoTensorNetwork

julia> c = dispatch!(variational_circuit(2, 1, [1=>2]), :random);

julia> eg = circuit2tn(c; initial_config=bit"00", final_config=bit"11")
EinGraph{Complex{Float64},Array{Complex{Float64},N} where N}
 T[1](2)
 T[2](2)
 T[1,3](2, 2)
 T[3,4](2, 2)
 T[2,5](2, 2)
 T[5,6](2, 2)
 T[4,7,8](2, 2, 2)
 T[6,9,8](2, 2, 2)
 T[7,10](2, 2)
 T[10,11](2, 2)
 T[9,12](2, 2)
 T[12,13](2, 2)
 T[11](2)
 T[13](2)

julia> dump_graph("_test", eg);

julia> eg2 = load_graph(eltype(eg), "_test");

julia> using OMEinsum

julia> res = contract(eg)
-0.005533928306495697 - 0.21124814706199962im
```

Here, `circuit2tn` convert a circuit to a "generalized tensor network" (or factor graph).
In order to general reasonable structures, we suggestion using `simplify_blocktypes(c)` before dumping.
`dump_graph` dumps this generated tensor network (the `EinGraph` instance) to three files, `_test.labels.dat`, `_test.sizes.dat` and `_test.tensors.dat` in plain text format. One can use `load_graph` to read these files.
This package conditionally depends on `OMEinsum`, which is able to evaluate the tensor network directly utilizing `@tensoropt` defined in `TensorOperations.jl`.
One can also load the data to python with the script in the example folder.

For more examples, see [example](example/) folder.

gha_language: Julia


text:
Steps
----------
* Copy pom.xml
* Copy web.xml
* Create class RootApplicationContextConfig
* Import BusinessConfig into RootApplicationContextConfig
* Import JpaConfig into BusinessConfig
* Create transactionManager in JpaConfig
* Define package to be scanned for jpa repository
* Create class MvcCoreConfig
* Add Owner entity
* Add OwnerRepository interface
* Add JpaOwnerRepository implementation
* Add ClinicService service
* Add ClinicServiceImpl implementation

Entities graph
----------
* BaseEntity is the root for all the other entities.
* NamedEntity extends BaseEntity, all the other entities which only have name, should extends from NamedEntity.
* Person extends BaseEntity.
* Owner extends Person, has OneToMany with pet.
* Pet extends NamedEntity, has OneToMany with visit.
* Visit extends BaseEntity, has ManyToOne with Pet.
* Vet extends Person.
* Specialty extends NamedEntity.
*

repository: midikang/midi-petclinic-home

repo_name: midikang/midi-petclinic-home


text:
# Changelog

## 4.4.5 - 2020-04-07
* Allow a setting to determine if the media library overfiles files on the disk or preserves them.
* Increase the max slug length of pages

## 4.4.4 - 2020-03-03
* Add fix for duplicating the homepage.

## 4.4.3 - 2020-03-03
* Remove the site name from the page title by default.

## 4.4.2 - 2020-01-24
* Fix issue with LocalisationMiddleware where it would throw an exception if the IP didn't belong to a country.

## 4.4.1 - 2020-01-08
* Fix missed change to `handle_uncaught_exception` in Django 2.2 compatability update.

## 4.4.0 - 2019-12-05
* Django 2.2 compatibility is now complete:
  * **Breaking change:** If you are using `LocalisationMiddleware`, change your `MIDDLEWARE_CLASSES` setting to `MIDDLEWARE`. The other CMS middleware is now compatible with both, but the check for localisation middleware now only looks at `MIDDLEWARE`, to simplify 2.2 compatibility.
  * **Breaking change:** `cms` must now be in your `INSTALLED_APPS`.
  * **Breaking change:** localised sites now use `geoip2` - you will need to [update your GeoIP database](https://dev.maxmind.com/geoip/geoip2/downloadable/).
  * All `ForeignKey`s now have an `on_delete` explicitly specified (one was missed in 4.2.0).

## 4.3.1 - 2019-12-04
* The [documentation](https://onespacemedia.github.io/cms/) has been completely rewritten.

## 4.3.0 - 2019-11-12
* Importing `cms.sitemaps` at the top level of a module containing an app's AppConfig no longer raises `AppRegistryNotReady`.
* `PageBase`'s help text for the `slug` field now makes sense.
* `OnlineBase` and its derivatives (including the Page model) now implement `get_preview_url()`, to generate a URL at which non-admin users can preview an object.
* Remove a pessimisation in `PageManager.get_homepage`.

## 4.2.0 - 2019-11-06
* Show usage of media library files on the file's change form.
* Make middleware compatible with both `MIDDLEWARE` and `MIDDLEWARE_CLASSES`.
* Ensure all `ForeignKey`s have an `on_delete` explicitly specified for Django 2.2 compatibility.
* Rename "Search engine optimization" fieldset of SearchMetaBaseAdmin to "SEO".

## 4.1.0 - 2019-10-25
* Make it possible for ContentBase derivatives to override how they are searched by Watson.

## 4.0.10 - 2019-10-18
* Fix `Video.embed_html()` function using the wrong renderer for local mp4 files.
* Remove `cached_url` from the Page model, because it is [unreliable](https://github.com/onespacemedia/cms/pull/181).

## 4.0.9 - 2019-10-11
* Remove key press listeners from image editor
* Fix an issue where get parameters in the URL made saving a new page impossible

## 4.0.8 - 2019-09-18
* Don't override `submit_line.html` - this should be a decision for the CMS skin or a project-local override.

## 4.0.7 - 2019-09-18
* Simplify template override for `pages/page/change_form.html`.

## 4.0.6 - 2019-09-19
* Fix saving pages from the changelist view when its content model has `fieldsets` under certain circumstances.
* Restore ordering of media library to be most recent first.

## 4.0.5 - 2019-09-03
* Add a class to the ImageRefField widget's image preview to allow for easier styling.

## 4.0.4 - 2019-08-27
* Fix an issue when changing page ContentType where the new ContentType has ManyToMany fields not on the original.

## 4.0.3 - 2019-08-08
* Big speedups in RequestPageManager.

## 4.0.2 - 2019-08-06
* Fix migration state.

## 4.0.1 - 2019-07-26
* Fix issue for multilingual site and offline pages [[See #176](https://github.com/onespacemedia/cms/pull/176/files)]

## 4.0.0 - 2019-07-26
* Decouple from django-suit
* Massive code clean up
* In admin image editing for media app

## 2.0.0 - 2016-10-03
* Switched to Jinja2 as the template engine.

extension: markdown

gha_license_id: NOASSERTION


text:
# CrowdStrike Container Image Scan [![Flake8](https://github.com/CrowdStrike/container-image-scan/actions/workflows/linting.yml/badge.svg)](https://github.com/CrowdStrike/container-image-scan/actions/workflows/linting.yml)

This script will scan a container and return response codes indicating pass/fail status.

Specifically, this script:
1. Tags your image using ``docker tag``
2. Authenticates to CrowdStrike using your [OAuth2 API keys](https://falcon.crowdstrike.com/support/api-clients-and-keys)
3. Pushes your image to CrowdStrike for evaluation using ``docker push``, after which CrowdStrike performs an Image Scan
4. Parses returned scan report, generating return error codes as needed

All output is sent to stdout/stderr.

## Prerequisites
This sample/demo script requires the [Docker Engine API python library](https://pypi.org/project/docker/) and the [``requests`` HTTP library](https://pypi.org/project/requests/). These can be installed via ``pip``:

```shell
$ pip3 install docker requests
```

## Usage
```shell
$ python3 cs_scanimage.py --help
usage: cs_scanimage.py [-h] -u CLIENT_ID -r REPO [-t TAG]
                       [-c {us-1,us-2,eu-1}] [--json-report REPORT]
                       [--log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}]

Crowdstrike - scan your container image.

optional arguments:
  -h, --help            show this help message and exit
  --json-report REPORT  Export JSON report to specified file
  --log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
                        Set the logging level

required arguments:
  -u CLIENT_ID, --clientid CLIENT_ID
                        Falcon OAuth2 API ClientID
  -r REPO, --repo REPO  Container image repository
  -t TAG, --tag TAG     Container image tag
  -c {us-1,us-2,eu-1}, --cloud-region {us-1,us-2,eu-1}
                        CrowdStrike cloud region
```

Note that CrowdStrike Falcon OAuth2 credentials may be supplied also by the means of environment variables: FALCON_CLIENT_ID, FALCON_CLIENT_SECRET, and FALCON_CLOUD_REGION. Establishing and retrieving OAuth2 API credentials can be performed at https://falcon.crowdstrike.com/support/api-clients-and-keys.

## Example Scan
This requires your image to exist locally, e.g. run ``docker pull`` prior to executing this script.

```shell
$ python cs_scanimage.py --clientid FALCON_CLIENT_ID --repo <repo> --tag <tag> --cloud-region <cloud_region>

please enter password to login
Password:
```

The command above will return output similar to:

```shell
running get_alerts_vuln
Alert: High severity vulnerability found
running get_alerts_malware
running get_alerts_malware
Leaked secrets detected
running get_alerts_malware
Alert: Misconfiguration found
```

The ```echo $?``` command can be utilized to review the return code, e.g:
```shell
echo $?
1
```

The ```echo $?``` above displays the returned code with the following mappings:
```shell
HighVulnerability = 1
Malware = 2
Success = 0
Secrets = 0
Misconfig = 0
ScriptFailure = 10
HighVulnerability and Malware = 3
```

## Running the Scan using CICD

1. You can use the [container-image-scan](https://github.com/marketplace/actions/crowdstrike-container-image-scan) GitHub Action in your GitHub workflows. Checkout the action at [https://github.com/marketplace/actions/crowdstrike-container-image-scan](https://github.com/marketplace/actions/crowdstrike-container-image-scan)
2. You can run the scan as part of your Jenkins pipeline builds.
   - Requirements:
     - Jenkins must be able to run Docker commands and connect to the Docker socket
     - python3 and pip3 must be installed
   Sample Jenkins pipeline script with configuration options as Jenkins Secrets:
   ```
    pipeline {
        agent any
        environment {
            FALCON_CLIENT_ID     = credentials('FALCON_CLIENT_ID')
            FALCON_CLIENT_SECRET = credentials('FALCON_CLIENT_SECRET')
            FALCON_CLOUD_REGION  = credentials('FALCON_CLOUD_REGION')
            CONTAINER_REPO       = credentials('CONTAINER_REPO')
            CONTAINER_TAG        = credentials('CONTAINER_TAG')
        }
        stages {
            stage('Container Image Scan') {
                steps {
                    sh '''
                    if [ ! -d container-image-scan ] ; then
                        git clone https://github.com/crowdstrike/container-image-scan
                    fi
                    pip3 install docker-py
                    python3 container-image-scan/cs_scanimage.py
                    '''
                }
            }
        }
    }
   ```
   Sample Jenkins pipeline script with only `FALCON_CLIENT_SECRET` as a Jenkins Secret:
   ```
    pipeline {
        agent any
        environment {
            FALCON_CLIENT_SECRET = credentials('FALCON_CLIENT_SECRET')
        }
        stages {
            stage('Container Image Scan') {
                steps {
                    sh '''
                    if [ ! -d container-image-scan ] ; then
                        git clone https://github.com/crowdstrike/container-image-scan
                    fi
                    pip3 install docker-py
                    python3 container-image-scan/cs_scanimage.py -u <your_falcon_client_id> -r docker.io/busybox -t latest -c us-1
                    '''
                }
            }
        }
    }
   ```

repository: shawndwells/cicd-falcon-tutorial

repo_name: shawndwells/cicd-falcon-tutorial


text:
# NEW VERSION:

https://github.com/Vytek/MayaVerse03

# MayaVerse
MayaVerse is an experimental Metaverse - Immersive Virtual World

This document describes the development and creation of the first Immersive Virtual World. MayaVerse will be a fully immersive computer recreated universe. It will be developed using the best technologies available to overcome the current paradigm of the "Immersive Virtual Worlds" and launch the user in a new vision.
What will be outlined is actually an idea, a project that we hope will soon become a reality. We believe il will be soon a reality, hoping that drawing a plot and describing what are the possibilities will encourage further progress and implementations.

Let's start from the correct definition of "MayaVerse":
3D immersive virtual environment recreated by computer, shared with multiple users over the Internet with a persistent possibility of insertion , modification and deletion of objects and agents and direct interaction through virtual devices. Furthermore programmable through a scripting language.
The above definition only partially clarifies the possibilities offered by a Metaverse. Here, then, is a brief "manifesto" that can detail more the characteristics of the MayaVerse project.
A micro manifesto for the perfect "Metaverse":

* Immersive Virtual Reality: Immersive Virtual Reality, designed for a sense of "presence" and "interaction" at a high level. One should not think of a simple HMD viewer connected to an environment recreated on the computer, but of a platform that "involves" the user and above all gives him the possibility of interacting with other users, with objects and also with automatic systems or systems guided by Artificial Intelligence.

* Open Source/Royalty Free protocols, standards, queues: the entire Metaverse source code should be released under Open Source lincense, but above all based on standards and non-proprietary protocols, open and certified by international bodies. Examples are the VRML standards and its evolution X3D which, however, after a period of good diffusion, have been "forgotten" by the IT industry. Recently, Carmack has also underlined this possibility with the creation of an open standard for describing a 3D scene and its transfer through the internet via glTF.

* Sandboxing User Generated contents In-World/Out-World: the ability to offer users tools for creating and editing any content within the virtualized environment is essential. The ability to import creations from other systems and software is also a goal that amplifies users' creativity and offers an unprecedented level of interaction. All current "Metaverse" offer this opportunity at various levels, which can then be specialized to create games, experiments and artistic forms of all kinds.

* Scripting system using software language as Javascript, C#, Go, Swift: directly correlated with the previous point is the need to program the entire environment through high-level languages. C#, Go and Swift seem to be perfect candidates even though the scene is currently dominated by Javascript. However, it is essential to give developers the option of creating links, automatically modifying the environment and interfacing it with other systems and platforms.

* Metaverse as protocol not only as API: it is quite obvious to think that the Metaverse exposes APIs, but it is even more important to assume and design a real protocol that allows different Metaverses to communicate with each other. . In the past, there have been several attempts such as MMOX, which has failed to overcome the draft state of the IETF.

* Crypto Currency inside Metaverse: Why not use Bitcoin or Ethereum directly? Despite many ads, still no Metaverse uses Crypto-currencies any kind to allow trade between users. This feature would instead make the platform unique and above all would involve the user more closely.

* Decentralized architectures: Almost all platforms for virtual worlds are based on classic client-server architecture. Moving to a peer-to-peer system would have enormous advantages. JanusVR, for example, allows you to use the incredible ipfs (Inter-Planetary File System) for the fast recovery of different assets.

Implementation of the Alfa version
The software is currently only developed for Windows platform.
The current Client system is based on SW:

3D Graphics Engine: Unity3D 2017.1.1f01

See list below

All server-side code relies on opensource services and software for Linux Server.
The tests were carried out on the following HW VR:

 - HTC Live 1.2
 - OculusRift CV1

[PLEASE SEE Wiki for more info!](https://bitbucket.org/enrico_speranza/mayaverse/wiki/Home)

Video:

- https://www.youtube.com/watch?v=k8pXD1YoS0E
- https://www.youtube.com/watch?v=1luKUOVQnZc

## Licenses

 - **Only the code in `Assets/Scripts` is released under the MIT license**
 - Other code libraries in `Assets/Libraries` all come with their own licenses
 - Any binary resources are more or less there on a "fair use" basis, **don't assume that you can just copy and use them**

## Useful links:
Configuration git:
[Link to file .gitignore](https://gist.github.com/Shogan/dad6786c58c5ad88e0ec)

## Open source Assets List ##

- https://github.com/thestonefox/VRTK (Commit: d227047f815dcd87d840eb993ce8b80c89ba10b8)
- https://github.com/ValveSoftware/steamvr_unity_plugin
- https://github.com/Akue/LSky
- https://github.com/facebook/360-Capture-SDK
- https://github.com/Demigiant/dotween
- https://github.com/ValveSoftware/steam-audio
- https://github.com/fpanettieri/unity-socket.io-DEPRECATED
- https://github.com/watson-developer-cloud/unity-sdk
- https://github.com/versionpatch/projectileTrajectoryU3d
- https://github.com/BayatGames/SaveGameFree
- https://github.com/Deadcows/CustomLogger
- https://github.com/EnricoMonese/DayNightCycle
- http://talesfromtherift.com/measuring-stick/
- http://talesfromtherift.com/vr-fps-counter/
- https://www.dropbox.com/s/f4li4hg22dqcu9h/TFP_Water.unitypackage?dl=1
- https://www.davidstenfors.com/download.php?file=Campfire.rar
- https://www.davidstenfors.com/download.php?file=Alchemy%20Station.rar
- https://github.com/Gris87/IniFile
Networking
- https://github.com/Vytek/HazelTestUDPClientUnity

## Free Assets ##

- [Advance INI Parse](https://www.assetstore.unity3d.com/en/#!/content/23706)
- [NVIDIA Ansel](https://www.assetstore.unity3d.com/en/#!/content/74758)
- [NVIDIA VRWorks](https://www.assetstore.unity3d.com/en/#!/content/84126)
- [Forest Generator](https://www.assetstore.unity3d.com/en/#!/content/29692)
- [Fps Graph Analyzer](https://www.assetstore.unity3d.com/en/#!/content/85130)
- [Screen Logger](https://www.assetstore.unity3d.com/en/#!/content/49114)
- [Autosaver](https://www.assetstore.unity3d.com/en/#!/content/38279)
- [Fluvio](https://www.assetstore.unity3d.com/en/#!/content/2888)
- [Pro Build](https://www.assetstore.unity3d.com/en/#!/content/11919)
- [[BFW]Simple Dynamic Clouds](https://www.assetstore.unity3d.com/en/#!/content/85665)
- https://developer.oculus.com/downloads/package/oculus-utilities-for-unity-5/

## Tutorial used ##

- [GAME ASSET TUTORIAL - Creating a Flag Using Unity 5 Cloth - Preview](https://www.youtube.com/watch?v=GiWD2PCzD3g)
- [GAME ASSET TUTORIAL - How to Create a Cloth in Unity 5 (PART 1/2)](https://www.youtube.com/watch?v=sbiuwaJ6PT4)
- [GAME ASSET TUTORIAL - How to Create a Cloth in Unity 5 (PART 2/2)](https://www.youtube.com/watch?v=UK8s7sowxiI)

repository: collabsoft/MayaVerse

repo_name: collabsoft/MayaVerse


text:
# codesnippets

a collection of code and algorithms I found useful, but didn't find anywhere else yet

### analyzeconcurrency.vbs

if you have excel data with start and end dates and item groups, and you want to analyse their synchronous overlapping/concurrency, this code will help. Contains an implementation of Marzullo's algorithm in VBA

### googleFindInSites.js

if you need to do many google searches but only on a limited number of sites, these functions can generate search-links
Here's a video showing how to use it: https://youtu.be/nW6GGYhr0fA

### htmlTemp1ChildrenAnimations.js

animations on DOM elements to run from the browser's devTools

repository: shnydercom/codesnippets

repo_name: shnydercom/codesnippets


text:
# Aleena
## _MongoDB_PointData_

[![N|Solid](https://cldup.com/dTxpPi9lDf.thumb.png)](https://nodesource.com/products/nsolid)

[![Build Status](https://travis-ci.org/joemccann/dillinger.svg?branch=master)](https://travis-ci.org/joemccann/dillinger)

This repository is for connecting, fetching, filtering, deleting and sending back the filtered data to Mongodb.

- setup_connection.py
- fetch_del.py
- point_cloud_filtering.py
- update.py

## Getting it

- To download MongoDB_PointData, either fork this github repo or simply use Pypi via pip.
      $ pip install Mongodb_PointData

#### set_connection.py
It setup the connection with MongoDB.

#### fetch_del.py
This contains code for colleting the data from database based on frame number limit and, deleting the fetched and filtered data based on same.

#### pointcloud_filtering.py
This contains code for filtering fetched point cloud data.

#### update.py
This contains code for updating the database with filtered point cloud data.

### Demo
Sample code for using all the packages.
#### Installation

To download MongoDB_PointData, either fork this github repo or simply use Pypi via pip:

```sh
pip install
```


text:
# Chips

[![Open bugs badge](https://img.shields.io/badge/dynamic/json.svg?label=open%20bugs&url=https%3A%2F%2Fapi.github.com%2Fsearch%2Fissues%3Fq%3Dis%253Aopen%2Blabel%253Atype%253ABug%2Blabel%253A%255BChips%255D&query=%24.total_count)](https://github.com/material-components/material-components-ios/issues?q=is%3Aopen+is%3Aissue+label%3Atype%3ABug+label%3A%5BChips%5D)

[Chips](https://material.io/components/chips) are compact elements that represent an input, attribute, or action. They allow users to enter information, make selections, filter content, or trigger actions. While buttons are expected to appear consistently and with familiar calls to action, chips should appear dynamically as a group of multiple interactive elements.

![Chips hero image](docs/assets/chips-hero.png)

**Contents**

* [Using chips](#using-chips)
* [Input chip](#input-chip)
* [Choice chip](#choice-chip)
* [Filter chip](#filter-chip)
* [Action chip](#action-chip)
* [Theming](#theming)

- - -

## Using chips

### Installing

To use chips in your app first add the following to your `Podfile`:

```bash
pod 'MaterialComponents/Chips'
```

Then, run the following command:

```bash
pod install
```

From there, import the relevant target or file.

#### Swift
```swift
import MaterialComponents.MaterialChips
```

#### Objective-C

```objc
#import "MaterialChips.h"
```

### Making chips accessible

Always verify that your chips meet minimum touch requirements, as defined by either Apple's Human Interface Guidelines or Material. Material recommends a 44x44 minimum touch target.

Remember to set any relevant `accessibilityLabels` or `accessibilityTraits`, especially if you are not satisfied with default system-assigned values.

**Types**

There are four types of chips: 1\. [Input (text entry)](#input-chip) 2\. [Choice](#choice-chip) 3\. [Filter](#filter-chip) 4\. [Action](#action-chip)

![Examples of the four different chip types](docs/assets/chips-composite.png)

It is possible to create each type of chip by instantiating a single `MDCChipView` and adidng it to your view controller just like any other `UIView`.

#### Swift
```swift
let chipView = MDCChipView()
chipView.titleLabel.text = "Tap me"
chipView.setTitleColor(UIColor.red, for: .selected)
chipView.sizeToFit()
chipView.addTarget(self, action: #selector(tap), for: .touchUpInside)
self.view.addSubview(chipView)
```

#### Objective-C
```objc
MDCChipView *chipView = [[MDCChipView alloc] init];
chipView.titleLabel.text = @"Tap me";
[chipView setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
[chipView sizeToFit];
[chipView addTarget:self
               action:@selector(tap:)
     forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:chipView];
```

`MDCChipView` allows for customization of the following:

### Ink ripple animation

Chips display animated ink splashes when the user presses the chip. Note that if you have a background color set for the `highlighted` state the ink animation will occur on top of that color.

### Stateful properties

Like `UIButton`, `MDCChipView` provides many state-dependant accessors. These methods allow you to set the background color, title
color, border style, and elevation, both for individual states and combinations of states. If no value is set for a given state, the `normal` value will used.

### Selected Image View

Setting the image for the `selectedImageView` is optional but can help clarify that a chip is selected. This image will only appear when the chip is selected. If you have an
image set on the standard `imageView`, then the `selectedImageView` will appear on top of it. Otherwise
you'll need to resize the chip to show the selected image. See the Filter chip example to see this
in action.

### Padding

There are 4 `padding` properties that determine a chip's layout: one for each of the chip's
subviews (`imageView` and `selectedImageView` share one padding property), and one which wraps all
the others (`contentPadding`). This is useful so that you can set each of the padding properties to
ensure your chips look correct whether or not they have an image and/or accessory view. The chip
uses these property to determine `intrinsicContentSize` and `sizeThatFits`.

### Adjusting chip sizes after changing the label

If the label of a chip in a collection view can be changed dynamically (e.g. in reaction to a user's
tap), then you may notice that the chip's frame does not automatically update to accomodate the new
size of the chip's label. To force your chip to update its layout when this happens you can invoke
`invalidateIntrinsicContentSize` on the chip view. For example:

#### Swift
```swift
chipView.invalidateIntrinsicContentSize()
```

#### Objective-C
```objc
[chipView invalidateIntrinsicContentSize];
```

## Input chip

Input chips represent a complex piece of information in compact form, such as an entity (person, place, or thing) or text. They enable user input and verify that input by converting text into chips.

We currently provide an implementation of Input Chips called `MDCChipField`.

#### Swift
```swift
let chipField = MDCChipField()
chipField.delegate = self
chipField.textField.placeholderLabel.text = "This is a chip field."
chipField.showChipsDeleteButton = true
chipField.sizeToFit()
view.addSubview(chipField)
```

#### Objective-C
```objc
MDCChipField *chipField = [[MDCChipField alloc] init];
chipField.delegate = self;
chipField.textField.placeholderLabel.text = @"This is a chip field.";
chipField.showChipsDeleteButton = true
[chipField sizeToFit];
[self.view addSubview:chipField];
```

## Choice chip

Choice chips allow selection of a single chip from a set of options.

Choice chips clearly delineate and display options in a compact area. They are a good alternative to toggle buttons, radio buttons, and single select menus.

It is easiest to create choice Chips using a `UICollectionView`:

- Use `MDCChipCollectionViewFlowLayout` as the `UICollectionView` layout:

#### Swift
```swift
let layout = MDCChipCollectionViewFlowLayout()
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
```

#### Objective-C
```objc
MDCChipCollectionViewFlowLayout *layout = [[MDCChipCollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
```

- Leave the default `UICollectionView` selection setting (single selection).
- Use `MDCChipCollectionViewCell` as `UICollectionView` cells. (`MDCChipCollectionViewCell` manages the state of the chip based on selection state of `UICollectionView` automatically)

#### Swift
```swift
func loadView() {
  super.loadView()

  collectionView.register(
      MDCChipCollectionViewCell.self,
      forCellWithReuseIdentifier: "identifier")
}

func collectionView(
  _ collectionView: UICollectionView,
  cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath) as! MDCChipCollectionViewCell
  let chipView = cell.chipView
  // configure the chipView to be a choice chip
  return cell
}
```

#### Objective-C
```objc
- (void)loadView {
  [super loadView];

  [_collectionView registerClass:[MDCChipCollectionViewCell class]
      forCellWithReuseIdentifier:@"identifier"];
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                           cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  MDCChipCollectionViewCell *cell =
      [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
  MDCChipView *chipView = cell.chipView;
  // configure the chipView to be a choice chip
  return cell;
}
```

- Use `UICollectionViewDelegate` methods `collectionView:didSelectItemAtIndexPath:` for reacting to new choices.

- Use `UICollectionView` `selectItemAtIndexPath:animated:scrollPosition:` method to edit choice selection programmatically.

## Filter chip

Filter chips use tags or descriptive words to filter content.

Filter chips clearly delineate and display options in a compact area. They are a good alternative to toggle buttons or checkboxes.

It is easiest to create filter Chips using a `UICollectionView`:

- Use `MDCChipCollectionViewFlowLayout` as the `UICollectionView` layout:

#### Swift
```swift
let layout = MDCChipCollectionViewFlowLayout()
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
```

#### Objective-C
```objc
MDCChipCollectionViewFlowLayout *layout = [[MDCChipCollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
```

- Allow multi cell selection in the `UICollectionView`:

#### Swift
```swift
collectionView.allowsMultipleSelection = true
```

#### Objective-C
```objc
collectionView.allowsMultipleSelection = YES;
```

- Use `MDCChipCollectionViewCell` as `UICollectionView` cells. (`MDCChipCollectionViewCell` manages the state of the chip based on selection state of `UICollectionView` automatically)

#### Swift
```swift
func loadView() {
  super.loadView()

  collectionView.register(
      MDCChipCollectionViewCell.self,
      forCellWithReuseIdentifier: "identifier")
}

func collectionView(
    _ collectionView: UICollectionView,
    cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath) as! MDCChipCollectionViewCell
    let chipView = cell.chipView
    // configure the chipView to be a filter chip
    return cell
}
```

#### Objective-C
```objc
- (void)loadView {
  [super loadView];

  [_collectionView registerClass:[MDCChipCollectionViewCell class]
      forCellWithReuseIdentifier:@"identifier"];
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                           cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  MDCChipCollectionViewCell *cell =
      [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
  MDCChipView *chipView = cell.chipView;
  // configure the chipView to be a filter chip
  return cell;
}
```

- Use `UICollectionViewDelegate` methods `collectionView:didSelectItemAtIndexPath:` and `collectionView:didDeselectItemAtIndexPath:` for reacting to filter changes.

- Use `UICollectionView` `deselectItemAtIndexPath:animated:` and `selectItemAtIndexPath:animated:scrollPosition:` methods to edit filter selection in code.

## Action chip

Action chips offer actions related to primary content. They should appear dynamically and contextually in a UI.

An alternative to action chips are buttons, which should appear persistently and consistently.

It is easiest to create action Chips using a `UICollectionView`:

- Use `MDCChipCollectionViewFlowLayout` as the `UICollectionView` layout:

#### Swift
```swift
let layout = MDCChipCollectionViewFlowLayout()
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
```

#### Objective-C
```objc
MDCChipCollectionViewFlowLayout *layout = [[MDCChipCollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
```

- Leave the default `UICollectionView` selection setting (single selection).
- Use `MDCChipCollectionViewCell` as `UICollectionView` cells. (`MDCChipCollectionViewCell` manages the state of the chip based on selection state of `UICollectionView` automatically)

#### Swift
```swift
func loadView() {
  super.loadView()

  collectionView.register(
      MDCChipCollectionViewCell.self,
      forCellWithReuseIdentifier: "identifier")
}

func collectionView(
  _ collectionView: UICollectionView,
  cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath) as! MDCChipCollectionViewCell
  let chipView = cell.chipView
  // configure the chipView to be an action chip
  return cell
}
```

#### Objective-C
```objc
- (void)loadView {
  [super loadView];

  [_collectionView registerClass:[MDCChipCollectionViewCell class]
      forCellWithReuseIdentifier:@"identifier"];
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                           cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  MDCChipCollectionViewCell *cell =
      [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
  MDCChipView *chipView = cell.chipView;
  // configure the chipView to be an action chip
  return cell;
}
```

- Make sure that `MDCChipCollectionViewCell` does not stay in selected state

#### Swift
```swift
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  // For action chips, we never want the chip to stay in selected state.
  // Other possible apporaches would be relying on theming or Customizing collectionViewCell
  // selected state.
  collectionView.deselectItem(at: indexPath, animated: false)
  // Trigger the action
}
```

#### Objective-C
```objc
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  // For action chips, we never want the chip to stay in selected state.
  // Other possible apporaches would be relying on theming or Customizing collectionViewCell
  // selected state.
  [collectionView deselectItemAtIndexPath:indexPath animated:NO];
  // Trigger the action
}
```

- Use `UICollectionViewDelegate` method `collectionView:didSelectItemAtIndexPath:` to Trigger the action.

### Anatomy and key properties

The following is an anatomy diagram of a chip:

![Chip anatomy diagram](docs/assets/chips-anatomy.png)

1.  Container
1.  Thumbnail (optional)
1.  Text
1.  Remove icon (optional)

#### Container attributes

                | Attribute                        | Related method(s)                               | Default value
-------------------- | -------------------------------- | ------------------------------- | -------------
**Color**            | N/A                              | `-setBackgroundColor:forState:`
`-backgroundColorForState:`  | On surface color at 12% opacity
**Ripple color**     | N/A                              | `-setRippleColor:forState:`
`-rippleColorForState:`  | White at 14% opacity
**Stroke width**     | N/A                              | `-setBorderWidth:forState:`
`-borderWidthForState:`  | 0
**Stroke color**     | N/A                              | `-setBorderColor:forState:`
`-borderColorForState:`  | `nil`
**Min height**       | `minimumSize`                    | N/A                                                      | `{ 0, 32 }`
**Padding**          | `contentPadding` | N/A | `{ 4, 4, 4, 4 }`
**Min touch target** | `centerVisibleArea`, `visibleAreaInsets` | N/A                          | `NO`, `{ 0, 0, 0, 0 }`

#### Thumbnail attributes

**Chip icon**

          | Attribute                                       | Related method(s)                                                     | Default value
-------------- | ----------------------------------------------- | --------------------------------------------------------------------- | -------------
**Icon**       | `imageView`, `selectedImageView`                | N/A                                                                   | `nil`
**Padding**    | `imagePadding`, `accessoryPadding` | N/A | `{ 0, 0, 0, 0 }`, `{ 0, 0, 0, 0 }`

#### Text attributes

          | Attribute                                       | Related method(s)                                                           | Default value
-------------- | ----------------------------------------------- | --------------------------------------------------------------------------- | -------------
**Text label** | `titleLabel`                                    | N/A                   | N/A
**Color**       | N/A                              | `-setTitleColor:forState:`
`-titleColorForState:`  | On surface color at 87% opacity
**Typography** | `titleFont`                        | N/A | Body 2
**Padding**    | `titlePadding` | N/A       | `{ 3, 8, 4, 8 }`

## Theming

`MDCChipView` supports Material Theming using a Container Scheme. To install the `MDCChipView` theming extension, first add the following line to your `Podfile`:

```bash
pod MaterialComponents/Chips+Theming
```

Then run the installer:

```bash
pod install
```

There are two theming variants for `MDCChipView`: the default theme and the outlined theme.

Below is a Chip collection with the Shrine outlined theme applied to it.

![shrine-chips](docs/assets/shrine-chips.png)

#### Swift

```swift
// Import the Chips Theming Extensions module
import MaterialComponents.MaterialChips_MaterialTheming
 ...
 // Create or use your app's Container Scheme
let containerScheme = MDCContainerScheme()
 // Theme the chip with either default theme
chip.applyTheme(withScheme: containerScheme)
 // Or outlined theme
chip.applyOutlinedTheme(withScheme: containerScheme)
```

#### Objective-C

```objc
// Import the Tabs Theming Extensions header
#import <MaterialComponents/MaterialChips+MaterialTheming.h>
 ...
 // Create or use your app's Container Scheme
MDCContainerScheme *containerScheme = [[MDCContainerScheme alloc] init];
 // Theme the chip with either default theme
[self.chip applyThemeWithScheme:containerScheme];
 // Or outlined theme
[self.chip applyOutlinedThemeWithScheme:containerScheme];
```

branch_name: refs/heads/develop

gha_language: Objective-C


text:
Motorcycle Part Identifier

Do you have several large boxes of unorganized OEM motorcycle parts?

Are you tired of having to manually search for the part number in order to find out what the part is for?

If so, this web app is for you.

    View the site »

Table of Contents

Features

How it works

Overview

Image preprocessing & text recognition

Built with

Limitations

Supported manufacturers

Data accuracy

      Development

Running a local copy

Browser security notes

Todo

License

## Features

### Real-time part identification

Point the camera at a Honda OEM part label, and the app will attempt to determine the part name.

### Inventory management

Search and manage part data, and download your inventory as a .CSV file.

## How it works

### Overview

This web app uses Tesseract.JS (a JavaScript port of the [Tesseract OCR library](https://en.wikipedia.org/wiki/Tesseract_(software))) to scan live video frames for text strings that match OEM part number formats.

To get part details, it sends part numbers to [a Python Flask backend](https://github.com/aduda9/mpi-backend), which queries eBay for matching parts.

All text recognition and image manipulation is performed in the browser! No images are sent externally. All inventory data is stored locally as well.

### Image preprocessing & text recognition

About once per second, a frame from the live video feed is preprocessed and sent to the OCR engine. The preprocessing is basically just [thresholding](https://en.wikipedia.org/wiki/Thresholding_(image_processing)), but it consists of three steps:

Conversion to greyscale

Average pixel value calculation

Thresholding, but using the average pixel value from step 2 as the threshold

The results of this process can be displayed in real time, just flip the "scanner vision" switch!

The boxes rendered on top of the camera are bounding boxes, generated by Tesseract.

### Built with

* [Tesseract.JS](https://github.com/naptha/tesseract.js#tesseractjs) for OCR
* [LokiJS](https://github.com/techfort/LokiJS) for client-side part data storage/filtering, and persistence
* [React](https://github.com/facebook/react)
* [react-webcam](https://github.com/mozmorris/react-webcam)

## Limitations

### Supported manufacturers

As of now, only Honda parts are supported.

### Data accuracy

The only way I could obtain OEM motorcycle part data (without web scraping) was to use eBay as the data source. So if a part hasn't been sold on eBay, the app won't be able to return information about it.

The part name is determined by analyzing eBay listing titles, so there is some variability with that as well. See the [backend](https://github.com/aduda9/mpi-backend) docs for more information.

## Development

### Running a local copy

To get a local copy up and running follow the steps below.

1. Clone the repo
   ```sh
   git clone https://github.com/aduda9/motorcycle-part-identifier.git
   ```
2. Install NPM packages
   ```sh
   npm install
   ```
2. Start (see note below)
   ```sh
   npm start
   ```

### Browser security notes

Most browsers will automatically deny camera access to pages served over regular HTTP. So, if you're running a local copy, you'll have to set ```HTTPS=true``` before running ```npm start```. See [this](https://stackoverflow.com/questions/44574399/create-react-app-how-to-use-https-instead-of-http) StackOverflow post for helpful information.

If you're working with a local copy of the backend, you'll also have to enable [mixed content](https://web.dev/what-is-mixed-content/) in your browser, or ensure that the backend is served over HTTPS as well.

## Todo

Add support for more OEM part formats (manufacturers)

Add support for manual part number entry

Add ability to edit part information

See the [open issues](https://github.com/aduda9/motorcycle-part-identifier/issues) for a list of known issues.

## License

Distributed under the MIT License. See `LICENSE` for more information.


text:
SMBUS I2C implementation for attiny13
---

## Introduction

This library very basic implementation of smbus protocol for attiny13 microcontroller
It should work pretty good on low speed 100kHz bus, no stretching needed.

It disigned for low power consumation and may work in sleep mode. INT0 interrupt used to detect start condition and wake-up microcontroller.

*PEC not supported*

## SMBUS Functions:
**PLEASE NOTE!**  There is some differences from original smbus protocol

The device has 2 memory slots for read and write. Smbus command, actually is a mem ptr to read/write operarion.Internal counter always incremented on ACK, so *data* may have multiply bytes in all functions until NACK reached.It means you can read as many bytes as needed for your process

Counter always resetted to 0 on Stop condition.

Following smbus functions implemented in firmware.

### smbus_read_byte
```
S Addr Rd [A] [Data] NA P
```
Sends *Data* to host controller.
### smbus_write_byte
```
S Addr Wr [A] Data [A] P
```
Reads *Data* from host controller.

### smbus_read_byte_data/smbus_read_word_data
```
S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] NA P
```
Sends *Data* to host controller from specified address.

### smbus_read_byte_data/smbus_read_word_data
```
S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] NA P
```
Reads *Data* from host controller into specified address.

## Hardware

SDA - External interrupt pin (wakeups microcontroller for communication)

SCL - Any GPIO pin ( PB0 by default )

```
       Attiny13a
        -------
      -|RST VCC|-
      -|PB3 PB2|-
      -|PB4 PB1|- SDA
      -|GND PB0|- SCL
        -------
```
## License
MIT. See LICENSE file


text:
# certbot-ansible-role
Ansible role to install LetsEncrypt's certificates on Ubuntu using CertBot

Pre-requisites:
  * Nginx installed
  * App being served on the given hostname (deploy_server_hostname in vars/default.yml)

Steps:
  * Clone this repo
  * Include this into your playbook
  * Fill in details in vars/default.yml
  * Run the playbook
  * See the green secure mark on your site url and feel Happy ;)

repository: prasadpilla/certbot-ansible-role

repo_name: prasadpilla/certbot-ansible-role


text:
# forex arbitrage

## Summary

This program is a proof of concept showing how you can detect arbitrage
opportunities using forex pricing data. It uses pricing data from
exchangeratesapi.io (free) to acquire the pricing data.

The data is taken and converted into a graph, with the weights being the
negative logarithm of the pricing data. The negative log is taken because I am
using the Bellman-Ford algorithm to detect arbitrage opportunities. The
Bellman-Ford algorithm detects negative cycles, but we want a situation where
the pricing data leads to a _positive_ cycle of prices, such that we can start
at some currency X, and perform some set of currency conversions such that we
end up at currency X, but with more money than we started from.

Because the Bellman-Ford algorithm adds weights, we need to figure out some
transformation that allows us to use addition to find a positive weight cycle.
We know that `log(a) + log(b) = log(a * b)`, which takes care of the addition
problem. Using `-log(x)` lets us turn positive cycles into negative ones, which
means that we can detect arbitrage opportunities by finding a negative cycle in
a graph.

## Usage

The program saves the generated conversion rate graph as a json file. You can
change the name of the json file from the default naming scheme using the `-o`
flag. You can also elect to load pricing data from a json file using the `-i`
flag, if you're just messing around or debugging and don't need the most recent
data.

## Development

Compile this program with:

```sh
cargo build

# or

cargo build --release
```

All files are formatted using `rustfmt`.

repository: kitesoft/forex-arbitrage

repo_name: kitesoft/forex-arbitrage


text:
# nf-core/smartseq

## Please use the version on nf-core: https://github.com/nf-core/smartseq2

----

**Preprocess scRNA-seq data generated with the SmartSeq2 protocol.**.

[![GitHub Actions CI Status](https://github.com/nf-core/foo/workflows/nf-core%20CI/badge.svg)](https://github.com/nf-core/foo/actions)
[![GitHub Actions Linting Status](https://github.com/nf-core/foo/workflows/nf-core%20linting/badge.svg)](https://github.com/nf-core/foo/actions)
[![Nextflow](https://img.shields.io/badge/nextflow-%E2%89%A519.10.0-brightgreen.svg)](https://www.nextflow.io/)

[![install with bioconda](https://img.shields.io/badge/install%20with-bioconda-brightgreen.svg)](http://bioconda.github.io/)
[![Docker](https://img.shields.io/docker/automated/nfcore/smartseq.svg)](https://hub.docker.com/r/nfcore/smartseq)

## Introduction

The pipeline is built using [Nextflow](https://www.nextflow.io), a workflow tool to run tasks across multiple compute infrastructures in a very portable manner. It comes with docker containers making installation trivial and results highly reproducible.

## Documentation

The nf-core/smartseq pipeline comes with documentation about the pipeline, found in the `docs/` directory:

1. [Installation](https://nf-co.re/usage/installation)
2. Pipeline configuration
   - [Local installation](https://nf-co.re/usage/local_installation)
   - [Adding your own system config](https://nf-co.re/usage/adding_own_config)
   - [Reference genomes](https://nf-co.re/usage/reference_genomes)
3. [Running the pipeline](docs/usage.md)
4. [Output and how to interpret the results](docs/output.md)
5. [Troubleshooting](https://nf-co.re/usage/troubleshooting)

This pipeline was developed to process single cell RNA-seq data generated
using the [Smart-Seq2 protocol](https://www.nature.com/articles/nprot.2014.006).

The pipeline features:

- Quality control using `fastqc` and `multiqc`
- Alignment using `STAR`
- Quantification using `rsem` or `featureCounts`
- TCR analysis using `TraCeR`.
- BCR analysis using `BraCeR`.

![flowchart](assets/flowchart.png)

## Credits

nf-core/smartseq was originally written by [Sandro Carollo](https://github.com/sandrocarollo),
[Giorgos Fotakis](https://github.com/abyssum) and [Gregor Sturm](https://github.com/grst)


text:
# Word-Segmentation-using-opencv-and-tensorflow

This is a dataset from Kaggle where the goal was to segment the captcha images with each character. Here we use the OpenCV library to
You can find the dataset [here](https://www.kaggle.com/fournierp/captcha-version-2-images).

![](Captcha%20Image.png)

The images are 5 letter words that can contain numbers. This dataset is a perfect opportunity to attempt to make __Optical Character Recognition__ algorithms.

Here, I have applied to approaches,
1) Using OpenCV and creating bounding box for the image using hard-coded dimensions for the bounding boxes as the reCAPTCHA images in the dataset since, the letters are at the same place for every image.

2) Using TensorFlow I trained the model using Convolutional, MaxPooling, and BatchNormalization layers and tested the model on the test dataset with test accuracy of __93%__.

gha_language: Jupyter Notebook