text:
<repo_name>rafaelfigueredog/IndorLocationSystem<file_sep>/getting-rssi.py
# -*- coding: utf-8 -*-
from bluepy.btle import Scanner, DefaultDelegate
from datetime import datetime
import numpy as np
import time
import math

class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        """ if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr """

def imprime(rssi):
    print '\x1b[2J\x1b[1;1H'
    print '\n RSSI:',rssi,'dbm'
    print ' Contador: ', count
    n = 3.00
    expoenteDist = -rssi-59/(10*n)
    distancia = math.pow(10, expoenteDist)
    distancias.append(distancia)
    print '\n Distancia:', distancia , 'm'

def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

nomeDoArquivo = raw_input("\nArquivo: ") # sem extensão
nomeDoArquivo = "dados/experimento8 (obstruido)/" + nomeDoArquivo + ".txt"
arquivo = open(nomeDoArquivo, 'w')

rssiList = []
distancias = []

timeout, start_time = time.time() + 600, datetime.now()

count = 0
while True:
    if (count >= 100):
        break
    # index is the hci port number of blutooth device, you can consult on terminal with command $ "rfkill"
    # timeout is a timer o scanner on while loop, it works as a delay
    scanner = Scanner(1).withDelegate(ScanDelegate())
    devices = scanner.scan(timeout = 3)
    for dev in devices:
        if (dev.addr == "c8:fd:19:37:2b:0a"):
            count += 1
            imprime(dev.rssi)
            rssiList.append(dev.rssi)
end_time = datetime.now()
arquivo.write(str(rssiList))
arquivo.write('\n')
arquivo.write(str(distancias))
arquivo.write('\n')
arquivo.write('Experiment time: {} '.format(end_time - start_time))
arquivo.close()
print('\n Experiment time: {} '.format(end_time - start_time))
<file_sep>/README.md

  Instituto Federal da Paraíba

  Grupo de Pesquisa em Comunicações e Processamento de Informação

# Indoor Location System for People with Visual Impairments using Bluetooth Low Energy

This repository contains the project developed by <NAME> as part of the research activities of the Communications and Information Processing Research Group at the Federal Institute of Paraíba.

##  Objective
The objective of this project is to implement a system that complements tactile signage to assist people with visual impairments, enabling their real-time orientation. Through the system, users will receive interactive feedback with information about their environment and options available to them, enhancing their ability to navigate even in unfamiliar environments.

## Contents
This repository contains the source code, documentation, and other materials related to the Indoor Location System for People with Visual Impairments using Bluetooth Low Energy project.

## Authors
- <NAME>
- <NAME>
- <NAME>
<file_sep>/experiment.py
# -*- coding: utf-8 -*-
from bluepy.btle import Scanner, DefaultDelegate
from datetime import datetime
import time

class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        """ if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr """

"""
def imprime(rssi):
    print '\x1b[2J\x1b[1;1H'
    print '\n RSSI:',rssi,'dbm' """

RSSI = []
sizeRSSI = 0
start_time = datetime.now()
while sizeRSSI < 600:

    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(10)

    for dev in devices:
        if (dev.addr == "7c:01:0a:77:3c:b9"):
            #imprime(dev.rssi)
            RSSI.append(dev.rssi)
            sizeRSSI += 1
        #print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
        #for (adtype, desc, value) in dev.getScanData():
        #    print "  %s = %s" % (desc, value)

end_time = datetime.now()
print '\n Experiment time: {} \n'.format(end_time - start_time)
print ' RSSI:', RSSI
print "\n Dados Coletados: ", sizeRSSI
<file_sep>/Octave/regressao-linear-IECOM.m
close all;
clear;
clc;

beta_0 = 1.0;
Ptx = -59;
d = 1:0.5:10; %% em metros
d = d';

rssi = [-60.0 -64.5 -71.0 -67.0 -64.0 -70.0 -69.0 -73.0 -75.0 -68.0 -68.0 -69.0 -70.5 -72.0 -61.0 -67.0 -71.0 -66.0 -71.0];

PL = Ptx - rssi;
PL = PL';

y = (PL - beta_0)/10;
x = log10(d);

 % Regressão Linear
 %% A = w*f
eta = (pinv(x'*x))*x'*y;
%L = eta*x;
PLm = beta_0 + 10*eta*log10(d);

 % Plota o gráfico de Pd em função da gamma (em dB) para cada valor de Pfa
h = figure;
semilogx(d,PL, 'ko','LineWidth',1.5);
hold on;
semilogx(d,PLm, 'r','LineWidth',1.5);
legend('Dados    ','Modelo', 'Location','NorthWest');
xlabel('d (m)', 'FontSize', 16, 'FontName','Times');
ylabel('PL (dB)', 'FontSize', 16, 'FontName','Times');
grid on;
set(gca,'FontSize', 14);
set(gca,'FontName','Times');
set(gca,'LineWidth',1.5);
set(h,'Units','Inches');
pos = get(h,'Position');
set(h,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)]);

% % % Salva a figura no formato pdf
nomefigura = ['beacons'];
print(h,nomefigura,'-dpdf','-r0');

languages: Markdown MATLAB Python

repo_name: rafaelfigueredog/IndorLocationSystem


text:
<repo_name>JiaShun-Xiao/VCM<file_sep>/R/mvMQS.R
mvMQS <- function(file_z1,file_z2,file_ref1,file_ref2=NULL,file_cov1=NULL,file_cov2=NULL,K1=NULL,K2=NULL,K12=NULL,X1=NULL,X2=NULL,snp_list=NULL,sd_method="Chromosome",pop="EUR",file_log=""){
  if(nchar(file_log)>0) sink(file_log,append=F,split=T)
  cat("Summary statistics file 1: ",file_z1,"\n",sep="")
  cat("Summary statistics file 2: ",file_z2,"\n",sep="")
  cat("Reference file 1: ",file_ref1,"\n",sep="")
  if(! is.null(file_ref2)) cat("Reference file 2: ",file_ref2,"\n",sep="")
  if(! is.null(file_cov1)) cat("Covariates file 1: ",file_cov1,"\n",sep="")
  if(! is.null(file_cov2)) cat("Covariates file 2: ",file_cov2,"\n",sep="")
  if(! is.null(file_log))cat("Writing to log file: ",file_log,"\n",sep="")

  cat("Reading data from summary statisitcs...\n")
  zf1 <- fread(file_z1,data.table = F,header = T,stringsAsFactors = F)
  zf2 <- fread(file_z2,data.table = F,header = T,stringsAsFactors = F)
  # colnames(zf1) <- colnames(zf2) <- c("SNP","N","Z","A1","A2")
  cat(nrow(zf1)," and ",nrow(zf2)," SNPs found in summary statistics files 1 and 2.\n",sep = "")

  if(is.null(file_ref2)){
    cat("There is only one reference panel. Assume two phenotypes are from the same population.\n")
    cat("Reading SNP info from the first reference panel...\n")
    ref1_info <- fread(paste(file_ref1,".bim",sep=""),data.table = F,stringsAsFactors = F)
    colnames(ref1_info) <- c("CHR","SNP","POS","BP","A1","A2")
    cat(nrow(ref1_info)," SNPs found in reference panel.\n",sep = "")

    # matching SNPs
    snps <- intersect(zf1$SNP,ref1_info$SNP)
    snps <- intersect(zf2$SNP,snps)
    if(!is.null(snp_list)) snps <- snps[snps%in%snp_list]

    zf1 <- zf1[match(snps,zf1$SNP),]
    zf2 <- zf2[match(snps,zf2$SNP),]
    idx_ref1 <- match(snps,ref1_info$SNP)
    ref1_info <- ref1_info[idx_ref1,]

    cat(length(snps)," SNPs are matched in both files.\n",sep = "")

    # replace T with A, replace G with C; A=1, C=2
    zf1$A1[zf1$A1=="T"] <- "A"
    zf1$A2[zf1$A2=="T"] <- "A"
    zf1$A1[zf1$A1=="G"] <- "C"
    zf1$A2[zf1$A2=="G"] <- "C"
    zf1_A1 <- ifelse(zf1$A1=="A",1,2)
    zf1_A2 <- ifelse(zf1$A2=="A",1,2)

    zf2$A1[zf2$A1=="T"] <- "A"
    zf2$A2[zf2$A2=="T"] <- "A"
    zf2$A1[zf2$A1=="G"] <- "C"
    zf2$A2[zf2$A2=="G"] <- "C"
    zf2_A1 <- ifelse(zf2$A1=="A",1,2)
    zf2_A2 <- ifelse(zf2$A2=="A",1,2)

    ref1_info$A1[ref1_info$A1=="T"] <- "A"
    ref1_info$A2[ref1_info$A2=="T"] <- "A"
    ref1_info$A1[ref1_info$A1=="G"] <- "C"
    ref1_info$A2[ref1_info$A2=="G"] <- "C"
    ref1_A1 <- ifelse(ref1_info$A1=="A",1,2)
    ref1_A2 <- ifelse(ref1_info$A2=="A",1,2)

    # remove ambiguous SNPs
    snps_rm <- (ref1_A1+ref1_A2)!=(zf1_A1+zf1_A2) | (ref1_A1+ref1_A2)!=(zf2_A1+zf2_A2) | (zf1_A1+zf1_A2)!=(zf2_A1+zf2_A2)

    snps <- snps[!snps_rm]
    idx_ref1 <- idx_ref1[!snps_rm]
    ref1_info <- ref1_info[!snps_rm,]
    zf1 <- zf1[!snps_rm,]
    zf2 <- zf2[!snps_rm,]

    cat(sum(snps_rm)," SNPs are removed because of ambiguity; ",sum(!snps_rm)," SNPs remained.\n",sep = "")

    # calculate kinship matrix if needed
    if(is.null(K1)){
      cat("Calculating kinship matrix...\n")
      if(is.null(X1)){
        ref1 <- read_data(file_ref1)
        X1 <- ref1$X[,idx_ref1]
      } else {
        X1 <- X1[,idx_ref1]
      }
      X1[X1==3] <- 0
      no_var <- apply(X1,2,function(x) all(diff(x)==0))
      if(sum(no_var)!=0){
        snps <- snps[!no_var]
        X1 <- X1[,!no_var]
        ref1_info <- ref1_info[!no_var,]
        zf1 <- zf1[!no_var,]
        zf2 <- zf2[!no_var,]
        cat(sum(no_var)," SNPs are removed because of no variation; ",length(snps)," SNPs remained.\n",sep = "")
      }
      X1 <- scale(X1)
      K1 <- X1%*%t(X1)/ncol(X1)
    }

    # based on the minor allel of reference panel, correct for the z score in summary statistics
    ind1 <- zf1$A1 != ref1_info$A1
    ind2 <- zf2$A1 != ref1_info$A1
    z_score1 <- zf1$Z
    z_score2 <- zf2$Z
    z_score1[ind1] <- -z_score1[ind1]
    z_score2[ind2] <- -z_score2[ind2]
    cat(sum(ind1)," SNPs have different minor alleles in phenotype 1, z-scores are corrected according to reference panel.\n",sep = "")
    cat(sum(ind2)," SNPs have different minor alleles in phenotype 1, z-scores are corrected according to reference panel.\n",sep = "")

    if(sd_method=="LD_block"){
      cat("Assigning SNPs to LD Blocks...\n")
      block <- read.table(system.file("extdata", "fourier_ls-all.bed", package = "medH"),header = T)
      group <- rep(0,nrow(zf1))
      idx_group <- 1
      for(i in 1:22){
        block_i <- block[block$chr==paste("chr",i,sep=""),]
        # chr_i <- snp_ref[snp_ref$CHR==i,]
        n_block <- nrow(block_i)

        for(j in 1:n_block){
          tmp <- with(ref1_info,CHR==i & BP>=block_i$start[j] & BP<block_i$stop[j])
          if(sum(tmp!=0)){
            group[tmp] <- idx_group
            idx_group <- idx_group+1
          }
        }
      }
    } else if(sd_method=="Jackknife"){
      group <- NULL
    } else if(sd_method=="Chromosome"){
      group <- ref1_info$CHR
    }

    if(is.null(file_cov1)){
      fit <- corr_ss(z_score1,z_score2,K1,K1,K1,zf1$N,zf2$N,Z1=NULL,Z2=NULL,group = group)
    } else {
      cov1 <- fread(file_cov1,data.table = F)
      cov1 <- data.matrix(cov1)
      fit <- corr_ss(z_score1,z_score2,K1,K1,K1,zf1$N,zf2$N,Z1=cov1,Z2=cov1,group = group)
    }

  } else {
    cat("There are two reference panels. Assume two phenotypes are from different populations.\n")
    cat("Reading SNP info from reference panels...\n")
    ref1_info <- fread(paste(file_ref1,".bim",sep=""),data.table = F,stringsAsFactors = F)
    ref2_info <- fread(paste(file_ref2,".bim",sep=""),data.table = F,stringsAsFactors = F)
    colnames(ref1_info) <- colnames(ref2_info) <- c("CHR","SNP","POS","BP","A1","A2")
    cat(nrow(ref1_info)," and ",nrow(ref2_info)," SNPs found in reference panel 1 and 2.\n",sep = "")

    # matching SNPs
    snps <- intersect(zf1$SNP,ref1_info$SNP)
    snps <- intersect(snps,zf2$SNP)
    snps <- intersect(snps,ref2_info$SNP)

    zf1 <- zf1[match(snps,zf1$SNP),]
    zf2 <- zf2[match(snps,zf2$SNP),]
    idx_ref1 <- match(snps,ref1_info$SNP)
    ref1_info <- ref1_info[idx_ref1,]
    idx_ref2 <- match(snps,ref2_info$SNP)
    ref2_info <- ref2_info[idx_ref2,]

    cat(length(snps)," SNPs are matched in all 4 files.\n",sep = "")

    # replace T with A, replace G with C; A=1, C=2
    zf1$A1[zf1$A1=="T"] <- "A"
    zf1$A2[zf1$A2=="T"] <- "A"
    zf1$A1[zf1$A1=="G"] <- "C"
    zf1$A2[zf1$A2=="G"] <- "C"
    zf1_A1 <- ifelse(zf1$A1=="A",1,2)
    zf1_A2 <- ifelse(zf1$A2=="A",1,2)

    ref1_info$A1[ref1_info$A1=="T"] <- "A"
    ref1_info$A2[ref1_info$A2=="T"] <- "A"
    ref1_info$A1[ref1_info$A1=="G"] <- "C"
    ref1_info$A2[ref1_info$A2=="G"] <- "C"
    ref1_A1 <- ifelse(ref1_info$A1=="A",1,2)
    ref1_A2 <- ifelse(ref1_info$A2=="A",1,2)

    zf2$A1[zf2$A1=="T"] <- "A"
    zf2$A2[zf2$A2=="T"] <- "A"
    zf2$A1[zf2$A1=="G"] <- "C"
    zf2$A2[zf2$A2=="G"] <- "C"
    zf2_A1 <- ifelse(zf2$A1=="A",1,2)
    zf2_A2 <- ifelse(zf2$A2=="A",1,2)

    ref2_info$A1[ref2_info$A1=="T"] <- "A"
    ref2_info$A2[ref2_info$A2=="T"] <- "A"
    ref2_info$A1[ref2_info$A1=="G"] <- "C"
    ref2_info$A2[ref2_info$S2=="G"] <- "C"
    ref2_A1 <- ifelse(ref2_info$A1=="A",1,2)
    ref2_A2 <- ifelse(ref2_info$A2=="A",1,2)

    # remove ambiguous SNPs
    snps_rm <- (ref1_A1+ref1_A2)!=(zf1_A1+zf1_A2) | (ref1_A1+ref1_A2)!=(zf2_A1+zf2_A2) | (ref1_A1+ref1_A2)!=(ref2_A1+ref2_A2) | (ref2_A1+ref2_A2)!=(zf1_A1+zf1_A2) | (ref2_A1+ref2_A2)!=(zf2_A1+zf2_A2) | (zf2_A1+zf2_A2)!=(zf1_A1+zf1_A2)

    snps <- snps[!snps_rm]
    idx_ref1 <- idx_ref1[!snps_rm]
    idx_ref2 <- idx_ref2[!snps_rm]
    ref1_info <- ref1_info[!snps_rm,]
    ref2_info <- ref2_info[!snps_rm,]

    zf1 <- zf1[!snps_rm,]
    zf2 <- zf2[!snps_rm,]

    cat(sum(snps_rm)," SNPs are removed because of ambiguity; ",sum(!snps_rm)," SNPs remained.\n",sep = "")

    # calculate kinship matrix if needed
    if(is.null(K1)&is.null(K2)){
      cat("Calculating kinship matrix from the both reference panels...\n")
      if(is.null(X1)){
        ref1 <- read_data(file_ref1)
        X1 <- ref1$X[,idx_ref1]
      } else {
        X1 <- X1[,idx_ref1]
      }
      X1[X1==3] <- 0

      if(is.null(X2)){
        ref2 <- read_data(file_ref2)
        X2 <- ref2$X[,idx_ref2]
      } else {
        X2 <- X2[,idx_ref2]
      }
      X2[X2==3] <- 0

      no_var <- apply(X1,2,function(x) all(diff(x)==0)) | apply(X2,2,function(x) all(diff(x)==0))
      if(sum(no_var)!=0){
        snps <- snps[!no_var]
        X1 <- X1[,!no_var]
        X2 <- X2[,!no_var]
        ref1_info <- ref1_info[!no_var,]
        ref2_info <- ref2_info[!no_var,]
        zf1 <- zf1[!no_var,]
        zf2 <- zf2[!no_var,]
        cat(sum(no_var)," SNPs are removed because of no variation; ",length(snps)," SNPs remained.\n",sep = "")
      }

      # align alleles in two reference panels based on the first ref
      ind_ref <- ref1_info$A1!=ref2_info$A1
      if(sum(ind_ref)>0){
        X2[,ind_ref] <- 1-(X2[,ind_ref]-1)
        cat(sum(ind_ref)," SNPs in the second reference panel are alligned for alleles according to the first.\n",sep="")
      }

      X1 <- scale(X1)
      K1 <- X1%*%t(X1)/ncol(X1)
      X2 <- scale(X2)
      K2 <- X2%*%t(X2)/ncol(X2)

      K12 <- X1%*%t(X2)/ncol(X1)

    } else if (is.null(K1)){
      cat("Calculating kinship matrix from the first reference panel...\n")
      if(is.null(X1)){
        ref1 <- read_data(file_ref1)
        X1 <- ref1$X[,idx_ref1]
      } else {
        X1 <- X1[,idx_ref1]
      }
      X1[X1==3] <- 0
      no_var <- apply(X1,2,function(x) all(diff(x)==0))
      if(sum(no_var)!=0){
        snps <- snps[!no_var]
        X1 <- X1[,!no_var]
        ref1_info <- ref1_info[!no_var,]
        zf1 <- zf1[!no_var,]
        cat(sum(no_var)," SNPs are removed because of no variation; ",ncol(X1)," SNPs remained.\n",sep = "")
      }
      X1 <- scale(X1)
      K1 <- X1%*%t(X1)/ncol(X1)
    } else if (is.null(K2)){
      cat("Calculating kinship matrix from the second reference panel...\n")
      if(is.null(X2)){
        ref2 <- read_data(file_ref2)
        X2 <- ref2$X[,idx_ref2]
      } else {
        X2 <- X2[,idx_ref2]
      }
      X2[X2==3] <- 0
      no_var <- apply(X2,2,function(x) all(diff(x)==0))
      if(sum(no_var)!=0){
        snps <- snps[!no_var]
        X2 <- X2[,!no_var]
        ref2_info <- ref2_info[!no_var,]
        zf2 <- zf2[!no_var,]
        cat(sum(no_var)," SNPs are removed because of no variation; ",ncol(X2)," SNPs remained.\n",sep = "")
      }
      X2 <- scale(X2)
      K2 <- X2%*%t(X2)/ncol(X2)
    }

    # based on the minor allel of reference panel, correct for the z score in summary statistics
    ind1 <- zf1$A1 != ref1_info$A1
    ind2 <- zf2$A1 != ref1_info$A1
    z_score1 <- zf1$Z
    z_score2 <- zf2$Z
    z_score1[ind1] <- -z_score1[ind1]
    z_score2[ind2] <- -z_score2[ind2]
    cat(sum(ind1)," SNPs have different minor alleles in phenotype 1, z-scores are corrected according to reference panel.\n",sep = "")
    cat(sum(ind2)," SNPs have different minor alleles in phenotype 1, z-scores are corrected according to reference panel.\n",sep = "")

    if(sd_method=="LD_block"){
      cat("Assigning SNPs to LD Blocks...\n")
      block <- read.table(system.file("extdata", paste0(pop,"_fourier_ls-all.bed"), package = "VCM"),header = T)
      group <- rep(0,nrow(zf1))
      idx_group <- 1
      for(i in 1:22){
        block_i <- block[block$chr==paste("chr",i,sep=""),]
        # chr_i <- snp_ref[snp_ref$CHR==i,]
        n_block <- nrow(block_i)

        for(j in 1:n_block){
          tmp <- with(ref1_info,CHR==i & BP>=block_i$start[j] & BP<block_i$stop[j])
          if(sum(tmp!=0)){
            group[tmp] <- idx_group
            idx_group <- idx_group+1
          }
        }
      }
    } else if(sd_method=="Jackknife"){
      group <- NULL
    } else if(sd_method=="Chromosome"){
      group <- ref1_info$CHR
    }

    if(is.null(file_cov1)){
      cov1 <- NULL
    } else {
      cov1 <- fread(file_cov1,data.table = F)
      cov1 <- data.matrix(cov1)
    }
    if(is.null(file_cov2)){
      cov2 <- NULL
    } else {
      cov2 <- fread(file_cov2,data.table = F)
      cov2 <- data.matrix(cov2)
    }

    cat("Calculate PVE...\n")
    fit <- corr_ss(z_score1,z_score2,K1,K2,K12,zf1$N,zf2$N,Z1=cov1,Z2=cov2,group = group)
  }

  cat("Done.\n")
  print(fit$H)

  if(nchar(file_log)>0) sink()
  return(c(fit,snps=list(snps)))
}
<file_sep>/R/LMM_gibbs.R
LMM_gibbs <- function(X,y,Z=NULL,burnin=10,maxIter=1500,tol=1e-6,a0=0,b0=0,c0=0,d0=0,verbose=T,dispEvery=20){
  p <- ncol(X)
  n <- length(y)

  # Project covariates
  if(is.null(Z)){
    Z <- matrix(1,n,1)
  } else{
    Z <- cbind(1,Z)
  }
  ZZ <- t(Z)%*%Z
  SZy <- solve(ZZ,t(Z)%*%y)  # This is the fixed effect beta0
  y <- y - Z %*% SZy  # project covariates, mean of y becomes 0
  SZX <- solve(ZZ,t(Z)%*%X)
  X <- X - Z %*% SZX

  Xsd <- sqrt(colMeans(X^2))
  X <- t(t(X)/Xsd)/sqrt(p)  # scale X

  xx <- colSums(X^2)
  xty <- t(y)%*%X

  # record gibbs results
  beta_all <- matrix(0,p,maxIter)
  s2_all <- matrix(0,p,maxIter)
  sb2_all <- rep(0,maxIter)
  se2_all <- rep(0,maxIter)
  PVE_all <- rep(0,maxIter)

  # Initialize
  yt <- rep(0,n)
  beta <- rep(0,p)
  se2 <- var(y)/2
  sb2 <- se2

  for(iter in 1:(burnin+maxIter)){
    # Sampling beta
    se2_sb2 <- se2/sb2
    xxsig <- xx + c(se2_sb2)
    s2 <- c(se2)/xxsig
    for(j in 1:p){
      yt_j <- yt - beta[j]*X[,j]
      mu_j <- (xty[j]-t(yt_j)%*%X[,j]) / xxsig[j]
      beta[j] <- mu_j + sqrt(s2[j])*rnorm(1)
      yt <- yt_j + beta[j]*X[,j]
    }

    # Sampling sb2
    a <- a0 + p/2
    b <- b0 + sum(beta^2)/2
    inv_sb2 <- rgamma(1,shape=a,rate=b)
    sb2 <- 1/inv_sb2

    # Sampling se2
    c <- c0 + n/2
    d <- d0 + sum((y-yt)^2)/2
    inv_se2 <- rgamma(1,shape = c,rate = d)
    se2 <- 1/inv_se2

    PVE <- var(yt)/var(y)

    # Record sampling results
    if(iter > burnin){
      beta_all[,iter-burnin] <- beta
      s2_all[,iter-burnin] <- s2
      sb2_all[iter-burnin] <- sb2
      se2_all[iter-burnin] <- se2
      PVE_all[iter-burnin] <- PVE
    }

    # Display
    if(verbose && (iter%%dispEvery)==0){
      if(iter<=burnin){
        cat("Burn-in iteration ",iter,"\n",sep="")
      } else{
        cat("Iteration ",iter-burnin,"\n",sep="")
      }
    }
  }

  mu <- rowMeans(beta_all) / Xsd / sqrt(p)
  cov_mu <- cov(t(beta_all))
  sb2 <- mean(sb2_all)
  var_sb2 <- var(sb2_all)
  se2 <- mean(se2_all)
  var_se2 <- var(se2_all)
  PVE <- mean(PVE_all)
  var_PVE <- var(PVE_all)

  H <- matrix(0,2,3)
  colnames(H) <- c("sb2","se2","PVE")
  H[1,] <- c(sb2,se2,PVE)
  H[2,] <- sqrt(c(var_sb2,var_se2,var_PVE))
  sampler <- list(beta=beta_all,s2=s2_all,sb2=sb2_all,se2=se2_all,PVE=PVE_all)

  return(list(beta0=SZy,mu=mu,cov_mu=cov_mu,H=H,sampler=sampler))
}

<file_sep>/README.md
VCM
===========
R package 'VCM' contains three approaches for solving variance components model: PX-EM algorithm, MM algorithm and Method of Moments.

Installation
===========

To install VCM, use the following code in R console:

```
#install.packages("devtools")
library(devtools)
install_github("mxcai/VCM")
```

Usage
===========
[The 'VCM' vignette](https://github.com/mxcai/VCM/blob/master/inst/doc/vignette.pdf) provides details of derivation and a quick start for the usage of the package.

References
==========

<NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2016). On high-dimensional misspecified mixed model analysis in genome-wide association study. The Annals of Statistics, 44(5), 2127-2160.

<NAME>., <NAME>., & <NAME>. (1998). Parameter expansion to accelerate EM: the PX-EM algorithm. Biometrika, 85(4), 755-770.

<NAME>., & <NAME>. (2000). The PX-EM algorithm for fast stable fitting of Henderson's mixed model. Genetics Selection Evolution, 32(2), 143.

<NAME>., <NAME>., <NAME>., & <NAME>. (2018). MM algorithms for variance components models. Journal of Computational and Graphical Statistics, (just-accepted), 1-30.

<NAME>., & <NAME>. (2018). A scalable estimator of SNP heritability for biobank-scale data. Bioinformatics, 34(13), i187-i194.

Development
==========

This R package is developed by <NAME> (<EMAIL>).
<file_sep>/demo/PXEM_vs_MM.R
library(ggplot2)
library(reshape2)
n <- 2000
d <- 5000
q <- 5

sg2 <- 0.1
se2 <- 1

X <- matrix(rnorm(n*d),n,d)
X <- scale(X)/sqrt(d)
w  <- c(rnorm(d,0,sqrt(sg2)))
y0 <- X%*%w

Z <- matrix(rnorm(n*q),n,q)
omega <- c(1:5)
y1 <- Z%*%omega

y  <- y0 + y1 + sqrt(se2)*rnorm(n)

# fit PXEM
fit_PXEM <- linRegPXEM(X=X,y=y,Z = Z,tol = 1e-6,maxIter =200)
yhat_PX <- predict(fit_PXEM,X,Z)
mean((yhat_PX-y)^2)

# fit MM
fit_MM <- linRegMM(X=X,y=y,Z=Z,tol=1e-6,maxIter = 200)
yhat_MM <- predict(fit_MM,X,Z)
mean((yhat_MM-y)^2)

# fit MoM
fit_MoM <- linReg_MoM(X=X,Z=Z,y=y)

lb <- cbind(PXEM=fit_PXEM$lb[-1],MM=fit_MM$lb[-1])

lb <- melt(lb)
names(lb) <- c('iter','method','likelihood')
P <- ggplot(lb,aes(x=iter,y=likelihood,color=method)) + geom_line()
P

<file_sep>/R/get_mu.R
get_mu <- function(X,y,Z,se2,sb2){
  p <- ncol(X)
  n <- length(y)

  ym <- mean(y)
  y  <- y-ym  # centerize y
  Xm <- colMeans(X)
  X <- scale(X,center = T,scale = F)  # centerize X
  Xsd <- sqrt(colMeans(X^2))
  X <- t(t(X)/Xsd)/sqrt(p)  # scale X
  K <- X %*% t(X)

  if(is.null(Z)){
    Z <- matrix(1,n,1)
  } else{
    Z <- cbind(1,Z)
  }

  eigenK <- eigen(K)
  eVal <- eigenK$values
  eVec <- eigenK$vectors

  yt <- t(eVec)%*%y
  Zt <- t(eVec)%*%Z

  D <- eVal/se2 + 1/sb2
  d <- 1/(D*se2*sb2) # <=> d <- 1/(sb2*eVal + se2) in the original paper, d = 1/D/se2/sb2
  beta0 <- solve((t(Zt*d))%*%Zt) %*% (t(Zt) %*% (yt*d))

  mu <- 1/se2 * t(X) %*% (eVec %*% ((yt - Zt%*%beta0) / D))  # after covnergence obtain mu using one E-step
  # recover beta0 and mu
  mu <- mu/Xsd/sqrt(p)
  if(ncol(Z)==1){
    beta0 <- beta0 + ym - colSums(mu*Xm)
  } else{
    beta0 <- beta0 + solve(ZZ,colSums(Z)*(ym-sum(mu*Xm)))  # = beta0 - (Z^TZ)^-1Z^T[(y^bar-X^bar%*%mu),...,(y^bar-X^bar%*%mu)]
  }
}
<file_sep>/R/MQS.R
MQS <- function(file_z,file_ref,file_cov=NULL,K=NULL,X=NULL,snp_list=NULL,sd_method="LD_block",pop="EUR",file_log=""){
  if(nchar(file_log)>0) sink(file_log,append=F,split=T)
  cat("Summary statistics file: ",file_z,"\n",sep="")
  cat("Reference file: ",file_ref,"\n",sep="")
  if(! is.null(file_cov)) cat("Covariates file: ",file_cov,"\n",sep="")
  if(! is.null(file_log))cat("Writing to log file: ",file_log,"\n",sep="")

  cat("Reading data from summary statisitcs...\n")
  z_G <- read.table(file_z,header = T,stringsAsFactors = F)
  colnames(z_G) <- c("SNP","N","Z","A1","A2")
  cat(nrow(z_G)," SNPs found in summary statistics.\n",sep = "")

  cat("Reading data from reference penal...\n")
  snp_ref <- read.table(paste(file_ref,".bim",sep=""),stringsAsFactors = F)
  colnames(snp_ref) <- c("CHR","SNP","POS","BP","A1","A2")
  cat(nrow(snp_ref)," SNPs found in reference penal.\n",sep = "")

  snp_match <- intersect(snp_ref$SNP,z_G$SNP)
  if(!is.null(snp_list)) snp_match <- snp_match[snp_match%in%snp_list]

  idx_z <- match(snp_match,z_G$SNP)
  z_G <- z_G[idx_z,]

  idx_ref <- match(snp_match,snp_ref$SNP)
  snp_ref <- snp_ref[idx_ref,]
  cat(length(snp_match)," SNPs are matched in both files.\n",sep = "")

  # replace T with A, replace G with C; A=1, C=2
  z_G$A1[z_G$A1=="T"] <- "A"
  z_G$A2[z_G$A2=="T"] <- "A"
  z_G$A1[z_G$A1=="G"] <- "C"
  z_G$A2[z_G$A2=="G"] <- "C"
  z_A1 <- ifelse(z_G$A1=="A",1,2)
  z_A2 <- ifelse(z_G$A2=="A",1,2)
  # z_G$A1 <- as.factor(z_G$A1)
  # z_G$A2 <- as.factor(z_G$A2)

  snp_ref$A1[snp_ref$A1=="T"] <- "A"
  snp_ref$A2[snp_ref$A2=="T"] <- "A"
  snp_ref$A1[snp_ref$A1=="G"] <- "C"
  snp_ref$A2[snp_ref$A2=="G"] <- "C"
  snp_A1 <- ifelse(snp_ref$A1=="A",1,2)
  snp_A2 <- ifelse(snp_ref$A2=="A",1,2)
  # snp_ref$A1 <- as.factor(snp_ref$A1)
  # snp_ref$A2 <- as.factor(snp_ref$A2)

  # remove fault SNPs
  snps_rm <- (snp_A1+snp_A2)!=(z_A1+z_A2)

  snp_match <- snp_match[!snps_rm]
  idx_ref <- idx_ref[!snps_rm]
  idx_z <- idx_z[!snps_rm]
  snp_ref <- snp_ref[!snps_rm,]
  z_G <- z_G[!snps_rm,]
  cat(sum(snps_rm)," SNPs are removed because of ambiguity; ",length(snp_match)," SNPs remained.\n",sep = "")

  # calculate kinship matrix if needed
  if(is.null(K) & is.null(X)){
    cat("Calculating kinship matrix...\n")
    ref <- read_data(file_ref)
    X <- ref$X[,idx_ref]
    X[X==3] <- 0
    no_var <- apply(X,2,function(x) all(diff(x)==0))
    if(sum(no_var)!=0){
      snp_match <- snp_match[!no_var]
      X <- X[,!no_var]
      snp_ref <- snp_ref[!no_var,]
      z_G <- z_G[!no_var,]
      cat(sum(no_var)," SNPs are removed because of no variation; ",ncol(X)," SNPs remained.\n",sep = "")
    }
    X <- scale(X)
    K <- X%*%t(X)/ncol(X)
    rm(ref,X)
    gc()
  } else if(!is.null(X)){
    cat("Calculating kinship matrix...\n")
    X <- X[,idx_ref]
    X[X==3] <- 0
    no_var <- apply(X,2,function(x) all(diff(x)==0))
    if(sum(no_var)!=0){
      snp_match <- snp_match[!no_var]
      X <- X[,!no_var]
      snp_ref <- snp_ref[!no_var,]
      z_G <- z_G[!no_var,]
      cat(sum(no_var)," SNPs are removed because of no variation; ",ncol(X)," SNPs remained.\n",sep = "")
    }
    X <- scale(X)
    K <- X%*%t(X)/ncol(X)
    rm(ref,X)
    gc()
  }

  # based on the minor allel of reference penal, correct for the z score in summary statistics
  ind <- z_G$A1 != snp_ref$A1
  z_score <- z_G$Z
  z_score[ind] <- -z_score[ind]
  cat(sum(ind)," SNPs have different minor allel, z-scores are corrected according to reference penal.\n",sep = "")

  if(sd_method=="LD_block"){
    cat("Assigning SNPs to LD Blocks...\n")
    block <- read.table(system.file("extdata", paste0(pop,"_fourier_ls-all.bed"), package = "VCM"),header = T)
    group <- rep(0,nrow(z_G))
    idx_group <- 1
    for(i in 1:22){
      block_i <- block[block$chr==paste("chr",i,sep=""),]
      # chr_i <- snp_ref[snp_ref$CHR==i,]
      n_block <- nrow(block_i)

      for(j in 1:n_block){
        tmp <- with(snp_ref,CHR==i & BP>=block_i$start[j] & BP<block_i$stop[j])
        if(sum(tmp!=0)){
          group[tmp] <- idx_group
          idx_group <- idx_group+1
        }
      }
    }
  } else if(sd_method=="Jackknife"){
    group <- NULL
  } else if(sd_method=="Chromosome"){
    group <- snp_ref$CHR
  }

  cat("Calculate PVE...\n")
  if(is.null(file_cov)){
    fit <- MoM_2var_ss(K,z_score,z_G$N,Z=NULL,group=group)
  } else {
    covar <- read.table(file_cov,header = F)
    covar <- data.matrix(covar)
    fit <- MoM_2var_ss(K,z_score,z_G$N,Z=covar,group=group)
  }

  cat("Done.\n")
  cat("h2 = ",fit$h," (",fit$se_h,")\n",sep="")

  if(nchar(file_log)>0) sink()
  return(c(fit,snps=list(snp_match)))
}
<file_sep>/R/RcppExports.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: <PASSWORD>

read_data <- function(stringname) {
    .Call('_VCM_read_data', PACKAGE = 'VCM', stringname)
}

branch_name: refs/heads/master

languages: Markdown R

repo_language: Markdown

repo_name: JiaShun-Xiao/VCM


text:
<file_sep>package com.example.yakovlev_golani.summerbreeze;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.example.yakovlev_golani.summerbreeze.fragments.ChallengeThreeFragment;
import com.example.yakovlev_golani.summerbreeze.fragments.HistoricalDataFragment;
import com.example.yakovlev_golani.summerbreeze.utils.Constants;

import java.util.List;

/**
 * Created by Yakovlev-Golani on 22/12/14.
 */
public class MapExtendedDataActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = new Bundle();

        setContentView(R.layout.activity_map_extended_data);
        initLoadingSpinnerView();

        FragmentTransaction ft = getFragmentManager().beginTransaction();

        Intent intent = getIntent();
        if(intent != null){
            Uri data = intent.getData();
            if (data != null){
                List<String> pathSegments = data.getPathSegments();
                if (pathSegments.size() >= 2){
                    String latitude = pathSegments.get(0);
                    String longitude = pathSegments.get(1);

                    args.putDouble(Constants.LATITUDE, Double.parseDouble(latitude));
                    args.putDouble(Constants.LONGITUDE, Double.parseDouble(longitude));
                }
            }
        }

        Fragment challengeThreeFragment = new ChallengeThreeFragment();
        challengeThreeFragment.setArguments(args);
        ft.add(R.id.current_weather_content, challengeThreeFragment);

        Fragment historicalDataFragment = new HistoricalDataFragment();
        historicalDataFragment.setArguments(args);

        ft.add(R.id.historical_content, historicalDataFragment);

        ft.commit();
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze.views;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.yakovlev_golani.summerbreeze.R;
import com.example.yakovlev_golani.summerbreeze.models.Weather;
import com.example.yakovlev_golani.summerbreeze.models.forecast.ForecastItem;
import com.example.yakovlev_golani.summerbreeze.models.forecast.Temp;
import com.example.yakovlev_golani.summerbreeze.utils.ImageUtils;
import com.example.yakovlev_golani.summerbreeze.utils.Utils;

import java.util.List;

/**
 * Created by Yakovlev-Golani on 21/12/14.
 */
public class ForecastItemView extends LinearLayout {
    private TextView dateText;
    private ImageView weatherImage;
    private TextView maxTemp;
    private TextView minTemp;

    public ForecastItemView(Context context) {
        super(context);
    }

    public ForecastItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ForecastItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void initViews(){
        if (dateText == null) {
            dateText = (TextView) findViewById(R.id.date_text);
            weatherImage = (ImageView) findViewById(R.id.weather_image);
            maxTemp = (TextView) findViewById(R.id.max_temperature);
            minTemp = (TextView) findViewById(R.id.min_temperature);
        }
    }

    private void setWeatherImage(Weather weather){
        if (weather != null) {
            ImageUtils.setWeatherIcon(getContext(), weatherImage, weather);
        }
    }

    private void setTemperatureText(Temp temp){
        if (temp != null) {
            Utils.setTemperatureText(getContext(), maxTemp, temp.getMax());
            Utils.setTemperatureText(getContext(), minTemp, temp.getMin());
        }
    }

    public void setForecastItem(ForecastItem forecastItem){
        if (forecastItem == null){
            return;
        }
        initViews();
        setDateText(forecastItem.getDt());

        List<Weather> weatherList = forecastItem.getWeather();
        if (weatherList != null && !weatherList.isEmpty()) {
            setWeatherImage(weatherList.get(0));
        }

        setTemperatureText(forecastItem.getTemp());
    }

    private void setDateText(Integer forecastItemDate) {
        if (forecastItemDate != null){
            dateText.setText(Utils.getDateString(forecastItemDate));
        }
    }
}
<file_sep>Summer Breeze - Sample Android Weather App
============

### Key Features
* Uses OpenWeatherMap APIs to display current weather, forecasts & historical weather
* Google maps with a weather layer is used to show weather on a map.

### Known Issues
* As a sample app, not all edge cases are covered (might crash on certain edge cases)
* Historical data is limited due to API restrictions
* Getting closest station API from OpenWeatherMap is somewhat unstable and therefore, a default station has been set for display purposes.
* Using the Google maps weather layer could be improved and instead of Google data, the OpenWeatherMap could be utilized for a more consistent UX.
* Developed on a Nexus 7 (2013) running Lollipop (not optimized for smartphones).

<file_sep>
package com.example.yakovlev_golani.summerbreeze.models.historicalweather;

import com.google.gson.annotations.Expose;

import javax.annotation.Generated;

@Generated("org.jsonschema2pojo")
public class Temp {

    @Expose
    private Double v;
    @Expose
    private Integer c;
    @Expose
    private Double mi;
    @Expose
    private Double ma;

    /**
     *
     * @return
     *     The v
     */
    public Double getV() {
        return v;
    }

    /**
     *
     * @param v
     *     The v
     */
    public void setV(Double v) {
        this.v = v;
    }

    /**
     *
     * @return
     *     The c
     */
    public Integer getC() {
        return c;
    }

    /**
     *
     * @param c
     *     The c
     */
    public void setC(Integer c) {
        this.c = c;
    }

    /**
     *
     * @return
     *     The mi
     */
    public Double getMi() {
        return mi;
    }

    /**
     *
     * @param mi
     *     The mi
     */
    public void setMi(Double mi) {
        this.mi = mi;
    }

    /**
     *
     * @return
     *     The ma
     */
    public Double getMa() {
        return ma;
    }

    /**
     *
     * @param ma
     *     The ma
     */
    public void setMa(Double ma) {
        this.ma = ma;
    }

}
<file_sep>package com.example.yakovlev_golani.summerbreeze.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.example.yakovlev_golani.summerbreeze.R;

/**
 * Created by Yakovlev-Golani on 11/12/14.
 */
public class ChallengeOneFragment extends Fragment{
    private TextView mMirrorText;

    public ChallengeOneFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.challenge1, container, false);

        mMirrorText = ((TextView) rootView.findViewById(R.id.text_mirror));
        ((EditText) rootView.findViewById(R.id.edit_me)).addTextChangedListener(
                new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        mMirrorText.setText(s);
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                }
        );

        return rootView;
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze.utils;

import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;

import com.example.yakovlev_golani.summerbreeze.R;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * Created by Yakovlev-Golani on 21/12/14.
 */
public class Utils {
    public static DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("MMM dd");

    public static String getDateString(Integer forecastItemDate) {
        DateTime dateTime = new DateTime(forecastItemDate.longValue() * 1000L);
        return Utils.DATE_FORMATTER.print(dateTime);
    }

    public static void setTemperatureText(Context context, TextView textView, Double temp) {
        textView.setText(String.valueOf(TemperatureConverter.getRoundTemperatureInCelsius(temp)) + context.getString(R.string.celsius_sign));
    }

    public static boolean hasInvalidLocationArguments(Bundle args) {
        return args == null || args.get(Constants.LATITUDE) == null || args.get(Constants.LONGITUDE) == null;
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.yakovlev_golani.summerbreeze.ForecastActivity;
import com.example.yakovlev_golani.summerbreeze.R;

/**
 * Created by Yakovlev-Golani on 22/12/14.
 */
public class ChallengeFourFragment extends ChallengeThreeFragment {

    @Override
    protected int getFragmentResourceId() {
        return R.layout.challenge4;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        View forecastButton = rootView.findViewById(R.id.show_forecast_button);
        if (forecastButton != null){
            forecastButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ForecastActivity.class);
                    startActivity(intent);
                }
            });
        }
        return rootView;
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze.fragments;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.yakovlev_golani.summerbreeze.BaseActivity;
import com.example.yakovlev_golani.summerbreeze.R;
import com.example.yakovlev_golani.summerbreeze.api.CurrentWeatherApi;
import com.example.yakovlev_golani.summerbreeze.models.Main;
import com.example.yakovlev_golani.summerbreeze.models.Weather;
import com.example.yakovlev_golani.summerbreeze.models.currentweather.CurrentWeather;

import java.util.List;

/**
 * Created by Yakovlev-Golani on 11/12/14.
 */
public class ChallengeTwoFragment extends CurrentWeatherFragment{
    private TextView mLocationName;
    private View mOkButton;

    protected void initViews(View rootView) {
        super.initViews(rootView);
        mLocationName = ((TextView) rootView.findViewById(R.id.city_name));
        mOkButton = rootView.findViewById(R.id.ok_button);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.challenge2, container, false);
        initViews(rootView);

        mOkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String locationName = mLocationName.getText().toString();
                if (!locationName.isEmpty()) {
                    ((BaseActivity)getActivity()).showLoadingSpinner();
                    getCurrentWeatherForLocationName(locationName);
                }
            }
        });
        return rootView;
    }

    private void getCurrentWeatherForLocationName(String locationString) {
        new AsyncTask<String, String, CurrentWeather>(){

            @Override
            protected CurrentWeather doInBackground(String... location) {
                String currentLocation = location[0];
                return CurrentWeatherApi.getCurrentWeather(currentLocation);
            }

            @Override
            protected void onPostExecute(final CurrentWeather currentWeather) {
                super.onPostExecute(currentWeather);
                showCurrentWeather(currentWeather);
            }
        }.execute(locationString);
    }

    private void showCurrentWeather(CurrentWeather currentWeather) {
        if (currentWeather != null) {
            Main main = currentWeather.getMain();
            List<Weather> weatherList = currentWeather.getWeather();

            showCurrentWeather(main, weatherList);
        }
        ((BaseActivity)getActivity()).hideLoadingSpinner();
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze.api;

import com.example.yakovlev_golani.summerbreeze.models.currentweather.CurrentWeather;
import com.example.yakovlev_golani.summerbreeze.models.currentweatherforlocation.CurrentWeatherForLocation;
import com.example.yakovlev_golani.summerbreeze.utils.NetworkResponseParser;

import org.apache.http.client.ClientProtocolException;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Locale;

/**
 * Created by Yakovlev-Golani on 18/12/14.
 */
public class CurrentWeatherApi {

    final static String CURRENT_WEATHER_PREFIX_BY_CITY = "http://api.openweathermap.org/data/2.5/weather?q=";
    final static String CURRENT_WEATHER_BY_LOCATION = "http://api.openweathermap.org/data/2.5/find?";
    final static String LOCATION_FORMAT = "lat=%.2f&lon=%.2f&cnt=1";

    public static CurrentWeather getCurrentWeather(String cityName) {

        try {
            String url = CURRENT_WEATHER_PREFIX_BY_CITY + URLEncoder.encode(cityName, "UTF-8");
            NetworkResponseParser<CurrentWeather> networkResponseParser = new NetworkResponseParser<CurrentWeather>(CurrentWeather.class);
            return networkResponseParser.getResponse(url);
        } catch (ClientProtocolException e) {
            //Toast.makeText(getActivity(), "Could not fetch data - ClientProtocolException" + e.getMessage(), Toast.LENGTH_LONG);
        } catch (IOException e) {
            //Toast.makeText(getActivity(), "Could not fetch data - IOException "  + e.getMessage(), Toast.LENGTH_LONG);
        } catch (Throwable throwable){

        }
        return null;
    }

    public static CurrentWeatherForLocation getCurrentWeather(double longitude, double latitude) {
        try {
            String url = CURRENT_WEATHER_BY_LOCATION + String.format(Locale.ENGLISH, LOCATION_FORMAT, latitude, longitude);
            NetworkResponseParser<CurrentWeatherForLocation> networkResponseParser = new NetworkResponseParser<CurrentWeatherForLocation>(CurrentWeatherForLocation.class);
            return networkResponseParser.getResponse(url);
        } catch (ClientProtocolException e) {
            //Toast.makeText(getActivity(), "Could not fetch data - ClientProtocolException" + e.getMessage(), Toast.LENGTH_LONG);
        } catch (IOException e) {
            //Toast.makeText(getActivity(), "Could not fetch data - IOException "  + e.getMessage(), Toast.LENGTH_LONG);
        } catch (Throwable throwable){

        }
        return null;
    }
}
<file_sep>
package com.example.yakovlev_golani.summerbreeze.models.historicalweather;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

import javax.annotation.Generated;

@Generated("org.jsonschema2pojo")
public class HistoricalWeather {

    @Expose
    private String message;
    @Expose
    private String cod;
    @Expose
    private String type;
    @SerializedName("station_id")
    @Expose
    private Integer stationId;
    @Expose
    private Double calctime;
    @Expose
    private Integer cnt;
    @Expose
    private java.util.List<HistoricalWeatherListItem> list = new ArrayList<HistoricalWeatherListItem>();

    /**
     *
     * @return
     *     The message
     */
    public String getMessage() {
        return message;
    }

    /**
     *
     * @param message
     *     The message
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     *
     * @return
     *     The cod
     */
    public String getCod() {
        return cod;
    }

    /**
     *
     * @param cod
     *     The cod
     */
    public void setCod(String cod) {
        this.cod = cod;
    }

    /**
     *
     * @return
     *     The type
     */
    public String getType() {
        return type;
    }

    /**
     *
     * @param type
     *     The type
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     *
     * @return
     *     The stationId
     */
    public Integer getStationId() {
        return stationId;
    }

    /**
     *
     * @param stationId
     *     The station_id
     */
    public void setStationId(Integer stationId) {
        this.stationId = stationId;
    }

    /**
     *
     * @return
     *     The calctime
     */
    public Double getCalctime() {
        return calctime;
    }

    /**
     *
     * @param calctime
     *     The calctime
     */
    public void setCalctime(Double calctime) {
        this.calctime = calctime;
    }

    /**
     *
     * @return
     *     The cnt
     */
    public Integer getCnt() {
        return cnt;
    }

    /**
     *
     * @param cnt
     *     The cnt
     */
    public void setCnt(Integer cnt) {
        this.cnt = cnt;
    }

    /**
     *
     * @return
     *     The list
     */
    public java.util.List<HistoricalWeatherListItem> getList() {
        return list;
    }

    /**
     *
     * @param list
     *     The list
     */
    public void setList(java.util.List<HistoricalWeatherListItem> list) {
        this.list = list;
    }

}
<file_sep>package com.example.yakovlev_golani.summerbreeze.utils;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

import java.util.ArrayList;

/**
 * Created by Yakovlev-Golani on 18/12/14.
 */
public class GooglePlayManager implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private static GooglePlayManager instance;

    private GoogleApiClient googleApiClient;

    private boolean isConnected = false;

    private ArrayList<GooglePlayManagerListener> googlePlayManagerListeners = new ArrayList<GooglePlayManagerListener>();

    private GooglePlayManager(Context context){
        // Create a GoogleApiClient instance
        googleApiClient = new GoogleApiClient.Builder(context)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        googleApiClient.connect();
    }

    public synchronized static GooglePlayManager getInstance(Context context){
        if (instance == null){
            instance = new GooglePlayManager(context);
        }

        return instance;
    }

    public void addListener(GooglePlayManagerListener googlePlayManagerListener){
        if (instance.isConnected){
            googlePlayManagerListener.onConnected();
        } else {
            googlePlayManagerListeners.add(googlePlayManagerListener);
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        setConnected(true);
    }

    private void setConnected(boolean connected) {
        isConnected = connected;
        for (GooglePlayManagerListener listener : googlePlayManagerListeners){
            if (isConnected){
                listener.onConnected();
            } else {
                listener.onNotConnected();
            }
        }
        googlePlayManagerListeners.clear();
    }

    @Override
    public void onConnectionSuspended(int i) {
        setConnected(false);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        setConnected(false);
    }

    public Location getLastLocation(){
        if (isConnected){
            return LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        }
        return null;
    }

    public static abstract class GooglePlayManagerListener {
        public abstract void onConnected();
        public abstract void onNotConnected();
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze.fragments;

import android.app.Fragment;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.yakovlev_golani.summerbreeze.R;
import com.example.yakovlev_golani.summerbreeze.models.Main;
import com.example.yakovlev_golani.summerbreeze.models.Weather;
import com.example.yakovlev_golani.summerbreeze.utils.ImageUtils;
import com.example.yakovlev_golani.summerbreeze.utils.Utils;

import java.util.List;

/**
 * Created by Yakovlev-Golani on 18/12/14.
 */
public abstract class CurrentWeatherFragment extends Fragment {

    private TextView mCurrentTemperature;
    private TextView mCurrentConditions;
    private ImageView mCurrentWeatherImage;

    protected void initViews(View rootView) {
        mCurrentTemperature = ((TextView) rootView.findViewById(R.id.current_temperature));
        mCurrentConditions = ((TextView) rootView.findViewById(R.id.current_conditions));
        mCurrentWeatherImage = ((ImageView) rootView.findViewById(R.id.current_weather_image));
    }

    protected void showCurrentWeather(Main main, List<Weather> weatherList) {
        if(main != null) {
            Utils.setTemperatureText(getActivity(), mCurrentTemperature, main.getTemp());
        }

        if (weatherList != null && weatherList.size() > 0){
            Weather weather = weatherList.get(0);
            mCurrentConditions.setText(getString(R.string.current_conditions) + weather.getDescription());
            ImageUtils.setWeatherIcon(getActivity(), mCurrentWeatherImage, weather);
        }
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze;

import android.app.Activity;
import android.view.View;
import android.widget.ProgressBar;

/**
 * Created by Yakovlev-Golani on 22/12/14.
 */
public abstract class BaseActivity extends Activity {

    private ProgressBar mLoadingSpinner;

    protected void initLoadingSpinnerView() {
        mLoadingSpinner = (ProgressBar) findViewById(R.id.loading_spinner);
    }

    public void showLoadingSpinner(){
        if(mLoadingSpinner != null) {
            mLoadingSpinner.setVisibility(View.VISIBLE);
        }
    }

    public void hideLoadingSpinner(){
        if(mLoadingSpinner != null) {
            mLoadingSpinner.setVisibility(View.GONE);
        }
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze.utils;

import android.content.Context;
import android.widget.ImageView;

import com.example.yakovlev_golani.summerbreeze.models.Weather;
import com.squareup.picasso.Picasso;

/**
 * Created by Yakovlev-Golani on 13/12/14.
 */
public class ImageUtils {
    public static final String PNG_EXTENSION = ".png";

    public static void setWeatherIcon(Context context, ImageView imageView, Weather weather){
        String url = Constants.ICON_URL_BASE + weather.getIcon() + PNG_EXTENSION;
        Picasso.with(context).load(url).fit().into(imageView);
    }
}
<file_sep>package com.example.yakovlev_golani.summerbreeze.fragments;

/**
 * Created by Yakovlev-Golani on 23/12/14.
 */
public class ChallengeSevenFragment extends ChallengeSixFragment {

    protected String getFileName() {
        return "challenge7_map.html";
    }

}
<file_sep>package com.example.yakovlev_golani.summerbreeze.fragments;

import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.yakovlev_golani.summerbreeze.BaseActivity;
import com.example.yakovlev_golani.summerbreeze.R;
import com.example.yakovlev_golani.summerbreeze.api.CurrentWeatherApi;
import com.example.yakovlev_golani.summerbreeze.models.Main;
import com.example.yakovlev_golani.summerbreeze.models.Weather;
import com.example.yakovlev_golani.summerbreeze.models.currentweatherforlocation.CurrentWeatherForLocation;
import com.example.yakovlev_golani.summerbreeze.models.currentweatherforlocation.WeatherLocations;
import com.example.yakovlev_golani.summerbreeze.utils.Constants;
import com.example.yakovlev_golani.summerbreeze.utils.LocationHelper;
import com.example.yakovlev_golani.summerbreeze.utils.Utils;

import java.util.List;

/**
 * Created by Yakovlev-Golani on 18/12/14.
 */
public class ChallengeThreeFragment extends CurrentWeatherFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        int challengeResourceId = getFragmentResourceId();
        View rootView = inflater.inflate(challengeResourceId, container, false);
        super.initViews(rootView);
        ((BaseActivity)getActivity()).showLoadingSpinner();

        Bundle args = getArguments();
        if (Utils.hasInvalidLocationArguments(args)) {
            LocationHelper.getLocation(getActivity(), new LocationHelper.LocationListener() {

                @Override
                public void onLocationReceived(Location location) {
                    showLocation(location);
                    ((BaseActivity) getActivity()).hideLoadingSpinner();
                }

                @Override
                public void onLocationFailed() {
                    Toast.makeText(getActivity(), "Cannot get location", Toast.LENGTH_LONG).show();
                    ((BaseActivity) getActivity()).hideLoadingSpinner();
                }
            });
        } else {
            showCurrentWeatherForLocation(args.getDouble(Constants.LATITUDE), args.getDouble(Constants.LONGITUDE));
        }

        return rootView;
    }

    protected int getFragmentResourceId() {
        return R.layout.challenge3;
    }

    private void showLocation(Location location) {
        if (location != null) {
            showCurrentWeatherForLocation(location.getLatitude(), location.getLongitude());
        } else {
            Toast.makeText(getActivity(), "Location cannot be determined", Toast.LENGTH_LONG).show();
        }
    }

    private void showCurrentWeatherForLocation(final double lat, final double lng) {

        AsyncTask<Void, Void, CurrentWeatherForLocation> locationCurrentWeatherAsyncTask = new AsyncTask<Void, Void, CurrentWeatherForLocation>() {

            @Override
            protected CurrentWeatherForLocation doInBackground(Void... voids) {

                return CurrentWeatherApi.getCurrentWeather(lng, lat);
            }

            @Override
            protected void onPostExecute(final CurrentWeatherForLocation currentWeather) {
                super.onPostExecute(currentWeather);
                showCurrentWeather(currentWeather);
            }
        };

        locationCurrentWeatherAsyncTask.execute();
    }

    protected void showCurrentWeather(CurrentWeatherForLocation currentWeather) {
        if (currentWeather != null) {
            java.util.List<WeatherLocations> weatherLocationsList = currentWeather.getList();
            if(weatherLocationsList != null && !weatherLocationsList.isEmpty()) {
                WeatherLocations weatherLocation = weatherLocationsList.get(0);
                List<Weather> weatherList = weatherLocation.getWeather();
                Main main = weatherLocation.getMain();
                showCurrentWeather(main, weatherList);
            }
        }
        ((BaseActivity)getActivity()).hideLoadingSpinner();
    }
}

languages: Java Markdown

repo_language: Java

repo_name: doronyg/SummerBreeze


text:
<file_sep>package mx.edu.ittepic.u1_tablasseekbar_zulmaisabelcoronellopez;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button botoncal;
    SeekBar seekBar;
    TextView avance;
    String concat,total;
    int selec,respuesta;
    ListView lista;
    String [] array = new String[21];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekBar = findViewById(R.id.seekBar);
        avance = findViewById(R.id.tvResultado);
        botoncal = findViewById(R.id.btncalcular);
        lista = findViewById(R.id.lvTablas);
        total="";
        concat="";
        selec=0;
        //-----------------------ListView---------------------------
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,array);

        //---------------------SeekBar--------------------------------
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                total="";
                concat="";
                avance.setText(""+progress);
                selec = progress;
                }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        botoncal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i=0;i<=20;i++){
                    respuesta=selec*i;
                    array[i]=""+selec+" X "+i+" = "+respuesta;
                }
                lista.setAdapter(adapter);
            }
        });
    }
}


text:
<repo_name>keepinit/rafdemo<file_sep>/README.md
# rafdemo
demo repo

repo_name: keepinit/rafdemo