text:
<repo_name>hassanyousuf/1012-10-17-carbuild<file_sep>/README.md
# 1012-10-17-carbuild

branch_name: refs/heads/master

repo_language: Markdown


text:
<file_sep>//Funções
void main(){
  showOutput(square(2));
  showOutput(square(2.5));
  //Arrow Function =>

}

dynamic square(var x) => x * x;

void showOutput(var msg){
  print(msg);
}<file_sep>/*
int
double
String
bool
dynamic
*/
void main(){
  int amount1 = 100;
  var amount2 = 200;

  print('Amount 1: $amount1 Amount 2: $amount2');

  double damount1 = 101.11;
  var damount2 = 122.22;

  print('Damount1: $damount1 e Damount2: $damount2');

  String firstName = 'Tarcisio';
  var lastName = 'Câmara';

  print(firstName + ' ' + lastName);

  bool isItTrue1 = true;
  var isItTrue2 = false;

  print('IsItTrue1: $isItTrue1 | isItTrue2: $isItTrue2');

  dynamic weakVariable = 100;
  print('weakVariable: $weakVariable \n');

  weakVariable = 'Dart is programming';
  print('weakVariable: $weakVariable \n');

}<file_sep>void main(){
  var s1 = 'Single quotes work well for string literals';
  var s2 = 'Double quotes work just as well';
  var s3 = 'Is\'s easy to escape the string delimiter.';
  var s4 = "It's even easier to use other delimiter.";

  print(s1);
  print(s2);
  print(s3);
  print(s4);

  //RAW String
  var s = r'In a raw string, not even \n gets especial tratament.';
  print(s);
}<file_sep>//Comentário de linha
/*
Comentário de multiplas linhas
deu pra
entender?
*/
///Documentação<file_sep>//While e Do While Loop

void main(){
  var num = 5;

  while(num > 0){
    print(num);
    num -= 1;
  }

  num = 6;
  do{
    print(num);
    num -= 1;
  }while(num > 0);
}<file_sep>//type teste

void main() {
  var x = 'Olá';
  if(x is int){
    print('inteiro');
  }
  else if(x is String){
    print('String');
  }
  else if(x is double){
    print('Double');
  }
  else{
    print('Outra coisa');
  }
}<file_sep>//Map

void main(){
  var gifts = {
    //Key Value
    'Primeiro': 'Boneco',
    'Segundo': 'Ps4',
    'Terceiro': 'Bola',
    5: 'Boneca'
  };
  var gift = Map();
  gift['Primeiro'] = 'Manga';

  print(gifts['Primeiro']);
  print(gifts[5]);
  print(gift['Primeiro']);
}<file_sep>//Class

class Person{
  String name;
  int age;

  Person(this.name, [this.age = 18]); //Constructor

  //Name constructor
  Person.guest(){
    name  = 'noName';
    age = 0;
  }

  void showOutput(){
    print(name);
    print(age);
  }
}

void main(){
  Person person1 = Person('Tarcisio', 33);
  person1.showOutput();

  var person2 = Person('Edivania', 33);
  person2.showOutput();

  var person3 = Person.guest();
  person3.showOutput();
}<file_sep># Projeto 2 - Calculadora de IMC

## Projeto feito em flutter/dart

App simples onde se coloca o peso e altura e ele retorna o valor do IMC e sua condição atual.
<file_sep>//dart:core
import 'dart:core';

void main(){
  var firstName = "Tarcisio";
  String lastName = "Câmara";
  print(firstName + ' ' + lastName);
}<file_sep># Estudos em Dart-Flutter
Arquivos de estudo da linguagem Dart - Flutter

## Curso de Dart da Free Code Camp (Completo)
## Curso de Flutter da Free Code Camp(em andamento)
<file_sep>void main(){
  for(var i = 0; i < 10; ++i){
    if(i % 2 == 0) continue;
    print('Odd $i');
  }

  for(var i = 0; i < 10; ++i){
    if(i == 6) break;
    print('Odd $i');
  }
}<file_sep>import 'dart:io';

void main(){
  //indices iniciais sendo inseridos com int.parse devido a leitura em dart ser em string
  //Então se faz necessária a conversão
  //Podemos definir tanto as variaveis e listas como int mas nesse caso é melhor deixar como var
  //Assim elas recebem uma String que será convertida para int
  var N = int.parse(stdin.readLineSync());
  var M = int.parse(stdin.readLineSync());
  //barra e movimento em Dart são listas e elas são definidas assim.
  var barra = new List(N + 1);
  var movimentos = new List(M + 1);

  //O resto do código é bem similar como em C e em outras linguagens
  for(int i=1; i<=N;i++){
    barra[i] = int.parse(stdin.readLineSync());
  }

  for (int i=1; i<=M;i++){
    movimentos[i] = int.parse(stdin.readLineSync());
  }

  List freq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

  for (int i=1;i<M;i++){
    int pI = movimentos[i];
    int pF = movimentos[i+1];
    if (i>1 && pF > pI) {
      pI++;
      };
    if (i>1 && pF < pI) {
      pI--;
      };
    if (pF > pI) {
			for (int j=pI;j<=pF;j++) {
        freq[barra[j]] += 1;
        };
		}
    else if (pF < pI) {
    		for (int j=pI;j>=pF;j--) {
          freq[barra[j]] += 1;
          };
		}
  }
  //Aqui printei a lista freq pra aparecer a sequencia reta e não um número abaixo do outro mas vcs mudam a criterio de vcs
  print(freq);

  /*for (int i=0;i<=9;i++) {
		print(freq[i]);
    }*/
}<file_sep>//Class final serve para fixar um valor e não alterar e const não pode alterar

class X{
  final name;
  static const int age = 10;

  X(this.name);
}

void main(){
  var x = X('Jack');
  print(x.name);
  print(X.age);
}<file_sep>//Switch Case
void main(){
  int number = 6;

  switch(number){
    case 0:
      print('Deu 0');
      break;
    case 1:
      print('Deu 1');
      break;
    default:
      print('Confuso!');
  }
}<file_sep>void main(){
  print(sum(10));
}

//dynamic sum(var num1, var num2) => num1 + num2;
//dynamic sum({var num1, var num2}) => num1 + num2;
dynamic sum(var num1,{var num2}) => num1 + (num2 ?? 0);<file_sep>class Veiculo{
  String modelo;
  int ano;

  Veiculo(this.modelo, this.ano){
    print(this.modelo);
    print(this.ano);
  }

  void showOutput(){
    print(modelo);
    print(ano);
  }
}

class Carro extends Veiculo{
  double price;

  Carro(String modelo, int ano, this.price) : super(modelo, ano);

  void showOutput(){
    super.showOutput();
    print(this.price);
  }
}

void main(){
  var car1 = Carro('Fusca', 1970, 5000);
  car1.showOutput();
}<file_sep>void main(){
  //Lists
  List names = ['Tarcisio', 'João', 'Maria'];
  //List names2 = names; <= Se fizer assim não copia e sim encaminha para o mesmo endereço
  var names2 = [...names];

  print(names[0]);
  print(names[1]);
  print(names.length);
  names[1] = 'Pedro';

  for(var n in names2){
    print(n);
  }
}<file_sep>//Função Anonima

void main(){
  var list = ['Maça', 'Banana', 'Laranja'];

  list.forEach((item){ //Função anonima
    print(item);
  });
}
<file_sep>//Set

void main(){
  //var halogens = <String> {};
  Set <String> names = {};

  print(names.runtimeType);

  /*for(var x in halogens){
    print(x);
  }*/
}<file_sep># Contador de pessoas

## Primeiro app desenvolvido em Flutter

O aplicativo só incrementa e decrementa a quantidade de pessoas de um local
quando esse total ultrapassa de 10 ele dá a mensagem de lotado, quando ele dá negativo ele da a mensagem mundo invertido
e quando esta entre 0 e 10 da a mensagem de Pode entrar.
<file_sep>//For Loop

void main(){
  for(var x = 1; x <= 10; x++){
    print(x);
  }
  var numbers = [1, 2, 3];

  for(var n in numbers){
    print(n);
  }

  for(var x = 0; x < numbers.length ; ++x){
    print(numbers[x]);
  }
}<file_sep>//Null Aware Operator
//(?.), (??), (??=)

class Num{
  int num = 10; //Se Atribuir a classe o n não será nulo mas se não será null
}
//var n;
//var n = Num();
//n?.num;
//if(n != null);
//
void main(){
  var n;
  int number;

  number = n?.num ?? 0;

  print(number);
}

languages: Markdown Dart

repo_name: tattudc/EstudosemDart-Flutter


text: <file_sep>"test ²âتش"


text:
<repo_name>debona/ShellBox<file_sep>/README.md
ShellBox
=========

ShellBox helps you to organize your **shellscripts** by splitting them in **commands libraries**.

If you spend much time on unix consoles in your developer's life, you probably built a set of ninja's scripts you use everyday to work an efficient way. ShellBox's original purpose is to provide a frame to build *project development Command Line Interfaces* (= your set of ninja's scripts).

### Features:

- **Lightly standardize shellscripts:**
    - Every library is composed of public commands and private functions.
    - Your libraries are directly executable: `$ a_library.sb a_command opt_1 opt_2 ...`.
- **Build libraries of reusable commands:**
    - Your scripts are sliced in namespaced commands libraries.
    - Every libraries can run other's command by requiring them: `require 'other_lib'; other_lib::command 'foo'`.
- **Designed for Command Line Interface:**
    - Easily create a command that generates a "manual" from your code documentation.
    - Enjoy the `bash` and `zsh` completions of commands and options.

## Getting started

### Installation

```sh
git clone git@github.com:debona/ShellBox.git ShellBox
cd ShellBox
export PATH="`pwd`/bin:$PATH" # make the shellbox libraries executable
export PATH="`pwd`/box:$PATH" # make the libraries of this shellbox available in your PATH
```

ShellBox is now ready for your current shell session.
To get it automatically available in all your shell sessions, add the PATH configuration to your `.profile` file.

```sh
echo "export PATH=\"`pwd`/bin:\$PATH\"" >> ~/.profile
echo "export PATH=\"`pwd`/box:\$PATH\"" >> ~/.profile
```

### Create your commands library

#### Basic library example

The first library allows you to print colored messages in shell console. The library print colors *iff* it's called in an interactive console.

`print.sb`:

```sh
#!/usr/bin/env shellbox
#
# A print library.
# It's purpose is to illustrate how ShellBox is fun.

# The following lines are executed when this library is required or executed.
if [[ -t 1 ]] && [[ -t 2 ]] # if stdout and stderr are tty, then define colors
then
	reset='\033[0m'
	yellowf='\033[33m'
fi

# COMMANDS:

## Print a warning message on stderr.
#
# @params	args	The warning message
function print::warning() {
	echo -e "${yellowf} ⚑ $@${reset}" >&2
}
```

Make `print.sb` executable: `chmod 755 print.sb`

Now you can execute `print` commands in your console:

```sh
$ ./print.sb warning "printed on stderr" 1> /dev/null
 ⚑ printed on stderr
```

#### Advanced library example

This library is an example of a library that rely on other's commands libraries. The `complexe.sb` library require our `print.sb` library and the `shared` library.

`complex.sb`:

```sh
#!/usr/bin/env shellbox
#
# A complex library.
# It's purpose is to illustrate how to rely on other libraries.

require 'print' # that means the complex library rely on the `print.sb` library

# COMMANDS:

## Print each parameter in one line.
#
# @params	args	The params to print
function complex::print() {
	if [[ $# -lt 1 ]]
	then
		print::warning 'There is no parameters'
	else
		complex_print_list "$@"
	fi
}

## Display a short help of the library or the help of the library command provided
#
# @param	[command_name]	The command name
function complex::help() {
	require 'shared' # a library can be required everywhere
	shared::help 'complex' "$@"
}

# PRIVATE FUNCTIONS:

## Print all the given params separated with the delimiter
#
# @param	args	The parameters
function complex_print_list() {
	for param in "$@"
	do
		echo " ● $param"
	done
}
```

Make `complex.sb` executable: `chmod 755 complex.sb`

Now you can execute `complex` commands in your console:

	$ complex.sb print `seq 1 3`
	 ● 1
	 ● 2
	 ● 3

	$ complex.sb help
	Available commands for this library:
	    complex help [command_name]
	    complex print args*

## How does it work?

Every **libraries** are executed through the `shellbox` **library interpreter**. This *interpreter* define few functions and then execute the given library command.

#### What happen when you execute a library command?

1. Your shell reads the first line of your script (the shebang) and runs the `shellbox` lib interpreter (with the lib as a parameter).
2. The interpreter declares few functions. The most important function is the **require** function.
3. The interpreter calls the **require** function on your library. The most important thing this function does is sourcing your library.
4. The interpreter looks for a function like `your_lib::the_command` to call, and then call it.

#### How does the require function look for libraries?

1. The **require** function look for the `*.sb` files available through your `PATH` environment var.
2. The function select the first library that match the given name.

### Actual limitations

- The `shellbox` *binary* must be in your `PATH` when you run a library command.
    - By the way, this command will work: `PATH="path/to/shellbox/bin:$PATH" my/libs/foo.sb`

## Licence

The code for this software is distributed under an MIT license.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
<file_sep>/bin/shellbox
#!/bin/bash
#
# Library command executer
# This script execute library commands of a given library. It is the only script which can be execute.
#
# @param	lib_file	The library file
# @param	command		The library command to run
# @params	options		All the library command options

####################################################################
###########                 GLOBAL VARS                  ###########
####################################################################

LIB_DIR="$( cd -P "`dirname "$1"`" && pwd )"

# Ensure the `LIB_DIR` is present in `PATH`.
[[ ":$PATH:" =~ ":$LIB_DIR:" ]] || PATH="$LIB_DIR:$PATH"

unset LIB_DIR # Avoid to leak.

####################################################################
###########               GLOBAL FUNCTIONS               ###########
####################################################################

## Source the library file.
# This mechanism rely on the `locate_library_file` function.
# Return 1 if the file can't be sourced
#
# @param	lib_name_or_file	the library name or path to a library file to source
function require() {
	local lib_name="$1"
	local status=0

	if [[ -x $lib_name ]]
	then
		local lib_file="$lib_name"
	else
		lib_name=$( basename_auto "$lib_name" )
		local lib_file=$( locate_library_file $lib_name )
	fi

	if ! source "$lib_file"
	then
		status=$?
		echo "$lib_name cannot be sourced from path:"
		echo "PATH=$PATH"
	fi

	return $status
}

## Find a library file across all directories present in PATH.
# It print the path of the first library file which match (the same way as PATH).
# Return 1 if the file can't be found in PATH
#
# @param	lib_name	The name of the library to locate
function locate_library_file() {
	local lib_name="$1"
	local library_dirs=$( echo $PATH | tr ':' ' ' )
	local fullpath=$( find $library_dirs -maxdepth 1 -type f -regex ".*/${lib_name}[\.a-zA-Z]*" 2> /dev/null | head -1 )

	[[ -n $fullpath ]] && echo "$fullpath" || return 1
}

## List all library file names which are available in PATH
#
function list_libraries() {
	local library_dirs=$( echo $PATH | tr ':' ' ' )
	local possible_file=$( find $library_dirs -maxdepth 1 -type f )
	grep --binary-file=without-match --files-with-matches '^#!/usr/bin/env shellbox$' $possible_file \
		| xargs -n 1 -J {} awk '{ if ( NR == 1 && $0 ~ "^#!/usr/bin/env shellbox$") { print FILENAME; exit 0; } else { exit 1; } }' {} \
		| sed -E 's:.*/([^/]+)$:\1:g' | sort -u
} 2> /dev/null

## List all library names which are available in PATH
#
function list_library_names() {
	list_libraries | sed -E 's:([^\.]+)(\..*):\1:g'
}

## List all commands available in the given library
#
# @param	lib_name	The name of the library
function list_library_commands() {
	local lib_name="$1"

	local reg="^${lib_name}::"
	local declared_func
	if [[ -n "$BASH" ]]
	then
		declared_func=$( require "$lib_name" && typeset -F | sed 's/declare -f //g' ) # the require is inside the fork to avoid to leak all the functions
	else
		declared_func=$( require "$lib_name" && functions | grep ' \(\) {' | sed 's/ \(\) \{//g' )
	fi
	echo "$declared_func" | egrep "$reg" | sed -E "s/$reg//g"
}

####################################################################
###########               PRIVATE FUNCTIONS              ###########
####################################################################

## Prints the name of the file, without any extension.
#
# @param	file	The file
function basename_auto() {
	local name=$( basename "$1" )
	echo "${name%%.*}"
}

## Print the command function for the given library and command.
# Return 1 if the command does not exist.
#
# @param	library_name	the library name
# @param	cmd_name	the command
function _command_function() {
	local library_name="$1"
	local cmd_name="$2"

	local cmd_function="${library_name}::${cmd_name}"
	if type $cmd_function &> /dev/null
	then
		echo $cmd_function
		return
	fi

	return 1
}

## Run a library command with options.
# This is the main function of shellbox.
#
# @param	lib_name_or_file	the library name or path to a library file
# @param	cmd_name			the command name
# @params	options				the options
function run_library_command() {
	local lib_name_or_file="$1"
	local cmd_name="$2"

	shift # can't run `shift 2` because if there is only one arg, it doesn't shift at all
	shift

	require "${lib_name_or_file}" || return 1

	local lib_name=$( basename_auto "$lib_name_or_file" )

	if _command_function "$lib_name" "$cmd_name" &> /dev/null
	then
		# The library command exists
		local cmd_function=$( _command_function "$lib_name" "$cmd_name" )
		$cmd_function "$@"
	else
		# The library command does not exist
		# Display the error
		require 'cli'
		cli::failure "This command does not exist:"
		echo "	- ${boldon}${purplef}$lib_name ${redf}$cmd_name${reset}"
		# Run the help command on the library
		local cmd_function=$( _command_function "$lib_name" "help" )
		$cmd_function
		return 1
	fi
}

####################################################################
###########               EXEC LIB COMMAND               ###########
####################################################################

if [[ -r "$1" ]]
then
	run_library_command "$@"
elif type "$1" &> /dev/null
then
	"$@"
fi
<file_sep>/source_me.sh
#!/bin/bash
#
#

# Compatibility:
#	bash (sourced and subshell)
#	zsh  (sourced and subshell)
if [[ -n "$BASH" ]]
then
	SHELLBOX_ROOT="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
else
	SHELLBOX_ROOT="$( cd -P "$( dirname "$0" )" && pwd )"
fi

# Put shellbox in path if needed
[[ ":$PATH:" =~ ":$SHELLBOX_ROOT/bin:" ]] || export PATH="$SHELLBOX_ROOT/bin:$PATH"

# Put this box in path if needed
[[ ":$PATH:" =~ ":$SHELLBOX_ROOT/box:" ]] || export PATH="$SHELLBOX_ROOT/box:$PATH"

if [[ -n "$BASH" ]]
then
	function __complete() {
		COMPREPLY=( $( complete.sb dispatch "$COMP_CWORD" ${COMP_WORDS[@]} ) )
	}
	complete -o bashdefault -o default -F __complete `shellbox list_libraries`
else
	autoload -U compinit
	compinit -i

	function __complete() {
		local params
		read -cA params
		local parameter_count="${#params}"
		((parameter_count=parameter_count-1))

		reply=( $( complete.sb dispatch $parameter_count ${params[@]} ) )
	}
	compctl -K __complete `shellbox list_libraries`
fi

languages: Markdown Shell

repo_name: debona/ShellBox


text:
<file_sep>SkypeMafia-visualization
========================

The aim of this visualization script is to celebrate the 10th birthday of Skype
by exposing the social graph around it.

Included are the founders, staff and investors who played a huge part
in making Skype possible in the first place, but also a network of new
startups founded and funded by these players, plus a number of more established
companies feeding on Skype-related talent.

Built on igraph package for R, the script takes two simple CSV input files:
* edge list of Person -> Company relationships & identifier for their role (founder, employee, investor/advisor)
* properties list for type, country of origin and formatting metadata of all entities mentioned in edge list

The data in Skype-specific CSV files has been acquired by (mostly manually) scanning public profiles
of mentioned players at sources such as Crunchbase, AngelList, LinkedIn, etc.

Data collection should be relatively easy to replicate for whatever group of people and companies you're
interested in if you were to fork this script. Use at your own risk.

[![Run on Repl.it](https://repl.it/badge/github/stamkivi/SkypeMafia-visualization)](https://repl.it/github/stamkivi/SkypeMafia-visualization)<file_sep>
#
# SkypeMafia social graph visualization
# created to celebrate 10th birthday of Skype on August 29th, 2013
# by <NAME> (about.me/sten)
#
# Special thanks to <NAME> (http://www.gsb.stanford.edu/users/sharique)
# for his OB322: Networks class at Stanford GSB
# and <NAME> for his R SNA reference
# (https://sites.google.com/site/daishizuka/toolkits/sna)
#

library(igraph) # for plotting

setwd("/Users/sten/Dropbox/git/SkypeMafia-visualization")
ver <- "v1.2"

# read the Entity Type, Location, edge size attributes
attributes <- read.csv(file = "skypemafia_attributes.csv", sep=",", row.names=NULL, header = TRUE)
# attributes <- attributes[ order(Name), ]

# read the Person / Relationship Type / Company data on edges
edges <- read.csv ("skypemafia_edges.csv", sep=",", header=TRUE, check.names=FALSE)

# convert to matrix (needed for edgelist manipulation, not graph.data.frame!)
#  edgesmatrix <- as.matrix(edges)
# create a graph, without the relationship type attribute (middle column)
#  g <- graph.edgelist(edgesmatrix[,c(1,2)],directed=TRUE)
#  dump <- get.data.frame(g, what="both")

g <- graph.data.frame(edges, directed=TRUE, vertices=attributes)

# map edge properties (color & weight) based on Role
E(g)[ Role == 1 ]$color <- "red"       # founder
E(g)[ Role == 2 ]$color <- "grey"      # employee
E(g)[ Role == 3 ]$color <- "darkgreen" # investor/advisor

E(g)[ Role == 1 ]$width <- 1.5           # founder
E(g)[ Role == 2 ]$width <- 1           # employee
E(g)[ Role == 3 ]$width <- 1.2          # investor/advisor

# make edges curved
# E(g)$curved <- autocurve.edges(g)
E(g)$curved <- 0.15

# copy attributes to respective vertexes
V(g)$label  <- V(g)$name
V(g)$size   <- attributes$Size
V(g)$type   <- as.character(attributes$Type)

V(g)[ type == "Startup" ]$color <- "red"
V(g)[ type == "Person" ]$color   <- "black"
V(g)[ type == "Company" ]$color  <- "darkred"
V(g)[ type == "VC" ]$color       <- "darkgreen"
V(g)[ type == "Founder" ]$color   <- "blue"
V(g)[ type == "Skype" ]$color     <- "blue"

# adjust label alignment for different sized vertices
V(g)$label.dist <- 0.15
V(g)[ type == "Person" ]$label.dist <- 0.05

####
#### Some very basic SNA measures
####

summary(g)

# Top 10 entities by betweenness centrality
-sort(-betweenness(g))[1:10]

# Top 20 entities by eigenvector centrality (not the tiny differences)
-sort(-evcent(g)$vector)[1:20]

# Top 10 by incoming and outgoing edges to/from a particular node
-sort(-degree(g, mode="in"))[1:10]
-sort(-degree(g, mode="out"))[1:10]

####
#### Plot all the vertices & edges we've got
####

pdf("skypemafia - full plot.pdf", family="sans", width=16,height=16)
# png(file="skypemafia plot.png", width=2000,height=2000)

l <- layout.fruchterman.reingold(g,niter=500,area=vcount(g)^2.3,repulserad=vcount(g)^2.8)
# l <- layout.fruchterman.reingold.grid(g)
# l <- layout.graphopt(g)

plot.igraph(g, layout=l,
            vertex.label.color="black", vertex.label.degree=pi/2, vertex.label.family="sans",
            vertex.label.cex=0.5,
            vertex.frame.color="white", vertex.size=V(g)$size/5,
            edge.arrow.size=0.1, main="#SkypeMafia 2013")
legend("bottomright", cex=0.5, border = FALSE, bty="n",
       legend=c("Skype, founders & acquisitions", "Startups & founding relationships", "Investors & money flow", "Other companies", "Working relationships"),
       fill=c("blue", "red", "darkgreen", "darkred", "grey"))

text(1, -1, ver, cex=0.5)

# close the graphics output device
dev.off()

####
#### Plot the money flows around Skype
####

g_invest <- g
g_invest <- g_invest - edges(E(g_invest)[Role==2])
g_invest <- g_invest - edges(E(g_invest)[Role==1])
g_invest <- g_invest - vertices(V(g_invest)[Type=="Company"])
g_invest <- g_invest - path("Skype")

g_invest <- g_invest - vertices(degree(g_invest)==0 ) # remove isolates

l_invest <- layout.fruchterman.reingold(g_invest,niter=500,area=vcount(g)^1.8,repulserad=vcount(g)^2.3)
#  <- layout.fruchterman.reingold.grid(g)
#  <- layout.graphopt(g)

pdf("skypemafia - money plot.pdf", family="sans")

plot.igraph(g_invest, layout=l_invest,
            vertex.label.color="black", vertex.label.degree=pi/2, vertex.label.family="sans",
            vertex.label.cex=0.3,
            vertex.frame.color="white", vertex.size=V(g_invest)$size/5,
            edge.arrow.size=0.1, main="#SkypeMafia Funding Flow")
legend("bottomright", cex=0.5, border = FALSE, bty="n",
       legend=c("Skype, founders & acquisitions", "Startups", "Investors & money flow"),
       fill=c("blue", "red", "darkgreen"))

text(-1, -1, ver, cex=0.5)

# close the graphics output device
dev.off()

####
#### Plot the founder activity around Skype
####

g_founder <- g

g_founder <- g_founder - edges(E(g_founder)[Role==2 & !to("Skype")])  # no work relationships outside Skype
g_founder <- g_founder - edges(E(g_founder)[Role==3])                 # no investing/advising
g_founder <- g_founder - vertices(V(g_founder)["<NAME>"])  # to hide a father->son "founding event" :)
g_founder <- g_founder - vertices(V(g_founder)[Type=="VC"])
g_founder <- g_founder - vertices(V(g_founder)[Type=="Company"])
# g_founder <- g_founder - path("Skype")

g_founder <- g_founder - vertices(degree(g_founder)==0 ) # remove isolates
g_founder <- g_founder - vertices(degree(g_founder, mode="out")==1) # remove non-founder employees (no other outbound connections but Skype)

V(g_founder)$label.dist <- 0.2
V(g_founder)[ type == "Person" ]$label.dist <- 0.08

l_founder <- layout.fruchterman.reingold(g_founder,niter=500,area=vcount(g)^2,repulserad=vcount(g)^2.8)

pdf("skypemafia - founder plot.pdf", family="sans")

plot.igraph(g_founder, layout=l_founder,
            vertex.label.color="black", vertex.label.degree=pi/2, vertex.label.family="sans",
            vertex.label.cex=0.3,
            vertex.frame.color="white", vertex.size=V(g_founder)$size/3,
            edge.arrow.size=0.1, main="#SkypeMafia Startup Founders")
legend("bottomright", cex=0.5, border = FALSE, bty="n",
       legend=c("Skype, founders & acquisitions", "Startups & founding relationships", "Working relationships"),
       fill=c("blue", "red", "grey"))

text(1, -1, ver, cex=0.5)

# close the graphics output device
dev.off()

####
#### Summary counts
####

print("Number of people on the graph:")
length(V(g)[ type == "Person" ])

print("Number of ex-Skype startup founders:")
length(V(g_founder)[ type == "Person" ])

print("Number of Skype-spawned startups:")
length(V(g_founder)[ type == "Startup" ])

print("Number of professional investors on the graph:")
length(V(g)[ type == "VC" ])

print("Number of individual angel investors:")
length(V(g_invest)[ type == "Person" ])

print("Number of investments captured:")
length(E(g_invest)[ Role == 3 ])

languages: Markdown R

repo_name: stamkivi/SkypeMafia-visualization


text:
<repo_name>gabrieldespindula/ble-test<file_sep>/webpage/README.md
# BLE test sensor

Available at https://gabrieldespindula.github.io/ble-test/webpage/

<file_sep>/webpage/app.js
var canvas = document.querySelector('#waves');
var ccdCanvas = document.querySelector('#ccdDisplay');
var statusText = document.querySelector('#statusText');
var lbIntTime = document.getElementById("intTime");
var lbLaserDist = document.getElementById("laserDistance");
var lbLaserStart = document.getElementById("laserDetectPx");
var lbLaserLength = document.getElementById("laserWaveLength");
var ccdMode = document.getElementById("ccdModeSelector");
var logEn = document.getElementById("logEnabled");

var heartRates = [];
var accelerometerX = [];
var accelerometerY = [];
var accelerometerZ = [];
var laserStart, laserLenght;
var chartLenght = 256;
var distance;
var ccd = Array(260).fill(0);
var nLogs = 0;

statusText.addEventListener('click', function() {
  statusText.textContent = 'Connecting...';
  heartRates = [];
  accelerometerX = [];
  accelerometerY = [];
  accelerometerZ = [];
  tkba.connect()
  .then(() => tkba.startNotificationsAccelerometer().then(handleAccelerometer))
  .then(() => tkba.startNotificationsCCD().then(handleCCD))
  .catch(error => {
    statusText.textContent = error;
  });
});

function handleAccelerometer(accData) {
  console.log('Accelerometer event settled');
  var postscale = 0;

  accData.addEventListener('characteristicvaluechanged', event => {
    //console.log('New notification - ' + event.target.value.getUint8(0) + ' ' + event.target.value.getUint8(1) + ' ' + event.target.value.getUint8(2));
    //statusText.textContent = event.target.value.getUint8(0) + event.target.value.getUint8(1) + event.target.value.getUint8(2) + event.target.value.getUint8(3) + event.target.value.getUint8(1) + event.target.value.getUint8(4) + event.target.value.getUint8(5);
    var accX, accY, accZ;

    var sign = event.target.value.getUint8(1) & (1 << 7);
    var accX = (((event.target.value.getUint8(1) & 0xFF) << 8) | (event.target.value.getUint8(0) & 0xFF));
    if (sign) {
       accX = 0xFFFF0000 | accX;  // fill in most significant bits with 1's
    }
    var sign = event.target.value.getUint8(3) & (1 << 7);
    var accY = (((event.target.value.getUint8(3) & 0xFF) << 8) | (event.target.value.getUint8(2) & 0xFF));
    if (sign) {
       accY = 0xFFFF0000 | accY;  // fill in most significant bits with 1's
    }
    var sign = event.target.value.getUint8(5) & (1 << 7);
    var accZ = (((event.target.value.getUint8(5) & 0xFF) << 8) | (event.target.value.getUint8(4) & 0xFF));
    if (sign) {
       accZ = 0xFFFF0000 | accZ;  // fill in most significant bits with 1's
    }

    postscale++;
    if(postscale>=20){
      postscale=0;
//      heartRates.push(accY);
//     accelerometerX.push(accX);
//      accelerometerY.push(accY);
//      accelerometerZ.push(accZ);
//      drawWaves();
    }
  });
}

function handleCCD(ccdData) {
  console.log('CCD event settled');
  var postscale = 0;

  ccdData.addEventListener('characteristicvaluechanged', event => {
    statusText.textContent = event.target.byteLenght;
    //console.log(event.target.value);

    if(ccdMode.innerHTML === "3"){

      var data = [event.target.value.getUint8(5),
                  event.target.value.getUint8(4),
                  event.target.value.getUint8(3),
                  event.target.value.getUint8(2)];
      var buf = new ArrayBuffer(4);
      var view = new DataView(buf);
      data.forEach(function (b, i) {
          view.setUint8(i, b);
      });
      distance = view.getFloat32(0);
      lbLaserDist.innerHTML = distance.toString() + "mm";
      lbIntTime.innerHTML = (event.target.value.getUint8(0)<<8 | event.target.value.getUint8(1)).toString() + " CPU clocks";

      if(logEn.innerHTML === "1"){
        $("#log").append('
'+distance.toString()+'
');
        $("#log").scrollTop(nLogs*100);
        $("#log").last().focus();
        nLogs++;
      }

      ccd.fill(0);
      ccd[Math.round(distance/0.0635)] = 2800;

      /*
      console.log(event.target.value.getUint8(0).toString() + " " +
                  event.target.value.getUint8(1).toString() + " " +
                  event.target.value.getUint8(2).toString() + " " +
                  event.target.value.getUint8(3).toString() + " " +
                  event.target.value.getUint8(4).toString() + " " +
                  event.target.value.getUint8(5).toString() );
      */
    }
    else {

      if((event.target.value.getUint8(0) == 0xac && event.target.value.getUint8(5) == 0xac) || postscale > 25){
        postscale=0;

        laserStart = event.target.value.getUint8(3);
        laserLenght = event.target.value.getUint8(4);
        distance = ((event.target.value.getUint8(3)+(event.target.value.getUint8(4).toString()/2))*0.0635);

        if(ccdMode.innerHTML === "2"){
          chartLenght = laserLenght;
        }

        lbLaserStart.innerHTML = "pixel number " + laserStart.toString();
        lbLaserLength.innerHTML = laserLenght.toString() + " pixels";
        lbIntTime.innerHTML = (event.target.value.getUint8(1)<<8 | event.target.value.getUint8(2)).toString() + " CPU clocks";
        lbLaserDist.innerHTML = distance.toString() + "mm";
      }

      for(var i=0 ; i<20 ; i+=2){
        ccd[postscale*10+i/2]=(((event.target.value.getUint8(i) & 0xFF) << 8) | (event.target.value.getUint8(i+1) & 0xFF));
      }
      if(ccdMode.innerHTML === "1"){
        ccd[postscale*10+10]=0xaaaaaaaa; //Add a peak just to visualize the "scanning"
      }

      postscale++;
    }

    drawCCD();
    drawWaves();
  });
}

function drawCCD() {
  requestAnimationFrame(() => {
    ccdCanvas.width = parseInt(getComputedStyle(canvas).width);
    ccdCanvas.height = 50;

    var context = ccdCanvas.getContext('2d');
    context.clearRect(0, 0, ccdCanvas.width, ccdCanvas.height);

    var square_side = canvas.width/chartLenght;
    for(var i = 3; i<258 ; i++)
    {
      var pixel = ((ccd[i]>>4).toString(16));
      var RR = ((pixel.length==1)?("0"+pixel):(pixel));
      context.fillStyle = '#'+RR+'0000';
      context.fillRect((i-3)*square_side, 0, square_side, 50);
      context.stroke();
    }
  });
}

function drawWaves() {
  requestAnimationFrame(() => {
    canvas.width = parseInt(getComputedStyle(canvas).width.slice(0, -2)) * devicePixelRatio;
    canvas.height = 200;//parseInt(getComputedStyle(canvas).height.slice(0, -2)) * devicePixelRatio;

    var context = canvas.getContext('2d');
    var margin = 2;
    var max = Math.max(0, Math.round(canvas.width / 11));
    var offset = Math.max(0, heartRates.length - max);
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.beginPath();
    context.lineWidth = 6;
    context.lineJoin = 'round';
    context.shadowBlur = '1';
    context.strokeStyle = '#581845';
    context.shadowOffsetY = '1';
    for (var i = 0; i < Math.max(accelerometerX.length, max); i++) {
      var lineHeight = Math.round(5*canvas.height/6 + accelerometerX[i + offset ]/100);//Math.round(heartRates[i + offset ] * canvas.height / 200);
      if (i === 0) {
        context.moveTo(11 * i, canvas.height - lineHeight);
      } else {
        context.lineTo(11 * i, canvas.height - lineHeight);
      }
      context.stroke();
    }

    context.beginPath();
    context.lineWidth = 6;
    context.lineJoin = 'round';
    context.shadowBlur = '1';
    context.strokeStyle = '#900c3f';
    context.shadowOffsetY = '1';
    for (var i = 0; i < Math.max(accelerometerY.length, max); i++) {
      var lineHeight = Math.round(3*canvas.height/6 + accelerometerY[i + offset ]/100);//Math.round(heartRates[i + offset ] * canvas.height / 200);
      if (i === 0) {
        context.moveTo(11 * i, canvas.height - lineHeight);
      } else {
        context.lineTo(11 * i, canvas.height - lineHeight);
      }
      context.stroke();
    }

    context.beginPath();
    context.lineWidth = 6;
    context.lineJoin = 'round';
    context.shadowBlur = '1';
    context.strokeStyle = 'c70039';
    context.shadowOffsetY = '1';
    for (var i = 0; i < Math.max(accelerometerZ.length, max); i++) {
      var lineHeight = Math.round(1*canvas.height/6 + accelerometerZ[i + offset ]/100);//Math.round(heartRates[i + offset ] * canvas.height / 200);
      if (i === 0) {
        context.moveTo(11 * i, canvas.height - lineHeight);
      } else {
        context.lineTo(11 * i, canvas.height - lineHeight);
      }
      context.stroke();
    }

    context.beginPath();
    context.lineWidth = 6;
    context.lineJoin = 'round';
    context.shadowBlur = '1';

    var square_side = canvas.width/chartLenght;
    for(var i = 3; i<258 ; i++)
    {
      if (i === 3) {
        context.moveTo(square_side * (i-3), canvas.height-((ccd[i]>>4)&0xff)-10);
      } else {
          context.lineTo(square_side * (i-3), canvas.height-((ccd[i]>>4)&0xff)-10);
      }
    }
    context.stroke();
  });
}

document.addEventListener("visibilitychange", () => {
  if (!document.hidden) {
    drawCCD();
    drawWaves();
  }
});

languages: Markdown JavaScript

repo_name: gabrieldespindula/ble-test


text:
<repo_name>niemdinhtrong/py_add_host_zabbix<file_sep>/test.py
import unittest
import zabbix
from main import get_host

class TestZabbix(unittest.TestCase):
    config = zabbix.get_config('setting')
    username = config['zabbix']['zabbix_username']
    passwd = config['zabbix']['zabbix_password']
    group = config['zabbix']['group_name']
    template = config['zabbix']['template_name']
    list_host = get_host('hosts')
    key = "9f01bf795a0fddcea5d9ed8b3864a581"
    zapi = zabbix.Zabbix(username, passwd, group, template)

    def test_get_key(self):
        a1, a2 = self.zapi.get_aut_key()
        self.assertEqual(a2, "Ok")

    def test_tem_id_ok(self):
        a1, a2 = self.zapi.get_tem_id(self.key)
        self.assertEqual(a2, "Ok")

    def test_tem_id_er(self):
        a1, a2 = self.zapi.get_tem_id("1235")
        self.assertEqual(a2, "Error")

    def test_group_id_ok(self):
        a1, a2 = self.zapi.get_group_id(self.key)
        self.assertEqual(a2, "Ok")

    def test_group_id_er(self):
        a1, a2 = self.zapi.get_group_id("adfgg")
        self.assertEqual(a2, "Error")

    def test_add_host_ok(self):
        a1 = self.zapi.add_host(self.key, self.list_host, 2, 10001)
        self.assertEqual(a1, "Ok")

    def test_add_host_er(self):
        a1 = self.zapi.add_host("adfgg", self.list_host, 2, 10001)
        self.assertEqual(a1, "Error")<file_sep>/README.md
# Sử dụng api để add host trên zabbix server

Nếu bạn muốn add host lên zabbix server để thực hiện giám sát. Thông thường ta sẽ lên web để thực hiện việc này. Nhưng trong trường hợp ta có rất nhiều host cần phải add thì việc thực hiện trên web sẽ mất rất nhiều thời gian. Chính vì vậu chúng ta có thể sử api để làm việc này một cách đơn giản hơn.

## Chuẩn bị một trường

**Cài đặt python**

```
yum install -y https://centos7.iuscommunity.org/ius-release.rpm

yum update

yum install -y python36u python36u-libs python36u-devel python36u-pip
```

**Tạo virtual environments**

```
python3.6 -m pip install --user virtualenv

python3.6 -m venv venv_zabbix

source venv_zabbix/bin/activate

pip install requests
```

## Download script

```
mkdir zabbix

cd zabbix

git clone https://github.com/niemdinhtrong/py_add_host_zabbix.git

cd py_add_host_zabbix
```

## Khai báo các host

Khi bạn download thư mục về trong thư mục sẽ gồm các file `hosts` `main.py` `setting` `zabbix.py`

Trước tiên bạn thực hiện khai báo các host trong muốn thực hiện add trong file `hosts`

Thực hiện khai báo host trong file `hosts` cần khai báo đúng định dạng ("name", "address") ví dụ như sau:

```
("host_1", "192.168.1.2")
("host_2", "192.168.1.3")
("client_3", "10.10.10.10")
```

Lưu ý mỗi dòng chỉ khai báo một địa chỉ và một host name

## Khai báo thông tin của zabbix server

Thực hiện khai báo thông tin của zabbix server trong file `setting`

```
[zabbix]
zabbix_addr = 192.168.1.1
zabbix_username = admin
zabbix_password = <PASSWORD>
group_name = Linux servers
template_name = Template OS Linux
```

Trong đó:
 * zabbix_addr: địa chỉ của zabbix server
 * zabbix_username: user để login zabbix server (trên web)
 * zabbix_passwd: <PASSWORD> để login zabbix server (trên web)
 * group_name: tên group bạn muốn add các host đó vào(chú ý viết đúng tên group giống trên web)
 * template_name: tên template mà ta muốn sử dụng cho các host (chú ý viết đúng tên giống trên web)

## Chạy chương trình

```
python main.py
```

languages: Markdown Python


text:
<repo_name>mdwaud/fast-units<file_sep>/lib/fast-units.rb
require "fast-units/version"
require 'set'

module FastUnits
  class Unit < Numeric
#    attr_accessor :scalar, :units

    def initialize(desc)
      pieces = desc.split(" ")
      if pieces.length == 2
        scalar, units = pieces
      else
        scalar = 1
        units = pieces[0]
      end
      @_units = FastUnits::Uom.new(units)
      @_scalar = Rational(scalar)
      return self
    end

    def scalar
      @_scalar.denominator == 1 ? @_scalar.to_i : @_scalar

    end

    def units
      @_units.to_s
    end

    def +(other)
      if other.class != FastUnits::Unit
        raise TypeError, other.class + ' cannot be added to a Unit'
      end
      compatible! other.units, self.units
      FastUnits::Unit.new((@_scalar + other.scalar).to_s + " " +@_units.to_s)
    end

    def -(other)
      if other.class != FastUnits::Unit
        raise TypeError, other.class + ' cannot be subtracted from a Unit'
      end
      compatible! other.units, self.units
      FastUnits::Unit.new((@_scalar - other.scalar).to_s + " " +@_units.to_s)
    end

    def *(other)
      scalar = @_scalar * other.scalar
      units = @_units * FastUnits::Uom.new(other.units)
      units.simplify
      FastUnits::Unit.new(scalar.to_s + " " + units.to_s)
    end

    def /(other)
      scalar = @_scalar / other.scalar
      units = @_units / FastUnits::Uom.new(other.units)
      units.simplify
      FastUnits::Unit.new(scalar.to_s + " " + units.to_s)
    end

    def <=>(other)
      compatible! other.units, @units
      return @_scalar <=> other.scalar
    end

    def to_s

      "%s %s" % [scalar, units]
    end

    def compatible?(other)
      begin
        if other.class != FastUnits::Unit
          raise ArgumentError, other.class + ' is not a Unit'
        end
        compatible! other.units, units
      rescue
        false
      end
    end

    def compatible!(units1, units2)
      if units1 != units2
        raise ArgumentError, units1 + ' is not compatible with ' + units2
      end
      true
    end
  end

  class Uom
    attr_accessor :num, :denom

    def initialize(text)
      if text != ''
        @num, @denom = parse_units(text)
      else
        @num, @denom = [],[]
      end
    end

    def parse_units(text)
      pieces = text.split("/")
      if pieces.length > 1
        [pieces[0].split('*'), pieces[1..-1]]
      elsif pieces.length > 0
        [[pieces[0]], []]
      else
        [[],[]]
      end
    end

    def condense(list)
      set = Set.new list
      built_list = set.map do |u|
        c = list.count(u)
        if c == 1
          u
        else
          u + '^' + c.to_s
        end
      end
      built_list
    end

    def to_s
      text = condense(@num).join('*')
      if @denom.length > 0
        text += '/' + condense(@denom).join('/')
      end
      text
    end

    def *(other_uom)
      u = FastUnits::Uom.new('')
      u.num = @num + other_uom.num
      u.denom = @denom + other_uom.denom
      u.simplify
      u
    end

    def /(other_uom)
      u = FastUnits::Uom.new('')
      u.num = @num + other_uom.denom
      u.denom = @denom + other_uom.num
      u.simplify
      u
    end

    def simplify
      num_copy = @num
      num_copy.each do |u|
        index = @denom.index u
        if index
          @num.delete_at @num.index(u)
          @denom.delete_at index
        end
      end
    end
  end
end

def Unit(args)
  FastUnits::Unit.new(args)
end<file_sep>/test/uom_test.rb
#require 'test_helper'
require 'minitest/autorun'
require 'fast-units'

describe 'FastUnits::Uom' do
  it "can parse mg" do
    uom = FastUnits::Uom.new('mg')
    assert_equal 'mg', uom.to_s
  end

  it "can parse ml" do
    uom = FastUnits::Uom.new('ml')
    assert_equal 'ml', uom.to_s
  end

  it "can make a simple mixture" do
    uom = FastUnits::Uom.new('mg/ml')
    assert_equal uom.num, ['mg']
    assert_equal uom.denom, ['ml']
    assert_equal 'mg/ml', uom.to_s
  end

  it "can make a simple mixture with complicated numerator" do
    uom = FastUnits::Uom.new('unit*mg/ml')
    assert_equal uom.num, ['unit','mg']
    assert_equal uom.denom, ['ml']
    assert_equal 'unit*mg/ml', uom.to_s
  end

  it "can condense units" do
    uom = FastUnits::Uom.new('mg*mg/ml')
    assert_equal uom.num, ['mg','mg']
    assert_equal uom.denom, ['ml']
    assert_equal 'mg^2/ml', uom.to_s
  end

  it "can multipy simple units" do
    uom = FastUnits::Uom.new('mg') * FastUnits::Uom.new('unit')
    assert_equal uom.num, ['mg','unit']
    assert_equal uom.denom, []
    assert_equal 'mg*unit', uom.to_s
  end

  it "can multipy two of the same units" do
    uom = FastUnits::Uom.new('mg') * FastUnits::Uom.new('mg')
    assert_equal uom.num, ['mg','mg']
    assert_equal uom.denom, []
    assert_equal 'mg^2', uom.to_s
  end

  it "can divide simple units" do
    uom = FastUnits::Uom.new('mg') / FastUnits::Uom.new('ml')
    assert_equal uom.num, ['mg']
    assert_equal uom.denom, ['ml']
    assert_equal 'mg/ml', uom.to_s
  end

  it "can divide two of the same units" do
    uom = FastUnits::Uom.new('mg') / FastUnits::Uom.new('ml') / FastUnits::Uom.new('ml')
    assert_equal uom.num, ['mg']
    assert_equal uom.denom, ['ml', 'ml']
    assert_equal 'mg/ml^2', uom.to_s
  end

  it "can handle exponents" do
    uom = FastUnits::Uom.new('mg/ml^2')
    assert_equal uom.num, ['mg']
    assert_equal uom.denom, ['ml','ml']
    assert_equal 'mg/ml^2', uom.to_s
  end

  it "can reduce from exponents" do
    uom = FastUnits::Uom.new('mg/ml^2')
    u2 = uom * FastUnits::Uom.new('ml')
    assert_equal 'mg/ml', u2.to_s
  end

  it "can simplify duplicate units" do
    uom = FastUnits::Uom.new('mg') * FastUnits::Uom.new('ml') / FastUnits::Uom.new('ml')
    assert_equal uom.num, ['mg']
    assert_equal uom.denom, []
    assert_equal 'mg', uom.to_s
  end
end<file_sep>/test/test_helper.rb
require 'minitest/autorun'
require 'fast-units'<file_sep>/test/units_test.rb
#require 'test_helper'
require 'minitest/autorun'
require 'fast-units'
#require 'ruby-units'

describe 'FastUnits' do
  it "can create a Unit in mg" do
    unit = Unit("1 mg")
    assert_equal 1, unit.scalar
    assert_equal 'mg', unit.units
  end

  it "can create a Unit in ml" do
    unit = Unit("1 ml")
    assert_equal 1, unit.scalar
    assert_equal 'ml', unit.units
  end

  it "can make a Unit from a rational number" do
    unit = Unit("1/10 ml")
    assert_equal Rational("1/10"), unit.scalar
    assert_equal 'ml', unit.units
  end

  it "can add two units in mg" do
    total = Unit("1 mg") + Unit("1 mg")
    assert_equal 2, total.scalar
    assert_equal 'mg', total.units
  end

  it "can add two units in ml" do
    total = Unit("1 ml") + Unit("1 ml")
    assert_equal 2, total.scalar
    assert_equal 'ml', total.units
  end

  it "can compare two units" do
    assert Unit("1.1 ml") > Unit("1 ml")
  end

  it "can check compatibility" do
    c = Unit("1 mg").compatible? Unit("2 mg")
    assert_equal true, c
  end

  it "can check compatibility" do
    c = Unit("1 mg").compatible? Unit("2 ml")
    assert_equal false, c
  end

  it "can check complicated compatibility" do
    c = Unit("1 mg/ml").compatible? Unit("2 ml")
    assert_equal false, c
  end

  it "can subtract two units in mg" do
    total = Unit("1 mg") - Unit("1 mg")
    assert_equal 0, total.scalar
    assert_equal 'mg', total.units
  end

  it "can make concentrations" do
    total = Unit("1 mg") / Unit("10 ml")
    assert_equal Rational("1/10"), total.scalar
    assert_equal 'mg/ml', total.units
  end

  it "can unmake concentrations" do
    total = Unit("10 mg/ml") * Unit("2 ml")
    assert_equal 20, total.scalar
    assert_equal 'mg', total.units
  end

  it "layered units are compatible " do
    unit = Unit("10 mg") / Unit("1 ml") / Unit("1 ml")
    c = unit.compatible? Unit('ml')
    assert_equal false, c
  end

  it "can multiply on layered units" do
    unit_1 = Unit("10 mg") / Unit("1 ml") / Unit("1 ml")
    unit_2 = Unit('ml')
    result = unit_1 * unit_2
    assert_equal Unit('10 mg/ml'), result
  end

  it "can convert to a string" do
    unit = Unit("10 mg/ml")
    assert_equal "10 mg/ml", unit.to_s
  end

  it "cannot add a mg to a ml" do
    #assert_raise TypeError do
    begin
      total = Unit("1 mg") + Unit("1 ml")
    rescue ArgumentError
      assert true
    else
      assert false
    end
  end

end

repo_language: Ruby

repo_name: mdwaud/fast-units


text:
<file_sep>var React = require('react');
var Layout = require('../Layout.react');
var NotesApp = require('../NotesApp.react');

var Home = React.createClass({
    render: function() {
        return (
            <Layout>

Hey, leave a note here.

                <NotesApp />
            </Layout>
        );
    }
});

module.exports = Home;
<file_sep>var AppDispatcher = require('../dispatcher/AppDispatcher');
var NoteConstants = require('../constants/NoteConstants');
var NoteWebAPIUtils = require('../utils/NoteWebAPIUtils');
var NoteStore = require('../stores/NoteStore');

function _onCreateEnd(err, res) {
    // [TODO] Implement error handling

    AppDispatcher.handleServerAction({
        actionType: NoteConstants.NOTE_CREATE_CONFIRM,
        id: res.body.id
    });
}

function _onDestroyEnd(err, res) {
    // [TODO] Implement error handling

    AppDispatcher.handleServerAction({
        actionType: NoteConstants.NOTE_DESTROY_CONFIRM,
        id: res.body.id
    });
}

var NoteActions = {

    /**
     * Create comment
     * @param {string} text Text of the comment
     */
    create: function(text) {
        var note = NoteStore.getCreatedNoteData(text);

        AppDispatcher.handleViewAction({
            actionType: NoteConstants.NOTE_CREATE,
            note: note
        });

        NoteWebAPIUtils.createNote(note).end(_onCreateEnd);
    },

    /**
     * @param {string} id
     */
    destroy: function(id) {
        AppDispatcher.handleViewAction({
            actionType: NoteConstants.NOTE_DESTROY,
            id: id
        });

        NoteWebAPIUtils.destroyNote(id).end(_onDestroyEnd);
    }
};

module.exports = NoteActions;
<file_sep>var React = require('react');
var App = require('../components/App.react');

// Wait for the browser page to load and render
// the App component
window.addEventListener('load', function() {
    React.render(<App />, document);
});
<file_sep>React Isomorphic Flux
===========

Simple Offline-first Isomorphic ReactJS Flux WebApp. WIP.

[Isomorphic webapps](http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/) are the future. Here we are traveling to the place where everyone will be in the next years. So let's take this trip and implement a simple and scalable student-kit grouping many interesting node modules together.

This is meant to be a reference for begginners with all these concepts.

**This is a work in progress. Contributions are highly welcome.**

## Roadmap

- [x] Server-rendering
- [x] Routes
- [x] Async rendering
- [x] Flux architecture
- [x] Optimistic UI
- [ ] Offline-first
- [ ] Environment config
- [ ] Companion articles

## License

MIT. See [LICENSE](https://github.com/hugobessaa/rocket-pack/blob/master/LICENSE) file.
<file_sep>var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var NoteConstants = require('../constants/NoteConstants');
var assign = require('object-assign');

var CHANGE_EVENT = 'change';

var _notes = {};

var NoteStore = assign({}, EventEmitter.prototype, {

    /**
     * Get the entire collection
     */
    getAll: function() {
        return _notes;
    },

    /**
     * @param {string} text Text of the message
     * @return {object} note
     */
    getCreatedNoteData: function(text) {

        // Using the current timestamp in the place of a real id
        var timestamp = Date.now();
        return {
            id: 'm_' + timestamp,
            text: text
        }
    },

    emitChange: function() {
        this.emit(CHANGE_EVENT);
    },

    /**
     * @param {function} callback
     */
    addChangeListener: function(callback) {
        this.on(CHANGE_EVENT, callback);
    },

    /**
     * @param {function} callback
     */
    removeChangeListener: function(callback) {
        this.removeListener(CHANGE_EVENT, callback);
    }
});

// Register to handle actions
AppDispatcher.register(function(payload) {
    var action = payload.action;
    var text;

    switch(action.actionType) {
        case NoteConstants.NOTE_CREATE:
            var note = action.note;
            text = note.text.trim();
            _notes[note.id] = note;
            break;

        case NoteConstants.NOTE_CREATE_CONFIRM:
            _notes[action.id].saved = true;
            break;

        case NoteConstants.NOTE_DESTROY:
            delete _notes[action.id];
            break;

        case NoteConstants.NOTE_CREATE_CONFIRM:
            if (typeof _notes[action.id] !== 'undefined') {
                delete _notes[action.id];
            }
            break;

        default:
            return true;
    }

    // This often goes in each case that should trigger a UI change. This store
    // needs to trigger a UI change after every view action, so we can make the
    // code less repetitive by putting it here.  We need the default case,
    // however, to make sure this only gets called after one of the cases above.
    NoteStore.emitChange();

    return true; // No errors. Needed by promise in Dispatcher.
});

module.exports = NoteStore;
<file_sep>var keyMirror = require('keymirror');

module.exports = keyMirror({
    NOTE_CREATE: null,
    NOTE_CREATE_CONFIRM: null,
    NOTE_DESTROY: null,
    NOTE_DESTROY_CONFIRM: null
});
<file_sep>var React = require('react');
var NoteActions = require('../actions/NoteActions');

var NotesForm = React.createClass({
    getInitialState: function() {
        return {
            text: this.props.text || ''
        }
    },

    render: function() {
        return (
            <form className="notes-form" onSubmit={this._onSubmit}>
                <input type="text" placeholder="Say something..." onChange={this._onTextChange} value={this.state.text} />
                <input className="btn--green" type="submit" value="Send" />
            </form>
        );
    },

    _onTextChange: function(e) {
        this.setState({
            text: e.target.value
        });
    },

    _onSubmit: function(e) {
        e.preventDefault();

        // Trigger the create action
        NoteActions.create(this.state.text);

        // Reset the state
        this.setState({
            text: ''
        })
    }
});

module.exports = NotesForm;
<file_sep>var React = require('react');
var Layout = require('../Layout.react');
var Link = require('react-router-component').Link;

var NotFound = React.createClass({
    render: function() {
        return (
            <Layout>

Nothing here. Go back to <Link href="/">home</Link>

            </Layout>
        );
    }
});

module.exports = NotFound;
<file_sep>
// Make it possible to use JSX on the server
require('node-jsx').install({
    extension: '.js'
});

var express = require('express');
var app = express();
var React = require('react');
var ReactAsync = require('react-async');
var App = React.createFactory(require('../components/App.react'));
var api = require('./api');

var url = require('url');

var bodyParser = require('body-parser');

// Serve static assets from ./static folder
// Used for any static/bundled assets
app.use(express.static('./static'));

// Captures all server requests. App handles routes internally.
app.get('*', function(req, res, next) {

    var path = url.parse(req.url).pathname;
    var reactApp = App({path: path});

    // Render App asynchronously
    ReactAsync.renderToStringAsync(reactApp, function(err, markup, data) {
        if (err) return next(err);
        res.send(ReactAsync.injectIntoMarkup(markup, data));
    });

});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/api', api);

app.listen(4000);
console.log('Listening to http://localhost:4000');
<file_sep>// Implementing a barebones api
// [TODO] Implement full RESTful API for Notes
var express = require('express');
var router = express.Router();

// Holds our notes. Not disk persistent yet
// [TODO] Persist data in a proper database. Probably Mongo
var _notes = {};

router.route('/notes')
    .get(function(req, res) {
        res.json(_notes);
    })

router.route('/notes/:id')

    .get(function(req, res) {
        var id = req.params.id;

        res.json(_notes[id]);
    })

    .post(function(req, res) {
        var note = req.body.note;
        var id = req.params.id;
        _notes[id] = note;

        res.json({ message: 'Added', id: id });
    })

    .put(function(req, res) {
        var note = req.body.note;
        var id = req.params.id;
        _notes[id] = note;

        res.json({ message: 'Updated', id: id });
    })

    .delete(function(req, res) {
        var id = req.params.id;
        delete _notes[id];

        res.json({ message: 'Deleted', id: id });
    });

module.exports = router;
<file_sep>// var NoteServerActions = require('../actions/NoteServerActions');
var request = require('superagent');

var NoteWebAPIUtils = {
    createNote: function(note) {
        return request
            .post('/api/notes/' + note.id)
            .send({note: note})
            .set('Accept', 'application/json');
    },

    destroyNote: function(id) {
        return request
            .del('/api/notes/' + id)
            .set('Accept', 'application/json');
    }
};

module.exports = NoteWebAPIUtils;

repo_name: hugobessaa/react-isomorphic-flux


text:
<repo_name>sameoo/1st-repo<file_sep>/README.md
# 1st-repo
Pythoin course start request


text:
<repo_name>luisliz/DBEmergencyUI<file_sep>/src/app/categories/categories.component.ts
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {ResourcesService} from '../services/resources.service';
import {AddDialogComponent} from '../add-dialog/add-dialog.component';
import {MatDialog} from '@angular/material/dialog';

@Component({
  selector: 'app-categories',
  templateUrl: './categories.component.html',
  styleUrls: ['./categories.component.scss']
})
export class CategoriesComponent implements OnInit {
  categories = [
    {link: ['/categories', 'baby_foods'], name: 'Baby Foods'},
    {link: ['/categories', 'batteries'], name: 'Batteries'},
    {link: ['/categories', 'canned_foods'], name: 'Canned Foods'},
    {link: ['/categories', 'clothings'], name: 'Clothings'},
    {link: ['/categories', 'dry_foods'], name: 'Dry Foods'},
    {link: ['/categories', 'fuels'], name: 'Fuels'},
    {link: ['/categories', 'heavy_equipments'], name: 'Heavy Equipments'},
    {link: ['/categories', 'ices'], name: 'Ices'},
    {link: ['/categories', 'medical_devices'], name: 'Medical Devices'},
    {link: ['/categories', 'medications'], name: 'Medications'},
    {link: ['/categories', 'power_generators'], name: 'Power Generators'},
    {link: ['/categories', 'waters'], name: 'Waters'},
  ];
  catname = {
    baby_foods: 'Baby Foods',
    batteries: 'Batteries',
    canned_foods: 'Canned Foods',
    clothings: 'Clothings',
    dry_foods: 'Dry Foods',
    fuels: 'Fuels',
    heavy_equipments: 'Heavy Equipments',
    ices: 'Ices',
    medical_devices: 'Medical Devices',
    medications: 'Medications',
    power_generators: 'Power Generators',
    waters: 'Waters',
  };

  cat;
  data;
  keys;

  constructor(private activatedRoute: ActivatedRoute, private resourcesService: ResourcesService, public dialog: MatDialog) {
  }

  ngOnInit(): void {
    this.activatedRoute.paramMap.subscribe(params => {
      this.cat = params.get('category');
      this.resourcesService.getResource(this.cat).subscribe((data) => {
        this.data = data['Resources'];
        this.keys = Object.keys(this.data[0]);
      });
    });
  }

  addToCart(row) {
    const dialogRef = this.dialog.open(AddDialogComponent, {
      width: '250px',
      data: {}
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
    });
  }

}
<file_sep>/src/app/categories/categories.component.scss
.example-container {
  width: 100%;
  height: 100%;
  border: 1px solid #555;

  .mat-drawer {
    width: 200px;
  }
}
.card-deck-container {
  padding: 20px;
}
.card-item {
  width: 100%;
  height: 100%;
  margin: 10px;
  .mat-card-content {
    height: 100%;
    font-size: 14pt;
  }
}
table {
  width: 100%;
}
.mat-row:hover {
  background-color: #575757;
}

languages: SCSS TypeScript

repo_language: SCSS

repo_name: luisliz/DBEmergencyUI


text:
<file_sep># anlan-his
年轻人的第一个系统。


text:
<repo_name>rs-lamnv/ruby-blog<file_sep>/app/views/users/_form.html.erb
<%= form_for @user, html: {class: "form-horizontal"} do |f| %>

      <%= f.label :name, "Name", class: "control-label col-sm-2" %>

        <%= f.text_field :name, class: "form-control", placeholder: "Enter Full Name" %>

      <%= f.label :address, "Address", class: "control-label col-sm-2" %>

        <%= f.text_field :address, class: "form-control", placeholder: "Enter Address" %>

      <%= f.label :tel, "Tel", class: "control-label col-sm-2" %>

        <%= f.text_field :tel, class: "form-control", placeholder: "Enter Tel" %>

      <%= f.label :email, "Email", class: "control-label col-sm-2" %>

        <%= f.text_field :email, class: "form-control", placeholder: "Enter Email" %>

      <%= f.label :username, "<NAME>", class: "control-label col-sm-2" %>

        <%= f.text_field :username, class: "form-control", placeholder: "Enter User Name" %>

    <% if @user.new_record? %>

        <%= f.label :tel, "PassWord", class: "control-label col-sm-2" %>

          <%= f.password_field :password, class: "form-control", placeholder: "Enter Password" %>

        <%= f.label :tel, "PassWord Confirmation", class: "control-label col-sm-2" %>

          <%= f.password_field :password_confirmation, class: "form-control", placeholder: "Enter Password Confirmation" %>

    <% end %>

        <% if @user.new_record? %>
          <button type="submit" class="btn btn-primary">Submit</button>
        <% else %>
          <button type="submit" class="btn btn-primary">Update</button>
        <% end %>

  <% end %>

<file_sep>/config/settings.yml
show_limit:
  show_5: 10
  show_10: 20
  show_25: 25
  show_30: 30
  show_40: 40
  show_50: 50<file_sep>/app/models/user.rb
class User < ApplicationRecord
	has_secure_password
	validates :name, presence: true, length: {maximum: 50}
end
<file_sep>/app/views/users/index.html.erb

List User

	<%= search_form_for @search, url: users_path do |f|%>
	<%= select_tag :limit, options_from_collection_for_select(Settings.show_limit, :second, :second, selected: params[:limit] || Settings.show_limit.limit),id: "show-limit",class: "form-control"%>
	<%= f.submit "search", class: "btn btn-info", style: "display: none; margin-right: 10px"%>
	<% end %>

	<%= link_to "Create", {controller: "users", action: "new"}, class: "btn btn-primary" %>

      	<%= sort_link @search, :id, default_order: :desc %>
        <%= sort_link @search, :name %>
        <%= sort_link @search, :address %>
        <%= sort_link @search, :tel %>
        <%= sort_link @search, :email %>
        <%= sort_link @search, :username %>
        <%= sort_link @search, :created_at %>
        <%= sort_link @search, :updated_at %>
        Action

    <% @users.each do |user| %>

      	<%= user.id %>
        <%= user.name %>
        <%= user.address %>
        <%= user.tel %>
        <%= user.email %>
        <%= user.username %>
        <%= user.created_at %>
        <%= user.updated_at %>

        	<%= link_to 'Edit', {:action => :edit, :id => user.id}, class: "btn btn-warning" %>
          <%= link_to 'Delete', {:action => :destroy, :id => user.id}, class: "btn btn-danger",data: { confirm: 'Are you sure?' },:method => :delete %>

    <% end %>

<%= paginate @users, theme: 'twitter-bootstrap-3' %>

languages: HTML+ERB Ruby YAML

repo_language: HTML+ERB

repo_name: rs-lamnv/ruby-blog


text:
<file_sep># hubtst
hub test

branch_name: refs/heads/main

repo_name: EIXFor/hubtst


text:
<repo_name>Mirhoda/Resume-React-App<file_sep>/src/Components/Registration.js
import React from 'react';
    export default function registration() {

              return (

                          FIRST NAME *
                          <input type="text" id="firstname" name="First_Name" maxLength={30} />

                          LAST NAME *
                          <input type="text" id="lastname" name="Last_Name" maxLength={30} />

                          DATE OF BIRTH *

                            <input type="date" id="dateofbirth" name="birthday" />

                          DEPARTMENT *

                            <select name="Department" id="department">
                              <option value=" ">Select</option>
                              <option value="Electrical & Electronics">Electrical & Electronics</option>
                              <option value="Electronics & Telecommunication">Electronics & Telecommunication</option>
                              <option value="Civil">Civil</option>
                              <option value="Mechanicle">Mechanicle</option>
                              <option value="Computer Science & IT">Computer Science & IT</option>
                            </select>

                          EMAIL ID *
                          <input type="email" id="emailid" name="Email_Id" maxLength={100} />

                          MOBILE NUMBER *

                            <input type="text" id="mobilenumber" name="Mobile_Number" maxLength={10} />

                          GENDER *

                            Male <input type="radio" id="gender" name="Gender" defaultValue="Male" />
                            Female <input type="radio" id="gender" name="Gender" defaultValue="Female" />

                          ADDRESS

                          <textarea id="address" name="Address" maxLength={100} defaultValue={""} />

                            <input className="button" type="button" id="entry" defaultValue="Submit" onsubmit="ageCalculator()" />

                          First Name
                          Last Name
                          Date of Birth
                          Department
                          Email Id
                          Mobile Number
                          Gender
                          Address

                  {/* Footer */}

Made with 💗

© 2021 <NAME>

              );
            }
    <file_sep>/src/Components/Home.js
import React from 'react';
    export default function Home() {
      return (

I'm Mobinul

A Web Developer.

Hello.

A mixed engineering professional of both hardware & software domains. I have worked for OEM company, which build new-age technology for the sensor. Right now pursuing PG in Internation business & Finance

Experience

Hardware Design & Development

I started developing electronics prototypes when I was in my graduation days. Completed Btech in Electronics engineering, joined as an Electronics engineer in a product manufacturing based company. I have added many feathers in design & development of many circuit board for interdisciplinary sectors. I have worked for Ministry of Defense & HAL.

Robotic Device Engineer

Robotics is what my passion is all about. Being an electronics engineer, I loved to build machines. I started my journey of robotics in my graduation days & won awards. I was finalist for IIT-Delhi RoboTryst.

Want to know more

          👉 CLICK ME 👈

Get In Touch

If you love technology as much as I do.

 Chill 🔸 Code 🔸 Execute

            <a className="btn" href="mailto:<EMAIL>">CONTACT ME

          LinkedIn
          Twitter
          GitHub

© 2021 Designed & Developed by Mobinul with 💗

      );
    }

repo_language: JavaScript

repo_name: Mirhoda/Resume-React-App


text:
<repo_name>karinavarlena/react-jedi-crud-app<file_sep>/src/App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link, Redirect } from "react-router-dom";
import NoMatch from './components/common/NoMatch';
import People from './components/pages/People';
import Planets from './components/pages/Planets';
import Starships from './components/pages/Starships';

// import './App.css';
import 'bootstrap/dist/css/bootstrap.css';

function App() {
    return (

        <Router>

                        <Link className="nav-link" to="/people">People</Link>

                        <Link className="nav-link" to="/planets">Planets</Link>

                        <Link className="nav-link" to="/starships">Starships</Link>

                <Switch>
                    <Route exact path="/">
                        <Redirect
                            to={{
                                pathname: "/people",
                                state: { from: "/" }
                            }}
                        />
                    </Route>
                    <Route path="/people">
                        <People/>
                    </Route>
                    <Route path="/planets">
                        <Planets/>
                    </Route>
                    <Route path="/starships">
                        <Starships />
                    </Route>
                    <Route path="*">
                        <NoMatch />
                    </Route>
                </Switch>

        </Router>

    );
}

export default App;
<file_sep>/src/components/pages/People.jsx
import React, { useState } from "react";
import Table from "../common/Table";
import Form from '../common/Form';
import NoMatch from '../common/NoMatch';
import { Switch, Route, Link, useRouteMatch, useHistory } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.css";

const data = [
    {first: 'Mark', last: 'Otto', handle: '@motto', id: '1'},
    {first: 'Carl', last: 'Reno', handle: '@ceno', id: '2'},
    {first: 'Steve', last: 'Smith', handle: '@ssteve', id: '3'}
]

const columns = Object.keys(data[0]);

function People() {
    const [people, setPeople] = useState(data);
    const { path } = useRouteMatch();
    const history = useHistory();

    const handleAppPerson = (personData) => {
        const data = [...people, personData];
        setPeople(data);
        history.push(path);
    }

    const handleDeletePerson = (personData) => {
        const data = people.filter(person => person.id !== personData.id);
        setPeople(data);
    }

    const getInitialPeopleData = () => {
        return columns.reduce((cols, columnName) => {
            cols[columnName] = "";
            return cols;
        }, {})
    }

    return (
        <Switch>
            <Route exact path={path}>

People

                <Link className="btn btn-secondary my-2" to={`${path}/new`}>New people</Link>

            </Route>
            <Route exact path={`${path}/new`}>
                <Form
                    initialData={getInitialPeopleData()}
                    columns={columns}
                    onAddData={handleAppPerson}
                />
            </Route>
            <Route path={`${path}/*`}>
                <NoMatch />
            </Route>
        </Switch>
    );
}

export default People;
<file_sep>/src/components/common/Table.jsx
import React from 'react';
import Button from "./Button";

function Table({columns, data, tableDescriptor, deleteHandle}) {
    return (

                {tableDescriptor}
                {columns.map(columnTitle => (
                    {columnTitle}
                ))}
                { deleteHandle? Delete	: null }

            {data.map((item, index) => (

                    {++index}
                    {columns.map(columnTitle => (
                        {item[columnTitle]}
                    ))}

                        { deleteHandle?
                            <Button
                                label="Delete"
                                classes="btn btn-secondary my-0"
                                onClick={() => deleteHandle(item)}
                            />:
                             null
                        }

            ))}

    )
}

export default Table;

repo_name: karinavarlena/react-jedi-crud-app


text:
<repo_name>rkram5424/SpeakEasy<file_sep>/www/js/controllers.js
angular.module('starter.controllers', [])

.controller('BrowseCtrl', function($scope, $state, $timeout, $ionicFilterBar, $ionicPopup, Data, Text) {
  $scope.data = Data.all();
  $scope.remove = function(item) {
    Data.remove(item);
  };

  $scope.tapCategory = function() {

  };

  $scope.tapItem = function () {

  };

  $scope.newCategory = function () {

  };

  $scope.newItem = function () {

  };

  var viewText = function (text){
    Text.setText(text);
	$state.go('text');
  }

  $scope.quickText = function () {
	$scope.modal = {};
    var myPopup = $ionicPopup.show({
      template: '<input type="text" ng-model="modal.text">',
      title: 'Text to show',
      scope: $scope,
      buttons: [
        { text: 'Cancel' },
        {
          text: '<b>Show</b>',
          type: 'button-positive',
          onTap: function(e) {
            if (!$scope.modal.text) {
              //don't allow the user to close unless he enters wifi password
              e.preventDefault();
            } else {
              viewText($scope.modal.text);
            }
          }
        }
      ]
  });

  myPopup.then(function(res) {
    console.log('Tapped!', res);
  });

  };

    var vm = this,
        items = [],
        filterBarInstance;

    for (var i = 1; i <= 1000; i++) {

        var item = {
            description: 'Description for item ' + i,
            date: 'test'
        };
        items.push(item);
    }

    vm.items = items;

    vm.showFilterBar = function () {
      filterBarInstance = $ionicFilterBar.show({
        items: vm.items,
        update: function (filteredItems) {
          vm.items = filteredItems;
        },
        filterProperties: 'description'
      });
    };

    return vm;
})

.controller('FavoritesCtrl', function($scope) {

})

.controller('SettingsCtrl', function($scope) {

})

.controller('TextCtrl', function($scope, $stateParams, Text) {
  $scope.view = {};
  //$scope.view.text = Text.getText();
  $scope.view.text = [Text.getText(), 'Tab: <NAME>'];
})

.controller('HistoryCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
});
<file_sep>/README.md
# SpeakEasy
A convenient app for ordering drinks in a loud EDM club.


text:
<file_sep>include _mixins.jade

section.user_quotes
  .wrapper
    h2.lead-head Reasons to be happy
    hr.devider
    .quotes
      +quote("You are alive", "Waking up to see another day is a blessing. Don't take it for granted. Make it count and be happy that you're alive.", "")
      +quote("Someone loves you", "Someone who really loves you sees what a mess you can be, how moody you can get, how hard you are to handle, but still wants you in their life.", "")
      +quote("Enjoy the moment", "Sometimes you will never know the true value of a moment until it becomes a memory.", "")
      +quote("Health is wealth", "It is health that is real wealth and not pieces of gold and silver.", "<NAME>")
    .btn-area
      a(href="#", class="btn") More Reasons
<file_sep>section.quotes
  display: flex
  justify-content: center
  background: $pale-bg
  .quote
    width: 35%
    padding-top: 50px
    padding-bottom: 50px

  p
    font-size: 36px
  .text
      font-weight: 600
  .author
      font-weight: 200

  .bg-img
    width: 65%
    background:
      image: linear-gradient(rgba(234, 226, 209, 0.2), rgba(234, 226, 209, 0.2)), url("../img/quote_pct.png")
      size: cover
      position: center

  @media (max-width: 720px)
    .quote
      padding-top: 25px
      padding-bottom: 25px
  @media (max-width: 640px)
    .quote
      width: 100%
    .bg-img
      display: none
<file_sep>//- menu list
mixin menu_item(item, id)
	li
		a(href="##{id}")= item

//- social media icon list
mixin social_item(url)
	li
		a(href="#")
			img(src="#{url}")

//- quotes block
mixin quote(theme, text, author)
	.quote
		h3.theme= theme
		p.text= text
		if author == ""
			p.author Anonymous
		else
			p.author= author

//- posters
mixin poster(url, text, main)
	.poster(style='background-image: linear-gradient(rgba(234, 226, 209, 0.2), rgba(234, 226, 209, 0.2)), url("#{url}")')
		.quote
			p.quote-text!= text
		if main == "true"
			.action
				a(href="#") Buy Now
				a(href="#") Share
<file_sep>section.daily_quote
  background:
    image: url("../img/daily_quote.png")
    size: cover
    color: rgba(234, 226, 209, 0.2)
  display: flex
  justify-content: center
  align-items: center
  .quote
    display: inline-block
    color: $white
    margin: 100px 0
    .lead-head
      text-align: center
      width: 50%
      margin: 0 auto 50px
      font-weight: 600
    p
      text-align: center
      font:
        size: 20px
        weight: 300
      .underline
        border-bottom: 0.1rem solid $white

  @media (max-width: 720px)
    .quote
      margin: 50px
      .lead-head
        width: 100%

  @media (max-width: 420px)
    .quote
      margin: 25px
<file_sep>footer.footer
  h3
    font:
      size: 20px
      weight: 600
    text-transform: uppercase
    letter-spacing: 5px
    margin-bottom: 50px
  a,
  p
    color: $black
    letter-spacing: 3px
    line-height: 2em
    margin: 0
  .navigation
    display: flex
    justify-content: space-between
    margin-top: 60px
    margin-bottom: 60px
    .box
      width: 100%
      margin-right: 50px
      &:last-child
        margin-right: 0
    ul
      padding: 0 50px 0 0
      list-style: none

      li
        a
          &:hover
            text-decoration: underline

    .subscribe
      h3
        margin-bottom: 30px
      input[type="email"]
        padding: 10px 15px
        background: $grey-bg
        letter-spacing: 3px
        border: none
        display: block
        margin: 25px 0 20px
        width: 100%
        box-sizing: border-box
        &:focus
          outline: 1.5px solid $grey

    .contact
      max-width: 280px
  .copyright
    display: flex
    justify-content: space-between
    flex-wrap: wrap
    align-items: center
    background: $grey-bg
    padding: 0 100px

    p
      letter-spacing: normal
    ul
      list-style: none
      display: flex
      flex-wrap: wrap
      align-items: center
      justify-content: center
      padding: 0
      li
        margin-right: 10px
        margin-top: 5px
        &:last-child
          margin-right: 0

        a
          opacity: 0.4
          filter: grayscale(100%)
          transition: all 0.25s
          &:hover
            opacity: 0.9

  @media (max-width: 1024px)
    .navigation
      flex-wrap: wrap
      .box
        width: 50%
        max-width: 300px
        box-sizing: border-box
        margin-right: 0
    .copyright
      justify-content: center

  @media (max-width: 720px)
    .navigation
      display: none
    .copyright
      padding: 0 50px
      p
        display: none

  @media (max-width: 420px)
    .copyright
      padding: 0 25px
<file_sep>include _mixins.jade

section.posters
  .wrapper
    h2.lead-head Buy Posters Prints
    hr.devider
    .posters-grid
      .main-area
        +poster("assets/img/main_poster.png", "Stay
True,
Stay
Gentleman", "true")
      .sub-area
        .poster-2
          +poster("assets/img/poster-2.png", "And muse of nature
with a poet’s eye<NAME>", "")
        .poster-1
          +poster("assets/img/poster-3.jpg", "Make Work
Fun & Play", "")
        .poster-1
          +poster("assets/img/poster-4.png", "Silence is
Golden", "")
    .btn-area
      a(href="#", class="btn") Browse Posters
<file_sep>/* HEADER STYLES */
.header
  overflow: hidden
  background:
    image: linear-gradient(rgba(234, 226, 209, 0.1), rgba(234, 226, 209, 0.1)), url("../img/header-bg.png")
    size: cover
    position: top
  position: relative
  padding-bottom: 80px

  .logo
    background: rgba(0, 0, 0, 1)
    padding: 10px 30px
    float: left
    margin: 50px 0 0 200px
    a
      display: inline-block
    h1
      text-align: center
      color: $white
      font:
        size: 30px
        weight: 700
      letter-spacing: 7px
      text-transform: uppercase

  nav
    .nav-menu
      position: relative
      float: right
      margin: 75px 200px 0 0
      border-top: 3px solid $white
      border-bottom: 3px solid $white
      font:
        size: 15px
        weight: 700
      color: $white
      line-height: 1.8em
      letter-spacing: 2px
      text-transform: uppercase
      cursor: pointer
      transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.275)
      transition-duration: 400ms
      transform:scale(1.1,1.1)

      &:hover
        transform: scale(1.2,1.2)
    .close-btn
      display: none
      z-index: 1
      position: absolute
      top: 5%
      left: 85%
      +size(50px)
      overflow: hidden
      cursor: pointer

      &:hover
        transform: scale(1.2,1.2)
        opacity: .7

      &::before, &::after
        content: ''
        position: absolute
        height: 2px
        width: 100%
        top: 50%
        left: 0
        background: $white
      &::before
        @include transform(rotate(45deg))
      &::after
        @include transform(rotate(-45deg))
      &::before, &::after
          height: 4px
          margin-top: -2px

  .slogan
    clear: both
    text-align: center

    h1
      font:
        size: 220px
        weight: 100
      color: $white
      text-transform: uppercase
      letter-spacing: 5px
      margin: 0
    p
      font:
        size: 64px
        weight: 700
      color: $white
      letter-spacing: 2px
      margin-top: -40px

  .is-displayed
    display: none
    background: rgba(0, 0, 0, .9)
    position: absolute
    top: 0
    +size(100%)

    ul
      margin-top: 5%
      list-style: none
      text-align: center
      padding: 50px 0

      li
        padding: .3% 10px
        a
          color: $grey
          font:
            size: 30px
            weight: 700
          letter-spacing: 5px
          transition: all 0.4s

          &:hover, &:focus
            color: $white
            text-decoration: underline

  /*  MEDIA QUERIES FOR HEADER*/
  @media (max-width: 1024px)
    .logo
      margin-left: 100px

    nav
      .nav-menu
        margin-right: 100px

  @media (max-width: 640px)
    .logo
      margin: 30px 0 0 30px
      transform: scale(.9)

    nav
      .nav-menu
        margin: 55px 30px 0 0
        transform: scale(.9)

      .close-btn
        +size(40px)

    .slogan
      p
        margin-top: -10px
    .is-displayed
      ul
        padding: 20px 0
        li
          a
            font-size: 28px

  @media (max-width: 480px)
    .logo
      transform: scale(.7)
      padding: 5px
      margin: 0
    nav
      .nav-menu
        margin: 30px 20px 0 0
        transform: scale(.8)
      .close-btn
        +size(30px)
    .is-displayed
      ul
        li
          a
            font-size: 22px
<file_sep>section.user_quotes
  .lead-head
    margin-top: 100px
  .devider
    margin: 20px 0 80px
    box-shadow: 0 1px
  .quotes
    +clearfix()
    display: flex
    flex-wrap: wrap

    .quote
      width: 50%
      box-sizing: border-box
      border: 0.1rem solid tint($black, 90%)
      padding: 40px

      .theme
        margin: 0
        font:
          size: 30px
          weight: 600
        text-transform: uppercase

      .text
        font-size: 20px
        margin: 0
        padding: 20px 0 10px

      .author
        margin: 0
        font:
          style: italic
          size: 20px
          weight: 300
  .btn-area
    margin: 40px 0 100px
    text-align: center
    .btn
      font-weight: 700

  @media (max-width: 640px)
    .lead-head
      margin-top: 50px
    .quotes
      flex-direction: row
      .quote
        width: 100%
        padding: 20px
    .btn-area
      margin: 40px 0
<file_sep>section.description
  .wrapper
    h2.lead-head The most inclusive
      span Free PSD Template
    .lead-text
      p Free for commercial and personal use.
      p You can easily edit its contents and code it for yourself or your client!
    hr.devider
    .main-text
      p Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget nisi eget tortor iaculis tristique. Aliquam tincidunt posuere tortor hendrerit elementum. Nunc laoreet lorem a sem auctor fringilla. Pellentesque dignissim accumsan lobortis. Sed pharetra erat vitae dui imperdiet quis commodo orci dapibus.
      p Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce at nunc libero. Nam metus lorem, rhoncus ac mattis ornare, blandit vel risus.
<file_sep>section.daily_quote
  .quote
    h2.lead-head I love you for all that you are, all that you have been, and all you're yet to be.
    p.description Quote of the day, from
      span.underline Love Quotes
<file_sep>//- menu list
include _mixins.jade

header.header
	.logo
		a(href=""): h1 Quotes

	nav
		.nav-menu Menu
		span.close-btn

	.slogan
		h1 Smile
		p it costs you nothing

	.is-displayed
		ul
			+menu_item("Home", 'home')
			+menu_item("About Us", 'about_us')
			+menu_item("Categories", 'categories')
			+menu_item("Gallery", 'gallery')
			+menu_item("Events", 'events')
			+menu_item("Blog", 'blog')
			+menu_item("Contact Us", 'contact_us')
<file_sep>section.posters
  background: $grey-bg
  .lead-head
    padding-top: 100px
  .devider
    margin: 20px 0 80px

  .posters-grid
    display: flex
    height: 650px
    .main-area
      width: 40%
      margin-right: 50px
      .poster
        background-position: top left
        box-shadow: 0 0 50px 5px rgba(0, 0, 0, 0.3)
        &:hover
          cursor: default
        .quote
          display: flex
          justify-content: center
          align-items: center
      .quote-text
        text-align: center
        font:
          size: 80px
          weight: 700
        color: $white
        text-transform: uppercase

    .sub-area
      +clearfix()
      width: 60%
      .poster-2
        width: 100%
        height: 50%
        padding-bottom: 50px
        box-sizing: border-box
        .poster
          background-position: 0 38%
        .quote-text
          font:
            size: 36px
            weight: 600
            style: italic
          color: $black
          margin: 50px 20px 0 50px
          span
            display: block
            font:
              size: 20px
              weight: 400
              style: normal
            color: $black

      .poster-1
        width: 50%
        float: left
        padding-right: 25px
        height: 50%
        box-sizing: border-box
        .poster
          background-position-y: 50px
          background-color: #e7e6e5
          background-repeat: no-repeat
        .quote-text
          text-align: center
          font:
            size: 30px
            weight: 700
          color: $white
          text-transform: uppercase
          line-height: 2.5rem
          span
            font:
              size: 31px
              weight: 800

        &:last-child
          padding-left: 25px
          padding-right: 0
          .poster
            background:
              size: cover
              position: center
              color: rgba(234, 226, 209, 0.2)
          .quote
            display: flex
            justify-content: center
            align-items: flex-end
            height: 100%

    .black
      color: $black
    .poster
      background:
        size: cover
        position: center
        color: rgba(234, 226, 209, 0.2)
      height: 100%
      transition: all 0.3s
      &:hover
        box-shadow: 0 0 50px 5px rgba(0, 0, 0, 0.3)
        cursor: pointer

      .quote
        display: inline-block
        width: 100%
        height: 85%
      .action
        display: flex
        justify-content: space-around
        align-items: center
        height: 15%
        a
          font:
            size: 20px
            weight: 600
          color: $white
          text-transform: uppercase
          letter-spacing: 2px
          text-decoration: none
          transition: all 0.3s
          padding: 10px 15px
          margin: 25px 0
          &:hover
            outline: 0.1rem solid $white
  .btn-area
    padding: 80px 0 100px
    text-align: center
    .btn
      font-weight: 700

  @media (max-width: 1024px)
    .posters-grid
      flex-direction: column
      justify-content: flex-start
      align-items: center
      height: auto
      .main-area
        width: auto
        margin-right: 0
      .sub-area
        width: 100%
        height: 500px
        .poster-2
          padding-top: 50px
          box-sizing: inherit
          .quote-text
            font-size: 30px
            margin: 30px 15px 0 30px
    .btn-area
      padding-top: 150px

  @media (max-width: 640px)
    .lead-head
      padding-top: 50px
  @media (max-width: 575px)
    .posters-grid
      .main-area
        width: 100%
      .sub-area
        height: 350px
        .poster-1
          padding-right: 10px
          .quote-text
            span
              font-size: 24px
          &:last-child
            padding-left: 10px
            .quote-text
              font-size: 22px
        .poster-2
          padding-top: 25px
          padding-bottom: 25px
          .quote-text
            font-size: 25px
            margin: 15px 10px 0 15px

  @media (max-width: 395px)
    .posters-grid
      .main-area
        .quote-text
          font-size: 32px !important
        .action
          a
            font-size: 14px
            &:hover
              outline: none
      .sub-area
        .poster-2
          .quote-text
            font-size: 20px
            margin: 15px
        .poster-1
          float: none
          width: 100%
          padding-right: 0
          &:last-child
            padding-left: 0
            padding-top: 25px
    .btn-area
      padding-top: 0
      margin-top: 260px
<file_sep>/* Basic Styles
  ------------------------------------	*/
body
  font:
    family: "Raleway", open-sans
  line-height: 1.6
  color: $black
  -webkit-font-smoothing: antialiased
  -webkit-text-size-adjust: 100%

a
  text-decoration: none

.wrapper
  margin: 0 100px

.lead-head
  font:
    size: 60px
    weight: 600
  margin: 0
  line-height: 1.3em

.devider
  width: 4.0625rem
  height: 0.1rem
  border: none
  background: $black

.btn
  display: inline-block
  padding: 10px 20px
  color: $black
  text-transform: uppercase
  font-weight: 600
  cursor: pointer
  border: 2px solid $black
  border-radius: 5px
  background: transparent
  letter-spacing: 3px
  transition: all 0.2s

  &:hover
    transform: scale(.88)

.top_btn
  position: fixed
  bottom: 5%
  right: 10%
  display: none
  +size(60px)
  background:
    image: url("../img/arrow-up.png")
    size: cover
  border: 4px solid $black
  transition: all 0.3s
  &:hover
    transform: scale(0.88)

@media (max-width: 720px)
  .wrapper
    margin: 0 50px
  .top_btn
    +size(40px)

@media (max-width: 420px)
  .wrapper
    margin: 0 25px
  .btn
    font-size: 14px
    padding: 5px 10px
<file_sep>//- menu list
include _mixins.jade

footer.footer
  .navigation.wrapper
    .browse.box
      h3 Browse
      ul
        +menu_item("Home", 'home')
        +menu_item("About Us", 'about_us')
        +menu_item("Categories", 'categories')
        +menu_item("Info", 'inifo')
        +menu_item("Services", 'services')
    .shop.box
      h3 Shop
      ul
        +menu_item("Accounts", 'accounts')
        li
          a(href="#") Help & Guide
        li
          a(href="#") Shipping & Returns
        +menu_item("FAQs", 'faq')

    .contact.box
      h3 Contact
      p Quotes PSD Template
          | Rudra Street, 12354 Villa
          | My State - My Country
          | 987658
      br
      p Phone: + 01 234 567 890
          | Fax: + 01 234 567 890
          | <EMAIL>
    .subscribe.box
      h3 Subscribe Now
      p Get our latest news and
        | product updates daily
      form
        input(type="email", placeholder="Email Adress")
        input(type="submit", value="Submit", class="btn")
  .copyright
    p 2016 © Copyright - Quotes PSD Templates. All rights reserved.
    .social-media
      ul
        +social_item("assets/img/fb.png")
        +social_item("assets/img/tw.png")
        +social_item("assets/img/linkedin.png")
        +social_item("assets/img/youtube.png")
        +social_item("assets/img/gplus.png")
        +social_item("assets/img/pinterest.png")
        +social_item("assets/img/instagram.png")
        +social_item("assets/img/email.png")
<file_sep>doctype html
html(lang="en")
	head
		title= title
		meta(charset="utf-8")
		meta(name="viewport", content="width=device-width, initial-scale=1.0")
		link(rel="stylesheet" href="assets/css/app.css")

	body#home

		include _partials/header.jade
		include _partials/description.jade
		include _partials/quotes.jade
		include _partials/user_quotes.jade
		include _partials/daily_quote.jade
		include _partials/posters.jade
		include _partials/footer.jade

		a(href="#home" class="top_btn")

		script(type="text/javascript" src="assets/js/jquery-3.1.1.min.js")
		script(type="text/javascript" src="assets/js/functions.min.js")
<file_sep># Design-Qoute
Project with usage: gulp-jade-sass-autoprefix

You can check the project out here: [https://scanerrr.github.io/Design-Qoute/](https://scanerrr.github.io/Design-Qoute/)

![alt tag](https://raw.githubusercontent.com/Scanerrr/Design-Qoute/master/Quotes-Web-Template.jpg)
<file_sep>@import "header"
@import "description"
@import "quotes"
@import "user_quotes"
@import "daily_quote"
@import "posters"
@import "footer"
<file_sep>section.quotes
  .quote.wrapper
    p.text I love people who make me laugh. I honestly think it’s the thing I like most, to laugh. It cures a multitude of ills. It's probably the most important thing in a person.
    p.author <NAME>
  .bg-img

<file_sep>section.description
  .wrapper
    text-align: center
    margin: 60px 15%
    p
      font-size: 20px
      line-height: 1.3
    .lead-head
      font-weight: 400
      span
        display: block
        font-weight: 600

    .lead-text
      margin-top: 40px
      p
        font-weight: 500
        margin: 0

    .devider
      margin: 30px auto 40px
    .main-text
      margin-bottom: 50px

  @media (max-width: 1024px)
    .wrapper
      margin: 40px 100px

  @media (max-width: 720px)
    .wrapper
      margin: 30px 50px

  @media (max-width: 720px)
    .lead-head
      margin-top: 50px

  @media (max-width: 420px)
    .wrapper
      margin: 20px 25px
<file_sep>// GLOBAL VARIABLES

// COLORS
$grey-bg: #f2f4f5
$pale-bg: #ffe9e2
$black: #000
$white: #fff
$grey: #626262

languages: Markdown Sass Pug

repo_name: Scanerrr/Design-Qoute


text:
<repo_name>JosephO1992/RateCalcApp<file_sep>/docs/app.js
const inputRate = document.querySelector("input.rate");
const inputOnCosts = document.querySelector("input.onCosts");
const inputMargin = document.querySelector("input.margin");
const calculateButton = document.querySelector("button.calculate");
const form = document.querySelector("form");
const outPut = document.querySelector(".answer");
// const incSuper = document.querySelector(".inc");
// const exclSuper = document.querySelector(".excl");
// const checkBoxArr = [incSuper, exclSuper];

let numInputRate;
let numInputOnCosts;
let numInputMargin;
let percentOncosts;
let finalDayRate;

function convertToNum(inputString) {
	// This function takes the inputs and converts them to numbers as they are strings by default
	let strV = inputString.value;
	let numV = parseInt(strV);
	return numV;
}

function convertToPercentage(Oncosts) {
	// This takes in the oncosts input and converts to a %
	percent = Oncosts / 100;
	numPercent = parseFloat(percent);
	return numPercent;
}

function totalDayRate(rate, percentage, margin) {
	// This function takes in the aleady converted inputs, then multiplies and returns the total figure
	// I will wrap this in an IF to make sure the % on costs are less than 100
	let finalPercent = percentage + 1;

	let totalRate = rate * finalPercent + margin;
	return totalRate;
}

function checkboxlimit(checkgroup, limit) {
	let checkGroupToCheck = checkgroup;
	let checkBoxLimit = limit;
	for (let i = 0; i < checkGroupToCheck.length; i++) {
		let count = 0;
		if (checkGroupToCheck[i].checked) {
			count += 1;
			if (count > checkBoxLimit) {
				console.log("too many checkboxes ticked");
			}
		}
	}
}

form.addEventListener("submit", (e) => {
	e.preventDefault();

	let numInputRate = convertToNum(inputRate);
	let numInputOnCosts = convertToNum(inputOnCosts);
	let numInputMargin = convertToNum(inputMargin);
	let percentOncosts = convertToPercentage(numInputOnCosts);
	let finalDayRate = totalDayRate(numInputRate, percentOncosts, numInputMargin);
	outPut.value = finalDayRate;
});
<file_sep>/readme.md
# Creating a rate calculator app

This will be able to perform some simple math within a form

I have created some simple input fields where I can put in some figures and it will pass back out a rate into the input box.

There are few functions to convert the inputs into numbers, as the original value returned is a string, which I cannot perform math with.

I also need to convert back the % figure inputted into an actual percent. For this I just divided that by 100. In the future, I would create
some test to make sure the % input can't go over 99%.

Originally, there was a an empty div, but I adjusted this to change the value of the text input box to the final value.
I chose to do this to keep the styling consistent and not having to worry about creating more divs on the page.