text:
<repo_name>Ddogzhouyuan/algs4_work<file_sep>/CH1/Solution1_3_5.java
package CH1;

import edu.princeton.cs.algs4.StdOut;

public class Solution1_3_5 {
	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<Integer>();
		int N = Integer.parseInt(args[0]);
		while (N > 0) {
			stack.push(N % 2);
			N /= 2;
		}
	}

}
<file_sep>/readme.md
# works of algs4
test
<file_sep>/Deque/RandomizedQueue.java
package assignment2;
import java.util.Iterator;
import java.util.NoSuchElementException;

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdRandom;

public class RandomizedQueue<Item> implements Iterable<Item> {
	private Item[] q;
	private int N = 0;

	public RandomizedQueue() {
		// construct an empty randomized queue
		q = (Item[]) new Object[2];
	}

	public boolean isEmpty() {
		// is the randomized queue empty?
		return N == 0;
	}

	public int size() {
		// return the number of items on the randomized queue
		return N;
	}

	private void resize(int max) {
		Item[] temp = (Item[]) new Object[max];
		for (int i = 0; i < N; i++) {
			temp[i] = q[i];
		}
		q = temp;
	}

	public void enqueue(Item item) {
		// add the item
		if (item == null) throw new NullPointerException();
		if (N == q.length) resize(2 * q.length);
		/*if (N == 0) {
			q[N++] = item;
			return;
		}
		int randomIndex = StdRandom.uniform(N);
		Item temp = q[randomIndex];
		q[randomIndex] = item;
		q[N++] = temp;*/
		q[N++] = item;
	}

	public Item dequeue() {
		// remove and return a random item
		if (isEmpty()) throw new NoSuchElementException();
		int offset = StdRandom.uniform(N);
		Item item = q[offset];
		if (offset != N - 1) q[offset] = q[N - 1];
		q[N - 1] = null;
		N--;
		if (N > 0 && N <= q.length/4) resize(q.length / 2);
		return item;
	}

	public Item sample()  {
		// return a random item (but do not remove it)
		if (isEmpty()) throw new NoSuchElementException();
		int offset = StdRandom.uniform(N);
		return q[offset];
	}

	private class ArrayIterator implements Iterator<Item>{
		private Item[] copyArray = (Item[]) new Object[q.length];
		private int copyN = N;

		public ArrayIterator() {
			for (int i = 0; i < q.length; i++) {
				copyArray[i] = q[i];
			}
		}

		public boolean hasNext() {
			return copyN != 0;
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}

		public Item next() {
			if (!hasNext()) throw new NoSuchElementException();
			int offset = StdRandom.uniform(copyN);
			Item item = copyArray[offset];
			if (offset != copyN - 1) {
				copyArray[offset] = copyArray[copyN - 1];
			}
			copyArray[copyN - 1] = null;
			copyN--;
			return item;
		}
	}

	public Iterator<Item> iterator() {
		// return an independent iterator over items in random order
		return new ArrayIterator();
	}

	public static void main(String[] args) {
		// unit testing (optional)
		RandomizedQueue<Integer> queue = new RandomizedQueue<Integer>();
		for (int i = 0; i < 10; i++) {
			queue.enqueue(i);
		}
		System.out.println(queue.size());
		for (Integer i : queue) {
			System.out.println(i);
		}
		System.out.println("sample:" + queue.sample());
		System.out.println("dequeue");
		while (!queue.isEmpty()) {
			System.out.println(queue.dequeue());
		}
		System.out.println(queue.size());
	}
}
<file_sep>/CH1/Solution1_1_9.java
package CH1;

public class Solution1_1_9 {
	public static String toBinaryString(int N) {
		String s = "";
	    for (int n = N; n > 0; n /= 2) {
	    	s = (n % 2) + s;
	    }
	    return s;
	}
	public static void main(String[] args) {
		int n = 100;
		String result = toBinaryString(n);
		System.out.println(result);
	}
}
<file_sep>/CH1/Solution1_1_1.java
package CH1;

public class Solution1_1_1 {
	static {
		System.out.println("a: " + (0 + 15) / 2);
	}

	static {
		System.out.println("b: " + (2.0e-6) * 100000000.1);
	}

	static {
		System.out.println("c:" + (true && false || true && true));
	}

	public static void main(String[] args) {

	}
}
<file_sep>/percolation/readme.md
# Relization of Union found in algorithm
<file_sep>/CH1/Solution1_1_2.java
package CH1;

public class Solution1_1_2 {
	static {
		System.out.println("a: " + (1 + 2.236) / 2 + " double");
		System.out.println("b: " + (1 + 2 + 3 + 4.0) + " double");
		System.out.println("c: " + (4.1 >= 4) + " Boolean");
		System.out.println("d: " + (1 + 2 + "3") + " String");
	}

	public static void main(String[] args) {

	}
}
<file_sep>/collinear/README.md
# Pattern Recognition for collinear points.
<file_sep>/CH1/UF_weightedquickunion.java
package CH1;

public class UF_weightedquickunion {

}
<file_sep>/CH1/Solution1_3_6.java
package CH1;

import edu.princeton.cs.algs4.StdIn;

public class Solution1_3_6 {
	public static void main(String[] args) {
		Queue<String> q = new Queue<String>();
		while (!StdIn.isEmpty()) {
			String item = StdIn.readString();
			q.enqueue(item);
		}

		Stack<String> stack = new Stack<String>();
		while (!q.isEmpty()) {
			stack.push(q.dequeue());
		}
		while (!stack.isEmpty()) {
			q.enqueue(stack.pop());
		}
	}
}
<file_sep>/CH1/Solution1_3_9.java
package CH1;

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class Solution1_3_9 {
	public static void main(String[] args) {
		Stack<String> ops = new Stack<String>();
		Stack<String> vals = new Stack<String>();
		String result = "";
		while (!StdIn.isEmpty()) {
			String item = StdIn.readString();
			if (!item.equals(")")) {
				if (item.equals("+") || item.equals("-") || item.equals("*") || item.equals("/")) {
					ops.push(item);
				} else vals.push(item);
			} else {
				String ops_temp = ops.pop();
				String val1 = vals.pop();
				String val2 = vals.pop();
				result = "(" + " " + val2 + " " + ops_temp + " " + val1 + " )";
				vals.push(result);
			}
		}
		StdOut.print(vals.pop());
	}
}
<file_sep>/CH1/Stack.java
package CH1;

import java.util.Iterator;

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class Stack<Item> {
	private Node first;
	private int N;

	private class Node {
		Item item;
		Node next;
	}

	public boolean isEmpty() {
		return N == 0;
	}

	public int size() {
		return N;
	}

	public void push(Item item) {
		Node oldfirst = first;
		first = new Node();
		first.item = item;
		first.next = oldfirst;
		N++;
	}

	public Item pop() {
		Item item = first.item;
		first = first.next;
		N--;
		return item;
	}

	public Item peek() {
		return first.item;
	}

	public void delete(int k) {
		if (k == 0) first = first.next;
		else {
			Node temp = first;
			for (int i = 1; i < k; i++) {
				temp = temp.next;
			}
			temp.next = temp.next.next;
		}
		N--;
	}

	public boolean find(String s) {
		Node temp = first;
		while (temp.next != null) {
			if (temp.item.equals(s)) return true;
			temp = temp.next;
		}
		if (temp.item.equals(s)) return true;
		else return false;
	}

	public void removeAfter(Node tar) {
		if (tar == null || tar.next == null) {}
		else tar.next = tar.next.next;
	}

	public void insertAfter(Node A, Node B) {
		if (A == null || B == null) {}
		else {
			B.next = A.next;
			A.next = B;
		}
	}

	public Node remove(String key) {
		Node temp = first;
		if (temp.item.equals(key)) temp = temp.next;
		while (temp.next != null) {
			if (temp.next.item.equals(key)) {
				temp.next = temp.next.next;
			}
		}
		return temp;
	}

	public Node reverse(Node x)
    {
       Node first = x;
       Node reverse = null;
       while (first != null) {
          Node second = first.next;
          first.next = reverse;
          reverse = first;
          first = second;
       }
       return reverse;
    }

	public Node reverse2(Node first)
    {
       if (first == null) return null;
       if (first.next == null) return first;
       Node second = first.next;
       Node rest = reverse(second);
       second.next = first;
       first.next = null;
       return rest;
    }

	public Iterator<Item> iterator() {
		return new ListIterator();
	}

	private class ListIterator implements Iterator<Item> {
		private Node current = first;

		public boolean hasNext() {
			return current != null;
		}

		public void remove() {

		}

		public Item next() {
			Item item = current.item;
			current = current.next;
			return item;
		}
	}

	public static Stack<String> copy(Stack<String> stack_old) {
		Iterator<String> iter = stack_old.iterator();
		Stack<String> temp = new Stack<String>();
		while (iter.hasNext()) {
			temp.push(iter.next());
		}
		Iterator<String> iter2 = temp.iterator();
		Stack<String> res = new Stack<String>();
		while (iter2.hasNext()) {
			res.push(iter2.next());
		}
		return res;
	}

	public static void main(String[] args) {
		Stack<String> s = new Stack<String>();

		while (!StdIn.isEmpty()) {
			String item = StdIn.readString();
			if (!item.equals("-")) s.push(item);
			else if (!s.isEmpty()) StdOut.println(s.pop() + " ");
		}
		StdOut.println("( " + s.size() + " left on stack)");
		Iterator<String> s_iter = s.iterator();
		while(s_iter.hasNext()) {
			StdOut.print(s_iter.next() + " ");
		}
		StdOut.print("\n");
		Stack<String> s_copy = copy(s);
		Iterator<String> s_copy_iter = s_copy.iterator();
		while(s_copy_iter.hasNext()) {
			StdOut.print(s_copy_iter.next() + " ");
		}
		StdOut.print("\n");
		StdOut.println(s.size());
		s.delete(1);
		StdOut.println(s.size());
		Iterator<String> s_iter2 = s.iterator();
		while(s_iter2.hasNext()) {
			StdOut.print(s_iter2.next() + " ");
		}

		StdOut.println("\n" + s.find("q"));
//		s.remove("be");
		s.first = s.reverse(s.first);
		Iterator<String> s_iter3 = s.iterator();
		while(s_iter3.hasNext()) {
			StdOut.print(s_iter3.next() + " ");
		}
		StdOut.print("\n");

		s.first = s.reverse2(s.first);
		Iterator<String> s_iter4 = s.iterator();
		while(s_iter4.hasNext()) {
			StdOut.print(s_iter4.next() + " ");
		}
		StdOut.print("\n");

		StdOut.println("\n" + s.find("q"));
//		s.remove("be");
		s.first = s.remove("be");
		Iterator<String> s_iter5 = s.iterator();
		while(s_iter5.hasNext()) {
			StdOut.print(s_iter5.next() + " ");
		}
		StdOut.print("\n");
	}
}
<file_sep>/CH1/Solution1_1_18.java
package CH1;

public class Solution1_1_18 {
    public static int mystery(int a, int b) {
       if (b == 0)     return 0;
       if (b % 2 == 0) return mystery(a+a, b/2);
       return mystery(a+a, b/2) + a;
    }

    public static int mystery2(int a, int b) {
        if (b == 0)     return 1;
        if (b % 2 == 0) return mystery2(a*a, b/2);
        return mystery2(a*a, b/2) * a;
     }

    public static void main(String[] args) {
    	int res1 = mystery(2, 25);
    	int res2 = mystery(3, 11);
    	int res3 = mystery2(2, 25);
    	int res4 = mystery2(3, 11);
    	System.out.println(res1);
    	System.out.println(res2);
    	System.out.println(res3);
    	System.out.println(res4);
    }

}
<file_sep>/Deque/README.md
# Realization of Queue
<file_sep>/collinear/FastCollinearPoints.java
package assignment3;

import java.util.ArrayList;
import java.util.Arrays;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Merge;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;

public class FastCollinearPoints {
	private ArrayList<LineSegment> lineSgmts;
	private Point[] pointSet;
	public FastCollinearPoints(Point[] points) {
		// finds all line segments containing 4 or more points
		if (points == null) throw new NullPointerException();

		int len = points.length;

		pointSet = Arrays.copyOf(points, len);
		lineSgmts = new ArrayList<LineSegment> ();
		Merge.sort(pointSet);

		for (int i = 0; i < len - 1; i++) {
			double[] slopesBefore = new double[i];
			Point[] pointAfter = new Point[len - i - 1];

			for (int j = 0; j < i; ++j) {
				slopesBefore[j] = pointSet[i].slopeTo(pointSet[j]);
			}

			for (int j = 0; j < len - i - 1; ++j) {
				pointAfter[j] = pointSet[i + j + 1];
			}

			Arrays.sort(slopesBefore);
			Arrays.sort(pointAfter, pointSet[i].slopeOrder());
			addNewSgmts(slopesBefore, pointSet[i], pointAfter);
		}
	}

	private void addNewSgmts(double[] slopeBefore, Point srtPoints, Point[] pointAfter) {
		int cnt = 1;
		int lenOfSub = pointAfter.length;
		double slope = Double.NEGATIVE_INFINITY;
		double lastSlope = Double.NEGATIVE_INFINITY;

		for (int j = 0; j < lenOfSub; ++j) {
			checkForDuplicates(srtPoints, pointAfter[j]);
			slope = srtPoints.slopeTo(pointAfter[j]);
			if (lastSlope != slope) {
				if (cnt >= 3 && !isSubSgmt(slopeBefore, lastSlope)) {
					lineSgmts.add(new LineSegment(srtPoints, pointAfter[j - 1]));
				}
				cnt = 1;
			}
			else cnt++;
			lastSlope = slope;
		}

		if (cnt >= 3 && !isSubSgmt(slopeBefore, lastSlope)) {
			lineSgmts.add(new LineSegment(srtPoints, pointAfter[lenOfSub - 1]));
		}
	}

	private boolean isSubSgmt(double[] slopeBefore, double slope) {
		int lo = 0;
		int hi = slopeBefore.length - 1;

		while (lo <= hi) {
			int mid = lo + (hi - lo) / 2;
			if (slope < slopeBefore[mid]) hi = mid - 1;
			else if (slope > slopeBefore[mid]) lo = mid + 1;
			else return true;
		}
		return false;
	}

	public int numberOfSegments() {
		// the number of line segments
		return lineSgmts.size();
	}

	public LineSegment[] segments() {
		// the line segments
		return lineSgmts.toArray(new LineSegment[numberOfSegments()]);
	}

	private void checkForDuplicates(Point p, Point q) {
		if (p == null | q == null) throw new NullPointerException();
		if (p.compareTo(q) == 0) throw new IllegalArgumentException();
	}

	public static void main(String[] args) {
		In in  = new In(args[0]);
		int n = in.readInt();
		Point[] points = new Point[n];

		for (int i = 0; i < n; i++) {
			int x = in.readInt();
			int y = in.readInt();
			points[i] = new Point(x, y);
		}

		StdDraw.enableDoubleBuffering();
		StdDraw.setXscale(0, 32768);
		StdDraw.setYscale(0, 32768);

		for (Point p: points) {
			p.draw();
		}

		StdDraw.show();
		FastCollinearPoints collinear = new FastCollinearPoints(points);

		for (LineSegment segment: collinear.segments()) {
			StdOut.println(segment);
			segment.draw();
		}
		StdDraw.show();

	}
}
<file_sep>/CH1/README.md
# Examples and solutions for alg4 Chapter1

branch_name: refs/heads/master

languages: Java Markdown

repo_language: Java


text:
<repo_name>pratikpattanayak/Anagrams<file_sep>/README.md
# Anagrams
This code can find out if the two strings are anagrams or not.

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word anagram can be rearranged into nag a ram, or the word binary into brainy or the word adobe into abode.

repo_language: Markdown

repo_name: pratikpattanayak/Anagrams


text:
<repo_name>marlo2222/Covid-API<file_sep>/README.md
# API para dados de covid no Ceará. :bar_chart:

## Descrição do projeto :pencil2:

API que fornece a consulta aos dados disponibilizados pelo governo do ceará sobre a situação da covid no estado.

Entre as informações disponibizadas extraidas do CSV:
- Casos por municipios(confirmados, obitos, curados).
- Incidência de casos.
- Entre outras informações.

## Executando o projeto :rocket:

### Clone o repositorio:
execute `https://github.com/marlo2222/Covid-API.git`
`cd Covid-API`

### Executando e instalando depencias do projeto:

- `docker-compose build`

- `docker-compose up -d`

:warning: OBS :warning: Caso não tenha o `docker` ou `docker-compose` em sua maquina utilize o seguinte [tutorial](https://phoenixnap.com/kb/install-docker-compose-ubuntu) :thumbsup:.

:pushpin: OBS : Todas as dependências incluindo uma imagem `Golang` e um imagem do `Consul` já foram definidas no dockerfile e nos arquivos do docker-compose. :smile:

### Executando o Agente Consul :

dentro do container da imagem do consul execute:

- `consul agent -server -ui -bootstrap-expect 1 -data-dir /var/consul.d -config-dir /etc/consul.d -node consul-master -client 0.0.0.0`

:pushpin: OBS: para entrar no container onde está executandoa imagem consul você pode usar : `docker-compose exec {container} bash`

### Sugestões e melhorias: :heart:

- Está é a primeira versão do projeto. Uma serie de melhorias ainda precisam ser feitas.

- Em breve estarei disponibilizando uma doc para os endpoints disponíveis  bem como um `link` para acesso.

### este projeto foi realizado junto com os colegas:

- [<NAME>](https://github.com/ArturCRS) :octocat:
<file_sep>/consul/Dockerfile
FROM nginx:1.18.0-alpine
RUN apk update && apk add bash bind-tools vim curl
RUN wget https://releases.hashicorp.com/consul/1.7.2/consul_1.7.2_linux_amd64.zip
RUN unzip consul_1.7.2_linux_amd64.zip && mv consul /usr/bin && rm -f consul*
RUN mkdir /etc/consul.d && mkdir /var/consul.d<file_sep>/Dockerfile
FROM golang:onbuild

RUN cd ~
RUN apt update
RUN apt install vim -y
RUN apt install unzip -y
RUN wget https://releases.hashicorp.com/consul/1.7.2/consul_1.7.2_linux_amd64.zip
RUN unzip -f consul_1.7.2_linux_amd64.zip
RUN mv consul /usr/bin && rm -f consul*
RUN mkdir /etc/consul.d && mkdir /var/consul.d

EXPOSE 8080<file_sep>/main.go
package main

import (

	"encoding/csv"
	"fmt"
	"log"
	"net/http"
	"github.com/gorilla/mux"
	"os"
	"encoding/json"
	"reflect"
	"time"
	//"strings"
)

var casos = []dadosUsuario{}

func abrirCSV() [][]string{

	csvFile, err := os.Open("csv/casos_coronavirus.csv")

	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Successfully Opened CSV file")

	defer csvFile.Close()

	csvLines, err := csv.NewReader(csvFile).ReadAll()

	if err != nil {
		fmt.Println(err)
	}

	return csvLines
}

//preencho a lit
func preencherListCasos(){

	csvLines := abrirCSV()

	for _, line := range csvLines {
		caso := dadosUsuario{}

			caso.bairroPaciente = line[0]
			caso.CLASSIFICACAOESTADOSIVEP = line[1]
			caso.CODIGOMUNICIPIOPACIENTE = line[2]
			caso.CODIGOPACIENTE = line[3]
			caso.COMORBIDADEASMASIVEP = line[4]
			caso.COMORBIDADECARDIOVASCULARSIVEP = line[5]
			caso.COMORBIDADEDIABETESSIVEP = line[6]
			caso.COMORBIDADEHEMATOLOGIASIVEP = line[7]
			caso.COMORBIDADEIMUNODEFICIENCIASIVEP = line[8]
			caso.COMORBIDADENEUROLOGIASIVEP = line[9]
			caso.COMORBIDADEOBESIDADESIVEP = line[10]
			caso.COMORBIDADEPNEUMOPATIASIVEP = line[11]
			caso.COMORBIDADEPUERPERASIVEP = line[12]
			caso.COMORBIDADERENALSIVEP = line[13]
			caso.COMORBIDADESINDROMEDOWNSIVEP = line[14]
			caso.DATACOLETAEXAME = line[15]
			caso.DATAENTRADAUTISSVEP = line[16]
			caso.DATAEVOLUCAOCASOSIVEP = line[17]
			caso.DATAINICIOSINTOMAS = line[18]
			caso.DATAINTERNACAOSIVEP = line[19]
			caso.DATANOTIFICACAO = line[20]
			caso.DATAOBITO = line[21]
			caso.DATARESULTADOEXAME = line[22]
			caso.DATASAIDAUTISSVEP = line[23]
			caso.DATASOLICITACAOEXAME = line[24]
			caso.ESTADOPACIENTE = line[25]
			caso.EVOLUCAOCASOSIVEP = line[26]
			caso.IDADEPACIENTE = line[27]
			caso.IDSIVEP = line[28]
			caso.MUNICIPIOPACIENTE = line[29]
			caso.OBITOCONFIRMADO = line[30]
			caso.PAISPACIENTE = line[31]
			caso.RESULTADOFINALEXAME = line[32]
			caso.SEXOPACIENTE = line[33]

			casos = append(casos, caso)
	}
}

//quantidade casos investigação
func getAmoutCasosInvestigacao(w http.ResponseWriter, r *http.Request){
	if len(casos) == 0{
		preencherListCasos()
	}
	quantidade := 0
	for _, caso := range casos {
		if caso.RESULTADOFINALEXAME != "Em An�lise" {
			quantidade ++
		}
	}
	resultado := map[string]int{"casosInvestigados": quantidade}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//quantidade numero exames
func getAmoutNumeroExames(w http.ResponseWriter, r *http.Request){
	if len(casos) == 0{
		preencherListCasos()
	}
	quantidade := 0
	for _, caso := range casos {
		if caso.DATACOLETAEXAME != "" {
			quantidade ++
		}
	}
	resultado := map[string]int{"NumeroExames": quantidade}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//quantidade casos confirmados
func getAmoutCasosConfirmados(w http.ResponseWriter, r *http.Request){
	if len(casos) == 0{
		preencherListCasos()
	}
	quantidade := 0
	for _, caso := range casos {
		if caso.RESULTADOFINALEXAME == "Positivo" {
			quantidade ++
		}
	}
	resultado := map[string]int{"casosConfirmados": quantidade}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//quantidade casos confirmados municipio
func getAmoutCasosConfirmadosMunicipio(w http.ResponseWriter, r *http.Request){
	if len(casos) == 0{
		preencherListCasos()
	}
	municipio := mux.Vars(r)
	quantidade := 0
	for _, caso := range casos {
		if caso.RESULTADOFINALEXAME == "Positivo" && caso.MUNICIPIOPACIENTE == municipio["municipio"]{
			quantidade ++
		}
	}
	resultado := map[string]int{municipio["municipio"]: quantidade}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//obitos acumulados
func getAmoutObitosAcumulados(w http.ResponseWriter, r *http.Request){
	if len(casos) == 0{
		preencherListCasos()
	}
	quantidade := 0
	for _, caso := range casos {
		if (caso.OBITOCONFIRMADO == "true"){
			quantidade ++
		}
	}
	resultado := map[string]int{"obitosConfirmados": quantidade}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}
//obitos acumulados municipio
func getAmoutObitosAcumuladosMunicipio(w http.ResponseWriter, r *http.Request){
	if len(casos) == 0{
		preencherListCasos()
	}
	municipio := mux.Vars(r)
	quantidade := 0
	for _, caso := range casos {

		if (caso.OBITOCONFIRMADO == "true" && caso.MUNICIPIOPACIENTE == municipio["municipio"]){
			quantidade ++
		}
	}
	resultado := map[string]int{municipio["municipio"]: quantidade}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//obitos 24 horas
func getAmoutObitos24Horas(w http.ResponseWriter, r *http.Request){
	timeNow := time.Now()
	fmt.Println(timeNow.Format("2017-02-07"))
}

//letalidade
func getAmoutLetalidade(w http.ResponseWriter, r *http.Request){
	if len(casos) == 0{
		preencherListCasos()
	}
	numMortes := 0
	numCasos := 0
	for _, caso := range casos {
		if (caso.OBITOCONFIRMADO == "true"){
			numMortes ++
		}
		if caso.RESULTADOFINALEXAME == "Positivo" {
			numCasos ++
		}
	}
	letalidade := (float64(numMortes)/float64(numCasos)) *100
	resultado := map[string]float64{"Letalidade": letalidade}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//letalidade
func getAmoutCasosRecuperados(w http.ResponseWriter, r *http.Request){
	if len(casos) == 0{
		preencherListCasos()
	}
	quantidade := 0
	for _, caso := range casos {
		if (caso.DATASAIDAUTISSVEP != ""){
			quantidade ++
		}
	}
	resultado := map[string]int{"CasosRecuperados": quantidade}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//estou pegando somente os positivos por enquanto{a lista e muito grande}
func getAll(w http.ResponseWriter, r *http.Request) {

	if len(casos) == 0{
		preencherListCasos()
	}

	resultado := [] dadosUsuario{}
	for _, caso := range casos {
		resultado = append(resultado, caso)
	}

	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//preciso ver se retorno somente a quantidade
func getNumeroExames(w http.ResponseWriter, r *http.Request) {

}

//casos confirmados
func getCasosConfirmados(w http.ResponseWriter, r *http.Request) {

	if len(casos) == 0{
		preencherListCasos()
	}
	resultado := [] dadosUsuario{}
	for _, caso := range casos {
		if caso.RESULTADOFINALEXAME == "Positivo" {
			resultado = append(resultado, caso)
		}
	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//casos confimados por municipio
func getCasosConfirmadosMunicipio(w http.ResponseWriter, r *http.Request) {

	if len(casos) == 0{
		preencherListCasos()
	}
	municipio := mux.Vars(r)
	resultado := []dadosUsuario{}
	for _, caso := range casos {
		if (municipio["municipio"] == caso.MUNICIPIOPACIENTE){
			if (caso.RESULTADOFINALEXAME == "Positivo"){
				resultado = append(resultado, caso)
			}
		}
	}
	fmt.Println(reflect.TypeOf(resultado))
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//casos confirmados por sexo.
func getCasosConfirmadosPorSexo(w http.ResponseWriter, r *http.Request) {
	if len(casos) == 0{
		preencherListCasos()
	}
	sexo := mux.Vars(r)
	resultado := []dadosUsuario{}
	for _, caso := range casos {
		if (sexo["sexo"] == caso.SEXOPACIENTE){
			if (caso.RESULTADOFINALEXAME == "Positivo"){
				resultado = append(resultado, caso)
			}
		}
	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//casos investigação
func getCasosInvestigacao(w http.ResponseWriter, r *http.Request) {
	if len(casos) == 0{
		preencherListCasos()
	}
	resultado := []dadosUsuario{}
	for _, caso := range casos {
		if (caso.RESULTADOFINALEXAME == "Em An�lise"){
			resultado = append(resultado, caso)
		}

	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//casos comfirmados e investigação
func getCasosConfirmadosInvestigacao(w http.ResponseWriter, r *http.Request) {
	if len(casos) == 0{
		preencherListCasos()
	}
	resultado := []dadosUsuario{}
	for _, caso := range casos {
		if (caso.RESULTADOFINALEXAME == "Em An�lise" || caso.RESULTADOFINALEXAME == "Positivo"){
			resultado = append(resultado, caso)
		}
	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//obitos geral
func getAllObitos(w http.ResponseWriter, r *http.Request) {
	if len(casos) == 0{
		preencherListCasos()
	}

	resultado := []dadosUsuario{}
	for _, caso := range casos {
		if (caso.OBITOCONFIRMADO == "true"){
			resultado = append(resultado, caso)
		}

	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//obitos municipio
func getObitosMunicipio(w http.ResponseWriter, r *http.Request) {
	if len(casos) == 0{
		preencherListCasos()
	}
	municipio := mux.Vars(r)
	resultado := []dadosUsuario{}
	for _, caso := range casos {
		if (municipio["municipio"] == caso.MUNICIPIOPACIENTE){
			if (caso.OBITOCONFIRMADO == "true"){
				resultado = append(resultado, caso)
			}
		}
	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}
//não tem na planilha -> falta fazer
func getCasosRecuperados(w http.ResponseWriter, r *http.Request) {
	if len(casos) == 0{
		preencherListCasos()
	}
	resultado := []dadosUsuario{}
	for _, caso := range casos {
		if (caso.DATASAIDAUTISSVEP != ""){
			resultado = append(resultado, caso)
		}
	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//casos confirmados sexo
func getCasosPorSexo(w http.ResponseWriter, r *http.Request) {
	if len(casos) == 0{
		preencherListCasos()
	}
	sexo :=mux.Vars(r)
	resultado := []dadosUsuario{}

	for _, caso := range casos {
		if caso.SEXOPACIENTE == sexo["sexo"] {
			resultado = append(resultado, caso)
		}
	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}

//so confirmados data -> passa a data no formato "aaaa-mm-dd"
func getCasosConfirmadosData(w http.ResponseWriter, r *http.Request) {
	if len(casos) == 0{
		preencherListCasos()
	}
	data :=mux.Vars(r)
   	data["data"] = data["data"]+" 00:00:00.0"
	resultado := []dadosUsuario{}
	for _, caso := range casos {
		if (data["data"] == caso.DATARESULTADOEXAME){
			if (caso.OBITOCONFIRMADO == "true"){
				resultado = append(resultado, caso)
			}
		}
	}
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(resultado)
}
type casosPorSexo struct{
	IDADEPACIENTE string
	MUNICIPIOPACIENTE string
	RESULTADOFINALEXAME string
	SEXOPACIENTE string
}

type NumeroExames struct{
	quantidade int `json:"qtd,omitempty"`
	exames []Exame `json:"exames,omitempty"`
}

type Exame struct{
	DATACOLETAEXAME string `json:"datacoletaexame,omitempty"`
	DATASOLICITACAOEXAME string `json:"datasolicitacaoexame,omitempty"`
}

type dadosUsuario struct {
	bairroPaciente string `json:"bairropaciente,omitempty"`
	CLASSIFICACAOESTADOSIVEP string `json:"classificacaoestadosivep,omitempty"`
	CODIGOMUNICIPIOPACIENTE string `json:"codigomunicipiopaciente,omitempty"`
	CODIGOPACIENTE string `json:"codigopaciente,omitempty"`
	COMORBIDADEASMASIVEP string `json:"comorbidadeasmasivep,omitempty"`
	COMORBIDADECARDIOVASCULARSIVEP string `json:"comorbidadecardiovascularsivep,omitempty"`
	COMORBIDADEDIABETESSIVEP string `json:"comorbidadediabetessivep,omitempty"`
	COMORBIDADEHEMATOLOGIASIVEP string `json:"comorbidadehematologiasivep,omitempty"`
	COMORBIDADEIMUNODEFICIENCIASIVEP string `json:"comorbidadeimunodeficienciasivep,omitempty"`
	COMORBIDADENEUROLOGIASIVEP string `json:"comorbidadeneurologiasivep,omitempty"`
	COMORBIDADEOBESIDADESIVEP string `json:"comorbidadeobesidadesivep,omitempty"`
	COMORBIDADEPNEUMOPATIASIVEP string `json:"comorbidadepneumopatiasivep,omitempty"`
	COMORBIDADEPUERPERASIVEP string `json:"comorbidaderenalsivep,omitempty"`
	COMORBIDADERENALSIVEP string `json:"comorbidaderenalsivep,omitempty"`
	COMORBIDADESINDROMEDOWNSIVEP string `json:"comorbidadesindromedownsivep,omitempty"`
	DATACOLETAEXAME string `json:"datacoletaexame,omitempty"`
	DATAENTRADAUTISSVEP string `json:"dataentradautissvep,omitempty"`
	DATAEVOLUCAOCASOSIVEP string `json:"dataevolucaocasosivep,omitempty"`
	DATAINICIOSINTOMAS string `json:"datainiciosintomas,omitempty"`
	DATAINTERNACAOSIVEP string `json:"datainternacaosivep,omitempty"`
	DATANOTIFICACAO string `json:"datanotificacao,omitempty"`
	DATAOBITO string `json:"dataobito,omitempty"`
	DATARESULTADOEXAME string `json:"dataresultadoexame,omitempty"`
	DATASAIDAUTISSVEP string `json:"datasaidautissvep,omitempty"`
	DATASOLICITACAOEXAME string `json:"datasolicitacaoexame,omitempty"`
	ESTADOPACIENTE string `json:"estadopaciente,omitempty"`
	EVOLUCAOCASOSIVEP string `json:"evolucaocasosivep,omitempty"`
	IDADEPACIENTE string `json:"idadepaciente,omitempty"`
	IDSIVEP string `json:"idsivep,omitempty"`
	MUNICIPIOPACIENTE string `json:"municipiopaciente,omitempty"`
	OBITOCONFIRMADO string `json:"obitoconfirmado,omitempty"`
	PAISPACIENTE string `json:"paispaciente,omitempty"`
	RESULTADOFINALEXAME string `json:"resultadofinalexame,omitempty"`
	SEXOPACIENTE string `json:"sexopaciente,omitempty"`
	//34
}

func main() {
	rotas := mux.NewRouter().StrictSlash(true)

	rotas.HandleFunc("/covid", getAll).Methods("GET")
	rotas.HandleFunc("/covid/numeroExames", getNumeroExames).Methods("GET")
	rotas.HandleFunc("/covid/casosConfirmados", getCasosConfirmados).Methods("GET")
	rotas.HandleFunc("/covid/casosConfirmados/{municipio}", getCasosConfirmadosMunicipio).Methods("GET")
	rotas.HandleFunc("/covid/casosConfirmadosSexo/{sexo}", getCasosConfirmadosPorSexo).Methods("GET")
	rotas.HandleFunc("/covid/casosInvestigacao", getCasosInvestigacao).Methods("GET")
	rotas.HandleFunc("/covid/casosConfirmadosInvestigacao", getCasosConfirmadosInvestigacao).Methods("GET")
	rotas.HandleFunc("/covid/obitos", getAllObitos).Methods("GET")
	rotas.HandleFunc("/covid/obitos/{municipio}", getObitosMunicipio).Methods("GET")
	rotas.HandleFunc("/covid/casosRecuperados", getCasosRecuperados).Methods("GET")
	rotas.HandleFunc("/covid/casos/{sexo}", getCasosPorSexo).Methods("GEt")
	rotas.HandleFunc("/covid/casosConfimadosData/{data}", getCasosConfirmadosData).Methods("GEt")
	//casos por sexo, por idade, por municipio. falta corrigir a questão de organizar as
	//requests por quantidade
	rotas.HandleFunc("/covid/getAmoutCasosInvestigacao", getAmoutCasosInvestigacao).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutNumeroExames", getAmoutNumeroExames).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutObitosAcumulados", getAmoutObitosAcumulados).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutObitosAcumuladosMunicipio/{municipio}", getAmoutObitosAcumuladosMunicipio).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutCasosConfirmados", getAmoutCasosConfirmados).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutCasosConfirmadosMunicipio", getAmoutCasosConfirmadosMunicipio).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutLetalidade", getAmoutLetalidade).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutNumeroExames", getAmoutNumeroExames).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutObitos24Horas", getAmoutObitos24Horas).Methods("GEt")
	rotas.HandleFunc("/covid/getAmoutCasosRecuperados", getAmoutCasosRecuperados).Methods("GEt")

	var port = ":8080"
	fmt.Println("Server running in port:", port)
	log.Fatal(http.ListenAndServe(port, rotas))

}

languages: Markdown Dockerfile Go


text:
<repo_name>thisjeremiah/gitlab<file_sep>/lib/publish.js
const urlJoin = require('url-join');
const got = require('got');
const fs = require('fs');
const FormData = require('form-data');
const debug = require('debug')('semantic-release:gitlab');
const resolveConfig = require('./resolve-config');
const getRepoId = require('./get-repo-id');

module.exports = async (pluginConfig, context) => {
  const {
    cwd,
    options: {repositoryUrl},
    nextRelease: {gitTag, gitHead, notes},
    logger,
  } = context;
  const {gitlabToken, gitlabUrl, gitlabApiPathPrefix, files} = resolveConfig(pluginConfig, context); // pass-in files
  const repoId = getRepoId(gitlabUrl, repositoryUrl);
  const encodedRepoId = encodeURIComponent(repoId);
  const apiUrl = urlJoin(gitlabUrl, gitlabApiPathPrefix);
  const encodedGitTag = encodeURIComponent(gitTag);

  debug('repoId: %o', repoId);
  debug('release name: %o', gitTag);
  debug('release ref: %o', gitHead);

  debug('Update git tag %o with commit %o and release description', gitTag, gitHead);

  const fileObjects = [];
  for (file of files) {
    debug('Upload file: %o', `${cwd}/${file}`);
    const form = new FormData();
    form.append('file', fs.createReadStream(`${cwd}/${file}`));
    try {
      const response = await got.post(
        urlJoin(apiUrl, `/projects/${encodedRepoId}/uploads`),
        {
          headers: {
            'PRIVATE-TOKEN': gitlabToken
          },
          body: form,
        },
      );
      debug('Response data: %o', response.body);
      const fileObject = JSON.parse(response.body);
      fileObjects.push(fileObject);
    } catch (e) {
      console.error(e);
    }
  }

  const notesWithFiles = fileObjects.reduce((acc, fileObject) => {
    return `${acc}<br/>${fileObject.markdown}`
  }, notes)

  await got.post(urlJoin(apiUrl, `/projects/${encodedRepoId}/repository/tags/${encodedGitTag}/release`), {
    json: true,
    headers: {'PRIVATE-TOKEN': gitlabToken},
    body: {
      tag_name: gitTag,
      description: notesWithFiles
    }, // eslint-disable-line camelcase
  });

  logger.log('Published GitLab release: %s', gitTag);

  return {url: urlJoin(gitlabUrl, encodedRepoId, `/tags/${encodedGitTag}`), name: 'GitLab release'};
};

repo_language: JavaScript

repo_name: thisjeremiah/gitlab


text:
<file_sep>mib
---
google cloud project name: useful-mile-644 (Pipeline!)
+ deploys source only.

repo_name: mattisbusycom/cakephp


text:
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Evaluator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world!\n");

            List<string> testCases = new List<string> {
                                        null,
                                        "",
                                        " ",
                                        "aaa",
                                        "1+1a",
                                        "1+2+3",
                                        "2-2+3",
                                        "2*4",
                                        "sqrt(4)",
                                        "2^2",
                                        "2^2+3*6",
                                        "2+4/sqrt(4)-4",
                                        "sqrt(4)+sqrt(4)"
            };

            /**
             * Precedence is as follows:
             *
             * 1.) Square root
             * 2.) Exponent
             * 3.) Multiplication
             * 4.) Division
             * 5.) Addition
             * 6.) Subtraction
             *
             * NOTE: This program cannot handle spaces within a math expression.
             *       This program cannot handle expression with open and closed parentheses.
             **/

            Console.WriteLine(Evaluator.evaluate("2-2+3"));

            foreach (string s in testCases)
            {
                try
                {
                    Console.WriteLine("The expression: " + s);
                    Console.WriteLine("The answer is " + Evaluator.evaluate(s) + "\n");
                }
                catch (InvalidFormat e)
                {
                    Console.WriteLine(e.Message + "\n");
                }
            }
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Evaluator
{
    public class Evaluator
    {
        public enum Operation
        {
            ADDITION,
            SUBSTRACTION,
            MULTIPLICATION,
            DIVISION,
            POWER,
            SQUAREROOT
        }

        /**
         * Evaluates the string and returns an mathematical answer if possible
         **/
        public static double evaluate(String inputString)
        {
            double result = 0;

            if (String.IsNullOrWhiteSpace(inputString))
            {
                return result;
            }

            List<string> expression = split(inputString);
            List<string> updatedExpression = new List<string>();

            /**
             * Precedence is as follows:
             *
             * 1.) Square root
             * 2.) Exponent
             * 3.) Multiplication
             * 4.) Division
             * 5.) Addition
             * 6.) Subtraction
             **/

            int i = 0;
            foreach (string s in expression)
            {
                if (s.Length > 3)
                {
                    if (s.Substring(0, 4).Equals(getOperationSign(Operation.SQUAREROOT)))
                    {
                        double x = 0;
                        string temp = s.Substring(5);
                        temp = temp.Remove(temp.Length - 1);

                        if (double.TryParse(temp, out x))
                        {
                            double answer = squareRoot(x);
                            updatedExpression.Add(answer.ToString());
                        }
                    }
                }
                else
                {
                    updatedExpression.Add(s);
                }
            }

            expression = updatedExpression;

            while (hasOperation(Operation.POWER, expression))
            {
                calculate(Operation.POWER, expression);
            }

            while (hasOperation(Operation.MULTIPLICATION, expression))
            {
                calculate(Operation.MULTIPLICATION, expression);
            }

            while (hasOperation(Operation.DIVISION, expression))
            {
                calculate(Operation.DIVISION, expression);
            }

            while (hasOperation(Operation.ADDITION, expression))
            {
                calculate(Operation.ADDITION, expression);
            }

            while (hasOperation(Operation.SUBSTRACTION, expression))
            {
                calculate(Operation.SUBSTRACTION, expression);
            }

            if (expression.Count == 1)
            {
                double.TryParse(expression[0], out result);
                return result;
            }
            else
            {
                throw new InvalidFormat("Invalid Format!");
            }
        }

        /**
         * Returns a string representation of the operation
         **/
        public static string getOperationSign(Operation operation)
        {
            switch (operation)
            {
                case Operation.ADDITION:
                    return "+";
                case Operation.SUBSTRACTION:
                    return "-";
                case Operation.MULTIPLICATION:
                    return "*";
                case Operation.DIVISION:
                    return "/";
                case Operation.POWER:
                    return "^";
                case Operation.SQUAREROOT:
                    return "sqrt";
                default:
                    return "";
            }
        }

        /**
         * Returns true if the operation is present within the expression.
         * Returns false otherwise.
         **/
        public static bool hasOperation(Operation operation, List<string> expression)
        {
            // Checks if the occurence of the operation is within the expression.
            //
            // The checking of square root operation is excluded because in the split function,
            // The somewhat regex of it is sqrt(1~9), thus cannot be handled easily by the Contains function

            if (expression.Contains(getOperationSign(operation)))
            {
                return true;
            }
            else
            {
                foreach (string s in expression)
                {
                    if (s.Length > 3)
                    {
                        if (s.Substring(0, 4).Equals(getOperationSign(Operation.SQUAREROOT)))
                        {
                            return true;
                        }
                    }
                }

                return false;
            }
        }

        /**
         * Calculates the expression based on the operations except the square root functionality.
         * */
        public static void calculate(Operation operation, List<string> expression)
        {
            int i = 0;
            while (i < expression.Count)
            {
                if (expression[i].Equals(getOperationSign(operation)))
                {
                    double x = 0, y = 0;
                    if (double.TryParse(expression[i - 1], out x) && double.TryParse(expression[i + 1], out y))
                    {
                        double answer = 0;

                        switch (operation)
                        {
                            case Operation.ADDITION:
                                answer = add(x, y);
                                break;
                            case Operation.SUBSTRACTION:
                                answer = subtract(x, y);
                                break;
                            case Operation.MULTIPLICATION:
                                answer = multiply(x, y);
                                break;
                            case Operation.DIVISION:
                                answer = divide(x, y);
                                break;
                            case Operation.POWER:
                                answer = raiseToExponent(x, y);
                                break;
                        }

                        // Remove the evaluated expression and replace it with the answer
                        expression.RemoveAt(i - 1);
                        expression.RemoveAt(i - 1);
                        expression.RemoveAt(i - 1);
                        expression.Insert(i - 1, answer.ToString());
                        i += 2;
                    }
                }
                else
                {
                    i++;
                }
            }
        }

        /**
         * Splits the input string into a list.
         **/
        public static List<string> split(string inputString)
        {
            List<string> result = new List<string>();

            char[] charArray = inputString.ToCharArray();
            char[] operators = { '+', '-', '*', '/', '^' };

            int i = 0;
            while (i < charArray.Length)
            {
                char c = charArray[i];

                if (Char.IsDigit(c))
                {
                    string digit = "" + c;
                    i += 1;
                    while (i < charArray.Length)
                    {
                        if (Char.IsDigit(charArray[i]))
                        {
                            digit += charArray[i];
                            ++i;
                        }
                        else
                        {
                            break;
                        }
                    }
                    result.Add(digit);
                }
                else if (operators.Contains(c))
                {
                    result.Add(c.ToString());
                    ++i;
                }
                else if (c.Equals('s'))
                {
                    if ((charArray.Length - (i + 1)) > 5)// smallest possible size is 7 characters : sqrt(x)
                    {
                        string s = c + "" + charArray[i + 1] + "" + charArray[i + 2] + "" + charArray[i + 3] + "" + charArray[i + 4]; // s q r t (
                        i += 5;

                        if (s.Equals("sqrt("))
                        {
                            if (Char.IsDigit(charArray[i]))
                            {
                                string paramValue = "" + charArray[i];
                                i += 1;
                                while (i < charArray.Length)
                                {
                                    if (Char.IsDigit(charArray[i]))
                                    {
                                        paramValue += charArray[i];
                                        ++i;
                                    }
                                    else
                                    {
                                        if (paramValue.Length > 0 && charArray[i].Equals(')'))
                                        {
                                            // By this point s should be "sqrt(x)"
                                            s += paramValue + "" + charArray[i].ToString();
                                            result.Add(s);
                                            ++i;
                                        }
                                        else
                                        {
                                            throw new InvalidFormat("Invalid Format!");
                                        }

                                        break;
                                    }
                                }
                            }
                            else
                            {
                                throw new InvalidFormat("Invalid Format!");
                            }
                        }
                    }
                    else
                    {
                        throw new InvalidFormat("Invalid Format!");
                    }

                }
                else
                {
                    throw new InvalidFormat("Invalid Format!");
                }
            }

            return result;
        }

        public static double add(double x, double y)
        {
            return x + y;
        }

        public static double subtract(double x, double y)
        {
            return x - y;
        }

        public static double multiply(double x, double y)
        {
            return x * y;
        }

        public static double divide(double x, double y)
        {
            if (y == 0)
            {
                throw new DivideByZeroException();
            }
            return x / y;
        }

        public static double raiseToExponent(double x, double y)
        {
            return Math.Pow(x, y);
        }

        public static double squareRoot(double x)
        {
            return Math.Sqrt(x);
        }

    }
}

repo_language: C#

repo_name: aamoreno/Evaluator


text:
<repo_name>sgonzalezlopez/coursera-test<file_sep>/module4_solution/src/menuapp/menu.controller.js
(function () {
'use strict';

angular.module('MenuApp')
.controller('MenuController', MenuController);

MenuController.$inject = ['items'];
function MenuController(items) {
  var menu = this;
  menu.categories = items;
}

})();
<file_sep>/module5_solution/src/public/signup/signup.controller.js
(function () {

angular.module('public')
.controller('SignupController', SignupController);

SignupController.$inject = ['MenuService', 'UserService'];
function SignupController(MenuService, UserService) {
  var signup = this;
  signup.completed = false;
  signup.errorMessage = "";

  signup.validateFav = function () {
    if (signup.user && signup.user.favdish) {
      var promise = MenuService.getItem(signup.user.favdish);
      promise.then(function (response) {
        if (!response) {
          signup.errorMessage = "No such menu number exists"
        }
        else {
          signup.errorMessage = ""
        }
      })
      .catch(function (error) {
        signup.errorMessage = "No such menu number exists"
      })
    }
  };

  signup.submit = function () {
    var promise = MenuService.getItem(signup.user.favdish);
    promise.then(function (response) {
      if (!response) {
        signup.completed = false;
        signup.errorMessage = "No such menu number exists"
      }
      else {
        signup.completed = true;
        var user = {
          firstName : signup.user.firstname,
          lastName : signup.user.lastname,
          email : signup.user.email,
          phone : signup.user.phone,
          favouriteDish : response
        };

        UserService.user = user;
        signup.errorMessage = ""
    }
      })
      .catch(function (error) {
        signup.completed = false;
        signup.errorMessage = "No such menu number exists"
      })
    };
};
})();
<file_sep>/module1_solution/app.js
(function () {
'use strict';

angular.module('LunchCheck', [])
.controller('LunchCheckController', LunchCheckController);

LunchCheckController.$inject = ['$scope'];
function LunchCheckController($scope) {
  $scope.lunchDescription = ""; // Field to store and link user entry
  $scope.message = "";          // Field to store output message
  $scope.msgStyle = "";         // Field to store message styles
  $scope.txtStyle = "";         // Field to store textBox styles

  $scope.processLunch = function () {
    // Calculate the number of items on the lunch description
    var numItems = calculateItems($scope.lunchDescription);

    // Evaluates the outputs (message and styles) depending on the number of items.
    if (numItems == 0) {      // In case empty string as imput
      $scope.message = "Please enter data first";
      $scope.msgStyle = {"color" : "red"};
      $scope.txtStyle = {"border-color" : "red"};
    }
    else if (numItems <= 3) { // Less or equal than the required limit
      $scope.message = "Enjoy!";
      $scope.msgStyle = {"color" : "green"};
      $scope.txtStyle = {"border-color" : "green"};
    }
    else {                    // More items than the minimum number
      $scope.message = "Too Much!";
      $scope.msgStyle = {"color" : "green"};
      $scope.txtStyle = {"border-color" : "green"};
    }
  };
}

function calculateItems(string) {
  var numItems = 0;

  // In case the string is not empty, we calculate the number of items. Otherwise, the result is 0.
  if (string != "") {
    var items = string.split(',');

    // Checks if items are different than '' and does NOT considered empty items.
    var i;
    for (i = 0; i < items.length; i++) {
      if (items[i].trim() != "") numItems++;  // If the item is empty or with spaces, it is not considered.
    }
  }
  return numItems;
}

})();
<file_sep>/module5_solution/src/public/my-info/my-info.controller.js
(function () {

angular.module('public')
.controller('MyInfoController', MyInfoController);

MyInfoController.$inject = ['UserService'];
function MyInfoController(UserService) {
  var myInfo = this;
  myInfo.user = UserService.user;

}

})();

repo_name: sgonzalezlopez/coursera-test


text:
<file_sep>/**
 *
 */
(function(angular) {

  angular.module('queryloader.controllers', [])
    .controller('QueryJobsController', [ '$scope', 'DataService', function($scope, DataService) {
      $scope.json = true;

      $scope.setData = function(data) {
        $scope.data = data;
      };

      $scope.getData = function() {
        console.log(DataService.getData());
        return DataService.getData();
      };

      var activate = function() {
        $scope.getData().success(function(data) {
          console.log(data);
          $scope.setData(data);
        });
      };

      activate();

    }]);
}(angular));<file_sep>/**
 *
 */
(function(angular) {

  var PageFactory = function() {
    var title = 'QueryLoader';
    var page = 'Home Page';
    var subtitle = 'What would you like to do?';

    return {
      getTitle: function() {
        return title;
      },
      setTitle: function(newTitle) {
        title = newTitle;
      },
      getPage: function() {
        return page;
      },
      setPage: function(newPage) {
        page = newPage;
      },
      getSubtitle: function() {
        return subtitle;
      },
      setSubtitle: function(newSubtitle) {
        subtitle = newSubtitle;
      }
    };
  };

  var DataFactory = function($http) {

    return {
      getData: function() {
        return $http.get('/queryjobs/status');
      }
    };
  }

  angular.module("queryloader.services", [])
    .factory('PageService', PageFactory)
    .factory('DataService', ['$http', DataFactory]);
} (angular));<file_sep>/**
 *
 */
(function(angular){
  angular.module('queryloader.routes', [])
    .config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/home');

    $urlRouterProvider.when('/queries', '/queries/json');

    $stateProvider
      .state('home', {
        url: '/home',
        templateUrl: 'app/partials/partial-home.html',
        controller: function($scope, PageService) {
          PageService.setPage("Home Page");
          PageService.setSubtitle("What would you like to do?");
        }
      })
      .state('queries', {
        url: '/queries',
        templateUrl: 'app/partials/partial-queries.html',
        controller: 'QueryJobsController'
      })
      .state('queries.json', {
        url: '/json',
        templateUrl: 'app/partials/partial-queries-json.html',
        controller: 'QueryJobsController'
      })
      .state('queries.table', {
        url: '/table',
        templateUrl: 'app/partials/partial-queries-table.html',
        controller: 'QueryJobsController'
      });
  });
} (angular));<file_sep>/**
 *
 */
(function(angular){

  angular.module('queryloader', ['ui.router', 'queryloader.routes', 'queryloader.controllers', 'queryloader.services']);

}(angular));<file_sep>package com.ijdanks.queryloader.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class QueryStats {

    @Id
    @GeneratedValue
    private Integer id;

    @Column
    private Integer queryId;

    @Column
    private String userid;

    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date datetimeSubmitted;

    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date datetimeFinished;

    @Column
    private Integer queryTime;

    /**
     * @return the id
     */
    public final Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public final void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return the queryId
     */
    public final Integer getQueryId() {
        return queryId;
    }

    /**
     * @return the userid
     */
    public final String getUserid() {
        return userid;
    }

    /**
     * @param userid the userid to set
     */
    public final void setUserid(String userid) {
        this.userid = userid;
    }

    /**
     * @param queryId the queryId to set
     */
    public final void setQueryId(Integer queryId) {
        this.queryId = queryId;
    }

    /**
     * @return the datetimeSubmitted
     */
    public final Date getDatetimeSubmitted() {
        return datetimeSubmitted;
    }

    /**
     * @param datetimeSubmitted the datetimeSubmitted to set
     */
    public final void setDatetimeSubmitted(Date datetimeSubmitted) {
        this.datetimeSubmitted = datetimeSubmitted;
    }

    /**
     * @return the datetimeFinished
     */
    public final Date getDatetimeFinished() {
        return datetimeFinished;
    }

    /**
     * @param datetimeFinished the datetimeFinished to set
     */
    public final void setDatetimeFinished(Date datetimeFinished) {
        this.datetimeFinished = datetimeFinished;
    }

    /**
     * @return the queryTime
     */
    public final Integer getQueryTime() {
        return queryTime;
    }

    /**
     * @param queryTime the queryTime to set
     */
    public final void setQueryTime(Integer queryTime) {
        this.queryTime = queryTime;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((datetimeFinished == null) ? 0 : datetimeFinished.hashCode());
        result = prime * result + ((datetimeSubmitted == null) ? 0 : datetimeSubmitted.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((queryId == null) ? 0 : queryId.hashCode());
        result = prime * result + ((queryTime == null) ? 0 : queryTime.hashCode());
        result = prime * result + ((userid == null) ? 0 : userid.hashCode());
        return result;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        QueryStats other = (QueryStats) obj;
        if (datetimeFinished == null) {
            if (other.datetimeFinished != null) {
                return false;
            }
        } else if (!datetimeFinished.equals(other.datetimeFinished)) {
            return false;
        }
        if (datetimeSubmitted == null) {
            if (other.datetimeSubmitted != null) {
                return false;
            }
        } else if (!datetimeSubmitted.equals(other.datetimeSubmitted)) {
            return false;
        }
        if (id == null) {
            if (other.id != null) {
                return false;
            }
        } else if (!id.equals(other.id)) {
            return false;
        }
        if (queryId == null) {
            if (other.queryId != null) {
                return false;
            }
        } else if (!queryId.equals(other.queryId)) {
            return false;
        }
        if (queryTime == null) {
            if (other.queryTime != null) {
                return false;
            }
        } else if (!queryTime.equals(other.queryTime)) {
            return false;
        }
        if (userid == null) {
            if (other.userid != null) {
                return false;
            }
        } else if (!userid.equals(other.userid)) {
            return false;
        }
        return true;
    }

}
<file_sep>package com.ijdanks.queryloader.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.query.Param;

import com.ijdanks.queryloader.model.QueryJobStatus;
import com.ijdanks.queryloader.model.QueryJobStatus.Status;

public interface QueryJobStatusRepository extends JpaRepository<QueryJobStatus, Integer>,
    QueryDslPredicateExecutor<QueryJobStatus> {

    List<QueryJobStatus> findByUseridOrderByIdAsc(final String userid);

    List<QueryJobStatus> findByStatusIn(final List<Status> status);

    @Query("SELECT job FROM QueryJobStatus job WHERE job.id NOT IN(SELECT stats.queryId "
            + "FROM QueryStats stats) AND job.status IN(:status)")
    List<QueryJobStatus> findNewFinishedQueries(@Param("status") final List<Status> status);
}
<file_sep>spring.datasource.url=jdbc:mysql://localhost/web_db
spring.datasource.username=web_db_user
spring.datasource.password=<PASSWORD>

http.mappers.json-pretty-print=true
<file_sep>package com.ijdanks.queryloader.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class QueryJobStatus {

    public enum Status {
        IN_PROGRESS,
        FINISHED,
        CANCELLED
    }

    @Id
    @GeneratedValue
    private Integer id;

    @Column
    private String userid;

    @Column
    private String tableName;

    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date datetimeSubmitted;

    @Column
    private String query;

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition = "ENUM('IN_PROGRESS','FINISHED','CANCELLED')")
    private Status status;

    @Column
    private Integer numResults;

    /**
     * @return the id
     */
    public final Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public final void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return the userid
     */
    public final String getUserid() {
        return userid;
    }

    /**
     * @param userid the userid to set
     */
    public final void setUserid(String userid) {
        this.userid = userid;
    }

    /**
     * @return the tableName
     */
    public final String getTableName() {
        return tableName;
    }

    /**
     * @param tableName the tableName to set
     */
    public final void setTableName(String tableName) {
        this.tableName = tableName;
    }

    /**
     * @return the datetimeSubmitted
     */
    public final Date getDatetimeSubmitted() {
        return datetimeSubmitted;
    }

    /**
     * @param datetimeSubmitted the datetimeSubmitted to set
     */
    public final void setDatetimeSubmitted(Date datetimeSubmitted) {
        this.datetimeSubmitted = datetimeSubmitted;
    }

    /**
     * @return the query
     */
    public final String getQuery() {
        return query;
    }

    /**
     * @param query the query to set
     */
    public final void setQuery(String query) {
        this.query = query;
    }

    /**
     * @return the status
     */
    public final Status getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public final void setStatus(Status status) {
        this.status = status;
    }

    /**
     * @return the numResults
     */
    public final Integer getNumResults() {
        return numResults;
    }

    /**
     * @param numResults the numResults to set
     */
    public final void setNumResults(Integer numResults) {
        this.numResults = numResults;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((datetimeSubmitted == null) ? 0 : datetimeSubmitted.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((numResults == null) ? 0 : numResults.hashCode());
        result = prime * result + ((query == null) ? 0 : query.hashCode());
        result = prime * result + ((status == null) ? 0 : status.hashCode());
        result = prime * result + ((tableName == null) ? 0 : tableName.hashCode());
        result = prime * result + ((userid == null) ? 0 : userid.hashCode());
        return result;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        QueryJobStatus other = (QueryJobStatus) obj;
        if (datetimeSubmitted == null) {
            if (other.datetimeSubmitted != null) {
                return false;
            }
        } else if (!datetimeSubmitted.equals(other.datetimeSubmitted)) {
            return false;
        }
        if (id == null) {
            if (other.id != null) {
                return false;
            }
        } else if (!id.equals(other.id)) {
            return false;
        }
        if (numResults == null) {
            if (other.numResults != null) {
                return false;
            }
        } else if (!numResults.equals(other.numResults)) {
            return false;
        }
        if (query == null) {
            if (other.query != null) {
                return false;
            }
        } else if (!query.equals(other.query)) {
            return false;
        }
        if (status != other.status) {
            return false;
        }
        if (tableName == null) {
            if (other.tableName != null) {
                return false;
            }
        } else if (!tableName.equals(other.tableName)) {
            return false;
        }
        if (userid == null) {
            if (other.userid != null) {
                return false;
            }
        } else if (!userid.equals(other.userid)) {
            return false;
        }
        return true;
    }
}

languages: Java JavaScript INI

repo_name: ijdanks/queryloader


text:
<file_sep># Hybrid_Astar
Motion-Planning and Control of an Autonomous car using the Hybrid A* algorithm


text:
<repo_name>aparker8/open-austin.github.io<file_sep>/README.md
# open-austin.org

### The Open Austin website

- [How to Draft a Blog Post](https://github.com/open-austin/open-austin.github.io/wiki/How-to-Draft-a-Blog-Post)
- [Development Instructions](#development-instructions)
- [Planning](#planning)
- [License](#license)

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

# Development Instructions
- *(Optional)* Install [**iTerm**](https://www.iterm2.com/) for a better Command Line App in OS X.
- _(Optional)_ Install [**oh-my-zsh**](https://github.com/robbyrussell/oh-my-zsh
) for a prettier command line interface and easier zsh configuration than bash.
	- `sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"`

Jekyll requires at least Ruby 2.1 but we recommend Ruby 2.4+

You can install a proper version of Ruby via homebrew and rbenv.

# Install command line tools if you haven't
xcode-select --install

# Install Homebrew if you haven't
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

# Install rbenv and ruby
brew install rbenv ruby-build
rbenv init
rbenv install 2.4.2
rbenv global 2.4.2
rbenv shell 2.4.2

# Install bundler and jekyll
- Install [**jekyll**](https://github.com/postmodern/chruby) to install Jekyll.
	- `gem install jekyll`

gem install jekyll bundler

# update rbenv config
rbenv rehash
eval "$(rbenv init -)

# Run all of the above using one command:
curl https://gist.githubusercontent.com/DirtyF/5d2bde5c682101b7b5d90708ad333bf3/raw/bbac59647ac66016cf443caf7d48c6ae173ae57f/setup-rbenv.sh | bash

## Start Jekyll

Once you've got everything installed, run

```
jekyll serve --incremental --watch --trace
```

Then go to

```
http://localhost:4000/
```

### Instructions for exporting content from Wordpress

```
gem install jekyll-import hpricot open_uri_redirections
ruby -rubygems -e 'require "jekyll-import";
    JekyllImport::Importers::WordpressDotCom.run({
      "source" => "import/openaustin.wordpress.2015-11-21.xml",
      "no_fetch_images" => false,
      "assets_folder" => "assets"
    })'
```

## Troubleshooting
* if you get permissions errors, run the command again with 'sudo'
```
sudo <your> <command here>
```
--------------------

# Planning

Staging Site: http://open-austin.github.io/

## Planning & Design
### Sitemap

![our sitemap](planning-design/site_architecture/oa-sitemap.png?raw=true)
[link to Gliffy](http://www.gliffy.com/go/publish/8981187)

### Design Docs
[Design Brief](planning-design/planning_and_analytics/OA Design Brief.pdf?raw=true)

[Colors/Typography](planning-design/typography/colorstypography2.png?raw=true)

### Mockups
[Homepage Mockups from 1-Sept](planning-design/final_mockups/oa_homepage_mockup.pdf?raw=true)

Higher fidelity Mockup from 24-Aug Meeting ([PDF](planning-design/other_mockups/OA Homepage 1.pdf?raw=true) AND [Sketch](planning-design/other_mockups/OA Homepage 1.sketch?raw=true))

[Original Lo-fi Mockup](planning-design/planning_and_analytics/lo-fi-mockup.jpg?raw=true)

### Requirements
[Link to functional requirements doc](https://docs.google.com/document/d/1dgYQunemFzfGPpmc6jJz5L1sCm0m7f9ZemPT0z6FK2c)

### Assets/Images
[Links to potential assets/images](https://github.com/open-austin/OA-Website/wiki/Assets-&-Images-for-potential-use)

# License

The code for this repository has been released into the public domain by Open Austin via the Unlicense.
<file_sep>/_projects/influence-texas.md
---
title:        Influence Texas
description:  Campaign finance, lobbying, and voting records all in one app.
access_at:    https://www.influencetexas.com/
project_at:   https://github.com/open-austin/influence-texas/
type:         website
status:       deployed
categories:   [ politics, campaign finance ]
contact:      <NAME> <	<EMAIL> >
cfa_stage:    beta
date:         2018-09-13 00:00:00
thumb:        influenceTX.png
screenshot:   influenceTX-screenshot.png
featured:     true
---


text:
<repo_name>fullstack-raghve/js-ds-algo<file_sep>/missingNo/index.js
//find missing no-
//i solved this problem - jgm nkb bbb shri ram
//first think basic logic
let arr = [1,2,3,5,6,7,8,10];
let emptyarry = []
function findMiss(arr){
for(let i=0;i<arr.length-1;i++){
    isExist = false;

       if(arr[i]+1 === arr[i+1]){
           isExist = true
           //break
      //  console.log(arr[i]+1 === arr[i+1])
       }
       if(!isExist){
        emptyarry.push(arr[i]+1)
       }
    }
}

let miss = findMiss(arr)
console.log(emptyarry)
<file_sep>/sumZero/sumzero.js
//find no. in an array , whom total is zero.
let array = [-2,-4,-3,2,3,4,5];
let pairArry = []
let map = {} // let some more
function getPairZero(array){
for(let i =0;i<array.length;i++){
    for(let j =1;j<array.length;j++){
     if(array[i]+array[j] === 0){
    // return [array[i],array[j]] //it return first match
    //pairArry.push(array[i],array[j]); //it will push all combination-repeat
     if(map[array[i]] && map[array[j]]){
         continue
     }else{
        pairArry.push(array[i],array[j]); //here no dulplication
        map[array[i]]  = true;
        map[array[j]] = true;
     }
     }
    }
}
}
///this solution has time complexity of quardatic 0*n2

let result = getPairZero(array);
console.log(result);
console.log(pairArry);
//console.log(map);<file_sep>/LEETCODE/usingmap.js
//time complexity == 0(n)

//[2,7,11,15],  t=9
//t-num
//we are saving complimnt nd index of that
// {
// 7:0
// }
 function twoSum(nums,target){
    let comp =new Map();
    const len = nums.length;

    for(let i = 0;i<len;i++){

        if(comp[nums[i]]>=0){ //ching in comp if no.exist,and this is the way to chck for no.

            return [comp[nums[i]],i]

}
        comp[target-nums[i]] = i;//saving index as value

    }
  return [];
    //console.log(comp); //first step to understand chk only this
}
const numss = [2,7,11,15];
//twoSum(numss,9)
console.log(twoSum(numss,9))
<file_sep>/findeven/even.js
//find even of a number

const number = [2,1,3,6,9,22,14,16]
let evennum = [];
let oddnum = [];
for(let num of number){
   // console.log('num',num)
    if(num%2 === 0){
        evennum.push(num);
        //console.log('even num',num)
        console.log('even num arr',evennum)

    }else{
        oddnum.push(num);
        console.log('odd num arr',oddnum)

    }
}<file_sep>/Fibonacci/index.js
//Q2: Return the N-th value of the Fibonacci sequence Recursively
//Recursive solution looks pretty simple (see code).
//https://www.fullstack.cafe/blog/fibonacci-interview-questions
//Let’s look at the diagram that will help you understand what’s going on here with the rest of our code. Function fib is called with argument 5:

//Complexity Analysis O(2^n) Exponential
//note-
//In case of recursion the solution take exponential time, that can be explained by the fact that the size of the tree exponentially grows when n increases. So for every additional element in the Fibonacci sequence we get an increase in function calls. Big O in this case is equal to O(2n). Exponential Time complexity denotes an algorithm whose growth doubles with each addition to the input data set.
// function fibonacci(n){
//     if(n<=1)
//       return n;
//     else
//       return fibonacci(n-1) + fibonacci (n-2);
//   }

function fib(n) {
    if (n < 2){
      return n
    }
    return fib(n - 1) + fib (n - 2)
  }
//console.log(fib(5)) ////0 1 1 2 3 //value of 5th index
//console.log(fib(4)) ////0 1 1 2
//console.log(fib(6)) //0 1 1 2 3 5 8

///Q3: Return the N-th value of the Fibonacci sequence. Solve in O(n) time
function fib1(n){
    let arr = [0, 1];
    for (let i = 2; i < n + 1; i++){
      arr.push(arr[i - 2] + arr[i -1])
    }
   return arr[n]
  }
  console.log(fib1(6))
  console.log(arr)
//value of 6th index
/// What is the run time complexity? - O(n)
// function fibonacci(n){
//     var fibo = [0, 1];

//     if (n <= 2) return 1;

//     for (var i = 2; i <=n; i++ ){
//      fibo[i] = fibo[i-1]+fibo[i-2];
//     }

//    return fibo[n];
//   }

//    fibonacci(12);
//     = 144 <file_sep>/removeDuplicate/better.js
//using has map
//linear solution

let array = [1,3,3,3,1,5,6,7,8,1]

function removeDup(array){
const map = {}
const result = []
for(let i = 0;i<array.length;i++){
    if(!map[array[i]]){
        result.push(array[i])
        map[array[i]] = true;
    }

}
return result;
}
 let op = removeDup(array);
console.log(op)

branch_name: refs/heads/main

repo_name: fullstack-raghve/js-ds-algo


text:
<file_sep>package eight.pair1;

public class ArrayAlg {public ArrayAlg() {
}

    public static ArrayAlg.Pair<String> minmax(String[] a) {
        if(a != null && a.length != 0) {
            String min = a[0];
            String max = a[0];

            for(int i = 1; i < a.length; ++i) {
                if(min.compareTo(a[i]) > 0) {
                    min = a[i];
                }

                if(max.compareTo(a[i]) < 0) {
                    max = a[i];
                }
            }

            return new ArrayAlg.Pair(min, max);
        } else {
            return null;
        }
    }

    public static class Pair<T> {
        private T first;
        private T second;

        public Pair() {
            this.first = null;
            this.second = null;
        }

        public Pair(T first, T second) {
            this.first = first;
            this.second = second;
        }

        public T getFirst() {
            return this.first;
        }

        public T getSecond() {
            return this.second;
        }

        public void setFirst(T first) {
            this.first = first;
        }

        public void setSecond(T second) {
            this.second = second;
        }
    }
}
<file_sep>package eight.pair2;

public class ArrayAlg {
    public ArrayAlg() {
    }

    public static <T extends Comparable> ArrayAlg.Pair<T> minmax(T[] a) {
        if (a != null && a.length != 0) {
            T min = a[0];
            T max = a[0];

            for (int i = 0; i < a.length; ++i) {
                if (min.compareTo(a[i]) > 0) {
                    min = a[i];
                }

                if (max.compareTo(a[i]) < 0) {
                    max = a[i];
                }
            }

            return new ArrayAlg.Pair(min, max);
        } else {
            return null;
        }
    }

    public static class Pair<T> {
        private T first;
        private T second;

        public Pair() {
            this.first = null;
            this.second = null;
        }

        public Pair(T first, T second) {
            this.first = first;
            this.second = second;
        }

        public T getFirst() {
            return this.first;
        }

        public T getSecond() {
            return this.second;
        }

        public void setFirst(T first) {
            this.first = first;
        }

        public void setSecond(T second) {
            this.second = second;
        }
    }
}
<file_sep>package six;

public class threadTest {
    int i = 0;

    public int getI() {
        return i;
    }

    public threadTest setI(int i) {
        this.i =i;
        return new threadTest();
    }
    public threadTest(){
        this.i =i;
    }

    public static void main(String[] args) {
        threadTest t= new threadTest();
        t.setI(1);
        t.setI(2);
        t.setI(3);
        t.setI(4);
        t.setI(5);
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(t.i);
                for (int a =5; a<10000;a++){
                    if(a>9990)System.out.println("aaaaaa");
                }
                System.out.println(t.i);
            }}).start();
        for (int a =5; a<1000000000;a++){
            t.setI(a);
        }
    }
}

repo_name: wadetpc/CoreJava


text:
<file_sep>package com.example.revisaohj;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class EditarPessoa extends AppCompatActivity {
    List<String> pessoas ;
    PessoaAdapter adapter;
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editar_pessoa);
       /* Intent result = getIntent();
        pessoas = result.getExtras().getParcelable("Listadepessoa");
        adapter = new PessoaAdapter(this,pessoas);*/
        listView = (ListView) findViewById(R.id.list);
        listView.setEmptyView(findViewById(android.R.id.empty));
        pessoas = new ArrayList<>();
        final Bundle[] extrast = {getIntent().getExtras()};
        final ArrayList<Pessoa> ListaRecebidav = extrast[0].getParcelableArrayList("pessoas");

        for (Pessoa aluno: ListaRecebidav) {
            pessoas.add(aluno.nome);
        }
        ArrayAdapter ar = new ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,pessoas);

        listView.setAdapter(ar);
    }
}
<file_sep>package com.example.revisaohj;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class PessoaAdapter extends BaseAdapter {
    Context ctx;
    List<Pessoa> listpessoas2;

    public PessoaAdapter(Context ctx, List<Pessoa> pessoas) {
        this.ctx = ctx;
        this.listpessoas2 = pessoas;
    }

    @Override
    public int getCount() {return listpessoas2.size(); }

    @Override
    public Object getItem(int position) {
        return listpessoas2.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parebt) {
        // passos 1
        Pessoa pessoa = listpessoas2.get(position);
        //passo2
        ViewHolder holder = null;
        if (convertView == null){
            Log.d("NGVL","View Nova => position: "+ position);
            convertView = LayoutInflater.from(ctx).inflate(R.layout.item, null);
            holder= new ViewHolder();

            holder.txtNome = (TextView) convertView.findViewById(R.id.txtNome);
            holder.txtidade =(TextView) convertView.findViewById(R.id.txtIdade);
            holder.txtCpf =(TextView) convertView.findViewById(R.id.txtCpf);
            holder.txtCpf =(TextView) convertView.findViewById(R.id.txtEmail);

            convertView.setTag(holder);

        }else {
            Log.d("NGVL","View existente => position: "+ position);
            holder = (ViewHolder)convertView.getTag();
        }
        //passo 3
        Resources res = ctx.getResources();

        holder.txtNome.setText(pessoa.nome);
        holder.txtEmail.setText(pessoa.email);
        holder.txtCpf.setText(pessoa.cpf);
        holder.txtidade.setText(pessoa.idade);

        return convertView;

    }
    static class ViewHolder
    {

        TextView txtNome, txtidade, txtCpf,txtEmail;
    }
}
<file_sep>package com.example.revisaohj;

import android.os.Parcel;
import android.os.Parcelable;

public class Pessoa  implements Parcelable {
   String nome;
   String email;
    String idade;
   String cpf;
   public Pessoa(String nome,String email,String idade,String cpf){
        this.nome=nome;
        this.email=email;
        this.idade=idade;
        this.cpf=cpf;

   }
   public Pessoa(){

   }

    protected Pessoa(Parcel in) {
        nome = in.readString();
        email = in.readString();
        idade = in.readString();
        cpf = in.readString();
    }

    public static final Creator<Pessoa> CREATOR = new Creator<Pessoa>() {
        @Override
        public Pessoa createFromParcel(Parcel in) {
            return new Pessoa(in);
        }

        @Override
        public Pessoa[] newArray(int size) {
            return new Pessoa[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(nome);
        dest.writeString(email);
        dest.writeString(idade);
        dest.writeString(cpf);
    }
}
<file_sep>package com.example.sqlere.Interface;

public interface Organization {
    void reconhecerElementos();
    void reconhecerListeners();
}
<file_sep>package com.example.sqlere;

public class Professor {

    int id ;
    private String nome;
    private String escola;
    private String disciplina;

    public Professor(int id, String nome, String escola, String disciplina) {
        this.id = id;
        this.nome = nome;
        this.escola = escola;
        this.disciplina = disciplina;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEscola() {
        return escola;
    }

    public void setEscola(String escola) {
        this.escola = escola;
    }

    public String getDisciplina() {
        return disciplina;
    }

    public void setDisciplina(String disciplina) {
        this.disciplina = disciplina;
    }
}

repo_name: RonaldofSantos/ProjetosAndroid