branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/main
|
<file_sep>$(document).ready(function() {
const source = $("#box-template").html();
const template = Handlebars.compile(source);
if($("#version-ajax").length) {
$.ajax({
url: "../db.php",
method: 'GET',
success: function(item) {
//array per la lista dei generi
var genres = [];
for (var i = 0; i < item.length; i++) {
var context = {
poster: item[i].poster,
title: item[i].title,
author: item[i].author,
genre: item[i].genre,
year: item[i].year
};
var html = template(context);
$(".box-card").append(html);
// variabile per il genere corrente
var currentGenre = item[i].genre;
// se non è già incluso allora lo inserisco nell'array
if (!genres.includes(currentGenre)) {
genres.push(currentGenre);
}
}// end for degli item
// scorro l'array con i vari generi e li stampo nelle option
for (var i = 0; i < genres.length; i++) {
$("#filter-genre").append(`
<option value="${genres[i]}">
${genres[i]}
</option>`);
}
}, //end succes reply
error: function() {
alert("Si è verificato un errore");
}
//end ajax
});
}//end if
// intercetto il cambio di genere nella select
$('#filter-genre').change(function() {
// svuoto il contenitore
$('.box-card').empty();
// recupero il value del genere selezionato
var selected_genre = $(this).val();
// faccio una chiamata ajax inviando al server il genere selezionato
$.ajax({
url: '../db.php',
method: 'GET',
data: {
genre: selected_genre
},
success: function(item) {
for (var i = 0; i < item.length; i++) {
var context = {
'poster': item[i].poster,
'title': item[i].title,
'author': item[i].author,
'year': item[i].year
};
var html = template(context);
$('.box-card').append(html);
}
},
error: function() {
alert('Si è verificato un errore');
}
});
});
// end ready
});
<file_sep><?php @include "../db.php"; ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- GOOGLE FONTS -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700;900&display=swap" rel="stylesheet">
<!-- JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Include Handlebars from a CDN -->
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>
<!-- STYLE -->
<link rel="stylesheet" href="../dist/app.css">
<title>PHP Dischi</title>
</head>
<body>
<header>
<h1>PHP DISCHI</h1>
</header>
<main>
<div class="container">
<div class="filter">
<select id="filter-genre">
<option value="">-- ALL --</option>
<?php foreach ($genres as $genre) { ?>
<option value="<?php echo $genre ?>">
<?php echo $genre ?>
</option>
<?php
} ?>
</select>
</div>
<div class="box-card">
<?php foreach ($dischi as $disco) { ?>
<div class="card">
<img src="<?php echo $disco["poster"] ?> " alt="<?php $disco["title"] ?>">
<p> <?php echo $disco["title"] ?> </p>
<p> <?php echo $disco["author"] ?> </p>
<p> <?php echo $disco["genre"] ?> </p>
<p> <?php echo $disco["year"] ?> </p>
</div>
<?php
} ?>
</div>
</div>
</main>
<script id="box-template" type="text/x-handlebars-template">
<div class="card">
<img src=" {{ poster }} " alt="{{ title }}">
<p>{{ title }}</p>
<p>{{ author }}</p>
<p>{{ genre }}</p>
<p>{{ year }}</p>
</div>
</script>
<script src="../dist/app.js" charset="utf-8"></script>
</body>
</html>
|
0391532924042ee224ed24c78edddfd4135be376
|
[
"JavaScript",
"PHP"
] | 2 |
JavaScript
|
ivanmincione/php-ajax-dischi
|
04a6129d1fb63eaf57e40a6cfcc393f845e11c7f
|
47adb34b520e55983face53d7c02970bbd96aa5c
|
refs/heads/master
|
<repo_name>RoyTrudell/FantasyFun<file_sep>/TopLevel.py
import pandas as pd
import numpy as np
import scipy as sp
|
a6952f9c99be3d44a3b3db268fb24b6395758bb3
|
[
"Python"
] | 1 |
Python
|
RoyTrudell/FantasyFun
|
24f1838e15e4de9226747e3be910ebb32ef5a7d5
|
512e3835b7b03d6cc30b5f9f47baab033aab638c
|
refs/heads/master
|
<file_sep>#' A function for adding error bars to barplots
#'
#' This function is a wrap around for barplot() that will add error bars. This
#' code was written by Dr. <NAME> at the U of A.
#' @param dv Numeric vector.
#' @param fac Factors.
#' @param ... Elipsis for passing arguements
#' @keywords error bars
#' @importFrom stats sd
#' @export
#' @examples
#' eb(mtcars$mpg, as.factor(mtcars$cyl), ylab = "Miles per gallon", xlab = "cyl")
eb <- function(dv, fac, ...) {
# error checking
if (!is.numeric(dv)) stop("first argument must be a vector of numbers")
if (!is.factor(fac)) stop("Second argument must be a factor")
if (length(dv) != length(fac))
stop("Arguments must be of the same length")
# set up variables
num.levels <- length(levels(fac))
lev.means <- numeric(num.levels)
lev.sds <- numeric(num.levels)
lev.sizes <- numeric(num.levels)
lev.errors <- numeric(num.levels)
# calculate error for each factor level
for (l in 1:num.levels) {
fl <- levels(fac)[l]
lev.means[l] <- mean(dv[fac == fl])
lev.sds[l] <- sd(dv[fac == fl])
lev.sizes[l] <- length(dv[fac == fl])
lev.errors[l] <- qnorm(0.975) * lev.sds[l] / sqrt(lev.sizes[l])
}
# how tall does the barplot have to be
mean.max <- ceiling(max(lev.means + lev.errors))
# make the plot
x <- barplot(lev.means, ylim = c(0,mean.max), ...)
# add the error bars
arrows(
x, lev.means - lev.errors,
x, lev.means + lev.errors,
code = 3, angle = 90, length = .1
)
}
<file_sep>#' A linear regression teaching tool
#'
#' This function takes user inputs, creates a data frame,
#' fits a linear model, and plots the output. The function
#' can take 4 optional arguments that adjust the relationship
#' between x and y. The purpose of this function is to help
#' teach the linear model.
#'
#' @param n Number of observations
#' @param intercept The y-intercept
#' @param slope The slope the line
#' @param sigma Spread around the mean
#' @param custAxis Logical. Set to true to use custom xlim/ylim
#' @param xlim Vector for x axis, 'custAxis' must be TRUE.
#' @param ylim Vector for y axis, 'custAxis' must be TRUE.
#' @keywords linear model plot
#' @import ggplot2
#' @importFrom stats rnorm coef
#' @export
#' @examples
#' # 'y' as a function of 'x' with 100 observations, intercept
#' # of 50, slope of 10, and sigma at 0.5
#' lm_ex()
#'
#' # Negative slope
#' lm_ex(n = 55, intercept = 25, slope = -5, sigma = 0.75)
lm_ex <- function(n = 100, intercept = 50, slope = 10, sigma = 0.5,
custAxis = FALSE, xlim = NULL, ylim = NULL){
# Define variables
x <- rnorm(n)
beta0 <- intercept
beta1 <- slope
sigma <- sigma
# Add linear effect to y
y <- beta0 + x * beta1 + rnorm(n = n, sd = sigma)
# make df
mod_df <- data.frame(x, y)
# fit model
mod_ex <- lm(y ~ x, data = mod_df)
# Plot it
annotations <- data.frame(
xpos = c(-Inf, 1),
ypos = c(coef(mod_ex)[1], coef(mod_ex)[1]),
annotateText = c(paste("y-intercept = ", round(coef(mod_ex)[1], 2)),
paste("Slope = ", round(coef(mod_ex)[2], 2))),
hjustvar = c(-0.20, -0.10),
vjustvar = c(-1, 2))
if (custAxis == FALSE) {
xlim <- xlim
ylim <- ylim
p <- ggplot(mod_df, aes(x = x, y = y)) +
geom_point(size = 3, color = 'grey30', alpha = 0.5) +
geom_point(size = 2, color = 'lightblue', alpha = 0.4) +
geom_abline(color = "darkred", lwd = 1,
slope = coef(mod_ex)[2],
intercept = coef(mod_ex)[1]) +
# Intercept lines
geom_vline(xintercept = 0, lty = 3, color = 'grey30') +
geom_hline(yintercept = coef(mod_ex)[1], lty = 3,
color = 'grey30') +
# Slope lines
geom_segment(aes(x = 0, xend = 1,
y = coef(mod_ex)[1], yend = coef(mod_ex)[1]),
lty = 2, color = 'darkred') +
geom_segment(aes(x = 1, xend = 1,
y = coef(mod_ex)[1],
yend = coef(mod_ex)[1] + coef(mod_ex)[2]),
lty = 2, color = 'darkred') +
geom_text(data = annotations, aes(x = .data$xpos, y = .data$ypos,
hjust = .data$hjustvar, vjust = .data$vjustvar,
label = .data$annotateText)) +
theme_bw(base_size = 20, base_family = "Times") +
theme(axis.title.y = element_text(size = rel(.9), hjust = 0.95),
panel.grid.major = element_line(colour = 'grey90', size = 0.15),
panel.grid.minor = element_line(colour = 'grey90', size = 0.15))
} else {
p <- ggplot(mod_df, aes(x = x, y = y)) +
geom_point(size = 3, color = 'grey30', alpha = 0.5) +
geom_point(size = 2, color = 'lightblue', alpha = 0.4) +
geom_abline(color = "darkred", lwd = 1,
slope = coef(mod_ex)[2],
intercept = coef(mod_ex)[1]) +
# Intercept lines
geom_vline(xintercept = 0, lty = 3, color = 'grey30') +
geom_hline(yintercept = coef(mod_ex)[1], lty = 3,
color = 'grey30') +
# Slope lines
geom_segment(aes(x = 0, xend = 1,
y = coef(mod_ex)[1], yend = coef(mod_ex)[1]),
lty = 2, color = 'darkred') +
geom_segment(aes(x = 1, xend = 1,
y = coef(mod_ex)[1],
yend = coef(mod_ex)[1] + coef(mod_ex)[2]),
lty = 2, color = 'darkred') +
geom_text(data = annotations, aes(x = .data$xpos, y = .data$ypos,
hjust = .data$hjustvar, vjust = .data$vjustvar,
label = .data$annotateText)) +
xlim(xlim) +
ylim(ylim) +
theme_bw(base_size = 20, base_family = "Times") +
theme(axis.title.y = element_text(size = rel(.9), hjust = 0.95),
panel.grid.major = element_line(colour = 'grey90', size = 0.15),
panel.grid.minor = element_line(colour = 'grey90', size = 0.15))
}
print(p)
}
<file_sep>
<!-- badges: start -->
[](https://github.com/jvcasillas/lingStuff/actions)
[](https://www.codefactor.io/repository/github/jvcasillas/lingstuff)
<!-- badges: end -->
## lingStuff <img src='https://raw.githubusercontent.com/jvcasillas/hex_stickers/master/stickers/lingStuff.png' align='right' width='275px' style="padding-left:5px;"/>
### Overview
This is a collection of `R` functions that I often use in my research.
Some are borrowed and edited, others are my own. Feel free to fork and
edit as you see fit.
#### Data sets
All data sets have been moved to the
[untidydata](https://github.com/jvcasillas/untidydata) package.
### Installation
In order to install this package you must have devtools and version
3.1.3 of R. Don’t know if you have devtools? Copy and paste this into
your console:
``` r
if (!require('devtools')) {
stop('The package devtools is not installed')
}
```
R will load devtools if you have it, otherwise it will give you an
error, in which case you should copy and paste the following code into
the console:
``` r
install.packages("devtools")
```
Now that you have `devtools` installed, you can install `lingStuff`.
``` r
devtools::install_github("jvcasillas/lingStuff")
```
<file_sep>---
title:
author: ""
date: ""
fontsize: 11pt
geometry: left=1in,right=1in,top=0.5in,bottom=1in
output: pdf_document
header-includes:
- \usepackage{fancyhdr}
- \usepackage{varwidth}
---
\pagestyle{fancyplain}
\lhead{}
\chead{\includegraphics[width=1.1\textwidth]{RUheader.png}}
\rhead{}
\lfoot{}
\cfoot{\thepage}
\rfoot{}
\fancyheadoffset{0.5in}
\renewcommand{\headrulewidth}{0pt}
\phantom{.}
\vspace{1.5in}
Rutgers University
Department of Spanish and Portuguese
ADDRESS HERE
New Brunswick, NJ 08901
\vspace{.15in}
To whom it may concern:
\vspace{.15in}
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Best regards,
\vspace{.75in}
\rule{5cm}{0.4pt}
<NAME>, PhD
Assistant Professor of Hispanic Linguistics
Rutgers University $|$ Department of Spanish and Portuguese
\href{mailto:<EMAIL>}{<EMAIL>}
[www.jvcasillas.com](http://www.jvcasillas.com)
<file_sep>---
title:
author: ""
date: ""
fontsize: 11pt
geometry: left=1in,right=1in,top=1in,bottom=1in
output: pdf_document
header-includes:
- \usepackage{fancyhdr}
- \usepackage{varwidth}
---
\pagestyle{fancyplain}
\lhead{\includegraphics[width=0.4\textwidth]{middlebury_language.png}}
\chead{}
\rhead{}
\lfoot{}
\cfoot{\thepage}
\rfoot{}
\fancyheadoffset{0in}
\renewcommand{\headrulewidth}{0pt}
\phantom{.}
\vspace{0.5in}
Middlebury College - Language Schools
School of Spanish
Middlebury, VT 05753
\vspace{.15in}
To whom it may concern:
\vspace{.15in}
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Best regards,
\vspace{.75in}
\rule{5cm}{0.4pt}
<NAME>, PhD
Assistant Professor of Hispanic Linguistics
Middlebury College | Language Schools
Rutgers University $|$ Department of Spanish and Portuguese
\href{mailto:<EMAIL>}{<EMAIL>}
[www.jvcasillas.com](http://www.jvcasillas.com)
<file_sep>#' A bivariate regression function
#'
#' This function will fit a linear model to two variables. The
#' criterion can be continuous or binary. For logistic regression,
#' set family = 'binomial'. For poisson regression, set family =
#' 'poisson'. If omitted, family will default to 'gaussian' for
#' standard linear regression.
#'
#' @param data A data frame.
#' @param x An independent variable
#' @param y A dependent variable
#' @param family A distribution ('gaussian', 'binomial', or 'poisson')
#' @keywords bivariate regression
#' @importFrom stats glm lm predict plogis
#' @import graphics
#' @export
#' @examples
#' # Linear regression
#' biVarPlot(data = cars, x = dist, y = speed)
#' biVarPlot(data = mtcars, x = cyl, y = mpg)
#' biVarPlot(data = Orange, x = age, y = circumference)
#' biVarPlot(data = ChickWeight, x = Time, y = weight)
#' biVarPlot(data = USArrests, x = UrbanPop, y = Rape)
#'
#' # Logistic regression
#' vot <- rnorm(20, 15, 5)
#' vot <- sort(vot)
#' phon <- c(0,1,0,0,0,0,0,1,0,1,0,1,0,1,1,1,1,1,1,1)
#' df1 <- data.frame(vot, phon)
#' biVarPlot(data = df1, x = vot, y = phon, family = 'binomial')
#'
#' # Poisson regression
#' time <- 1:10
#' counts <- c(18, 17, 21, 20, 25, 27, 30, 43, 52, 50)
#' df2 <- data.frame(time, counts)
#' biVarPlot(data = df2, x = time, y = counts, family = 'poisson')
biVarPlot <- function(data, x, y, family = 'Gaussian'){
# This function takes a dataframe and two columns (i.e. numeric vectors)
# and fits a bivariate linear regression.
# It will produce a scatterplot with a regression line, 95% CI, R2, and
# print the model output
# Check inputs
if(!is.data.frame(data)) {
stop('I am so sorry, but this function requires a dataframe\n',
'You have provided an object of class: ', class(data)[1])
}
# Make columns of dataframe available w/o quotes
arguments <- as.list(match.call())
dv = eval(arguments$y, data)
iv = eval(arguments$x, data)
# Get column names for plot labels
yLab = as.character(arguments$y)
xLab = as.character(arguments$x)
if (family == 'poisson'){
# Fit the model
mod = glm(dv ~ iv, family = 'poisson')
# Use model to predict data for CIs
xvals = seq(from = min(iv) - 100, to = max(iv) + 100, by = 0.01)
newdata = data.frame(iv = xvals)
predY = predict(mod, newdata)
SEs = predict(mod, newdata, se.fit = T)$se.fit
seUB <- exp(predY + 1.96 * SEs)
seLB <- exp(predY - 1.96 * SEs)
# Plot the data, including regression line, CIs, and R2
plot(dv ~ iv, type = 'n', frame = TRUE, ylab = yLab, xlab = xLab)
polygon(x = c(xvals, rev(xvals)),
y = c(seUB, rev(seLB)),
border = NA, col = 'grey90')
curve(predict(mod, data.frame(iv = x), type = "resp"), add = TRUE)
points(iv, dv, bg = "lightblue", col = "darkred", cex = 0.8, pch = 21)
abline(mod, lwd = 1.25, col = 'grey20')
# Print summary of model fit
print(summary(mod))
} else if(family == 'binomial'){
# Fit the model
mod = glm(dv ~ iv, family = family)
# Use model to predict data for CIs
xvals = seq(from = min(iv) - 100, to = max(iv) + 100, by = 0.01)
newdata = data.frame(iv = xvals)
predY = predict(mod, newdata)
SEs = predict(mod, newdata, se.fit = T)$se.fit
seUB <- plogis(predY + 1.96 * SEs)
seLB <- plogis(predY - 1.96 * SEs)
# Plot the data, including regression line, CIs, and R2
plot(dv ~ iv, type = 'n', frame = TRUE, ylab = yLab, xlab = xLab)
polygon(x = c(xvals, rev(xvals)),
y = c(seUB, rev(seLB)),
border = NA, col = 'grey90')
curve(predict(mod, data.frame(iv = x), type = "resp"), add = TRUE)
points(iv, dv, bg = "lightblue", col = "darkred", cex = 0.8, pch = 21)
# Print summary of model fit
print(summary(mod))
} else {
# Fit the model
mod = lm(dv ~ iv)
# Use model to predict data for CIs
xvals = seq(from = min(iv) - 100, to = max(iv) + 100, by = 0.01)
newdata = data.frame(iv = xvals)
predY = predict(mod, newdata)
SEs = predict(mod, newdata, se.fit = T)$se.fit
# Plot the data, including regression line, CIs, and R2
plot(dv ~ iv, type = 'n', frame = TRUE, ylab = yLab, xlab = xLab)
polygon(x = c(xvals, rev(xvals)),
y = c(predY + 1.96 * SEs, rev(predY - 1.96 * SEs)),
border = NA, col = 'grey90')
points(iv, dv, bg = "lightblue", col = "darkred", cex = 0.8, pch = 21)
abline(mod, lwd = 1.25, col = 'grey20')
text(x = (max(iv) - (max(iv) * 0.05)), y = (max(dv) - (max(dv) * 0.05)),
bquote(R^2 == .(format(round(summary(mod)$r.squared, 2), nsmall = 2))))
# Print summary of model fit
print(summary(mod))
}
}
<file_sep>#' A cross over function
#'
#' This function allows you to calculate boundary/crossover point in
#' logistic regression models.
#' @param mod A glm object
#' @param cont_pred The continuous (x) predictor
#' @param grouping_var (logical) Set to TRUE to include grouping var
#' @param int_adj With grouping variable, include intercept adjustment
#' @param slope_adj With grouping variable, include interaction (slope adjustment)
#' @keywords crossover
#' @export
#' @examples
#' # Generate data
#' set.seed(1)
#' vot = rnorm(20, 15, 5)
#' vot = sort(vot)
#' phon1 = c(0,1,0,0,0,0,0,1,0,1,0,1,0,1,1,1,1,1,1,1)
#' group1 = rep('g1', 20)
#' df1 = data.frame(vot = vot, phon = phon1, group = group1)
#'
#' phon2 = c(1,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1)
#' group2 = rep('g2', 20)
#' df2 = data.frame(vot = vot, phon = phon2, group = group2)
#' df <- rbind(df1, df2)
#'
#' # Fit model
#' glm1 <- glm(phon ~ vot, data = df, family = "binomial")
#' glm2 <- glm(phon ~ vot * group, data = df, family = "binomial")
#'
#' # Get crossover point
#' cross_over(mod = glm1, cont_pred = 'vot')
#'
#' # Get crossover point of grouping variables
#' cross_over(mod = glm2, cont_pred = 'vot')
#' cross_over(mod = glm2, cont_pred = 'vot', grouping_var = TRUE,
#' int_adj = 'groupg2', slope_adj = 'vot:groupg2')
#'
#' # Plot regression with crossover point
#' library(ggplot2)
#' ggplot(df, aes(x = vot, y = phon)) +
#' geom_smooth(method = 'glm', method.args = list(family = 'binomial')) +
#' geom_vline(xintercept = cross_over(mod = glm1, cont_pred = 'vot'))
#'
#' ggplot(df, aes(x = vot, y = phon, color = group)) +
#' geom_smooth(method = 'glm', method.args = list(family = 'binomial'),
#' se = FALSE) +
#' geom_vline(xintercept = cross_over(mod = glm2, cont_pred = 'vot')) +
#' geom_vline(xintercept = cross_over(mod = glm2, cont_pred = 'vot',
#' grouping_var = TRUE,
#' int_adj = 'groupg2',
#' slope_adj = 'vot:groupg2'))
cross_over <- function(mod, cont_pred, grouping_var = FALSE,
int_adj, slope_adj) {
if (class(mod)[1] == "glm") {
# Store intercept
int <- summary(mod)$coefficients['(Intercept)', 'Estimate']
# Store continuous x var
slope <- summary(mod)$coefficients[cont_pred, 'Estimate']
# For bivariate models
if (grouping_var == FALSE) {
# Calculate crossover
co <- int / slope * -1
# For models with grouping vars
} else {
# Calculate group level intercept
int_derived <- int + summary(mod)$coefficients[int_adj, 'Estimate']
# Calculate slope adjustment
slope_derived <- slope + summary(mod)$coefficients[slope_adj, 'Estimate']
# Calculate crossover
co <- int_derived / slope_derived * -1
}
return(co)
} else {
stop("Error: this function requires a glm object\n",
"You have provided an object of class: ", class(mod)[1])
}
}
<file_sep>---
title: 'myProject'
subtitle: ''
author: ''
date: 'Rutgers University </br> `r Sys.Date()`'
output:
xaringan::moon_reader:
lib_dir: libs
css: ["hygge",
"https://www.jvcasillas.com/ru_xaringan/css/rutgers.css",
"https://www.jvcasillas.com/ru_xaringan/css/rutgers-fonts.css"]
nature:
beforeInit: ["https://www.jvcasillas.com/ru_xaringan/js/ru_xaringan.js"]
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
ratio: "16:9"
---
# Slide
```{r echo=FALSE}
library(knitr)
read_chunk('../scripts/myProject.R')
```
```{r, 'load', echo=FALSE, fig.retina=2}
```
<file_sep>#' A b function
#'
#' This function allows you to calculate b from a vector hits
#' and a vector a false alarms.
#'
#' @param data A data frame.
#' @param h A vector of hits (0 = miss, 1 = hit).
#' @param f A vector of false alarms (0 = correct rejection, 1 = false alarm).
#' @keywords b prime
#' @export
#' @examples
#' # Create some data
#' set.seed(1); library(dplyr)
#' axb <- data.frame(subj = sort(rep(1:10, each = 20, times = 10)),
#' group = gl(2, 1000, labels = c("g1", "g2")),
#' hit = c(rbinom(1000, size = c(0, 1), prob = .8),
#' rbinom(1000, size = c(0, 1), prob = .6)),
#' fa = c(rbinom(1000, size = c(0, 1), prob = .3),
#' rbinom(1000, size = c(0, 1), prob = .4))
#' )
#'
#' # Calculate b on entire data frame
#' b(axb, hit, fa)
#'
#' # Calculate b for each subject
#' # by group, plot it, and run a
#' # linear model
#' axb %>%
#' group_by(subj, group) %>%
#' summarize(b = b(., hit, fa)) %T>%
#' {
#' plot(b ~ as.numeric(group), data = .,
#' main = "b as a function of group", xaxt = "n",
#' xlab = "Group", ylab = "b")
#' axis(1, at = 1:2, labels = c("g1", "g2"))
#' abline(lm(b ~ as.numeric(group), data = .), col = "red")
#' } %>%
#' lm(b ~ group, data = .) %>%
#' summary()
b <- function(data, h, f){
if(!is.data.frame(data)) {
stop('I am so sorry, but this function requires a dataframe\n',
'You have provided an object of class: ', class(data)[1])
}
# Make columns of dataframe available w/o quotes
arguments <- as.list(match.call())
hits = eval(arguments$h, data)
fas = eval(arguments$f, data)
hRate = mean(hits)
faRate = mean(fas)
if(faRate <= .5 & hRate >= .5)
{
b <- (5 - 4 * hRate) / (1 + 4 * faRate)
} else if(faRate <= hRate & hRate <= .5)
{
b <-(hRate^2 + hRate) / (hRate^2 + faRate)
} else {
b <- ((1 - faRate)^2 + (1 - hRate)) / ((1 - faRate)^2 + (1 - faRate))
}
return(b)
}
<file_sep>#' A function for saving R packages to a .bib file
#'
#' This function will generate a .bib file for an R package.
#'
#' @param package A character vector of the package you want to cite.
#' @param file_name A character vector for the file name of the output. Defaults to the package name.
#' @keywords bibtex
#' @importFrom utils capture.output citation toBibtex
#' @export
#' @examples
#' # Create a .bib file called "test.bib" to cite the tidyverse
#' # save_to_bib("tidyverse", "test")
save_to_bib <- function(package, file_name = NULL) {
# Check if filename is provided
if (is.null(file_name)) {
f_name <- paste0(package, ".bib")
} else {
f_name = paste0(file_name, ".bib")
}
# Get package name and write file
pkg <- citation(package)
writeLines(capture.output(toBibtex(pkg)), f_name)
cat(f_name, "saved to working directory.\n")
}
<file_sep>#' A new project function
#'
#' This function will create a new project directory for you
#' with subdirectories, and .Rmd and .R templates.
#'
#' @param name A name for your project
#' @param type A valid .Rmd output (html, pdf, word)
#' @keywords projects
#' @export
#' @examples
#' # Create a new project with html report
#' # create_project(name = 'my_project', type = 'html')
create_project <- function(name = 'my_project', type = 'html') {
# Get path to working directory
current_path <- getwd()
# Get list of files in wd
dir_files <- list.files('.')
# If project folder already exists STOP
# Otherwise create directories
if (name %in% dir_files == TRUE) {
# The directory you want to create already exists in wd
stop("\nThis directory already exists. Choose another name or delete the poser directory.")
} else {
# Store project directory name
dir_name <- paste('/', name, sep = '', collapse = '')
# Store path to project directory
home_dir <- paste(current_path, dir_name, sep = '', collape = '')
# Create project directory
dir.create(path = home_dir)
# Print to console so you know it worked
cat(paste(name, 'created.\n', sep = " "))
# Set paths for secondary directories and store in vector
scripts_dir <- paste(home_dir, 'scripts', sep = '/', collapse = '')
figs_dir <- paste(home_dir, 'figs', sep = '/', collapse = '')
data_dir <- paste(home_dir, 'data', sep = '/', collapse = '')
slides_dir <- paste(home_dir, 'slides', sep = '/', collapse = '')
docs_dir <- paste(home_dir, 'docs', sep = '/', collapse = '')
all_dirs <- c(scripts_dir, figs_dir, data_dir, slides_dir, docs_dir)
# Create secondary directories
for (i in all_dirs) {
dir.create(path = i)
}
# Print secondary structure success
cat("Secondary structure added.\n")
# Store .Rmd file path for report
report <- paste(docs_dir, '/', name, '.Rmd', sep = '', collapse = '')
# Create .Rmd file and set basic template
file.create(report)
writeLines(c("---",
paste("title: '", name, "'", sep = ""),
"subtitle: \'\'",
"author: \'\'",
"date: \'Last update: `r Sys.time()`\'",
paste("output: ", type, "_document", sep = ''),
"---",
"",
"```{r echo=FALSE}",
"library(knitr)",
paste("source('../scripts/", name, ".R')", sep = ''),
"```",
"",
"```{r, 'load', echo=FALSE}", "```"), report)
# Store .R script path
script <- paste(scripts_dir, '/', name, '.R', sep = '', collapse = '')
# Create .R script and set basic template
file.create(script)
writeLines(c("# Load libraries",
"library(lingStuff)",
"",
"biVarPlot(cars, dist, speed)"), script)
# Store .Rmd file path for slides
slides <- paste(slides_dir, '/', name, '.Rmd', sep = '', collapse = '')
# Create .Rmd file for slides and set basic template
file.create(slides)
writeLines(c("---",
paste("title: '", name, "'", sep = ""),
"subtitle: \'\'",
"author: \'\'",
"date: \'Rutgers University </br> `r Sys.Date()`\'",
"output: ",
" xaringan::moon_reader:",
" lib_dir: libs",
" css: [\"hygge\", \"rutgers\", \"rutgers-fonts\"]",
" nature:",
" beforeInit: [\"https://www.jvcasillas.com/ru_xaringan/js/ru_xaringan.js\"]",
" highlightStyle: github",
" highlightLines: true",
" countIncrementalSlides: false",
" ratio: \"16:9\"",
"---",
"",
"# Slide",
"",
"```{r echo=FALSE}",
"library(knitr)",
paste("source('../scripts/", name, ".R')", sep = ''),
"```",
"",
"```{r, 'load', echo=FALSE, fig.retina=2}", "```"), slides)
}
cat('Finished. :) \n')
}
<file_sep>#' A vowel plot function
#'
#' This function will plot f1/f2 data. The function takes 4
#' obligatory arguments and optionally one can include a
#' grouping variable ('group'). This function is a wrapper
#' for ggplot. Columns from the data frame must be wrapped
#' in quotation marks.
#'
#' @param data A data frame.
#' @param vowel A factor with vowels as levels
#' @param f1 A continuous variable
#' @param f2 A continuous variable
#' @param group An optional grouping variable for facets
#' @param print Logical for printing descriptives
#' @keywords vowel plot
#' @importFrom stats as.formula aggregate
#' @export
#' @examples
#' # Vowel plot without grouping variable
#'
#' library("untidydata")
#' data("spanish_vowels")
#' #vowel_plot(data = spanish_vowels, vowel = 'vowel', f1 = 'f1', f2 = 'f2',
#' # group = NULL)
#'
#' # Vowel plot with grouping variable
#' # vowel_plot(data = spanish_vowels, vowel = 'vowel', f1 = 'f1', f2 = 'f2',
#' # group = 'gender')
vowel_plot <- function(data, vowel, f1, f2, group = NULL, print = FALSE) {
# Check inputs for data frame
if(!is.data.frame(data)) {
stop('I am so sorry, but this function requires a dataframe\n',
'You have provided an object of class: ', class(data)[1])
}
# If no faceting needed
if (length(group) == 0) {
# Calculate means of f1/f2 as a function of vowel and print it
means_formula <- as.formula(paste("cbind(", f1, ",", f2, ")", "~", vowel))
means <- aggregate(means_formula, FUN = mean, data = data)
if (print == TRUE) {
return(means)
}
# Plot
p <- ggplot(data,
aes_string(x = f2, y = f1, color = vowel, label = vowel)) +
stat_ellipse(type = "norm", show.legend = FALSE, geom = "polygon", alpha = 0.15) +
geom_text(alpha = 0.3, show.legend = FALSE, size = 2.5) +
geom_text(data = means, aes_string(x = f2, y = f1, color = vowel,
label = vowel), size = 9, show.legend = FALSE, color = 'grey40') +
scale_y_reverse() +
scale_x_reverse(position = "top") +
ylab('F1 (Hz)') + xlab('F2 (Hz)') +
scale_color_brewer(palette = 'Set1') +
theme_bw(base_size = 12, base_family = "Times New Roman")
# If faceting needed
} else {
# Calculate means of f1/f2 as a function of vowel and grouping variable
# and print it
means_formula <- as.formula(paste("cbind(", f1, ",", f2, ")", "~", vowel, "+", group))
means <- aggregate(means_formula, FUN = mean, data = data)
if (print == TRUE) {
return(means)
}
# Plot
p <- ggplot(data,
aes_string(x = f2, y = f1, color = vowel, label = vowel)) +
stat_ellipse(type = "norm", show.legend = FALSE, geom = "polygon", alpha = 0.15) +
geom_text(alpha = 0.3, show.legend = FALSE, size = 2.5) +
geom_text(data = means, aes_string(x = f2, y = f1, label = vowel),
size = 9, show.legend = FALSE, color = 'grey40') +
scale_y_reverse() +
scale_x_reverse(position = "top") +
facet_grid(as.formula(paste(".~ ", group))) +
ylab('F1 (Hz)') + xlab('F2 (Hz)') +
scale_color_brewer(palette = 'Set1') +
theme_bw(base_size = 12, base_family = "Times New Roman")
}
return(p)
}
<file_sep>#' A euclidean distance function
#'
#' This function allows you to calculate the euclidean distance between two vectors
#' @param data A data frame
#' @param var1 Numeric vector (generally f1).
#' @param var2 Numeric vectors (generally f2).
#' @keywords euclidean distance
#' @export
#' @examples
#' # Create some data
#' df <- data.frame(vowel = gl(n = 2, k = 5, labels = c('a', 'o')),
#' var1 = rnorm(10, 10, 2),
#' var2 = rnorm(10, 20, 2))
#'
#' # Calculate euc.dist on entire data frame
#' euc_dist(data = df, var1 = var1, var2 = var2)
#'
#' # Calculate euc.dist for each vowel
#' library(dplyr)
#' df %>%
#' group_by(., vowel) %>%
#' summarise(euc = euc_dist(., var1 = var1, var2 = var2))
euc_dist <- function(data, var1, var2){
if(!is.data.frame(data)) {
stop('I am so sorry, but this function requires a dataframe\n',
'You have provided an object of class: ', class(data)[1])
}
# Make columns of dataframe available w/o quotes
arguments <- as.list(match.call())
var1 = eval(arguments$var1, data)
var2 = eval(arguments$var2, data)
x <- sqrt(sum((var1 - var2)^2))
return(x)
}
<file_sep>#' An inverse logit function
#'
#' This function allows you to calculate probability from log odds
#' @param mod A glm object
#' @keywords inverse logit
#' @import dplyr
#' @importFrom rlang .data
#' @export
#' @examples
#' # Generate data
#' set.seed(1)
#' vot <- rnorm(20, 15, 5)
#' vot <- sort(vot)
#' fac <- rnorm(20, 100, 100)
#' phon <- c(0,1,0,0,0,0,0,1,0,1,0,1,0,1,1,1,1,1,1,1)
#' df <- data.frame(vot = vot, fac = fac, phon = phon)
#'
#' # Fit models
#' glm0 <- glm(phon ~ vot, data = df, family = "binomial")
#' glm1 <- glm(phon ~ vot + fac, data = df, family = "binomial")
#' glm2 <- glm(phon ~ vot * fac, data = df, family = "binomial")
#' testLM <- lm(speed ~ dist, data = cars)
#'
#' # Get beta weights as probabilities
#' library(dplyr)
#' inv_logit(glm0)
#' inv_logit(glm1)
#' inv_logit(glm2)
#' #inv_logit(testLM) # Gives an error
inv_logit <- function(mod) {
# Check to see if mod = glm object, if not, stop
if (class(mod)[1] == 'glm')
{
# Get betas weights and save them to DF
tempDF <- as.data.frame(summary(mod)$coefficients[, 1])
# Change name of betas column to 'betas'
names(tempDF)[names(tempDF)=="summary(mod)$coefficients[, 1]"] <- "betas"
# Set row names as column
tempDF$variables <- rownames(tempDF)
# Group by 'betas' and calculate inverse logit for all values
betasDF <- group_by(tempDF, .data$variables, .data$betas) %>%
summarise(prob = (exp(.data$betas) / (1 + exp(.data$betas)))) %>%
as.data.frame()
return(betasDF)
} else {
stop('Error: this function requires a glm object\n',
'You have provided an object of class: ', class(mod)[1])
}
}
<file_sep>---
title: 'myProject'
subtitle: ''
author: ''
date: 'Last update: `r Sys.time()`'
output: html_document
---
```{r echo=FALSE}
library(knitr)
read_chunk('../scripts/myProject.R')
```
```{r, 'load', echo=FALSE}
```
<file_sep>#' Function for calculating d prime
#'
#' This function will calculate d prime from a vector of hits
#' and a vector of false alarms.
#'
#' This metric is common in discrimination experiments.
#' Note: If your participants are at ceiling, you may want to
#' consider another analysis.
#' @param data A data frame.
#' @param h A vector of hits (0 = miss, 1 = hit).
#' @param f A vector of false alarms (0 = correct rejection, 1 = false alarm).
#' @keywords d prime
#' @importFrom stats qnorm
#' @export
#' @examples
#' # Create some data
#' set.seed(1); library(dplyr)
#' axb <- data.frame(subj = sort(rep(1:10, each = 20, times = 10)),
#' group = gl(2, 1000, labels = c("g1", "g2")),
#' hit = c(rbinom(1000, size = c(0, 1), prob = .8),
#' rbinom(1000, size = c(0, 1), prob = .6)),
#' fa = c(rbinom(1000, size = c(0, 1), prob = .3),
#' rbinom(1000, size = c(0, 1), prob = .4))
#' )
#'
#' # Calculate d prime on entire data frame
#' dPrime(axb, hit, fa)
#'
#'
#' # Calculate d prime for each subject by group, plot it,
#' # and run a linear model
#' library(dplyr)
#' axb %>%
#' group_by(subj, group) %>%
#' summarize(dp = dPrime(., hit, fa)) %T>%
#' {
#' plot(dp ~ as.numeric(group), data = .,
#' main = "d' as a function of group", xaxt = "n",
#' xlab = "Group", ylab = "d' prime")
#' axis(1, at = 1:2, labels = c("g1", "g2"))
#' abline(lm(dp ~ as.numeric(group), data = .), col = "red")
#' } %>%
#' lm(dp ~ group, data = .) %>%
#' summary()
dPrime <- function(data, h, f){
if(!is.data.frame(data)) {
stop('I am so sorry, but this function requires a dataframe\n',
'You have provided an object of class: ', class(data)[1])
}
# Make columns of dataframe available w/o quotes
arguments <- as.list(match.call())
hits = eval(arguments$h, data)
fas = eval(arguments$f, data)
dp = qnorm(mean(hits)) - qnorm(mean(fas))
return(dp)
}
<file_sep>#' An inverse logit function
#'
#' This function allows you to calculate probability from log odds
#' @param x An integer
#' @keywords inverse logit
#' @import dplyr
#' @importFrom rlang .data
#' @export
#' @examples
#' inv_logit_manual(1)
inv_logit_manual <- function(x) {
val <- 1 / (1 + exp(-x))
return(val)
}
|
a09ed92e22ab13cc06228a27641141ddaddda708
|
[
"Markdown",
"R",
"RMarkdown"
] | 17 |
R
|
jvcasillas/lingStuff
|
7169b2cdaa9fcaeaeaa2ebf555223a5f67655f2d
|
fb06c4c044e8d310f07497d7119d4505cda1b4f2
|
refs/heads/master
|
<file_sep>package com.shao.house.house.mapper;
import com.shao.house.house.model.HouseUser;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface HouseUserMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table house_user
*
* @mbggenerated
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table house_user
*
* @mbggenerated
*/
int insert(HouseUser record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table house_user
*
* @mbggenerated
*/
int insertSelective(HouseUser record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table house_user
*
* @mbggenerated
*/
HouseUser selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table house_user
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(HouseUser record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table house_user
*
* @mbggenerated
*/
int updateByPrimaryKey(HouseUser record);
//根据房屋ID找到 houseUser
List<HouseUser> getMaster(Long id);
//根据用户id找到 houseUser
List<HouseUser> getMyHoust(long id);
}<file_sep>package com.shao.house.house.service;
import com.shao.house.house.mapper.CommunityMapper;
import com.shao.house.house.model.Community;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.enterprise.inject.New;
import java.util.List;
@Service
public class CommunityService implements CommunityMapper {
@Autowired
private CommunityMapper communityMapper;
@Override
public int deleteByPrimaryKey(Integer id) {
return 0;
}
@Override
public int insert(Community record) {
return 0;
}
@Override
public int insertSelective(Community record) {
return 0;
}
@Override
public Community selectByPrimaryKey(Integer id) {
return null;
}
@Override
public int updateByPrimaryKeySelective(Community record) {
return 0;
}
@Override
public int updateByPrimaryKey(Community record) {
return 0;
}
@Override
public List<Community> getCommunityList() {
return communityMapper.getCommunityList();
}
@Override
public Integer selectIdByName(String name) {
return 0;
}
public Integer gteIdByname (String name){
Integer ID=communityMapper.selectIdByName(name);
if(ID==null){
System.out.println("新建小区");
Community community= new Community();
community.setCityCode("110000");
community.setName(name);
community.setCityName("北京市");
communityMapper.insertSelective(community);
ID = community.getId();
}
return ID;
//return 1;
}
}
<file_sep>package com.shao.house.house.service;
import com.shao.house.house.mapper.HouseUserMapper;
import com.shao.house.house.model.HouseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class HouseUserService implements HouseUserMapper{
@Autowired
private HouseUserMapper houseUserMapper;
@Override
public int deleteByPrimaryKey(Long id) {
return 0;
}
@Override
public int insert(HouseUser record) {
return 0;
}
@Override
public int insertSelective(HouseUser record) {
return houseUserMapper.insertSelective(record);
}
@Override
public HouseUser selectByPrimaryKey(Long id) {
return null;
}
@Override
public int updateByPrimaryKeySelective(HouseUser record) {
return 0;
}
@Override
public int updateByPrimaryKey(HouseUser record) {
return 0;
}
@Override
public List<HouseUser> getMaster(Long houseId) {
return houseUserMapper.getMaster(houseId);
}
@Override
public List<HouseUser> getMyHoust(long id) {
return houseUserMapper.getMyHoust(id);
}
public Long getMasterId(Long houseId) {
List<HouseUser> houseUserList=houseUserMapper.getMaster(houseId);
Long masterId =Long.getLong("0");
for (int i=0;i<houseUserList.size();i++){
HouseUser houseUser=houseUserList.get(i);
if(houseUser.getType()){
masterId =houseUser.getUserId();
}
}
return masterId;
}
public List<Long> getCollecterId(Long houseId) {
List<HouseUser> houseUserList=houseUserMapper.getMaster(houseId);
List<Long> collectIds = new ArrayList<>();
for (int i=0;i<houseUserList.size();i++){
HouseUser houseUser=houseUserList.get(i);
if(!houseUser.getType()){
collectIds.add(houseUser.getUserId());
}
}
return collectIds;
}
public List<Long> getMyHouseId(Long userId) {
List<HouseUser> houseUserList=houseUserMapper.getMyHoust(userId);
// System.out.println("getMyHouseId:"+houseUserList);
List<Long> myHouseId = new ArrayList<>();
if(houseUserList!=null){
for (int i=0;i<houseUserList.size();i++){
HouseUser houseUser=houseUserList.get(i);
if(houseUser.getType()){
System.out.println("my houseUser:"+houseUser);
Long a=houseUser.getHouseId();
myHouseId.add(a);
}
}
}
System.out.println("my houseUser:"+myHouseId);
return myHouseId;
}
public List<Long> getCollectHouseId(Long userId) {
List<HouseUser> houseUserList=houseUserMapper.getMyHoust(userId);
// System.out.println("getCollectHouseId:"+houseUserList);
List<Long> CollectIds = new ArrayList<>();
if(houseUserList!=null){
for (int i=0;i<houseUserList.size();i++){
HouseUser houseUser=houseUserList.get(i);
if(!houseUser.getType()){
System.out.println("collect houseUser:"+houseUser);
CollectIds.add(houseUser.getHouseId());
}
}
}
System.out.println("collect houseUser:"+CollectIds);
return CollectIds;
}
}
<file_sep>package com.shao.house.house.service.infa;
public interface IHouseService {
}
<file_sep>package com.shao.house.house.model;
import java.util.Date;
public class HouseUser {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column house_user.id
*
* @mbggenerated
*/
private Long id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column house_user.house_id
*
* @mbggenerated
*/
private Long houseId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column house_user.user_id
*
* @mbggenerated
*/
private Long userId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column house_user.create_time
*
* @mbggenerated
*/
private Date createTime;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column house_user.type
*
* @mbggenerated
*/
private Boolean type;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house_user.id
*
* @return the value of house_user.id
*
* @mbggenerated
*/
public Long getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house_user.id
*
* @param id the value for house_user.id
*
* @mbggenerated
*/
public void setId(Long id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house_user.house_id
*
* @return the value of house_user.house_id
*
* @mbggenerated
*/
public Long getHouseId() {
return houseId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house_user.house_id
*
* @param houseId the value for house_user.house_id
*
* @mbggenerated
*/
public void setHouseId(Long houseId) {
this.houseId = houseId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house_user.user_id
*
* @return the value of house_user.user_id
*
* @mbggenerated
*/
public Long getUserId() {
return userId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house_user.user_id
*
* @param userId the value for house_user.user_id
*
* @mbggenerated
*/
public void setUserId(Long userId) {
this.userId = userId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house_user.create_time
*
* @return the value of house_user.create_time
*
* @mbggenerated
*/
public Date getCreateTime() {
return createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house_user.create_time
*
* @param createTime the value for house_user.create_time
*
* @mbggenerated
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house_user.type
*
* @return the value of house_user.type
*
* @mbggenerated
*/
public Boolean getType() {
return type;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house_user.type
*
* @param type the value for house_user.type
*
* @mbggenerated
*/
public void setType(Boolean type) {
this.type = type;
}
@Override
public String toString() {
return "HouseUser{" +
"id=" + id +
", houseId=" + houseId +
", userId=" + userId +
", createTime=" + createTime +
", type=" + type +
'}';
}
}<file_sep>package com.shao.house.house.controller;
import com.alibaba.fastjson.JSONObject;
import com.shao.house.house.model.House;
import com.shao.house.house.model.HouseUser;
import com.shao.house.house.model.User;
import com.shao.house.house.service.HouseService;
import com.shao.house.house.service.HouseUserService;
import com.shao.house.house.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@CrossOrigin//解决跨域问题!
@Controller
@ResponseBody
public class HouseUserController {
@Autowired
private HouseUserService houseUserService;
@Autowired
private UserService userService;
@Autowired
private HouseService houseService;
@RequestMapping(value = {"/getMaster"})
public User getMaster(@RequestBody JSONObject data){
System.out.println("data:"+data);
long userId = houseUserService.getMasterId(data.getLong("houseId"));
System.out.println("userId:"+userId);
User user =userService.selectByPrimaryKey(userId);
if(user!=null){
System.out.println("user:"+user);
return user;
}else {
return new User();
}
}
@RequestMapping(value = {"/getHouses"})
public JSONObject getCollectHouses (@RequestBody JSONObject data){
System.out.println("data:"+data);
List<House> houseListCollect=new ArrayList<>();
List<House> houseListMy=new ArrayList<>();
List<Long> collectHouseIds = new ArrayList<>();
List<Long> myHouseIds = new ArrayList<>();
JSONObject object=new JSONObject();
myHouseIds=houseUserService.getMyHouseId(data.getLong("userId"));
collectHouseIds=houseUserService.getCollectHouseId(data.getLong("userId"));
if(collectHouseIds!=null){
for(int i=0;i<collectHouseIds.size();i++){
House house=houseService.selectByPrimaryKey(collectHouseIds.get(i));
if (house!=null){
System.out.println(house);
houseListCollect.add(house);
}
}
}
if(myHouseIds!=null){
for(int i=0;i<myHouseIds.size();i++){
House house=houseService.selectByPrimaryKey( myHouseIds.get(i) );
if (house!=null){
System.out.println(house);
houseListMy.add(house);
}
}
}
// System.out.println("houseListCollect houseListMy"+houseListCollect+houseListMy);
object.put("houseListCollect",houseListCollect);
object.put("houseListMy",houseListMy);
// System.out.println("houseListCollect houseListMy"+object);
return object;
}
}
<file_sep>package com.shao.house.house.other;
import sun.awt.SunHints;
public class Tag {
public static final Tags TAGS=new Tags();
}
<file_sep>package com.shao.house.house.other;
import javax.enterprise.inject.New;
import java.util.HashMap;
import java.util.List;
public class Tags {
public static HashMap maps;
{
HashMap hashMap =new HashMap();
hashMap.put(1,"精装修");
hashMap.put(2,"交通便利");
hashMap.put(3,"毛坯房");
hashMap.put(4,"有全套家具");
hashMap.put(5,"拎包入住");
hashMap.put(6,"地铁站附近");
hashMap.put(7,"隔音好");
hashMap.put(8,"支持合租");
hashMap.put(9,"押一付三");
hashMap.put(0,"押一付一");
hashMap.put(10,"独家");
hashMap.put(11,"学区房");
hashMap.put(12,"唯一住房");
this.maps=hashMap;
}
public HashMap getMaps() {
return maps;
}
public String getContent(Integer id) {
System.out.println("id:"+id);
return maps.get(id).toString();
}
}
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50719
Source Host : localhost:3306
Source Database : houses
Target Server Type : MYSQL
Target Server Version : 50719
File Encoding : 65001
Date: 2019-04-11 15:08:06
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for community
-- ----------------------------
DROP TABLE IF EXISTS `community`;
CREATE TABLE `community` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`city_code` varchar(11) NOT NULL DEFAULT '' COMMENT '城市编码',
`city_name` varchar(11) NOT NULL DEFAULT '' COMMENT '城市名称',
`name` varchar(50) NOT NULL DEFAULT '' COMMENT '小区名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='小区表';
-- ----------------------------
-- Table structure for house
-- ----------------------------
DROP TABLE IF EXISTS `house`;
CREATE TABLE `house` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(20) NOT NULL DEFAULT '' COMMENT '房屋名字',
`type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1销售2出租',
`price` int(11) NOT NULL DEFAULT '0' COMMENT '单位:元',
`images` varchar(1024) NOT NULL DEFAULT '' COMMENT '图片地址',
`area` int(11) NOT NULL DEFAULT '0' COMMENT '面积',
`beds` int(11) NOT NULL DEFAULT '0' COMMENT '卧室数',
`baths` int(11) NOT NULL DEFAULT '0' COMMENT '卫生间数',
`remarks` varchar(512) NOT NULL DEFAULT '' COMMENT '房屋描述',
`floor_plan` varchar(255) NOT NULL DEFAULT '' COMMENT '户型图地址',
`tags` varchar(20) NOT NULL DEFAULT '' COMMENT '标签',
`create_time` datetime NOT NULL DEFAULT '2019-01-01 00:00:00' COMMENT '创建时间',
`city_id` int(11) NOT NULL DEFAULT '0' COMMENT '城市名称',
`community_id` int(11) NOT NULL DEFAULT '0' COMMENT '小区名称',
`state` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1上架2下架',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for house_user
-- ----------------------------
DROP TABLE IF EXISTS `house_user`;
CREATE TABLE `house_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`house_id` bigint(20) NOT NULL DEFAULT '0',
`user_id` bigint(20) NOT NULL DEFAULT '0',
`create_time` datetime NOT NULL DEFAULT '2019-01-01 00:00:00' COMMENT '创建时间',
`type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1售卖 2收藏',
PRIMARY KEY (`id`),
KEY `house_id_user_id_type` (`house_id`,`user_id`,`type`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='维护房产和用户的关系';
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(20) NOT NULL DEFAULT '' COMMENT '姓名',
`phone` char(13) NOT NULL DEFAULT '' COMMENT '电话',
`email` varchar(90) NOT NULL DEFAULT '' COMMENT '电子邮件地址',
`aboutme` varchar(255) NOT NULL DEFAULT '' COMMENT '自我介绍',
`password` varchar(255) NOT NULL DEFAULT '' COMMENT '经过md5加密的密码',
`avatar` varchar(255) NOT NULL DEFAULT '' COMMENT '头像',
`type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '类型 1普通用户 2房产经纪人',
`create_time` datetime NOT NULL DEFAULT '2019-01-01 00:00:00' COMMENT '创建时间',
`enable` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否启用 1启用 0停用',
PRIMARY KEY (`id`),
KEY ` idx_email` (`email`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';
<file_sep><file_sep>package com.shao.house.house.model;
import java.util.Date;
public class House {
private Long id;
private String name;
private Boolean type;
private Integer price;
private String images;
private Integer area;
private Integer beds;
private Integer baths;
private String remarks;
private String floorPlan;
private String tags;
private Date createTime;
private Integer cityId;
private Integer communityId;
private Boolean state;
public Long getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.id
*
* @param id the value for house.id
*
* @mbggenerated
*/
public void setId(Long id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.name
*
* @return the value of house.name
*
* @mbggenerated
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.name
*
* @param name the value for house.name
*
* @mbggenerated
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.type
*
* @return the value of house.type
*
* @mbggenerated
*/
public Boolean getType() {
return type;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.type
*
* @param type the value for house.type
*
* @mbggenerated
*/
public void setType(Boolean type) {
this.type = type;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.price
*
* @return the value of house.price
*
* @mbggenerated
*/
public Integer getPrice() {
return price;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.price
*
* @param price the value for house.price
*
* @mbggenerated
*/
public void setPrice(Integer price) {
this.price = price;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.images
*
* @return the value of house.images
*
* @mbggenerated
*/
public String getImages() {
return images;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.images
*
* @param images the value for house.images
*
* @mbggenerated
*/
public void setImages(String images) {
this.images = images == null ? null : images.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.area
*
* @return the value of house.area
*
* @mbggenerated
*/
public Integer getArea() {
return area;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.area
*
* @param area the value for house.area
*
* @mbggenerated
*/
public void setArea(Integer area) {
this.area = area;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.beds
*
* @return the value of house.beds
*
* @mbggenerated
*/
public Integer getBeds() {
return beds;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.beds
*
* @param beds the value for house.beds
*
* @mbggenerated
*/
public void setBeds(Integer beds) {
this.beds = beds;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.baths
*
* @return the value of house.baths
*
* @mbggenerated
*/
public Integer getBaths() {
return baths;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.baths
*
* @param baths the value for house.baths
*
* @mbggenerated
*/
public void setBaths(Integer baths) {
this.baths = baths;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.remarks
*
* @return the value of house.remarks
*
* @mbggenerated
*/
public String getRemarks() {
return remarks;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.remarks
*
* @param remarks the value for house.remarks
*
* @mbggenerated
*/
public void setRemarks(String remarks) {
this.remarks = remarks == null ? null : remarks.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.floor_plan
*
* @return the value of house.floor_plan
*
* @mbggenerated
*/
public String getFloorPlan() {
return floorPlan;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.floor_plan
*
* @param floorPlan the value for house.floor_plan
*
* @mbggenerated
*/
public void setFloorPlan(String floorPlan) {
this.floorPlan = floorPlan == null ? null : floorPlan.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.tags
*
* @return the value of house.tags
*
* @mbggenerated
*/
public String getTags() {
return tags;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.tags
*
* @param tags the value for house.tags
*
* @mbggenerated
*/
public void setTags(String tags) {
this.tags = tags == null ? null : tags.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.create_time
*
* @return the value of house.create_time
*
* @mbggenerated
*/
public Date getCreateTime() {
return createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.create_time
*
* @param createTime the value for house.create_time
*
* @mbggenerated
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.city_id
*
* @return the value of house.city_id
*
* @mbggenerated
*/
public Integer getCityId() {
return cityId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.city_id
*
* @param cityId the value for house.city_id
*
* @mbggenerated
*/
public void setCityId(Integer cityId) {
this.cityId = cityId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.community_id
*
* @return the value of house.community_id
*
* @mbggenerated
*/
public Integer getCommunityId() {
return communityId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.community_id
*
* @param communityId the value for house.community_id
*
* @mbggenerated
*/
public void setCommunityId(Integer communityId) {
this.communityId = communityId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column house.state
*
* @return the value of house.state
*
* @mbggenerated
*/
public Boolean getState() {
return state;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column house.state
*
* @param state the value for house.state
*
* @mbggenerated
*/
public void setState(Boolean state) {
this.state = state;
}
@Override
public String toString() {
return "House{" +
"id=" + id +
", name='" + name + '\'' +
", type=" + type +
", price=" + price +
", images='" + images + '\'' +
", area=" + area +
", beds=" + beds +
", baths=" + baths +
", remarks='" + remarks + '\'' +
", floorPlan='" + floorPlan + '\'' +
", tags='" + tags + '\'' +
", createTime=" + createTime +
", cityId=" + cityId +
", communityId=" + communityId +
", state=" + state +
'}';
}
}<file_sep>package com.shao.house.house.controller;
import com.alibaba.fastjson.JSONObject;
import com.shao.house.house.model.House;
import com.shao.house.house.model.User;
import com.shao.house.house.service.UserService;
import jdk.nashorn.internal.scripts.JO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
@CrossOrigin//解决跨域问题!
@Controller
@ResponseBody
public class UserController {
@Autowired
public UserService userService;
@RequestMapping(value = {"/emailLogin"})
public JSONObject login(@RequestBody JSONObject data) {
System.out.println(data);
JSONObject Object = new JSONObject();
System.out.println("email:" + data.getString("email"));
User user = userService.selectByEmail(data.getString("email"));
// System.out.println("user:"+user.toString());
if (user == null) {
List<Integer> list = new LinkedList<>();
System.out.println("meiyou !");
Object.put("state", 2);
} else {
if (user.getPassword().equals(data.getString("pass"))) {
Object.put("state", 0);
Object.put("user", user);
} else {
Object.put("state", 1);
}
}
// System.out.println(user.toString());
return Object;
}
@RequestMapping(value = {"/register"})
public JSONObject insetuser(@RequestBody JSONObject data) {
System.out.println(data);
User user = new User();
user.setAboutme(data.getString("aboutme"));
user.setAvatar(data.getString("avatar"));
user.setCreateTime(new Date());
user.setEmail(data.getString("email"));
user.setName(data.getString("name"));
user.setPassword(data.getString("<PASSWORD>"));
user.setPhone(data.getString("phone"));
user.setType(true);
user.setEnable(true);
long state = userService.insertSelective(user);
// long state = 1;
JSONObject object = new JSONObject();
if (state == 1) {
User getUser = userService.selectByEmail(data.getString("email"));
// User getUser=userService.selectByEmail("11");
object.put("user", getUser);
System.out.println("state:" + state + " user: " + getUser);
}
object.put("state", state);
return object;
}
@RequestMapping(value = {"/edit"})
public JSONObject upUser(@RequestBody JSONObject data) {
System.out.println(data);
User user = new User();
user.setAboutme(data.getString("aboutme"));
user.setId(data.getLong("id"));
user.setAvatar(data.getString("avatar"));
user.setPhone(data.getString("phone"));
long state = userService.updateByPrimaryKeySelective(user);
// long state = 1;
JSONObject object = new JSONObject();
if (state == 1) {
User getUser = userService.selectByEmail(data.getString("email"));
// User getUser=userService.selectByEmail("11");
object.put("user", getUser);
System.out.println("state:" + state + " user: " + getUser);
}
object.put("state", state);
return object;
}
@RequestMapping(value = {"/user/{id}"})
public User getHouseBuId(@PathVariable int id) {
// System.out.println(new House());
System.out.println("id:" + id);
User user = userService.selectByPrimaryKey((long) id);
// System.out.println(user.toString());
return user;
}
@RequestMapping(value = {"/hello"})
public String index(Object object) {
Logger log = Logger.getLogger("hello ");
log.info("kkkkk");
System.out.println("hello world");
System.out.println(object);
return "Hello World";
}
}
|
055d4eedac894b3a9f7a3c6756e6587e86b3d98e
|
[
"Markdown",
"Java",
"SQL"
] | 12 |
Java
|
suiliuxunying/houses
|
60cc8d7e3b3dd54f572433e7503afd59acf315bb
|
4a682c5b06ca6059bae8867317c4a2f9fd1032da
|
refs/heads/master
|
<file_sep><?php
namespace Helpers;
class Tools {
private static $posts = array();
// --- XSS free
public static function getPost($name, $default = "") {
if (array_key_exists($name, $_POST)) {
$post = $_POST[$name];
if (is_string($post))
$post = self::_sanitize($post);
return $post;
}
return $default;
}
public static function getGet($name, $default = "") {
if (array_key_exists($name, $_GET)) {
$get = $_GET[$name];
if (is_string($get))
$get = self::_sanitize($get);
return $get;
}
return $default;
}
public static function getRequest($name, $default = "") {
if (array_key_exists($name, $_REQUEST)) {
$req = $_REQUEST[$name];
if (is_string($req))
$req = self::_sanitize($req);
return $req;
}
return $default;
}
// --- Raw
public static function getRawPost($name, $default = "") {
if (array_key_exists($name, $_POST))
return $_POST[$name];
return $default;
}
public static function getRawGet($name, $default = "") {
if (array_key_exists($name, $_GET))
return $_GET[$name];
return $default;
}
public static function getRawRequest($name, $default = "") {
if (array_key_exists($name, $_REQUEST))
return $_REQUEST[$name];
return $default;
}
// --- Private functions
// Prevent XSS injection
private static function _sanitize($value) {
return strip_tags( trim($value) );
}
}
<file_sep><?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit2e88ac0d7fab9c9a543e40cd443dad0f::getLoader();
<file_sep><?php
namespace Models;
use Core\Model;
use Helpers\Database;
class mAccueil extends Model{
const F_ID_RECETTE = "id_recette";
const F_NOM_RECETTE = "nom_recette";
const F_ID_INGREDIENT = "id_ingredient";
const F_NOM_INGREDIENT = "nom_ingredient";
private $table = Database::K_V_RECSINGS;
public function __construct()
{
parent::__construct();
}
public function getRecetteRandom()
{
$idRecette = self::F_ID_RECETTE;
$sql = "SELECT * FROM $this->table ";
$sql .= "ORDER BY RAND() LIMIT 1 ";
return $this->db->select($sql);
}
}<file_sep>var addReceipes = {
template:`
<div class="col-xs-6">
<h2>Add tes recettes: </h2>
<div class="row">
<div class="col-xs-12">
<label>Nom de la recette: </label>
<input type="text">
Ex: <NAME>
</div>
<div class="col-xs-12">
<label>Temps de préparation/cuisson de la recette: </label>
<input type="text">
Ex: 80
</div>
<div class="col-xs-12">
<label>Niveau de difficulté de la recette: </label>
<input type="text">
Ex: Facile/Moyen/Difficile
</div>
<div class="col-xs-12">
<button class="">Go</button>
</div>
</div>
</div>`,
}<file_sep><?php
namespace Controllers;
use Core\Controller;
use Core\View;
use Helpers\Assets;
use Helpers\Url;
use Helpers\Tools;
use Models\mAddIngredient;
class AjoutRecetteController extends Controller {
public function __construct() {
parent::__construct();
}
public function ajax()
{
$action = Tools::getPost("action");
$dbg["action"] = $action;
if($action == "save-ingredient")
{
$this->addIngredient($dbg);
}
}
public function index() {
$data['JS'] = Assets::js([
]);
View::renderTemplate('header', $data);
View::render('ajoutRecetteView', $data);
View::renderTemplate('footer', $data);
}
public function addIngredient($dbg)
{
// Récuperation des infos de l'ingredient
$nom = Tools::getPost("nom");
$type = Tools::getPost("type");
$cal = Tools::getPost("cal");
$prix = Tools::getPost("prix");
var_dump($nom, $type, $cal, $prix).die;
$model = new mAddIngredient();
//$model->addIngredient();
}
}<file_sep>"use strict";
var addIngredients = {
props: ["value", "placeholders"],
template: `
<div class="col-xs-6">
<h2>Add tes ingrédients: </h2>
<div class="row">
<div class="col-xs-12 text-center form-group">
<label class="col-xs-12">Nom de l'ingrédient: </label>
<input class="input-style form-control" type="text" :placeholder="placeholders.nomIng" v-model="value.nomIng">
</div>
<div class="col-xs-12 text-center form-group">
<label class="col-xs-12">Type de l'ingrédient: </label>
<input class="input-style form-control" type="text" :placeholder="placeholders.typeIng" v-model="value.typeIng">
</div>
<div class="col-xs-12 text-center form-group">
<label class="col-xs-12">Calories de l'ingrédient /100g: </label>
<input class="input-style form-control" type="text" :placeholder="placeholders.calIng" v-model="value.calIng">
</div>
<div class="col-xs-12 text-center form-group">
<label class="col-xs-12">Prix de l'ingrédient /kg: </label>
<input class="input-style form-control" type="text" :placeholder="placeholders.prixIng" v-model="value.prixIng">
</div>
<div class="col-xs-12 text-center form-group">
<button class="btn btn-success" style="width:50%;" @click="clickBtn">Ajouter l'ingrédient</button>
</div>
</div>
</div>`,
methods: {
clickBtn: function() {
/* if(!(this.value.nomIng && this.value.typeIng && this.value.calIng && this.value.prixIng)) {
return alert(Error.ErrSaisie);
} */
this.$emit("save-ingredient");
},
},
}
<file_sep><?php
namespace Models;
use Core\Model;
class mAddIngredient extends Model {
public function __construct()
{
parent::__construct();
}
public function addIngredient($nom, $type, $calories, $prix)
{
}
}
<file_sep><?php
extract($data);
use Helpers\Url;
?>
<script>
var ajaxUrladdIng = "<?= Url::URI_AJAX_ADD; ?>";
console.log(ajaxUrladdIng)
</script>
<div id="app">
<add-ingredients v-model="ingredient" :placeholders="grille.placeholdersIng" @save-ingredient="saveIng"></add-ingredients>
<add-receipes></add-receipes>
</div><file_sep><?php
/**
* Welcome controller.
*
* @author <NAME> - <EMAIL>
*
* @version 2.2
* @date June 27, 2014
* @date updated Sept 19, 2015
*/
namespace Controllers;
use Core\Controller;
use Core\View;
use Helpers\Assets;
use Helpers\Url;
use Helpers\hError;
use Helpers\Tools;
use Models\mAccueil;
/**
* Sample controller showing a construct and 2 methods and their typical usage.
*/
class Welcome extends Controller
{
/**
* Call the parent construct.
*/
public function __construct()
{
parent::__construct();
}
public function ajax() {
$action = Tools::getPost("action");
$dbg["action"] = $action;
if($action == "load-recette-random") {
$this->loadRecetteRandom($dbg);
return;
}
}
/**
* Define Index page title and load template files.
*/
public function index()
{
$data['title'] = "Accueil ";
$data['css'] = Assets::css([
]);
$data['js'] = Assets::js([
]);
View::renderTemplate('header', $data);
View::render('welcome/welcome', $data);
View::renderTemplate('footer', $data);
}
public function loadRecetteRandom($dbg)
{
$model = new mAccueil();
$recette = $model->getRecetteRandom();
$error = hError::NO_ERROR;
$array = [
"status" => $error,
"dbg" => $dbg,
"recette" => $recette,
];
echo json_encode($array);
exit();
}
/**
* Define Subpage page title and load template files.
*/
public function subPage()
{
$data['title'] = $this->language->get('subpage_text');
$data['welcome_message'] = $this->language->get('subpage_message');
View::renderTemplate('header', $data);
View::render('welcome/subpage', $data);
View::renderTemplate('footer', $data);
}
}
<file_sep><?php
namespace Helpers;
class hError {
const NO_ERROR = 1;
public const ERROR_AJAX = "L'action n'existe pas !";
public function getMessage($error)
{
echo self::$error;
}
}<file_sep>Error = {
ErrSaisie: "Erreur de saisie, vérifiez vos champs :)",
}<file_sep><?php
/**
* Sample layout.
*/
use Core\Language;
use Helpers\Assets;
use Helpers\Url;
extract($data);
?>
<script>
var ajaxAccueilUrl = "<?= DIR . Url::URI_AJAX_ACCUEIL ?>";
var srcPlat = "<?= DIR . Url::relativeTemplatePath() . "/img/" ?>";
</script>
<div class="row">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<div style=" margin-bottom: 20px; margin-top: 100px;">
<img id="image-du-plat" alt="" style="width: 100%; height: 100%">
</div>
<div id="nom-du-plat" class="text-center" style="margin-bottom: 20px; font-size: 20pt;"> Pâtes carbo ? </div>
<div class="row">
<button id="btn-non" onclick="clickBtnNon()" class="col-xs-6 btn btn-primary btn-lg">Non</button>
<button id="btn-oui" type="button" class="col-xs-6 btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Oui</button>
</div>
</div>
<div class="col-xs-4"></div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="btn-save" type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
|
5881da6af16b58be6a1455c0448e4ff2b4413775
|
[
"JavaScript",
"PHP"
] | 12 |
PHP
|
LaurentFrizon/koikonmange
|
bda071d5391fddafe6a0a582aefd0b801079ffa2
|
567c6d0e106ddc9aa2b8bafe23642b868cdf6c5b
|
refs/heads/master
|
<file_sep>/*************************************************************************
> File Name: mysql_test.cpp
> Created Time: 2014年05月06日 星期二 20时35分16秒
************************************************************************/
#include<iostream>
#include<string>
#include<mysql.h>
using namespace std;
int main()
{
MYSQL mysql;
MYSQL_RES *result;
MYSQL_FIELD *field;
MYSQL_ROW row;
mysql_init(&mysql);
mysql_real_connect(&mysql,"localhost","leo","123","db_2048",0,NULL,0);
mysql_query(&mysql,"select *from tb_record order by score desc");
result=mysql_use_result(&mysql);
cout<<"\n\t\t---------------GAME RECORD----------------"<<endl;;
cout<<" -------------------------------------------------------------------"<<endl;
string sep="\t|\t";
int attribute_cnt=1;
cout<<" ";
while((field=mysql_fetch_field(result))!=NULL)
{
cout<<field->name;
if(attribute_cnt<4)
cout<<sep;
++attribute_cnt;
}
cout<<endl;
cout<<" -------------------------------------------------------------------"<<endl;
int rank=1;
//bug! if there is a data named 'NULL' in db,there will apear a bug.
while((row=mysql_fetch_row(result)))
{
cout<<" "<<rank<<sep<<row[1]<<sep<<row[2]<<sep<<row[3]<<endl;
cout<<" -------------------------------------------------------------------"<<endl;
++rank;
}
mysql_free_result(result);
mysql_close(&mysql);
}
<file_sep>Old 2048 tiny game
How to run
1. make
2. ./interface.sh
How to play
1. Type Enter to show memu
2. Single Player Mode
When single mode selected, game will start after 3 mins
Input u(up)\d(down)\l(left)\r(right) to move
Input an integer "n" to random move "n" times
Input a(again) to restart game
Input q(quit) to quit game
After game input user name to store data into file(DB)
3. Network Head2Head
Type Enter to show menu
Select to be Server of Client
Establish server
Client input server's IP to connect to server
Client input "start game" to start game
Anyone who game over, the other will receive an the game result
4. High Scores
To query game record of Single Player Mode order by scores desc
5. How To Play
Refer to How to play
Note:
Input "q" to quit
<file_sep>#########################################################################
# File Name: interface.sh
# Created Time: 2014年05月07日 星期三 10时24分11秒
#########################################################################
#!/bin/bash
opt1="Single Player"
opt2="Network Head2Head"
opt3="High Scores"
opt4="How To Play"
opt5="Exit"
clear
echo "Welcome to my tiny game!"
echo "Give you order by input the number of the choices..."
echo
IFS='/'
opt="$opt1/$opt2/$opt3/$opt4/$opt5"
select var in $opt;do
if [ "$var" = $opt1 ]; then
echo You have choosed: $var
echo
echo After 3 seconds the game will begin...
echo
sleep 3
./game_start
elif [ "$var" = $opt2 ]; then
echo You have choosed: $var
echo
opt21="Choose To Be Server"
opt22="Choose To Be Client"
opt23="Go Back"
optin2="$opt21/$opt22/$opt23"
select var2 in $optin2;do
if [ "$var2" = $opt21 ]; then
echo You have choosed: $var2
echo
echo Wait for the client....
./tcpsrv
elif [ "$var2" = $opt22 ]; then
echo You have choosed: $var2
echo
echo -n "Input your host IP address:"
read IPaddr
echo Connecting to ths host $IPaddr ...
sleep 1
echo Try to input \'start game\' to start the game!
./tcpcli $IPaddr
elif [ "$var2" = $opt23 ]; then
echo You hava choosed: $var2
echo
break
fi
done
elif [ "$var" = $opt3 ];then
echo You have choosed: $var
# ./getRecord
elif [ "$var" = $opt4 ];then
echo You have choosed: $var
echo
less res/howToPlay
elif [ "$var" = $opt5 ];then
exit
else
echo Unknow input!
echo -e "\nAfter 1 seconds,you can input again...\n"
sleep 1
fi
done
IFS=' '
exit 0
<file_sep>-- MySQL dump 10.13 Distrib 5.5.37, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: db_2048
-- ------------------------------------------------------
-- Server version 5.5.37-0ubuntu0.14.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `tb_record`
--
DROP TABLE IF EXISTS `tb_record`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tb_record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(20) DEFAULT 'ANONYMOUS',
`score` int(11) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `tb_record`
--
LOCK TABLES `tb_record` WRITE;
/*!40000 ALTER TABLE `tb_record` DISABLE KEYS */;
INSERT INTO `tb_record` VALUES (1,'sys_1',2349,'2014-05-07 07:43:18'),(2,'sys_2',79834,'2014-05-07 07:43:18'),(21,'ANONYMOUS',64,'2014-05-07 11:51:38');
/*!40000 ALTER TABLE `tb_record` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2014-05-07 20:23:07
<file_sep>#########################################################################
# File Name: test_interface.sh
# Title:
# Description:
# Created Time: 2015年11月01日 星期日 10时43分56秒
#########################################################################
#!/bin/bash
opt1="single"
opt2="multiple"
opt3='exit'
clear
IFS='/'
opt="$opt1/$opt2/$opt3"
select var in $opt
do
if [ "$var" = $opt1 ]
then
echo "you choose single!"
echo "$var"
else
exit
fi
done
<file_sep>/*************************************************************************
> File Name: a.cpp
> Created Time: 2014年05月04日 星期日 22时10分06秒
************************************************************************/
#include<iostream>
#include<vector>
#include<stack>
#include<stdio.h>
#include<stdlib.h>
#include<ctime>
#include<cmath>
using namespace std;
int G[6][6];
int Score;
vector<int*> emptyG;
bool full=false; //boost up autoOperate speed
int moveTimes;
int actualMoveTimes;
void insertRecord(string name,int score);
void init();
void updateScore();
void yield();
void autoOperate(int cnt);
void moveGrids(char dir);
int getValue(char dir,int m,int n);
void changeValue(char dir,int (*G)[6],int m,int n,int value);
void printResult();
bool checkDeath();
void init()
{
moveTimes=0;
actualMoveTimes=-1;
//set border
for(int i=0;i!=6;++i)
{
G[0][i]=-1;
G[i][0]=-1;
G[5][i]=-1;
G[i][5]=-1;
}
emptyG.clear();
//inital grid and emptyGrid
for(int i=1;i<5;++i)
{
for(int j=1;j<5;++j)
{
G[i][j]=0;
emptyG.push_back(&G[i][j]);
}
}
yield();
printResult();
}
//creat 2 in empty grid randomly,update emptyG vector
void yield()
{
if(emptyG.empty())
cerr<<"Grids is full!Yield failed..."<<endl;
int offset=emptyG.size()-1; //caution offset=0 is special
int randomOffset;
if(offset==0)
randomOffset=0;
else
{
srand((unsigned)time(NULL));
randomOffset=rand()%offset;
}
vector<int*>::iterator iter=emptyG.begin()+randomOffset;
**iter=2;
//emptyG.erase(iter); //moveGrids will updte emptyG vector
++actualMoveTimes;
}
//update Score
void updateScore()
{
Score=0;
for(int i=1;i!=5;++i)
{
for(int j=1;j!=5;++j)
{
if(G[i][j]!=0&&G[i][j]!=2)
{
int temp=G[i][j];
Score+=temp*(log(temp)/log(2)-1);
}
}
}
}
//print current grids
void printResult()
{
updateScore();
system("clear");
cout<<"--------2048 C++ DEVISION HAVE FUN!!!-------\n"<<endl;
cout<<"Current Score:"<<Score<<endl;
cout<<"--------------------------------------------"<<endl;
for(int i=1;i!=5;++i)
{
for(int j=1;j!=5;++j)
{
if(j==1)
cout<<"\t";
if(G[i][j]!=0)
cout<<G[i][j]<<"\t";
else
cout<<"[]"<<"\t";
if(j==4)
cout<<endl;
}
cout<<endl;
}
cout<<"--------------------------------------------"<<endl;
cout<<endl;
}
//wait for operate
//before this emptyG.empty()=false should be promised
void waitOperate()
{
}
//belongs to moveGrids,help to handle the deriction
int getValue(char dir,int m,int n)
{
if(dir=='l')
{
int temp=m;
m=n;
n=temp;
}
if(dir=='d')
{
m=5-m;
}
if(dir=='r')
{
int temp=m;
m=n;
n=temp;
n=5-n;
}
return G[m][n];
}
void changeValue(char dir,int (*G)[6],int m,int n,int value)
{
if(dir=='l')
{
int temp=m;
m=n;
n=temp;
}
if(dir=='d')
{
m=5-m;
}
if(dir=='r')
{
int temp=m;
m=n;
n=temp;
n=5-n;
}
G[m][n]=value;
}
//move the grids,dir is in(u d ,s r)
//caution:when checkDeath=false && emptyG.empty()=true,there is a direction we can't move,only the other 3 choices will make sense
void moveGrids(char dir)
{
moveTimes++;
for(int j=1;j<5;++j)
{
//sum operation,put the result into stk
stack<int> stk;
for(int i=1;i<5;++i)
{
//int cur=G[i][j];
int cur=getValue(dir,i,j);
while(!stk.empty())
{
int before=stk.top();
if(before!=cur)
{
break;
}
else
{
stk.pop();
cur=cur+before;
}
}
if(cur!=0)
stk.push(cur);
}
//put the result into the current line
int sz=stk.size();
for(int i=sz+1;i<5;++i)
{
//G[i][j]=0;
changeValue(dir,G,i,j,0);
}
while(sz)
{
//G[sz][j]=stk.top();
changeValue(dir,G,sz,j,stk.top());
stk.pop();
--sz;
}
}
//update emptyG vector
emptyG.clear();
for(int i=1;i<5;++i)
{
for(int j=1;j<5;++j)
{
if(G[i][j]==0)
emptyG.push_back(&G[i][j]);
}
}
//boost autoOperation
if(emptyG.empty())
full=true;
else
full=false;
}
//check the Grids to return dead or not
bool checkDeath()
{
bool res=true;
for(int j=1;j<5;++j)
{
if(!res)
break;
for(int i=1;i<5;++i)
{
if(G[i][j]==0)
{
res=false;
break;
}
int t=G[i][j];
if(t==G[i+1][j]||t==G[i-1][j]||t==G[i][j+1]||t==G[i][j-1])
{
res=false;
break;
}
}
}
return res;
}
//auto operate cnt times
void autoOperate(int cnt)
{
cout<<"Auto operating "<<cnt<<" times,please wait...\n"<<endl;
char opt[4]={'u','d','l','r'};
while(cnt--)
{
if(full)
{
if(checkDeath())
break;
}
srand((unsigned)time(NULL));
int randomIx=rand()%4;
char dir=opt[randomIx];
moveGrids(dir);
if(full)
{
++cnt;
continue;
}
yield();
printResult();
}
printResult();
}
int main()
{
init();
bool quit=false; //use to quit the program
while(!checkDeath()&&!quit)
{
cout<<"----Input u (up) d(down) l(left) r(right) to move the Grids----"<<endl;
cout<<"--Input n(number) to let the Grids move n times automaticlly --"<<endl;
cout<<"-----Input q to quit the game,a(again) to restart the game-----"<<endl;
cout<<"Input>>";
char ch;
while(cin>>ch)
{
if(ch=='u'||ch=='d'||ch=='l'||ch=='r')
{
moveGrids(ch);
if(emptyG.empty())
continue;
yield();
printResult();
break;
}
else if(isdigit(ch))
{
int cnt=0;
cin.putback(ch);
cin>>cnt;
autoOperate(cnt);
break;
}
else if(ch=='q')
{
quit=true;
break;
}
else if(ch=='a')
{
init();
break;
}
else
{
//fflush(stdin);zo //vc6.0 not transplantable
char t;
while((t=getchar())!='\n')
;
cin.clear();
cout<<"Undefined Input!"<<endl;
cout<<"Input>>";
}
}
}
if(quit)
cout<<"------------------BYE BYE-------------------\n"<<endl;
else
cout<<"---------GAME OVER! STUPID MACHINE!--------\n"<<endl;
cout<<"-------Attempted To Move "<<moveTimes<<" Times.-------\n"<<endl;
cout<<"---Actual Moved "<<actualMoveTimes<<" Times. Final Score:"<<Score<<".---\n"<<endl;
string name;
string cleanStdin; //Caution:clean the stdin first,otherwise getline will read '\n' into name
getline(cin,cleanStdin);
cout<<"\nInput your name:";
getline(cin,name);
//insertRecord(name,Score);
}
<file_sep>#include"unp.h"
#include<pthread.h>
int Score;
void a2srv();
bool other_head_dead;
void* thr_fn(void *arg);
int sockfd, n;
char sendline[MAXLINE],recvline[MAXLINE];
int main(int argc, char **argv)
{
struct sockaddr_in servaddr;
pid_t pid;
if (argc != 2)
err_quit("usage: a.out <IPaddress>");
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
err_sys("socket error");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(1300);
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
err_quit("inet_pton error for %s", argv[1]);
if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
err_sys("connect error");
while(fgets(sendline,MAXLINE,stdin)!=NULL)
{
int n;
int other_score=0;
int ix=0;
if(!strcmp(sendline,"start game\n"))
{
pthread_t ntid;
int err;
writen(sockfd,sendline,strlen(sendline));
printf("After 3 seconds,the game will begin...\n");
sleep(3);
err=pthread_create(&ntid,NULL,thr_fn,NULL);
}
else
{
printf("Please input 'start game' to run the game!\n");
continue;
}
while( (n=readline(sockfd,recvline,MAXLINE))!=0)
{
if(!strcmp(recvline,"game over!!!\n"))
{
other_head_dead=true;
printf("Game over!\nWaiting for the result!\n");
}
else
{
recvline[n]='\0';
//printf("%d\n",n); //debug;
//printf("%s\n",recvline); //debug
while(recvline[ix]!='\0')
++ix;
for(int i=ix-1;i>=0;--i)
{
other_score=other_score*10+recvline[i]-'0';
}
printf("The other guy scored: %d\n",other_score);
if(Score>other_score)
printf("You win!\n");
else if(Score<other_score)
printf("You lose!\n");
else
printf("The game ends in a tie!\n");
exit(0);
}
}
}
exit(0);
}
void *thr_fn(void* arg)
{
a2srv();
printf("Your score is %d\n",Score);
strcpy(sendline,"game over!!!\n");
//printf("%s\n",sendline); //debug
writen(sockfd,sendline,strlen(sendline));
sleep(1);
char score[20];
int ix;
int temp=Score;
if(temp==0)
{
score[0]='0';
score[1]='\0';
}
else
{
for(ix=0;temp!=0;++ix)
{
score[ix]=temp%10+'0';
temp/=10;
}
score[ix]='\0';
}
strcpy(sendline,score);
//printf("%s\n",sendline); //debug
writen(sockfd,sendline,strlen(sendline));
}
<file_sep>#include<stdlib.h>
#include<unistd.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<stdio.h>
#include<errno.h>
#include<sys/wait.h>
#define SA struct sockaddr
#define MAXLINE 4096
#define LISTENQ 1024
#define bzero(ptr,n) memset(ptr,0,n)
void err_quit(const char *,...);
void err_sys(const char *,...);
void err_msg(const char *,...);
ssize_t writen(int,const void*,size_t);
ssize_t readline(int,void*,size_t);
<file_sep>/*************************************************************************
> File Name: mysql_test.cpp
> Created Time: 2014年05月06日 星期二 20时35分16秒
************************************************************************/
#include<iostream>
#include<string>
#include<string.h>
#include<stack>
#include<mysql.h>
using namespace std;
//work for insert values,change int into string
string intToString(int i)
{
if(i==0)
return "0";
string res;
stack<char> stk;
while(i!=0)
{
char cur=i%10;
stk.push('0'+cur);
i/=10;
}
while(!stk.empty())
{
char cur=stk.top();
res+=cur;
stk.pop();
}
return res;
}
void insertRecord(string name,int score)
{
MYSQL mysql;
mysql_init(&mysql);
if(NULL==mysql_real_connect(&mysql,"localhost","leo","123","db_2048",0,NULL,0))
cout<<"Connection has been estabilashed."<<endl;
string myQuery;
if(name=="")
{
myQuery="insert into tb_record(score) values(";
}
else
{
myQuery="insert into tb_record(user,score) values('";
myQuery+=name;
myQuery+="',";
}
myQuery+=intToString(score);
myQuery+=")";
if(mysql_real_query(&mysql,myQuery.c_str(),strlen(myQuery.c_str())))
{
cout<<"Insert error!"<<endl;
cout<<mysql_error(&mysql)<<endl;
}
}
<file_sep>EXECUTABLE=game_start tcpcli tcpsrv
all:$(EXECUTABLE)
game_start:
g++ -o game_start game.cpp
#insert.o:insert.cpp
#g++ -c insert.cpp -I/usr/include/mysql/ -L/usr/lib/mysql -lmysqlclient
#get:getRecord.cpp
#g++ getRecord.cpp -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient -o getRecord
tcpcli:tcpcli.cpp
g++ game4network.cpp tcpcli.cpp error.cpp writen.c readline.c -lpthread -I./ -o tcpcli
tcpsrv:tcpsrv.cpp
g++ game4network.cpp tcpsrv.cpp error.cpp writen.c -lpthread -I./ -o tcpsrv
clean:
rm *.o $(EXECUTABLE)
<file_sep>#include"unp.h"
#include<pthread.h>
int Score;
void a2srv();
bool other_head_dead;
void* thr_fn(void *arg);
int listenfd, connfd;
ssize_t n;
char buffpro[MAXLINE];
char buffthr[MAXLINE];
int main(int argc, char **argv)
{
struct sockaddr_in servaddr;
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(1300);
bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
listen(listenfd, LISTENQ);
for ( ; ; ) {
connfd = accept(listenfd, (SA *) NULL, NULL);
while( (n=read(connfd,buffpro,MAXLINE))>0)
{
buffpro[n]='\0';
//printf("buffpro1: %s\n",buffpro); //debug
if(!strcmp(buffpro,"start game\n"))
{
pthread_t ntid;
int err;
printf("After 3 seconds,the game will begin...\n");
sleep(3);
err=pthread_create(&ntid,NULL,thr_fn,NULL);
}
else if(!strcmp(buffpro,"game over!!!\n"))
{
other_head_dead=true;
printf("Game over!\nWaiting for the result!\n");
}
else
{
int other_score=0;
int ix=0;
//printf("buffpro1: %s\n",buffpro); //debug
while(buffpro[ix]!='\0')
++ix;
for(int i=ix-1;i>=0;--i)
{
other_score=other_score*10+buffpro[i]-'0';
}
printf("The other guy scored: %d\n",other_score);
sleep(6);
if(Score>other_score)
printf("You win!!!\n");
else if(Score<other_score)
printf("You lose!!!\n");
else
printf("The game ends in a tie!\n");
exit(0);
}
}
if(n<0)
err_sys("str_echo:read error");
close(connfd);
}
}
void *thr_fn(void* arg)
{
a2srv();
printf("Your score is %d\n",Score);
strcpy(buffthr,"game over!!!\n");
writen(connfd,buffthr,strlen(buffthr));
char score[20];
int ix;
int temp=Score;
if(temp==0)
{
score[0]='0';
score[1]='\0';
}
else
{
for(ix=0;temp!=0;++ix)
{
score[ix]=temp%10+'0';
temp/=10;
}
score[ix]='\0';
}
strcpy(buffthr,score);
//printf("%s\n",buffthr); //debug
writen(connfd,buffthr,strlen(buffthr));
}
|
6442b69df17f245412b0b3903e4c7fd097647489
|
[
"SQL",
"Markdown",
"Makefile",
"C",
"C++",
"Shell"
] | 11 |
C++
|
leowww24/2048
|
d4777232867812a5fec30259cecb59387fc1431a
|
fa603adc62859ae26a7b0f84b48028369d35cf49
|
refs/heads/master
|
<file_sep># ntupleSkim
# ntupleSkim
# ntupleSkim
<file_sep>#include <iostream>
#include <sstream>
#include <string>
#include <math.h>
#include <vector>
#include <algorithm>
#include "PDAnalyzer.h"
#include "TDirectory.h"
#include "TBranch.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TLorentzVector.h"
#include "TFile.h"
// additional features
#include "PDSecondNtupleWriter.h" // second ntuple
//#include "DataSetFilter.cc" // dataset filter
#include "PDMuonVar.cc"
#include "PDSoftMuonMvaEstimator.cc"
#include "AlbertoUtil.cc"
using namespace std;
/*
pdTreeAnalyze /lustre/cmswork/abragagn/ntuList/MC2016Lists/BsToJpsiPhi_BMuonFilter_2016_DCAP.list hist.root -v histoMode RECREATE -v use_gen t -n 10000
*/
PDAnalyzer::PDAnalyzer() {
std::cout << "new PDAnalyzer" << std::endl;
// user parameters are set as names associated to a string,
// default values can be set in the analyzer class contructor
setUserParameter( "verbose", "f" );
setUserParameter( "process", "BsJPsiPhi" );
setUserParameter( "useTightSel", "f" );
setUserParameter( "useHLT", "f" );
setUserParameter( "ptCut", "40.0" ); //needed for paolo's code for unknow reasons
}
PDAnalyzer::~PDAnalyzer() {
}
void PDAnalyzer::beginJob() {
PDAnalyzerUtil::beginJob();
// user parameters are retrieved as strings by using their names;
// numeric parameters ( int, float or whatever ) can be directly set
// by passing the corresponding variable,
// e.g. getUserParameter( "name", x )
getUserParameter( "verbose", verbose );
getUserParameter( "process", process );
getUserParameter( "useTightSel", useTightSel );
getUserParameter( "useHLT", useHLT );
getUserParameter( "ptCut", ptCut ); //needed for paolo's code for unknow reasons
// to skim the N-tuple "uncomment" the following lines
dropBranch( "*tau*" );
dropBranch( "*ele*" );
initWSkim( new TFile( "skim.root", "RECREATE" ) );
// additional features
// DataSetFilter::beginJob();
SetBpMassRange(5.15, 5.40);
return;
}
void PDAnalyzer::book() {
// putting "autoSavedObject" in front of the histo creation
// it's automatically marked for saving on file; the option
// is uneffective when not using the full utility
return;
}
void PDAnalyzer::reset() {
// automatic reset
autoReset();
return;
}
bool PDAnalyzer::analyze( int entry, int event_file, int event_tot ) {
if ( verbose ) {
cout << " +++++++++++++++++++++++++++ " << endl;
cout << "entry: "
<< entry << " " << event_file << " " << event_tot << endl;
cout << "run: " << runNumber << " , "
<< "evt: " << eventNumber << endl;
}
else {
if ( (!(event_tot%10) && event_tot<100 ) ||
(!(event_tot %100) && event_tot<1000 ) ||
(!(event_tot %1000) && event_tot<10000 ) ||
(!(event_tot %10000) && event_tot<100000 ) ||
(!(event_tot %100000) && event_tot<1000000 ) ||
(!(event_tot %1000000) && event_tot<10000000 ) )
cout << " == at event " << event_file << " " << event_tot << endl;
}
// flag to be set "true" or "false" for events accepted or rejected
int whichHLT = 0;
if(useHLT && (process=="BsJPsiPhi")){
bool hltFlag = false;
for(int i=0; i<nHLTStatus; ++i){
if(!hltAccept->at( i )) continue;
if((hltPath->at( i ) == PDEnumString::HLT_Dimuon0_Jpsi3p5_Muon2_v) || (hltPath->at( i ) == PDEnumString::HLT_Dimuon0_Jpsi_Muon_v)) {hltFlag = true; whichHLT += pow(2, 1);}
if(hltPath->at( i ) == PDEnumString::HLT_DoubleMu4_JpsiTrkTrk_Displaced_v) {hltFlag = true; whichHLT += pow(2, 2);}
if(hltPath->at( i ) == PDEnumString::HLT_DoubleMu4_JpsiTrk_Displaced_v) {hltFlag = true; whichHLT += pow(2, 3);}
}
if(!hltFlag) return false;
}
if(useHLT && (process=="BuJPsiK")){
bool hltFlag = false;
for(int i=0; i<nHLTStatus; ++i){
if(!hltAccept->at( i )) continue;
if(hltPath->at( i ) == PDEnumString::HLT_DoubleMu4_JpsiTrk_Displaced_v) {hltFlag = true; whichHLT += pow(2, 3);}
}
if(!hltFlag) return false;
}
if(nMuons<3) return false;
if( GetCandidate(process, useTightSel)<0 ) return false;
fillSkim();
return true;
}
void PDAnalyzer::endJob() {
// to skim the N-tuple "uncomment" the following line
closeSkim();
return;
}
void PDAnalyzer::save() {
# if UTIL_USE == FULL
// explicit saving not necessary for "autoSavedObjects"
autoSave();
#elif UTIL_USE == BARE
// explicit save histos when not using the full utility
#endif
return;
}
// to plot some histogram immediately after the ntuple loop
// "uncomment" the following lines
/*
void PDAnalyzer::plot() {
TCanvas* can = new TCanvas( "muoPt", "muoPt", 800, 600 );
can->cd();
can->Divide( 1, 2 );
can->cd( 1 );
hptmumax->Draw();
hptmu2nd->Draw();
return;
}
*/
// ======MY FUNCTIONS===============================================================================<file_sep>#ifndef PDSecondNtupleData_h
#define PDSecondNtupleData_h
#include <vector>
#include "NtuTool/Common/interface/TreeWrapper.h"
using namespace std;
class PDSecondNtupleData: public virtual TreeWrapper {
public:
void Reset() { autoReset(); }
PDSecondNtupleData() {
muoPt = new vector <float>;
muoEta = new vector <float>;
muoPhi = new vector <float>;
trkDxy = new vector <float>;
trkExy = new vector <float>;
trkDz = new vector <float>;
trkEz = new vector <float>;
muoPFiso = new vector <float>;
muoLund = new vector <int>;
muoAncestor = new vector <int>;
muoSoftMvaValue = new vector <float>;
}
virtual ~PDSecondNtupleData() {
}
void initTree() {
treeName = "PDsecondTree";
setBranch( "muoPt", &muoPt , 8192, 99, &b_muoPt );
setBranch( "muoEta", &muoEta , 8192, 99, &b_muoEta );
setBranch( "muoPhi", &muoPhi , 8192, 99, &b_muoPhi );
setBranch( "trkDxy", &trkDxy , 8192, 99, &b_trkDxy );
setBranch( "trkExy", &trkExy , 8192, 99, &b_trkExy );
setBranch( "trkDz", &trkDz , 8192, 99, &b_trkDz );
setBranch( "trkEz", &trkEz , 8192, 99, &b_trkEz );
setBranch( "muoPFiso", &muoPFiso , 8192, 99, &b_muoPFiso );
setBranch( "muoLund", &muoLund , 8192, 99, &b_muoLund );
setBranch( "muoAncestor", &muoAncestor , 8192, 99, &b_muoAncestor );
setBranch( "muoSoftMvaValue", &muoSoftMvaValue , 8192, 99, &b_muoSoftMvaValue );
}
vector <int> *muoLund, *muoAncestor;
vector <float> *muoSoftMvaValue;
vector <float> *muoPt, *muoEta, *muoPhi, *trkDxy, *trkExy, *trkDz, *trkEz, *muoPFiso;
TBranch *b_muoPt, *b_muoEta, *b_muoPhi, *b_trkDxy, *b_trkExy, *b_trkDz, *b_trkEz, *b_muoPFiso;
TBranch *b_muoLund, *b_muoAncestor, *b_muoSoftMvaValue;
private:
PDSecondNtupleData ( const PDSecondNtupleData& a );
PDSecondNtupleData& operator=( const PDSecondNtupleData& a );
};
#endif
|
b4808d7221d326feafd072643490abd5ab2cb374
|
[
"Markdown",
"C++"
] | 3 |
Markdown
|
abragagn/BPHPD-ntupleSkim
|
5fb7fdf1b67e69b1a0ca6e5dccfb9fa1a4a6f74d
|
4c31820595be54accbd4d38c9f89bfe38633faa4
|
refs/heads/master
|
<repo_name>Naveen2905/weUnited<file_sep>/scripts/liveData.js
const liveDataApp = {
url: `https://api.covid19api.com/summary`
};
//Country Covid-19 Data
liveDataApp.all = function (countryName) {
$.ajax({
url: liveDataApp.url,
method: 'GET',
dataType: 'json',
}).then(function (response) {
const allCountries = response.Countries;
//Iterating through Array
allCountries.forEach(country => {
const selectedCountry = country.Slug;
if (countryName == selectedCountry) {
console.log(`${countryName} = ${selectedCountry}`);
//Country Name
const name = country.Country;
$('.coName').html(`<h3>${name}</h3>`);
//New Cases
$('.newHeading').html(`New Cases`)
const newCon = country.NewConfirmed;
$('.nCon').html(`Confirmed : ${newCon}`);
const newDeaths = country.NewDeaths;
$('.nDeaths').html(`Deaths : ${newDeaths}`);
const newRecovered = country.NewRecovered;
$('.nRecovered').html(`Recovered : ${newRecovered}`);
// Total Cases
$('.totalHeading').html(`Total Cases`)
const totalCon = country.TotalConfirmed;
$('.tCon').html(`Confirmed : ${totalCon}`);
const totalDeaths = country.TotalDeaths;
$('.tDeaths').html(`Deaths : ${totalDeaths}`);
const totalRecovered = country.TotalRecovered;
$('.tRecovered').html(`Recovered : ${totalRecovered}`);
}
})
})
}
liveDataApp.init = function () {
liveDataApp.all()
// Function to get country and display news;
$('.countrySearch').on('submit', function (e) {
e.preventDefault();
const countryName = $('#countryName').val().toLowerCase();
this.reset();
liveDataApp.all(countryName);
});
}
$(function () {
liveDataApp.init();
$.ajax({
url: liveDataApp.url,
method: 'GET',
dataType: 'json',
}).then(function (response) {
const allCountries = response.Countries;
//Iterating through Array
allCountries.forEach(country => {
const selectedCountry = country.Slug;
if ('india' == selectedCountry) {
//Country Name
const name = country.Country;
$('.coName').append(`<h3>${name}</h3>`);
//New Cases
$('.newHeading').append(`New Cases`)
const newCon = country.NewConfirmed;
$('.nCon').append(`Confirmed : ${newCon}`);
const newDeaths = country.NewDeaths;
$('.nDeaths').append(`Deaths : ${newDeaths}`);
const newRecovered = country.NewRecovered;
$('.nRecovered').append(`Recovered : ${newRecovered}`);
// Total Cases
$('.totalHeading').append(`Total Cases`)
const totalCon = country.TotalConfirmed;
$('.tCon').append(`Confirmed : ${totalCon}`);
const totalDeaths = country.TotalDeaths;
$('.tDeaths').append(`Deaths : ${totalDeaths}`);
const totalRecovered = country.TotalRecovered;
$('.tRecovered').append(`Recovered : ${totalRecovered}`);
//Indian States Cases
fetch("https://corona-virus-world-and-india-data.p.rapidapi.com/api_india", {
"method": "GET",
"headers": {
"x-rapidapi-key": "<KEY>",
"x-rapidapi-host": "corona-virus-world-and-india-data.p.rapidapi.com"
}
})
.then(response => response.json())
.then(function (data) {
$(".loading").hide();
const allStates = data.state_wise;
// const stateArray = []
// stateArray.push(allStates)
// stateArray.forEach(function (eachData) {
// console.log(eachData);
// })
for (const property in allStates) {
const stateName = property
const stateData = allStates[property]
if (stateName === 'State Unassigned') {
return false
}
$('.states').append(`<li class='stateLinks'><a href="#">${stateName}</a></li>`)
$('.stateLinks a').on('click', function () {
if (this.text === stateName) {
const currentCityData = stateData;
const nCases = currentCityData.deltaconfirmed;
const nDeaths = currentCityData.deltadeaths;
const nRecovered = currentCityData.deltarecovered
const lastUpdated = currentCityData.lastupdatedtime
swal(stateName + " Data", 'New Cases: ' + nCases + '\n' + 'New Deaths: ' + nDeaths + '\n' + 'New Recovered: ' + nRecovered + '\n' + '\n' + 'Last Updated data on ' + lastUpdated);
}
})
}
})
.catch(err => {
console.error(err);
});
}
})
})
});<file_sep>/scripts/news.js
const worldNewsApp = {
query: `"coronavirus" OR "covid-19"`,
key: 'dbd2da25f5f84f779e6ee7f7c49c5f7d',
pageSize: 20,
}
const newsApp = {
key: 'dbd2da25f5f84f779e6ee7f7c49c5f7d',
query: 'covid-19',
category: 'health',
country: 'ca',
};
const indiaNewsApp = {
key: 'dbd2da25f5f84f779e6ee7f7c49c5f7d',
query: 'covid-19',
category: 'health',
country: 'in',
};
//World News---------------------------------
worldNewsApp.world = function () {
$('ul.newsLists').empty(); // empty the ul before fetching and adding new data
$.ajax({
url: `https://newsapi.org/v2/everything`,
method: 'GET',
dataType: 'json',
data: {
apiKey: worldNewsApp.key,
q: worldNewsApp.query,
pageSize: worldNewsApp.pageSize,
}
}).then(function (data) {
data.articles.forEach(function (eachWorldNews) {
const htmlToAppend = `<li>
<a href=${eachWorldNews.url} target="_blank">
<h3>${eachWorldNews.title}</h3>
<img src=${eachWorldNews.urlToImage} alt="${eachWorldNews.title}">
<p>${eachWorldNews.description}</p>
</a>
</li>`
$('ul.newsLists').append(htmlToAppend);
})
})
}
//Canada news ----------------------------------
newsApp.canada = function () {
$('ul.newsLists').empty(); // empty the ul before fetching and adding new data
$.ajax({
url: `https://newsapi.org/v2/top-headlines`,
method: 'GET',
dataType: 'json',
data: {
apiKey: newsApp.key,
q: newsApp.query,
category: newsApp.category,
country: newsApp.country,
}
}).then(function (result) {
// Iterrating through array
result.articles.forEach(function (eachNews) {
const htmlToAppend = `<li>
<a href=${eachNews.url} target="_blank">
<h3>${eachNews.title}</h3>
<img src=${eachNews.urlToImage} alt="${eachNews.title}">
<p>${eachNews.description}</p>
</a>
</li>`
$('ul.newsLists').append(htmlToAppend);
})
})
}
//India news ----------------------------------
indiaNewsApp.india = function () {
$('ul.newsLists').empty(); // empty the ul before fetching and adding new data
$.ajax({
url: `https://newsapi.org/v2/top-headlines`,
method: 'GET',
dataType: 'json',
data: {
apiKey: indiaNewsApp.key,
q: indiaNewsApp.query,
category: indiaNewsApp.category,
country: indiaNewsApp.country,
}
}).then(function (result) {
// Iterrating through array
result.articles.forEach(function (eachNews) {
const htmlToAppend = `<li>
<a href=${eachNews.url} target="_blank">
<h3>${eachNews.title}</h3>
<img src=${eachNews.urlToImage} alt="${eachNews.title}">
<p>${eachNews.description}</p>
</a>
</li>`
$('ul.newsLists').append(htmlToAppend);
})
})
}
newsApp.init = function () {
// Default Selection
worldNewsApp.world();
$('.worldSelection').addClass('selected');
// Function to get country and display news;
$('.search a').on('click', function (e) {
if (e.target.name === 'ca') {
newsApp.canada();
} else if (e.target.name === 'in') {
indiaNewsApp.india();
}
else {
worldNewsApp.world();
}
$('.search a').removeClass('selected')
$(this).addClass('selected')
});
}
$(function () {
newsApp.init();
});
|
210399d10df654d4c9d575f6dc9d6f2d71d2cdc6
|
[
"JavaScript"
] | 2 |
JavaScript
|
Naveen2905/weUnited
|
ef54bce0a2ea57a31a4e5cb82310cc6c35ecca87
|
dcb3776610a8f44d5dffeed0a02d38ecb9d814a0
|
refs/heads/master
|
<repo_name>GopalanRamya/date-a-scientist<file_sep>/CapstoneProject/dating_skeleton.py
import sys
import time
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from collections import Counter
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from sklearn import preprocessing
from sklearn import svm
from sklearn.linear_model import LinearRegression
from sklearn.metrics import precision_recall_curve
from sklearn.utils.fixes import signature
from sklearn.metrics import confusion_matrix
#Create your df here:
df = pd.read_csv('profiles.csv')
df.dropna(inplace=True)
#### Data augmentation ####
### Augmentation 1: Augment body_type column
bodyType = {'a little extra':1, 'average':2, 'thin':3, 'athletic':4, 'fit':5, 'skinny':6, 'curvy': 7,
'full figured':8, 'jacked':9, 'rather not say':10, 'used up':11, 'overweight':12}
df.body_type.fillna('rather not say', inplace=True);
df.body_type = [bodyType[item] for item in df.body_type];
statusMap = {'single':1, 'married': 2, 'available': 3, 'seeing someone': 4, 'unknown': 5}
df.status = df.status.map(statusMap)
### Augmentation 2: Augment smokes column
df.smokes.fillna('rather not say', inplace=True);
smokesMap = {'sometimes':1, 'no':2, 'when drinking':3, 'yes':4, 'trying to quit':5, 'rather not say':6}
df.smokes = df.smokes.map(smokesMap)
### Augmentation 3: Augment drugs column
df.drugs.fillna('rather not say', inplace=True);
drugsMap = {'never':1, 'sometimes':2, 'often':3, 'rather not say':4}
df.drugs = df.drugs.map(drugsMap)
### Augmentation 4: Augment orientation column
df.orientation.fillna('rather not say', inplace=True);
orientationMap = {'straight':1, 'bisexual':2, 'gay':3}
df.orientation = df.orientation.map(orientationMap)
### Augmentation 5: Create column based on frequency count of the word "love" in essay0
df.essay0.fillna('', inplace=True);
loveCnts = df.essay0.apply(lambda x: x.count("cool"))
#### Construct Feature and label data ####
dfFeatureVector = df[['orientation', 'height']];
#dfFeatureVector['love'] = loveCnts
mean = (dfFeatureVector.mean())
variance = (dfFeatureVector.var()) ** 0.5
dfFeatureVectorScaled = preprocessing.scale(dfFeatureVector)
dfLabels = df['sex']
labelMap = {'m':0, 'f':1}
dfLabels = dfLabels.map(labelMap)
#### Data Plots ####
### Plot 1: Status, age pie chart
N = 101 # data points
xBins = [15, 35, 55, 75]; # Max and min of df.age used to determine hist boundaries
yBins = [1, 2, 3, 4, 5];
hist, xBins, yBins = np.histogram2d(df.age, df.status, bins=(xBins, yBins))
labels=['Age15-35,single', '', '', '', 'Age35-55,single', '', '', '', 'Age55-75,single', '', '', '']
labelsLegend=['Age15-35,single', 'Age15-35,married', 'Age15-35,available', 'Age15-35,seeing someone', 'Age35-55,single', 'Age35-55,married', 'Age35-55,available', 'Age35-55,seeing someone', 'Age55-75,single', 'Age55-75,married', 'Age55-75,available', 'Age55-75,seeing someone']
fig, ax = plt.subplots()
size = 0.3
cmap = plt.get_cmap("tab20c")
inner_colors = cmap(np.array(range(hist.shape[0] * hist.shape[1])))
ax.pie(hist.flatten(), radius=1.0, labels=labels, colors=inner_colors, wedgeprops=dict(width=size, edgecolor='w'))
ax.set(aspect="equal", title='Age & status pie chart')
ax.legend(labelsLegend, bbox_to_anchor=(1, 1))
plt.show()
### Plot 2: Scatter plot of height v/s income of female and male users
dfMale = df.loc[(df['sex'].isin(['m']))]
dfMale2 = dfMale.loc[(df['income'] != -1)]
N = 100
dfMaleHeight = dfMale2['height'].iloc[1:N]
dfMaleIncome = dfMale2['income'].iloc[1:N]
dfFemale = df.loc[(df['sex'].isin(['f']))]
dfFemale2 = dfFemale.loc[(df['income'] != -1)]
dfFemaleHeight = dfFemale2['height'].iloc[1:N]
dfFemaleIncome = dfFemale2['income'].iloc[1:N]
plt.scatter(dfFemaleHeight, dfFemaleIncome, color='tab:pink',label='female')
plt.scatter(dfMaleHeight, dfMaleIncome, color='b', alpha=0.75, label='male')
plt.legend()
plt.xlabel('Height')
plt.ylabel('Income')
plt.title('Height and income stats of 100 male and female users')
plt.show()
#### Obtain train and test data ####
[x_train, x_test, y_train, y_test] = train_test_split(dfFeatureVectorScaled, dfLabels, test_size=0.2)
#### Build classifier ####
### Classifier 1: KNN
accuracy = []
times = []
x = list(range(1,1000))
for k in range(1,1000):
classifier = KNeighborsClassifier(n_neighbors=k)
classifier.fit(x_train, y_train)
t0 = time.time()
result = classifier.score(x_test, y_test)
accuracy.append(result)
times.append((time.time() - t0)/len(x_test))
plt.figure()
plt.xlabel('Number of neighbors')
plt.ylabel('Accuracy')
plt.plot(x,accuracy)
plt.show
plt.figure()
plt.xlabel('Number of neighbors')
plt.ylabel('time taken to score test set')
plt.plot(x,times)
plt.show()
### Classifier 2: SVM
g = [0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 1.0]
result = []
times = []
for i in g:
classifier = svm.SVC(kernel='linear',gamma=i)
classifier.fit(x_train, y_train)
t0 = time.time()
result.append(classifier.score(x_test, y_test))
times.append((time.time() - t0)/len(x_test))
plt.figure()
plt.xlabel('gamma')
plt.ylabel('Accuracy')
plt.plot(g, result)
plt.show()
plt.figure()
plt.xlabel('gamma')
plt.ylabel('time taken to score test set')
plt.plot(g, times)
plt.show()
y_score = classifier.predict(x_test)
print('SVM: confusion matrix for male female classification')
print(confusion_matrix(y_test, y_score))
dfAge = df['age']
dfICnts = df['income'] #df.essay0.apply(lambda x: x.count(" i "))
x_train, x_test, y_train, y_test = train_test_split(dfICnts.values.reshape(-1,1), dfAge.values.reshape(-1,1), test_size=0.2)
model = LinearRegression()
model.fit(x_train, y_train)
times = []
t0 = time.time()
print('Linear Regression score for age determination')
print(model.score(x_test, y_test))
print('Linear Regression: time taken')
times.append((time.time() - t0)/len(x_test))
print(times)
print('Linear Regression: coefficient and intercept values')
print(model.coef_)
print(model.intercept_)
### Regression 2: KNN
n_neighbors = range(1,700)
scores = []
times = []
for k in n_neighbors:
model = KNeighborsRegressor(k)
model.fit(x_train, y_train)
t0 = time.time()
scores.append(model.score(x_test, y_test))
times.append((time.time() - t0)/len(x_test))
plt.figure()
plt.xlabel('neighbors')
plt.ylabel('Accuracy')
plt.title('KNN Regression')
plt.plot(n_neighbors, scores)
plt.show()
plt.figure()
plt.xlabel('neighbors')
plt.ylabel('Time taken')
plt.title('KNN Regression')
plt.plot(n_neighbors, times)
plt.show()
|
40863212b22496082c04346f6f7873d961eeaa57
|
[
"Python"
] | 1 |
Python
|
GopalanRamya/date-a-scientist
|
8a43358d934797b8c3f793f34b5cc5e92735dd34
|
2e335c7c68eb0521702cd8362488865a2078893e
|
refs/heads/master
|
<repo_name>CyberFlameGO/SpawnProtect<file_sep>/README.md
SpawnProtect
============
SpawnProtect is a spawn protection (and more) plugin for MCServer. By default, it simply prevents people from building in spawn who don't have permission to do som but it also has more permissions that can be configured easily.
Installation
------------
SpawnProtect is a default plugin, so it should be installed automatically, but if it is not, simply clone the repo into your Plugins folder and enable SpawnProtect as a plugin in your settings.ini.
Alternatively, you may download the [latest zip](http://ci.berboe.co.uk/job/SpawnProtect/lastSuccessfulBuild/artifact/SpawnProtect.zip) and extract it into your Plugins folder.
Features
--------
* Block people from building and placing blocks in spawn without permission.
* Notify people when they move into and out of spawn.
* Block explosions in spawn.
Disable PvP in spawn.
Disable mobs in spawn.
Configuration
-------------
Change the values at the top of main.lua
<file_sep>/OnPlayerMoving.lua
-- Copyright (c) 2014 <NAME>
-- Permission is hereby granted, free of charge, to any person obtaining a
-- copy of this software and associated documentation files (the
-- "Software"), to deal in the Software without restriction, including
-- without limitation the rights to use, copy, modify, merge, publish,
-- distribute, sublicense, and/or sell copies of the Software, and to
-- permit persons to whom the Software is furnished to do so, subject to
-- the following conditions:
-- The above copyright notice and this permission notice shall be included
-- in all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-- Globals
PLAYERLOCATIONS = {}
-- Code Start
function OnPlayerMoving(Player)
local world = Player:GetWorld():GetName()
local playerx = Player:GetPosX()
local playery = Player:GetPosY()
local playerz = Player:GetPosZ()
local name = Player:GetName()
if PLAYERLOCATIONS[name] ~= nil then
if not IsInSpawn(PLAYERLOCATIONS[name]["x"], PLAYERLOCATIONS[name]["y"], PLAYERLOCATIONS[name]["z"], PLAYERLOCATIONS[name]["world"]) then
if IsInSpawn(playerx, playery, playerz, world) then
-- Load message preferences from file.
local PlayersIni = IniFile()
PlayersIni:ReadFile(PLUGIN:GetLocalFolder() .. "/players.ini")
local SendMessages = PlayersIni:GetValueSetB("EntryMessages", name, SPAWNMESSAGE)
if SendMessages ~= false then
SendMessage(Player, "You have entered spawn!")
end
end
else
if not IsInSpawn(playerx, playery, playerz, world) then
-- Load message preferences from file.
local PlayersIni = IniFile()
PlayersIni:ReadFile(PLUGIN:GetLocalFolder() .. "/players.ini")
local SendMessages = PlayersIni:GetValueSetB("EntryMessages", name, SPAWNMESSAGE)
if SendMessages ~= false then
SendMessage(Player, "You have exited spawn!")
end
end
end
end
PLAYERLOCATIONS[name] = {x = playerx, y = playery, z = playerz, world = world}
end
<file_sep>/main.lua
-- Copyright (c) 2012-2014 <NAME>
-- Permission is hereby granted, free of charge, to any person obtaining a
-- copy of this software and associated documentation files (the
-- "Software"), to deal in the Software without restriction, including
-- without limitation the rights to use, copy, modify, merge, publish,
-- distribute, sublicense, and/or sell copies of the Software, and to
-- permit persons to whom the Software is furnished to do so, subject to
-- the following conditions:
-- The above copyright notice and this permission notice shall be included
-- in all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-- Configuration
-- Show messages upon entering and exiting spawn by default?
SPAWNMESSAGE = false
-- Allow players to toggle entry and exit messages?
ALLOWMESSAGETOGGLE = true
-- Default radius to protect in. Set to -1 to disable.
PROTECTIONRADIUS = 10
-- Globals
PLUGIN = {}
LOGPREFIX = ""
WORLDSPAWNPROTECTION = {}
-- Plugin Start
function Initialize( Plugin )
PLUGIN = Plugin
Plugin:SetName( "SpawnProtect" )
Plugin:SetVersion( 1 )
LOGPREFIX = "[" .. Plugin:GetName() .. "] "
-- Hooks
cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_BREAKING_BLOCK, OnPlayerBreakingBlock)
cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_MOVING, OnPlayerMoving)
cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_PLACING_BLOCK, OnPlayerPlacingBlock)
-- Commands
if ALLOWMESSAGETOGGLE then
cPluginManager.BindCommand("/togglespawnmessage", "spawnplus.togglemessage", ToggleMessages, " - Toggle the message upon entering and leaving spawn.")
end
-- Load the world spawn protection values fron the INI file.
cRoot:Get():ForEachWorld(
function (world)
local WorldIni = cIniFile()
WorldIni:ReadFile(world:GetIniFileName())
WORLDSPAWNPROTECTION[world:GetName()] = WorldIni:GetValueSetI("SpawnProtect", "ProtectRadius", PROTECTIONRADIUS)
WorldIni:WriteFile(world:GetIniFileName())
end
)
LOG( LOGPREFIX .. "Plugin v" .. Plugin:GetVersion() .. " Enabled!" )
return true
end
function OnDisable()
LOG( LOGPREFIX .. "Plugin Disabled!" )
end
function ToggleMessages(Split, Player)
-- Load message preferences from file.
local PlayersIni = IniFile()
PlayersIni:ReadFile(PLUGIN:GetLocalFolder() .. "/players.ini")
local SendMessages = PlayersIni:GetValueSetB("EntryMessages", Player:GetName(), SPAWNMESSAGE)
PlayersIni:WriteFile(PLUGIN:GetLocalFolder() .. "/players.ini")
if SendMessages == "true" then
PlayersIni:SetValueB("EntryMessages", Player:GetName(), false)
SendMessageSuccess(Player, "Spawn entry messages disabled!")
else
PlayersIni:SetValueB("EntryMessages", Player:GetName(), true)
SendMessageSuccess(Player, "Spawn entry messages enabled!")
end
PlayersIni:WriteFile(PLUGIN:GetLocalFolder() .. "/players.ini")
return true
end
function IsInSpawn(x, y, z, worldName)
-- Get Spawn Coordinates for the World
local world = cRoot:Get():GetWorld(worldName)
local spawnx = world:GetSpawnX()
local spawny = world:GetSpawnY()
local spawnz = world:GetSpawnZ()
-- Get protection radius for the world.
local protectRadius = GetSpawnProtection(worldName)
if protectRadius == -1 then
-- There is no spawn for this world, so the player can't be in it.
return false
end
-- Check if the specified coords are in the spawn.
if not ((x <= (spawnx + protectRadius)) and (x >= (spawnx - protectRadius))) then
return false -- Not in spawn area.
end
if not ((y <= (spawny + protectRadius)) and (y >= (spawny - protectRadius))) then
return false -- Not in spawn area.
end
if not ((z <= (spawnz + protectRadius)) and (z >= (spawnz - protectRadius))) then
return false -- Not in spawn area.
end
-- If they're not not in spawn, they must be in spawn!
return true
end
function GetSpawnProtection(WorldName)
return WORLDSPAWNPROTECTION[WorldName]
end
<file_sep>/OnBreakPlaceBlock.lua
-- Copyright (c) 2012-2014 <NAME>
-- Permission is hereby granted, free of charge, to any person obtaining a
-- copy of this software and associated documentation files (the
-- "Software"), to deal in the Software without restriction, including
-- without limitation the rights to use, copy, modify, merge, publish,
-- distribute, sublicense, and/or sell copies of the Software, and to
-- permit persons to whom the Software is furnished to do so, subject to
-- the following conditions:
-- The above copyright notice and this permission notice shall be included
-- in all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
function OnPlayerPlacingBlock(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ, BlockType)
-- Don't fail if the block is air.
if BlockFace == -1 then
return false
end
-- Does the player have permission to bypass the spawn protection?
if Player:HasPermission("spawnprotect.bypass") then
return false
end
local world = Player:GetWorld():GetName()
if IsInSpawn(BlockX, BlockY, BlockZ, world) then
SendMessageInfo(Player, "Go further from spawn to build")
return true
end
return false
end
function OnPlayerBreakingBlock(Player, BlockX, BlockY, BlockZ, BlockFace, Status, OldBlockType, OldBlockMeta)
-- Don't fail if the block is air.
if BlockFace == -1 then
return false
end
-- Does the player have permission to bypass the spawn protection?
if Player:HasPermission("spawnprotect.bypass") then
return false
end
local world = Player:GetWorld():GetName()
if IsInSpawn(BlockX, BlockY, BlockZ, world) then
SendMessageInfo(Player, "Go further from spawn to build")
return true
end
return false
end
|
5431e20a883fe37522e126548a257c11cdd21f32
|
[
"Markdown",
"Lua"
] | 4 |
Markdown
|
CyberFlameGO/SpawnProtect
|
fa9c89c4e62fdff0d3b764f9cbdfae53c04dc4f4
|
c95af6f44c51a3862a17ad06c45056df41b6868a
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.contrib.pipeline.images import ImagesPipeline
from scrapy import Request
class ImagePipeline(ImagesPipeline):
def get_media_requests(self, item, info):
yield Request(item['product_image'])
def item_completed(self, results, item, info):
images = [x for ok, x in results if ok]
if images:
image = images[0]
path = image['path'].split('/')[-1]
item['product_image'] = path
return item
<file_sep># -*- coding: utf-8 -*-
# Scrapy settings for uniquip_net_au project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'none'
SPIDER_MODULES = ['uniquip_net_au.spiders']
NEWSPIDER_MODULE = 'uniquip_net_au.spiders'
ITEM_PIPELINES = {
'uniquip_net_au.pipelines.ImagePipeline': 1
}
IMAGES_STORE = '/home/kalombo/projects/uniquip_net_au/images'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:35.0) ' \
'Gecko/20100101 Firefox/35.0'
FEED_EXPORTERS = {
'csv': 'uniquip_net_au.csv_exporter.OrderCsvItemExporter',
}
FIELDS_TO_EXPORT = ['product_url', 'product_title', 'product_image']<file_sep># -*- coding: utf-8 -*-
import scrapy
from uniquip_net_au.items import ProductItem
class ProductsSpider(scrapy.Spider):
name = "products"
allowed_domains = ["uniquip.net.au"]
start_urls = (
'http://uniquip.net.au/',
)
def parse(self, response):
for url in response.xpath('//a[@class="list_bg_sub"]/@href').extract():
yield scrapy.Request(url, callback=self.products_page)
def products_page(self, response):
xpath = '//div[@class="product_list_content"]/div/h3/a/@href'
for url in response.xpath(xpath).extract():
yield scrapy.Request(url, callback=self.product_page)
def product_page(self, response):
item = ProductItem()
item['product_url'] = response.url
xpath = '(//div[@itemprop="name"]/h2/text())[1]'
item['product_title'] = ''.join(response.xpath(xpath).extract())
xpath = '//div[@itemprop="description"]//img/@src'
image_urls = response.xpath(xpath).extract()
if image_urls:
item['product_image'] = image_urls[0]
yield item
|
4e3b059b9368e690c495c4fe489096c9a5ff2525
|
[
"Python"
] | 3 |
Python
|
kalombos/uniquip_net_au
|
8325ecb4f78d0fdf1455e301bf25ad52d909a62c
|
30d183da1531dbf11adf89c86c69c8458780d627
|
refs/heads/master
|
<file_sep>class Admin::RestaurantsController < Admin::AdminController
def index
@restaurants = Restaurant.all
end
def new
@restaurant = Restaurant.new
end
def create
restaurant = Restaurant.new(params[:restaurant])
restaurant.tastepoint = 5
restaurant.speedpoint = 5
restaurant.amountpoint = 5
restaurant.servicepoint = 5
restaurant.count = 1
restaurant.save
redirect_to :action => admin_restaurants_path
end
def edit
@restaurant = Restaurant.find(params[:id])
end
def update
restaurant = Restaurant.update(params[:id], params[:restaurant])
redirect_to :action => admin_restaurants_path
end
def show
@restaurant = Restaurant.find(params[:id])
@menus = @restaurant.menus
end
def destroy
Restaurant.destroy(params[:id])
redirect_to :action => admin_restaurants_path
end
end
<file_sep>class Goodbad < ActiveRecord::Base
belongs_to :menu
belongs_to :user
end
<file_sep>class Menu < ActiveRecord::Base
has_many :goodbads
belongs_to :restaurant
end
<file_sep>class Array
def random(weights=nil)
return random(map {|n| n.send(weights)}) if weights.is_a? Symbol
weights ||= Array.new(length, 1.0)
total = weights.inject(0.0) {|t,w| t+w}
point = rand * total
zip(weights).each do |n,w|
return n if w >= point
point -= w
end
end
def randomize(weights=nil)
return randomize(map {|n| n.send(weights)}) if weights.is_a? Symbol
weights = weights.nil? ? Array.new(length, 1.0) : weights.dup
#pick out elements until there are none left
list, result = self.dup, []
until list.empty?
# pick an element
result << list.random(weights)
# remove the element from the temporary list and its weight
weights.delete_at(list.index(result.last))
list.delete result.last
end
result
end
end
<file_sep>class User < ActiveRecord::Base
validates_length_of :username, :maximum => 15, :minimum => 3
validates_format_of :username, :with => /\A(^[a-zA-Z0-9]+$)\z/i
validates_presence_of :username
validates_presence_of :password
validates_uniqueness_of :username
validates_uniqueness_of :mailname
validates_confirmation_of :password
has_many :evaluations
has_many :goodbads
has_many :contact
end
<file_sep>class FixColumnName < ActiveRecord::Migration
def up
rename_column :menus, :like, :liking
rename_column :menus, :dislike, :disliking
end
def down
end
end
<file_sep>#encoding = UTF-8
class EvaluateController < ApplicationController
def new_ev
if (Evaluation.first(:conditions => ['user_id = ? and restaurant_id = ?',session[:user_id],params[:res_id]]))
temp_ev = Evaluation.first(:conditions => ['user_id = ? and restaurant_id = ?',session[:user_id],params[:res_id]])
restaurant = Restaurant.find(params[:res_id])
restaurant.count = restaurant.count - 1
restaurant.tastepoint = restaurant.tastepoint - temp_ev.taste
restaurant.speedpoint = restaurant.speedpoint - temp_ev.speed
restaurant.amountpoint = restaurant.amountpoint - temp_ev.amount
restaurant.servicepoint = restaurant.servicepoint - temp_ev.service
Evaluation.destroy(temp_ev.id)
restaurant.save
end
@restaurant = Restaurant.find(params[:res_id])
@evaluation = Evaluation.new
render :layout => false
end
def create_ev
evaluation = Evaluation.new(params[:evaluation])
if (evaluation.review.length<10) || (evaluation.review.length>140)
redirect_to :back, :notice => "리뷰는 10자 이상,140자이하로 써주세요..."
else
if (evaluation.taste>=0 && evaluation.taste<=10)&&(evaluation.speed>=0 && evaluation.speed<=10)&&(evaluation.amount>=0 && evaluation.amount<=10) && (evaluation.service>=0 && evaluation.service<=10)
restaurant = Restaurant.find(params[:res_id])
user = User.find(session[:user_id])
evaluation.restaurant_id = restaurant.id
evaluation.user_id = user.id
restaurant.count = restaurant.count + 1
restaurant.tastepoint = restaurant.tastepoint + evaluation.taste
restaurant.speedpoint = restaurant.speedpoint + evaluation.speed
restaurant.amountpoint = restaurant.amountpoint + evaluation.amount
restaurant.servicepoint = restaurant.servicepoint + evaluation.service
evaluation.save
restaurant.save
redirect_to :controller => "bab", :action => "index"
else
redirect_to :back
end
end
end
def good_menu
user = User.find(session[:user_id])
if Goodbad.first( :conditions => ['user_id = ? and menu_id =?', session[:user_id], params[:menu_id]])
goodbad = Goodbad.first( :conditions => ['user_id = ? and menu_id =?', session[:user_id], params[:menu_id]])
menu = Menu.find(params[:menu_id])
else
goodbad = Goodbad.new
goodbad.good = false
goodbad.bad = false
menu = Menu.find(params[:menu_id])
goodbad.menu_id = menu.id
goodbad.user_id = user.id
end
if goodbad.good == false
goodbad.good = true
if goodbad.bad == true
goodbad.bad = false
menu.disliking = menu.disliking - 1
end
menu.liking = menu.liking + 1
end
goodbad.save
menu.save
render :json => menu
end
def bad_menu
user = User.find(session[:user_id])
if Goodbad.first( :conditions => ['user_id = ? and menu_id =?', session[:user_id], params[:menu_id]])
goodbad = Goodbad.first( :conditions => ['user_id = ? and menu_id =?', session[:user_id], params[:menu_id]])
menu = Menu.find(params[:menu_id])
else
goodbad = Goodbad.new
goodbad.good = false
goodbad.bad = false
menu = Menu.find(params[:menu_id])
goodbad.menu_id = menu.id
goodbad.user_id = user.id
end
if goodbad.bad == false
goodbad.bad = true
if goodbad.good == true
goodbad.good = false
menu.liking = menu.liking - 1
end
menu.disliking = menu.disliking + 1
end
goodbad.save
menu.save
render :json => menu
end
def cancel_good
user = User.find(session[:user_id])
goodbad = Goodbad.first(:conditions => ['user_id = ? and menu_id = ?', session[:user_id], params[:menu_id]])
menu = Menu.find(params[:menu_id])
if goodbad.good == true
goodbad.good = false
menu.liking = menu.liking - 1
end
goodbad.save
menu.save
render :json => menu
end
def cancel_bad
user = User.find(session[:user_id])
goodbad = Goodbad.first(:conditions => ['user_id =? and menu_id =?', session[:user_id], params[:menu_id]])
menu = Menu.find(params[:menu_id])
if goodbad.bad == true
goodbad.bad = false
menu.disliking = menu.disliking - 1
end
goodbad.save
menu.save
render :json => menu
end
end
<file_sep>class Restaurant < ActiveRecord::Base
has_many :evaluations
has_many :menus
has_attached_file :avatar, :default_url => 'bag.png', :path => '/home/co9901/s301/public/system/:attachment/:id/:style/:filename', :url => 'http://co9901.cafe24.com:9901/system/avatars/:id/:style/:filename'
end
<file_sep>user = User.where("mailcheck = ?", false).order('created_at ASC limit 5')
user.each do |u|
if u.authorized == false
AuthorityMailer.confirm_email(u).deliver
else
AuthorityMailer.change_passwd_email(u).deliver
end
u.mailcheck = true
u.save
end
<file_sep>class CreateRestaurants < ActiveRecord::Migration
def change
create_table :restaurants do |t|
t.string :resname
t.string :phone
t.integer :tastepoint
t.integer :speedpoint
t.integer :servicepoint
t.integer :amountpoint
t.integer :count
t.has_attached_file :avatar
t.text :resinfo
t.string :restype
t.timestamps
end
end
end
<file_sep>class Admin::ContactsController < Admin::AdminController
def index
@contacts = Contact.order('created_at desc').all
end
def destroy
Contact.new.destroy(params[:id])
redirect_to :action => admin_contacts_path
end
def show
@contact = Contact.find(params[:id])
end
def destroy
Contact.destroy(params[:id])
redirect_to :action => admin_contacts_path
end
end
<file_sep>#encoding = UTF-8
class AuthorityMailer < ActionMailer::Base
default :from => "<EMAIL>"
def confirm_email(user)
@user = user
@url = "http://co9901.cafe24.com/authorize/confirm?user=#{@user.username}&authorized_token=#{@user.authorize_token}"
mail(:to => <EMAIL>", :subject => "밥통 인증 메일")
end
def change_passwd_email(user)
@user = user
mail(:to => <EMAIL>", :subject => "밥통 새 비밀번호")
end
end
<file_sep>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//require jquery
//=require jquery_ujs
//require_tree .
/////////////////////popup
popupStatus = 0;
function loadPopup(popUp){
if(popupStatus==0){
$("#backgroundPopup").css({
"opacity":"0.7"
});
$("#backgroundPopup").fadeIn("slow");
$(popUp).fadeIn("slow");
popupStatus=1;
}
}
function disablePopup(popUp){
if(popupStatus==1){
$("#backgroundPopup").fadeOut("slow");
$(popUp).fadeOut("slow");
popupStatus = 0;
}
}
function centerPopup(popUp){
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $(popUp).height();
var popupWidth = $(popUp).width();
$(popUp).css({
"position" : "fixed",
"top" : "20px",
"left" : windowWidth/2-popupWidth/2
});
}
////////////////////////////////////////////////////
$(document).ready(function(){
/////////////////////////////////////////////////////////////////
$(".signupPop").click(function(){
centerPopup('#signupContact');
loadPopup('#signupContact');
});
$("#popupContactClose").click(function(){
disablePopup('#signupContact');
});
$(document).keydown(function(e){
if(e.keyCode==27 && popupStatus==1){
disablePopup('#signupContact');
}
});
/////////////////////////////////////////////////////////////
centerPopup('#loading');
$('#footer span').click(function(){
$('#deglee').toggle("fast");
});
});
<file_sep>class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :mailname
t.string :username
t.string :password
t.string :authorize_token
t.boolean :authorized
t.boolean :mailcheck
t.timestamps
end
end
end
<file_sep>#encoding = UTF-8
class AuthorizeController < ApplicationController
skip_before_filter :check_login
skip_before_filter :require_login
def confirm
user = User.where("username = ?", params[:user]).first
if (user.authorize_token == params[:authorized_token])
user.authorized = true
user.save
session[:user_id] = user.id
redirect_to "/", :notice => "인증 성공"
else
redirect_to "/", :notice => "인증 실패"
end
end
end
<file_sep>#encoding = UTF-8
class BabController < ApplicationController
skip_before_filter :require_login, :only => [:index, :main, :today_res, :search, :show_all,:select, :select_result, :new_contact, :create_contact, :deny_access, :select_help, :select_result_help]
def index
end
def main
@taste_restaurants = Restaurant.order('tastepoint/count desc limit 5')
@speed_restaurants = Restaurant.order('speedpoint/count desc limit 5')
@amount_restaurants = Restaurant.order('amountpoint/count desc limit 5')
@service_restaurants = Restaurant.order('servicepoint/count desc limit 5')
@new_restaurants = Restaurant.order('created_at desc limit 3')
@new_evaluations = Evaluation.order('created_at desc limit 3')
render :layout => false
end
def view_menu
@num = params[:res_id]
@menus = Menu.where(:restaurant_id => params[:res_id]).order("liking+disliking DESC")
@menus_all = []
@set_all = []
@menus.each do |m|
menu = {}
goodbad = {}
menu['menu'] = m
@goodbad = m.goodbads.first(:conditions => ['user_id = ?', session[:user_id]])
menu['goodbad'] = @goodbad
if m.setmenu == false
@menus_all << menu
elsif m.setmenu == true
@set_all << menu
end
end
render :layout => false
end
def view_res
@restaurant = Restaurant.find(params[:res_id])
@ev_temps = Evaluation.find(:all, :order => "created_at desc", :conditions => ['restaurant_id = ?', params[:res_id]], :limit => 3)
# @menus = Menu.where(:restaurant_id => params[:res_id])
# @menu_view_res = @menus.sort_by{"|m| (m.liking-m.disliking)"}.first(1)
@menu_view_res = Menu.where(:restaurant_id => params[:res_id]).order("liking-disliking DESC").limit(1)
#@menus_all = []
#@set_all = []
#@menus.each do |m|
# menu = {}
#goodbad = {}
#menu['menu'] = m
#@goodbad = m.goodbads.first(:conditions => ['user_id = ?', session[:user_id]])
#menu['goodbad'] = @goodbad
#if m.setmenu == false
#@menus_all << menu
#elsif m.setmenu == true
# @set_all << menu
#end
#end
render :layout => false
end
def more_comment
@num = params[:res_id]
@ev_all = Evaluation.find(:all, :order => "created_at desc", :conditions => ['restaurant_id = ?', params[:res_id]])
render :layout => false
end
def show_all
if params[:type] == 'chinese'
@results = Restaurant.where("restype = ?", "중식").paginate(:page => params[:page], :per_page => 12)
elsif params[:type] == "chicken"
@results = Restaurant.where("restype =?","치킨").paginate(:page => params[:page], :per_page => 12)
elsif params[:type] == "pizza"
@results = Restaurant.where("restype =?","피자").paginate(:page => params[:page], :per_page => 12)
elsif params[:type] == "korea"
@results = Restaurant.where("restype = ?","한식").paginate(:page => params[:page], :per_page => 12)
elsif params[:type] == "dosirak"
@results = Restaurant.where("restype = ?","도시락").paginate(:page => params[:page], :per_page => 12)
elsif params[:type] == "etc"
@results = Restaurant.where("restype = ?","기타").paginate(:page => params[:page], :per_page => 12)
else
@results = Restaurant.paginate(:page => params[:page], :per_page => 12)
end
render :layout => false
end
def search
@results = Restaurant.where('resname LIKE ? ',"%#{params[:search]}%").paginate(:page => params[:page], :per_page => 4)
render :layout => false
end
def select
render :layout => false
end
def today_res
date = Time.now.year.to_s + Time.now.month.to_s + Time.now.day.to_s
r = Recommendation.find_by_date(date)
if r.nil?
samples = []
samples.concat(Restaurant.all)
choice = samples.sample
res_id = choice.id
new_r = Recommendation.new
new_r.date = date
new_r.res_id = res_id
new_r.save
@today_res = choice
else
@today_res = Restaurant.find(r.res_id)
end
@today_menus = Menu.where(:restaurant_id => @today_res.id)
@menu_today_res = @today_menus.sort_by{"|m| (m.liking-m.disliking)"}.first(1)
render :layout => false
end
def select_result
########################################select type##
@selected = []
if (params[:chinese] == "1")
@selected += Restaurant.where('restype = ? ' , '중식').to_ary
end
if (params[:pizza] == "1")
@selected += Restaurant.where('restype = ?', '피자').to_ary
end
if (params[:chicken] == "1")
@selected += Restaurant.where('restype = ?', '치킨').to_ary
end
if (params[:dosirak] == "1")
@selected += Restaurant.where('restype = ?', '도시락').to_ary
end
if (params[:korea] == "1")
@selected += Restaurant.where('restype = ?', '한식').to_ary
end
if (params[:etc] == "1")
@selected += Restaurant.where('restype = ?', '기타').to_ary
end
if (@selected.count == 0)
@selected += Restaurant.all
end
######################################################
############################priority select###########
p1 = params[:priority_1]
p2 = params[:priority_2]
p3 = params[:priority_3]
p4 = params[:priority_4]
Rails.logger.info "======= selected rest==========="
Rails.logger.info @selected
if (params["#{p1}_level"] == "0")
filtering_1 = @selected.randomize{"|f1| (f1.#{p1}point/f1.count)"}.first(10)
elsif (params["#{p1}_level"] == "1")
filtering_1 = @selected.randomize{"|f1| f1.count"}.first(10)
elsif (params["#{p1}_level"] == "2")
filtering_1 = @selected.randomize{"|f1| -(f1.#{p1}point/f1.count)"}.first(10)
end
if (params["#{p2}_level"] == "0")
filtering_2 = filtering_1.randomize{"|f1| (f1.#{p2}point/f1.count)"}.first(7)
elsif (params["#{p2}_level"] == "1")
filtering_2 = filtering_1.randomize{"|f1| f1.count"}.first(7)
elsif (params["#{p2}_level"] == "2")
filtering_2 = filtering_1.randomize{"|f1| -(f1.#{p2}point/f1.count)"}.first(7)
end
if (params["#{p3}_level"] == "0")
filtering_3 = filtering_2.randomize{"|f1| (f1.#{p3}point/f1.count)"}.first(5)
elsif (params["#{p3}_level"] == "1")
filtering_3 = filtering_2.randomize{"|f1| f1.count"}.first(5)
elsif (params["#{p3}_level"] == "2")
filtering_3 = filtering_2.randomize{"|f1| -(f1.#{p3}point/f1.count)"}.first(5)
end
if (params["#{p4}_level"] == "0")
filtering_4 = filtering_3.randomize{"|f1| (f1.#{p4}point/f1.count)"}.first(3)
elsif (params["#{p4}_level"] == "1")
filtering_4 = filtering_3.randomize{"|f1| f1.count"}.first(3)
elsif (params["#{p4}_level"] == "2")
filtering_4 = filtering_3.randomize{"|f1| -(f1.#{p4}point/f1.count)"}.first(3)
end
######################################################
@final_sel = filtering_4.sample
@final_menus = Menu.where(:restaurant_id => @final_sel.id)
@menu_final_res = @final_menus.randomize{"|m| (m.liking-m.disliking)"}.first(1)
render :layout => false
end
def new_contact
@contact = Contact.new
render :layout => false
end
def create_contact
contact = Contact.new(params[:contact])
if session[:user_id].nil?
contact.user_id = 1
else
contact.user_id = session[:user_id]
end
contact.save
redirect_to :action => "index", :controller => "bab"
end
def select_help
render :layout => false
end
def select_result_help
render :layout => false
end
end
<file_sep>class CreateGoodbads < ActiveRecord::Migration
def change
create_table :goodbads do |t|
t.references :menu
t.references :user
t.boolean :good
t.boolean :bad
t.timestamps
end
end
end
<file_sep>class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :require_login
before_filter :check_login
private
def require_login
unless logged_in?
render :partial =>"deny_access"
end
end
def logged_in?
!!session[:user_id]
end
def check_login
if !session[:user_id].nil?
@current_user = User.find(session[:user_id])
end
end
end
<file_sep>require 'test_helper'
class BabHelperTest < ActionView::TestCase
end
<file_sep>class Admin::MenusController < Admin::AdminController
def new
@menu = Menu.new
end
def create
menu = Menu.new(params[:menu])
menu.liking = 0
menu.disliking = 0
restaurant = Restaurant.find(params[:restaurant_id])
menu.restaurant_id = restaurant.id
menu.save
redirect_to admin_restaurant_path(:id => menu.restaurant_id)
end
def edit
@menu = Menu.find(params[:id])
end
def update
menu = Menu.update(params[:id], params[:menu])
redirect_to admin_restaurant_path(:id => menu.restaurant_id)
end
def destroy
menu = Menu.destroy(params[:id])
goodbad = Goodbad.destroy(params[:id])
redirect_to admin_restaurant_path(:id => menu.restaurant_id)
end
end
<file_sep>#encoding = UTF-8
class UserController < ApplicationController
skip_before_filter :require_login, :except => [:change_passwd, :update_passwd]
skip_before_filter :check_login
def new
@user = User.new
end
def create
params[:user][:password] = <PASSWORD>.<PASSWORD>(params[:user][:password])
params[:user][:password_confirmation] = <PASSWORD>::SHA256.hexdigest(params[:user][:password_confirmation])
params[:user][:authorize_token] = <PASSWORD>56.hexdigest(Time.now.to_s+rand().to_s)
params[:user][:authorized] = false
params[:user][:mailcheck] = false
user = User.new(params[:user])
if User.first(:conditions => {:username => params[:user][:username]})
redirect_to "/", :notice => "이미 있는 아이디 입니다."
elsif User.first(:conditions => {:mailname => params[:user][:mailname]})
redirect_to "/", :notice => "이미 사용된 메일 입니다."
elsif params[:user][:password_confirmation] != params[:user][:password]
redirect_to "/", :notice => "비밀번호가 다릅니다."
elsif (params[:user][:username].length < 3 || params[:user][:username].length > 15)
redirect_to "/", :notice => "아이디는 3자이상,15자이하만 가능합니다."
elsif params[:user][:username].match(/\A(^[a-zA-Z0-9]+$)\z/i).nil?
redirect_to "/", :notice => "아이디는 영어,숫자만 가능합니다."
end
if user.save
redirect_to "/", :notice => "스누메일에 접속하여 인증해 주세요. 서버가 느려서 늦게 갈 수도 있어요..^^;"
end
end
def login
params[:user][:password] = <PASSWORD>(params[:user][:password])
user = User.first(:conditions => {:username => params[:user][:username]})
if user.nil?
redirect_to :back, :notice => "없는 회원입니다."
else
if user.password == params[:user][:password]
if user.authorized == true
session[:user_id] = user.id
redirect_to "/"
else
redirect_to "/", :notice => "스누메일에 접속하여 인증해 주세요."
end
else
redirect_to :back, :notice => "비밀번호가 틀렸습니다."
end
end
end
def logout
session[:user_id] = nil
redirect_to "/"
end
def change_passwd
render :layout => false
end
def update_passwd
user = User.find(session[:user_id])
params[:user][:now_passwd] = Digest::SHA256.hexdigest(params[:user][:now_passwd])
params[:user][:want_passwd] = Digest::SHA256.hexdigest(params[:user][:want_passwd])
params[:user][:want_passwd_re] = Digest::SHA256.hexdigest(params[:user][:want_passwd_re])
if user.password == params[:user][:now_passwd]
if params[:user][:want_passwd] == params[:user][:want_passwd_re]
user.password = params[:user][:want_passwd]
user.save
redirect_to "/", :notice => "비밀번호가 성공적으로 변경되었습니다."
else
redirect_to :back, :notice => "비밀번호 변경 실패!"
end
else
redirect_to :back, :notice => "비밀번호 변경 실패!"
end
end
def find_passwd
render :layout => false
end
def send_passwd
user = User.where('username = ?', params[:user][:username]).first
if user.nil?
redirect_to "/", :notice => "없는 아이디입니다."
else
if user.mailname == params[:user][:mailname]
new_passwd = (0...15).map{ ('a'..'z').to_a[rand(26)] }.join
user.authorize_token = new_passwd
user.password = <PASSWORD>.<PASSWORD>(new_<PASSWORD>)
user.mailcheck = false
user.save
redirect_to "/", :notice => "새 비밀번호가 메일로 보내졌습니다. 아마 곧."
else
redirect_to :back, :notice => "아이디와 메일이 일치하지 않습니다."
end
end
end
end
|
b3745f287a243ba7d608c1b900667edc823c2a16
|
[
"JavaScript",
"Ruby"
] | 21 |
Ruby
|
heyjusang/bab
|
ba21e523281da2de85f9308b8d5fe10aef844797
|
29bb837b2ca5e3bbc00eaa5f5b838321046b6e05
|
refs/heads/master
|
<file_sep>package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"sort"
"github.com/AlecAivazis/survey/v2"
)
const (
categoriesUrl string = "https://www.getonbrd.com/api/v0/categories?"
tagsUrl string = "https://www.getonbrd.com/api/v0/tags?page="
)
var opts = []string{"1)Total jobs", "2)Total jobs by category", "3)Average salary by category",
"4)Median salary by category", "5)Total jobs by tag/technology", "6) Exit"}
type attributes struct {
Title string `json:"title"`
Functions string `json:"functions"`
// Benefits string `json:"benefits"`
Desirable string `json:"desirable"`
Remote bool `json:"remote"`
RemoteMod string `json:"remote_modality"`
RemoteZone string `json:"remote_zone"`
Country string `json:"country"`
Category string `json:"category_name"`
// Perks []string `json:"perks"`
MinSalary int `json:"min_salary"`
MaxSalary int `json:"max_salary"`
Modality string `json:"modality"`
Seniority string `json:"seniority"`
// PublishedAt int `json:"published_at"`
}
type jobDetails struct {
Data []struct {
Id string `json:"id"`
// Type string `json:"type"`
Attributes attributes `json:"attributes"`
} `json:"data"`
}
type Categories struct {
Data []struct {
Id string `json:"id"`
} `json:"data"`
}
type Tags struct {
Data []struct {
Id string `json:"id"`
} `json:"data"`
}
type jobByCategory struct {
categoryName string
total int
}
type jobsByTag struct {
tagName string
total int
}
var (
jobCategories []string
tags []string
totalJobs int
totalJobsByCategory []jobByCategory
avgSalariesByCategory []jobByCategory
medianSalariesByCategory []jobByCategory
avgSalariesList []int
totalJobsByTag []jobsByTag
jobDetailsArray []jobDetails
)
var qs = []*survey.Question{
{
Name: "options",
Prompt: &survey.Select{
Message: "Get:",
Options: opts,
Default: "1)Total jobs",
},
},
}
func main() {
getJobCategories()
getJobDetails()
getTags()
initSurvey()
}
func initSurvey() {
fmt.Println(" ")
answers := struct {
Option string `survey:"options"`
}{}
err := survey.Ask(qs, &answers)
if err != nil {
fmt.Println(err.Error())
return
}
switch answers.Option[:1] {
case "1":
fmt.Println("Total jobs: ", getTotalJobs())
case "2":
fmt.Println("Total jobs by category: ", getTotalJobsByCategory())
case "3":
fmt.Println("Average salary : ", getAvgSalariesByCategory())
case "4":
fmt.Println("Median salaries::: ", getMedianSalariesByCategory())
case "5":
getJobsByTag()
fmt.Println("Total jobs by tag/technology: ", totalJobsByTag)
case "6":
os.Exit(0)
}
initSurvey()
}
func getJobCategories() {
body := getRequest(categoriesUrl)
var cat Categories
err := json.Unmarshal(body, &cat)
if err != nil {
fmt.Println("error ", err)
panic(err)
}
for i := range cat.Data {
jobCategories = append(jobCategories, cat.Data[i].Id)
}
}
// get job details by category
func getJobDetails() {
for i := range jobCategories {
url := fmt.Sprintf("https://www.getonbrd.com/api/v0/categories/%s/jobs?", jobCategories[i])
body := getRequest(url)
var jd jobDetails
err := json.Unmarshal(body, &jd)
if err != nil {
fmt.Println("error ", err)
panic(err)
}
jobDetailsArray = append(jobDetailsArray, jd)
}
}
func getTotalJobs() int {
for _, jd := range jobDetailsArray {
totalJobs += len(jd.Data)
}
return totalJobs
}
func getTotalJobsByCategory() []jobByCategory {
for _, jd := range jobDetailsArray {
totalJobsByCategory = append(totalJobsByCategory, jobByCategory{jd.Data[0].Attributes.Category, len(jd.Data)})
}
return totalJobsByCategory
}
func getAvgSalariesByCategory() []jobByCategory {
var avgSalaryByCategory, jobsLen, totalAvgSalaryByCategory int
avgSalariesByCategory = nil
for _, jd := range jobDetailsArray {
avgSalariesList = nil
jobsLen = 0
totalAvgSalaryByCategory = 0
avgSalaryByCategory = 0
for _, data := range jd.Data {
if data.Attributes.MinSalary > 0 || data.Attributes.MaxSalary > 0 {
jobsLen++
avgSalaryByCategory = (data.Attributes.MinSalary + data.Attributes.MaxSalary) / 2
totalAvgSalaryByCategory += (data.Attributes.MinSalary + data.Attributes.MaxSalary) / 2
avgSalariesList = append(avgSalariesList, avgSalaryByCategory)
}
}
if jobsLen > 0 {
avgSalariesByCategory = append(avgSalariesByCategory,
jobByCategory{jd.Data[0].Attributes.Category, totalAvgSalaryByCategory / jobsLen})
}
}
return avgSalariesByCategory
}
func getMedianSalariesByCategory() []jobByCategory {
var avgSalaryByCategory, jobsLen, totalAvgSalaryByCategory int
avgSalariesByCategory = nil
medianSalariesByCategory = nil
for _, jd := range jobDetailsArray {
avgSalariesList = nil
jobsLen = 0
totalAvgSalaryByCategory = 0
avgSalaryByCategory = 0
for _, data := range jd.Data {
if data.Attributes.MinSalary > 0 || data.Attributes.MaxSalary > 0 {
jobsLen++
avgSalaryByCategory = (data.Attributes.MinSalary + data.Attributes.MaxSalary) / 2
totalAvgSalaryByCategory += (data.Attributes.MinSalary + data.Attributes.MaxSalary) / 2
avgSalariesList = append(avgSalariesList, avgSalaryByCategory)
}
}
if len(avgSalariesList) > 0 {
medianSalariesByCategory = append(medianSalariesByCategory,
jobByCategory{jd.Data[0].Attributes.Category, getMedian(avgSalariesList)})
}
}
return medianSalariesByCategory
}
func getMedian(n []int) int {
sort.Ints(n) // sort the numbers
mNumber := len(n) / 2 // middle number, truncates if odd
// is Odd?
if len(n)%2 != 0 {
return n[mNumber]
}
return (n[mNumber-1] + n[mNumber]) / 2
}
// get all tags
func getTags() {
for i := 1; i < 5; i++ {
body := getRequest(tagsUrl + fmt.Sprintf("%d", i))
var tag Tags
err := json.Unmarshal(body, &tag)
if err != nil {
fmt.Println("error ", err)
panic(err)
}
for _, data := range tag.Data {
tags = append(tags, data.Id)
}
}
}
func getJobsByTag() {
for i := range tags {
page := 1
totalJobs := 0
j := 1
for j > 0 {
url := fmt.Sprintf("https://www.getonbrd.com/api/v0/tags/%s/jobs?page=%d", tags[i], page)
body := getRequest(url)
var jd jobDetails
err := json.Unmarshal(body, &jd)
if err != nil {
fmt.Println("error ", err)
panic(err)
}
totalJobs += len(jd.Data)
page++
j = len(jd.Data)
}
totalJobsByTag = append(totalJobsByTag, jobsByTag{tags[i], totalJobs})
}
}
func getRequest(url string) []byte {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println(err)
}
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
}
return body
}
<file_sep>module github.com/kristofff/getonbrdScrapper
go 1.15
require github.com/AlecAivazis/survey/v2 v2.2.8
|
d3377f54a72da33417295d6b21702bac99a54d79
|
[
"Go Module",
"Go"
] | 2 |
Go
|
krystofff/getonbrdScraper
|
9b2e3d15c22ee8ec83f057bbbd13e2f58c4cd6cc
|
75274d25b38aed1c659841be5855de57754afe87
|
refs/heads/master
|
<repo_name>schmulen/simpleApp13<file_sep>/SimpleApp/App/Views/Views/ConnectDetailView.swift
//
// ConnectDetailView.swift
// SimpleApp
//
// Created by <NAME> on 7/24/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct ConnectDetailView: View {
var model: ConnectModel
var body: some View {
VStack(alignment: .leading) {
Text("Connect detail")
model.image
.renderingMode(.original)
.resizable()
.frame(width: 155, height: 155)
.cornerRadius(5)
Text(model.name)
.foregroundColor(.primary)
.font(.caption)
}
.padding(.leading, 15)
}
}
<file_sep>/SimpleApp/App/Views/TopViews/MainView.swift
//
// MainView.swift
// SimpleApp
//
// Created by <NAME> on 7/23/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import Foundation
import SwiftUI
struct MainView: View {
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var appState: AppState
@EnvironmentObject var marinaStore: SimpleNetworkStore<MarinaModel>
@EnvironmentObject var boatStore: SimpleNetworkStore<BoatModel>
@State var funStore:FunStore = FunStore(storeConfig: StoreConfig.local)
@State var choreStore:ChoreStore = ChoreStore(storeConfig: StoreConfig.local)
@State var connectStore:ConnectStore = ConnectStore(storeConfig: StoreConfig.local)
var body: some View {
NavigationView {
VStack {
VStack {
Text("Featured View")
}
List{
Section() {
FunRowView(categoryName: "Fun", items: funStore.models)
}.listRowInsets(EdgeInsets())
Section() {
ChoreRowView(categoryName: "Chores", items: choreStore.models)
}.listRowInsets(EdgeInsets())
Section() {
ConnectRowView(categoryName: "Connect", items: connectStore.models)
}.listRowInsets(EdgeInsets())
}
}
.navigationBarItems(leading: addButton, trailing: profileButton)
}
}
private var profileButton: some View {
NavigationLink(destination: UserView()){
Image(systemName: "person.circle")
}
}
private var addButton: some View {
NavigationLink(destination: NewChoreView() ) {
Image(systemName: "plus")
}
}
}
<file_sep>/SimpleApp/ContentView.swift
//
// ContentView.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var appState: AppState
@EnvironmentObject var marinaStore: SimpleNetworkStore<MarinaModel>
@EnvironmentObject var boatStore: SimpleNetworkStore<BoatModel>
enum TopView {
case tabView
case mainView
case authenticationView
case purchaseView
}
var body: some View {
Group {
if appState.topView == .mainView {
MainView()
.environmentObject(appState)
.environmentObject(marinaStore)
.environmentObject(boatStore)
}
if appState.topView == .tabView {
TopTabView()
.environmentObject(appState)
.environmentObject(marinaStore)
.environmentObject(boatStore)
}
if appState.topView == .authenticationView {
AutheticationView()
.environmentObject(appState)
}
if appState.topView == .purchaseView {
PurchaseView()
.environmentObject(appState)
}
EmptyView()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
<file_sep>/SimpleApp/App/AppState.swift
//
// AppState.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
import Combine
import CloudKit
class AppState: ObservableObject {
public let objectWillChange = ObservableObjectPublisher()
public let isSimulator: Bool
private var serverConfig: StoreConfig
private var userStore = SimpleUserStore()
var currentDeviceInfo: DeviceModel = DeviceModel()
var currentAppInfo: AppModel = AppModel()
@Published var currentUserModel: UserModel? = nil
@Published var currentPurchaseModel: PurchaseModel? = nil
//@Published var topView: ContentView.TopView = .tabView {
@Published var topView: ContentView.TopView = .mainView {
willSet {
updateChanges()
}
}
init(
) {
#if targetEnvironment(simulator)
isSimulator = true
serverConfig = .local
#else
isSimulator = false
serverConfig = .local
#endif
}
private func updateChanges() {
DispatchQueue.main.async {
self.objectWillChange.send()
}
}
}
// MARK: - StartupServices
extension AppState {
public func onStartup() {
checkAuthStatus()
checkPurchaseStatus()
updateDeviceAndAppDataOnServer()
}
private func checkAuthStatus() {
// TODO: checkAuthStatus
}
private func checkPurchaseStatus() {
// TODO: checkPurchaseStatus
}
private func updateDeviceAndAppDataOnServer() {
// TODO: updateDeviceAndAppDataOnServer
}
}
// MARK: - Purchase Services
extension AppState {
public func makePurchase(
purchase: PurchaseModel.PurchaseStatus
) -> Result<PurchaseModel,Error> {
let newModel = PurchaseModel(id: UUID(), status: purchase)
self.currentPurchaseModel = newModel
return .success(newModel)
}
public func verifyPurchase(
purchase: String
) -> Result<PurchaseModel?,Error> {
guard let activePurchase = self.currentPurchaseModel else {
return .success(nil)
}
return .success(activePurchase)
}
}
// MARK: - Authentication Services
extension AppState {
public func signOut(){
self.userStore.signOut() { (result) in
switch result {
case .failure(let error):
print("error \(error)")
case .success(let model):
self.currentUserModel = model
}
self.updateChanges()
}
}
public func signIn(
email: String,
password:String,
completion: @escaping (Result<UserModel, Error>) -> ()
){
self.userStore.signIn(email: email, password: <PASSWORD>) { (result) in
switch result {
case .failure(let error):
print("error \(error)")
case .success(let model):
self.currentUserModel = model
}
completion(result)
self.updateChanges()
}
}
public func register(
email: String,
password:<PASSWORD>,
completion: @escaping (Result<UserModel, Error>) -> ()
) {
self.userStore.register(email: email, password: <PASSWORD>) { (result) in
switch result {
case .failure(let error):
print("error \(error)")
case .success(let model):
self.currentUserModel = model
}
completion(result)
self.updateChanges()
}
}
}
<file_sep>/SimpleApp/App/Views/Views/MarinaRowView.swift
//
// MarinaRowView.swift
// SimpleApp
//
// Created by <NAME> on 7/21/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct MarinaRowView: View {
var model: MarinaModel
var body: some View {
VStack {
Text(model.name)
}
}
}
struct MarinaRowView_Previews: PreviewProvider {
static var previews: some View {
MarinaRowView(model: MarinaModel.mock)
}
}
<file_sep>/SimpleApp/App/Views/Views/BoatRowView.swift
//
// BoatRowView.swift
// SimpleApp
//
// Created by <NAME> on 7/21/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct BoatRowView: View {
var model: BoatModel
var body: some View {
VStack {
Text(model.name)
}
}
}
struct BoatRowView_Previews: PreviewProvider {
static var previews: some View {
BoatRowView(model: BoatModel.mock)
}
}
<file_sep>/SimpleApp/LocalStores/Models/FunModel.swift
//
// FunModel.swift
// SimpleApp
//
// Created by <NAME> on 7/23/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import Foundation
import SwiftUI
public struct FunModel: Hashable, Codable, Identifiable {
public var id: Int
var name: String
fileprivate var imageName: String
}
extension FunModel {
var image: Image {
ImageStore.shared.image(name: imageName)
}
}
<file_sep>/README.md
SimpleApp13
====
Simple iOS13 SwiftUI and Combine app
## First Run
- `git clone <EMAIL>:mschmulen/simpleApp13.git`
- CMD+R to run in simulator
## General Overview
- Global AppState `ObservableObject` as dependecy injected and shared app state.
- TopLevel app experience is 3 tabs (TopTabView) with Boats (BoatView), Marinas (MarinaView), and User (UserView) tabs.
- Parent context view to manage and display the 3 "Top Views": TopTabView, AuthenticationView, PurchaseView
## Sessions
*WIP Potential topics* TBD
- Beautify AuthenticationView and PurchaseView
- Local Storage to persist simple user state
- Remote data services
- `Bindable` View properties.
- SwiftUI Detail View of models ( with edit )
---
## Time Log
- v0.0, basic app infastructure of global app state, three tabs, 2 models, with user, device and purchase service. (~2.0)
<file_sep>/SimpleApp/LocalStores/LocalUserStore.swift
//
// LocalUserStore.swift
// SimpleApp
//
// Created by <NAME> on 7/23/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
import Combine
public final class LocalUserStore: ObservableObject {
public let objectWillChange = ObservableObjectPublisher()
private var storeConfig: StoreConfig
@Published public var models: [LocalUserModel] = load("userData.json")
public init(storeConfig: StoreConfig) {
self.storeConfig = storeConfig
}
private func updateChanges() {
DispatchQueue.main.async {
self.objectWillChange.send()
}
}
enum InternalError:Error {
case unknown
case invalidResponseFromServer
}
}
<file_sep>/SimpleApp/App/Views/SupportingViews/UserView.swift
//
// UserView.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct UserView: View {
@Environment(\.window) var window: UIWindow?
@Environment(\.presentationMode) var presentationMode
@EnvironmentObject var appState: AppState
@State var devMessage: String?
var body: some View {
NavigationView {
List{
if devMessage != nil {
Text("\(devMessage!)")
.foregroundColor(.red)
.onTapGesture {
self.devMessage = nil
}
}
Section(header: Text("User Information")) {
if appState.currentUserModel == nil {
Button(action: {
self.appState.topView = .authenticationView
}) {
Text("Sign In")
.foregroundColor(.blue)
}
}
else {
Text("email: \(appState.currentUserModel?.email ?? "~")")
Button(action: {
self.appState.signOut()
}) {
Text("Sign Out")
.foregroundColor(.blue)
}
}
}
Section(header: Text("Purchase Information")) {
Button(action: {
self.appState.topView = .purchaseView
}) {
Text("Show Purchase View ")
.foregroundColor(.blue)
}
Text("purchaseStatus: \(appState.currentPurchaseModel?.status.friendlyName ?? "~")")
Text("id: \(appState.currentPurchaseModel?.id.uuidString ?? "~")")
}
Section(header: Text("Device Information")) {
Text("idfv: \(appState.currentDeviceInfo.idfv?.uuidString ?? "~")")
Text("localeLanguageCode: \(appState.currentDeviceInfo.localeLanguageCode ?? "~")")
Text("localeRegionCode: \(appState.currentDeviceInfo.localeRegionCode ?? "~")")
}
Section(header: Text("App Information")) {
Text("appID: \(appState.currentAppInfo.appID)")
Text("appBuildVersin: \(appState.currentAppInfo.appBuildVersin)")
Text("appShortVersion: \(appState.currentAppInfo.appShortVersion)")
}
}
.navigationBarTitle("User")
}
}
}
<file_sep>/SimpleApp/App/Views/SupportingViews/PurchaseView.swift
//
// PurchaseView.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct PurchaseView: View {
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var appState: AppState
var body: some View {
VStack {
Text("PurchaseView")
Spacer()
VStack(alignment: .center, spacing: 20.0) {
Button(action: {
let _ = self.appState.makePurchase(purchase: .premium)
self.appState.topView = .tabView
}) {
Text("Yes! purchase premium for $X.XX")
}.padding()
Button(action: {
self.appState.topView = .tabView
}) {
Text("No Thanks")
}.padding()
}.padding()
Spacer()
}
}
}
struct PurchaseView_Previews: PreviewProvider {
static var previews: some View {
PurchaseView()
}
}
<file_sep>/SimpleApp/App/Views/Views/ChoreRowView.swift
//
// ChoreRowView.swift
// SimpleApp
//
// Created by <NAME> on 7/24/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct ChoreRowView: View {
var categoryName: String
var items: [ChoreModel]
var body: some View {
VStack(alignment: .leading) {
Text(self.categoryName)
.font(.headline)
.padding(.leading, 15)
.padding(.top, 5)
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 0) {
ForEach(self.items) { model in
NavigationLink(
destination: ChoreDetailView(
model: model
)
) {
ChoreItemView(model: model)
}
}
}
}
.frame(height: 185)
}
}
}
struct ChoreItemView: View {
var model: ChoreModel
var body: some View {
VStack(alignment: .leading) {
model.image
.renderingMode(.original)
.resizable()
.frame(width: 155, height: 155)
.cornerRadius(5)
Text(model.name)
.foregroundColor(.primary)
.font(.caption)
}
.padding(.leading, 15)
}
}
struct ConnectRowView: View {
var categoryName: String
var items: [ConnectModel]
var body: some View {
VStack(alignment: .leading) {
Text(self.categoryName)
.font(.headline)
.padding(.leading, 15)
.padding(.top, 5)
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 0) {
ForEach(self.items) { model in
NavigationLink(
destination: ConnectDetailView(
model: model
)
) {
ConnectItemView(model: model)
}
}
}
}
.frame(height: 185)
}
}
}
struct ConnectItemView: View {
var model: ConnectModel
var body: some View {
VStack(alignment: .leading) {
model.image
.renderingMode(.original)
.resizable()
.frame(width: 155, height: 155)
.cornerRadius(5)
Text(model.name)
.foregroundColor(.primary)
.font(.caption)
}
.padding(.leading, 15)
}
}
struct FunRowView: View {
var categoryName: String
var items: [FunModel]
var body: some View {
VStack(alignment: .leading) {
Text(self.categoryName)
.font(.headline)
.padding(.leading, 15)
.padding(.top, 5)
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 0) {
ForEach(self.items) { model in
NavigationLink(
destination: FunDetailView(
model: model
)
) {
FunItemView(model: model)
}
}
}
}
.frame(height: 185)
}
}
}
struct FunItemView: View {
var model: FunModel
var body: some View {
VStack(alignment: .leading) {
model.image
.renderingMode(.original)
.resizable()
.frame(width: 155, height: 155)
.cornerRadius(5)
Text(model.name)
.foregroundColor(.primary)
.font(.caption)
}
.padding(.leading, 15)
}
}
<file_sep>/SimpleApp/App/Views/Views/BoatsView.swift
//
// BoatsView.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct BoatsView: View {
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var appState: AppState
@EnvironmentObject var marinaStore: SimpleNetworkStore<MarinaModel>
@EnvironmentObject var boatStore: SimpleNetworkStore<BoatModel>
@State var devMessage: String?
var changeSelectedTabCallback: (TopTabView.TabViewIndex)->Void
var body: some View {
NavigationView {
List{
if devMessage != nil {
Text("\(devMessage!)")
.foregroundColor(.red)
.onTapGesture {
self.devMessage = nil
}
}
Section(header: Text("Boats")) {
ForEach( boatStore.models) { model in
BoatRowView(model: model)
}
}
Section(header: Text("Marinas")) {
ForEach( marinaStore.models) { model in
NavigationLink(destination: MarinaDetailView(model: model)) {
MarinaRowView(model: model)
}
}
}
}
.navigationBarTitle("Boats")
.navigationBarItems(leading: addButton, trailing: profileButton)
}
}
private var profileButton: some View {
HStack {
if appState.currentPurchaseModel == nil {
Button(action:onProfile) { Image(systemName: "star.circle") }
} else {
Button(action:onProfile) { Image(systemName: "star.circle.fill") }
}
if appState.currentUserModel == nil {
Button(action:onProfile) { Image(systemName: "person.circle") }
} else {
Button(action:onProfile) { Image(systemName: "person.circle.fill") }
}
}
}
private var addButton: some View {
Button(action:onAdd) { Image(systemName: "plus") }
}
func onAdd() {
self.boatStore.createModel( BoatModel.mock)
}
func onProfile() {
changeSelectedTabCallback(.user)
}
}
<file_sep>/SimpleApp/App/Views/Views/ChoreDetailView.swift
//
// ChoreDetailView.swift
// SimpleApp
//
// Created by <NAME> on 7/24/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct ChoreDetailView: View {
var model: ChoreModel
var body: some View {
VStack(alignment: .leading) {
Text("Chore detail")
model.image
.renderingMode(.original)
.resizable()
.frame(width: 155, height: 155)
.cornerRadius(5)
Text(model.name)
.foregroundColor(.primary)
.font(.caption)
}
.padding(.leading, 15)
}
}
struct NewChoreView: View {
var body: some View {
VStack(alignment: .leading) {
Text("New detail")
// model.image
// .renderingMode(.original)
// .resizable()
// .frame(width: 155, height: 155)
// .cornerRadius(5)
// Text(model.name)
// .foregroundColor(.primary)
// .font(.caption)
}
.padding(.leading, 15)
}
}
<file_sep>/SimpleApp/Store/SimpleNetworkStore.swift
//
// SimpleNetworkStore.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
import Combine
public enum StoreConfig {
case prod
case stage
case local
}
public protocol NetworkModel: Codable, Identifiable {
associatedtype ModelType: Codable, Identifiable
static var mockJSON: ModelType { get }
static var mock: ModelType { get }
}
/// Generic Network Store
public final class SimpleNetworkStore<T:NetworkModel>: ObservableObject {
public let objectWillChange = ObservableObjectPublisher()
private var storeConfig: StoreConfig
private var url: URL {
URL(string: "http://api.server.org/boats/")!
}
@Published public var models: [T] = [] {
willSet {
updateChanges()
}
}
public init(storeConfig: StoreConfig) {
self.storeConfig = storeConfig
}
private func updateChanges() {
DispatchQueue.main.async {
self.objectWillChange.send()
}
}
enum InternalError:Error {
case unknown
case invalidResponseFromServer
}
}
extension SimpleNetworkStore {
public func fetch() {
switch storeConfig {
case .prod:
print( "TODO: fetchNetwork")
fetchNetwork()
case .stage:
print( "TODO: fetchNetwork")
fetchNetwork()
case .local:
DispatchQueue.main.async {
self.models = []
self.models.append(T.mockJSON as! T)
}
}
}
private func fetchNetwork() {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("Error: invalid HTTP response code")
return
}
guard let data = data else {
print("Error: missing response data")
return
}
do {
let models = try JSONDecoder().decode([T].self, from: data)
DispatchQueue.main.async {
self.models = models
}
}
catch {
print("Error: \(error.localizedDescription)")
}
}
task.resume()
} //end fetchNetwork
}
extension SimpleNetworkStore {
public func createModel(
_ model:T,
completion: ((Result<T, Error>) -> ())? = nil
) {
guard let encoded = try? JSONEncoder().encode(model) else {
print("Failed to encode model")
return
}
let url = URL(string: "https://reqres.in/api/cupcakes")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = encoded
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
if let error = error {
completion?(.failure(error))
} else {
completion?(.failure(InternalError.unknown))
}
return
}
if let decodedModel = try? JSONDecoder().decode(T.self, from: data) {
self.models.append(decodedModel)
self.updateChanges()
completion?(.success(decodedModel))
} else {
completion?(.failure(InternalError.invalidResponseFromServer))
}
}.resume()
}
public func deleteModel(
id: String,
completion: ((Result<T, Error>) -> ())? = nil
) {
// TODO DeleteItem
}
func fetchItem(
id: String,
completion: ((Result<T, Error>) -> ())? = nil
) {
let mockModel = T.mock
guard let encoded = try? JSONEncoder().encode(mockModel) else {
print("Failed to encode model")
return
}
let url = URL(string: "https://reqres.in/api/cupcakes")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = encoded
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
if let error = error {
completion?(.failure(error))
} else {
completion?(.failure(InternalError.unknown))
}
return
}
if let decodedModel = try? JSONDecoder().decode(T.self, from: data) {
completion?(.success(decodedModel))
} else {
completion?(.failure(InternalError.invalidResponseFromServer))
}
}.resume()
}
// TODO updateModel
// public func updateModel(
// _ model:T,
// completion: ((Result<T, Error>) -> ())? = nil
// ) {
//
// guard let encoded = try? JSONEncoder().encode(model) else {
// print("Failed to encode model")
// return
// }
//
// let url = URL(string: "https://reqres.in/api/cupcakes")!
// var request = URLRequest(url: url)
// request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// request.httpMethod = "POST"
// request.httpBody = encoded
//
// URLSession.shared.dataTask(with: request) { data, response, error in
//
// guard let data = data else {
// if let error = error {
// completion?(.failure(error))
// } else {
// completion?(.failure(InternalError.unknown))
// }
// return
// }
//
// if let decodedModel = try? JSONDecoder().decode(T.self, from: data) {
// self.models.append(decodedModel)
// self.updateChanges()
// completion?(.success(decodedModel))
// } else {
// completion?(.failure(InternalError.invalidResponseFromServer))
// }
//
// }.resume()
// }
}
<file_sep>/SimpleApp/App/Views/SupportingViews/AuthenticationView.swift
//
// LoginView.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct AutheticationView: View {
@Environment(\.window) var window: UIWindow?
@Environment(\.presentationMode) var presentationMode
@EnvironmentObject var appState: AppState
@State var email: String = "<EMAIL>"
@State var password: String = ""
@State var errorMessage: String?
var body: some View {
VStack {
Text("Authentication View")
Spacer()
if errorMessage != nil {
Text(errorMessage!)
.foregroundColor(.red)
Spacer()
}
VStack {
TextField("email", text: $email)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("password", text: $password)
.textFieldStyle(RoundedBorderTextFieldStyle())
}.padding()
HStack {
Button(action: {
self.appState.signIn(email: self.email, password: "<PASSWORD>") { result in
switch result {
case .success( _ ):
self.appState.topView = .tabView
self.presentationMode.wrappedValue.dismiss()
case .failure( let error):
self.errorMessage = "Sign In Error \(error)"
//self.appState.topView = .tabView
}
}
}) {
Text("Sign In")
}.padding()
Spacer()
Button(action: {
self.appState.register(email: self.email, password: "<PASSWORD>") { result in
switch result {
case .success( _ ):
self.appState.topView = .tabView
self.presentationMode.wrappedValue.dismiss()
case .failure( let error):
self.errorMessage = "Register In Error \(error)"
}
}
}) {
Text("Register")
}.padding()
}.padding()
Spacer()
Button(action: {
self.appState.topView = .tabView
}) {
Text("Cancel")
}.padding()
Spacer()
}
}
}
struct AuthenticationView_Previews: PreviewProvider {
static var previews: some View {
AutheticationView()
}
}
<file_sep>/SimpleApp/Store/NetworkModels/DeviceModel.swift
//
// DeviceModel.swift
// SimpleApp
//
// Created by <NAME> on 7/20/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import Foundation
import SwiftUI
/// Information about this device
struct DeviceModel {
let idfv: UUID?
let localeLanguageCode: String?
let localeRegionCode: String?
let localePreferredLanguages: [String]
init() {
self.idfv = UIDevice.current.identifierForVendor
let locale = Locale.current
self.localeLanguageCode = locale.languageCode
self.localeRegionCode = locale.regionCode
self.localePreferredLanguages = Locale.preferredLanguages
}
}
<file_sep>/SimpleApp/Store/NetworkModels/MarinaModel.swift
//
// MarinaModel.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import Foundation
/// Marina Model
public struct MarinaModel: NetworkModel {
public typealias ModelType = MarinaModel
public let id: String
public let name: String
public let info: String
public let country: String
}
extension MarinaModel {
public static var mock: ModelType {
return MarinaModel(
id: UUID().uuidString,
name: "Marina \(Int.random(in: 1...100))",
info: "some info",
country: "US"
)
}
public static var mockJSON: ModelType {
let str = """
{
"id": "5005477",
"name": "<NAME>",
"info": "Marina in Panaam",
"country": "pa"
}
"""
let data = Data(str.utf8)
do {
let model = try JSONDecoder().decode(MarinaModel.self, from: data)
return model
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
fatalError()
}
}
}
<file_sep>/SimpleApp/App/Views/Views/MarinaDetailView.swift
//
// MarinaDetail.swift
// SimpleApp
//
// Created by <NAME> on 7/22/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct MarinaDetailView: View {
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var appState: AppState
@EnvironmentObject var marinaStore: SimpleNetworkStore<MarinaModel>
@EnvironmentObject var boatStore: SimpleNetworkStore<BoatModel>
@State var devMessage: String?
var model: MarinaModel
var body: some View {
VStack {
Text("Marina Detail")
Text("Name: \(model.name)")
Text("Info: \(model.info)")
}
}
}
<file_sep>/SimpleApp/Store/Models/UserModel.swift
//
// UserModel.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import Foundation
/// User Model
public struct UserModel: NetworkModel {
public typealias ModelType = UserModel
public var id: Int
public var email: String
}
extension UserModel {
public static var mock: UserModel {
return UserModel(
id: 12345,
email: "<EMAIL>"
)
}
public static var mockJSON: UserModel {
return UserModel(
id: 12346,
email: "<EMAIL>"
)
}
}
<file_sep>/SimpleApp/Store/NetworkModels/BoatModel.swift
//
// BoatModel.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import Foundation
/// Boat Model
public struct BoatModel : NetworkModel {
public typealias ModelType = BoatModel
public let id: String
public let name: String
public let info: String
public let imageURL: String
public let hullMaterial: String
public let loa: String
public let lwl: String
public let displacement: String
public let beam: String
public let rig: String
}
extension BoatModel {
public static var mock: ModelType {
return BoatModel(
id: UUID().uuidString,
name: "Boat \(Int.random(in: 1...100))",
info: "some info",
imageURL: "https://images.boats.com/resize/1/22/57/7472257_20200606162043594_1_XLARGE.jpg?t=1591461800000&w=600&h=600",
hullMaterial: "Fiberglass",
loa: "39.92 ft / 12.17 m",
lwl: "34.00 ft / 10.36 m",
displacement: "23,520 lb / 10,668 kg",
beam: "12.33 ft / 3.76 m",
rig: "Cutter"
)
}
public static var mockJSON: ModelType {
let str = """
{
"id": "5005477",
"name": "Valiant 40",
"info": "Valiant 40",
"imageURL": "https://images.boats.com/resize/1/22/57/7472257_20200606162043594_1_XLARGE.jpg?t=1591461800000&w=600&h=600",
"hullMaterial": "Fiberglass",
"loa": "39.92 ft / 12.17 m",
"lwl": "34.00 ft / 10.36 m",
"displacement": "23,520 lb / 10,668 kg",
"beam":"12.33 ft / 3.76 m",
"rig":"cutter",
}
"""
let data = Data(str.utf8)
do {
let model = try JSONDecoder().decode(BoatModel.self, from: data)
return model
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
fatalError()
}
}
}
<file_sep>/SimpleApp/App/Views/TopViews/TopTabView.swift
//
// TopTabView.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import SwiftUI
struct TopTabView: View {
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var appState: AppState
@EnvironmentObject var marinaStore: SimpleNetworkStore<MarinaModel>
@EnvironmentObject var boatStore: SimpleNetworkStore<BoatModel>
public enum TabViewIndex: Int {
case boats = 0
case marinas = 1
case user = 2
}
@State private var selectedTab: Int = TabViewIndex.boats.rawValue
var body: some View {
TabView(selection: $selectedTab) {
BoatsView(changeSelectedTabCallback: changeTab)
.environmentObject(appState)
.environmentObject(marinaStore)
.environmentObject(boatStore)
.tabItem {
Image(systemName:"wind")
Text("Boats")
}.tag(TabViewIndex.boats.rawValue)
MarinasView(changeSelectedTabCallback: changeTab)
.environmentObject(appState)
.environmentObject(marinaStore)
.environmentObject(boatStore)
.tabItem {
Image(systemName:"globe")
Text("Marinas")
}.tag(TabViewIndex.marinas.rawValue)
UserView()
.environmentObject(appState)
.tabItem {
Image(systemName:"person.circle")
Text("User")
}.tag(TabViewIndex.user.rawValue)
}
}
func changeTab(tab: TabViewIndex) {
self.selectedTab = tab.rawValue
}
}
<file_sep>/SimpleApp/Store/SimpleUserStore.swift
//
// SimpleUserStore.swift
// SimpleApp
//
// Created by <NAME> on 7/19/20.
// Copyright © 2020 jumptack. All rights reserved.
//
import Combine
import SwiftUI
public final class SimpleUserStore {
struct RegisterRequestModel: Codable {
var email: String
var password: String
}
struct SignInResponseModel: Codable {
var token: String
}
enum InternalError:Error {
case unknown
case invalidResponseFromServer
}
}
/// UserStore
extension SimpleUserStore {
public func signOut(
completion: @escaping (Result<UserModel?, Error>) -> ()
){
completion(.success(nil))
}
public func signIn(
email: String,
password:String,
completion: @escaping (Result<UserModel, Error>) -> ()
){
// let model = UserModel(id:12345, email:email)
// completion(.success(model))
let model = RegisterRequestModel(email: email, password: <PASSWORD>)
guard let encoded = try? JSONEncoder().encode(model) else {
completion(.failure(InternalError.unknown))
return
}
let url = URL(string: "https://reqres.in/api/login")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = encoded
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
if let error = error {
completion(.failure(error))
} else {
completion(.failure(InternalError.unknown))
}
return
}
if let decodedModel = try? JSONDecoder().decode(SignInResponseModel.self, from: data) {
print( "token: \(decodedModel.token)")
let user = UserModel(id: 5555, email: email)
completion(.success(user))
} else {
completion(.failure(InternalError.invalidResponseFromServer))
}
}.resume()
}
public func register(
email: String,
password:String,
completion: @escaping (Result<UserModel, Error>) -> ()
) {
let model = RegisterRequestModel(email: email, password: <PASSWORD>)
guard let encoded = try? JSONEncoder().encode(model) else {
completion(.failure(InternalError.unknown))
return
}
let url = URL(string: "https://reqres.in/api/register")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = encoded
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
if let error = error {
completion(.failure(error))
} else {
completion(.failure(InternalError.unknown))
}
return
}
if let decodedModel = try? JSONDecoder().decode(UserModel.self, from: data) {
completion(.success(decodedModel))
} else {
completion(.failure(InternalError.invalidResponseFromServer))
}
}.resume()
}
}
|
125cdabe7f4f394b0513baacc4238c8563955c8b
|
[
"Swift",
"Markdown"
] | 23 |
Swift
|
schmulen/simpleApp13
|
8c48a82641878950fa627950ab3235e9d4d0540f
|
91de4fa5750ec14d79ea3a715b3f190372efc730
|
refs/heads/master
|
<repo_name>Simon947a/Simpd_v9<file_sep>/Lab3/Lab3Script.R
library(ahp)
ahpFile <- system.file("extdata", "data.ahp", package="ahp")
dataAhp <- Load(ahpFile)
Calculate(dataAhp)
print(dataAhp, priority = function(x) x$sparent$priority["total", x$name])
Visualize(dataAhp)
Analyze(dataAhp)
AnalyzeTable(dataAhp)
<file_sep>/Lab2/Lab2Script.R
library("MCDA")
library("OutrankingTools")
#install.packages("OutrankingTools")
# the performance table
performanceMatrix <- cbind(
c(5,5.2,5.5,5.3),
c(2,2,3,4),
c(16,16,32,64),
c(8,13,16,13),
c(449,649,829,1899)
)
# Vector containing names of alternatives
alternatives <- c("Nokia 3","Nokia 5","Noia 6","Nokia 8")
# Vector containing names of criteria
criteria <- c( "Display","RAM","ROM","Camera","Price")
criteriaWeights <- c(0.25,0.45,0.10,0.12,0.08)
# vector indicating the direction of the criteria evaluation .
minmaxcriteria <- c("max","max","max","max","min")
# Matrix containing the profiles.
profiles <- cbind(c(-100,-50),c(-1000,-500),c(4,7),c(4,7),c(15,20))
# vector defining profiles' names
profiles_names <-c("b1","b2")
# thresholds vector
IndifferenceThresholds <- c(15,80,1,0.5,1)
PreferenceThresholds <- c(40,350,3,3.5,5)
VetoThresholds <- c(100,850,5,4.5,8)
# Testing
Electre_tri(performanceMatrix,
alternatives,
profiles,
profiles_names,
criteria,
minmaxcriteria,
criteriaWeights,
IndifferenceThresholds,
PreferenceThresholds,
VetoThresholds,
lambda=NULL)
|
b2aa39bb4e51c1900fb92f44588cce9cd38324e4
|
[
"R"
] | 2 |
R
|
Simon947a/Simpd_v9
|
def87a842940504141b365162d93e893c545261b
|
d024850873aed8aadef708ad690a0911fffbeb49
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Unirest;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
public function convert(Request $request){
$response = Unirest\Request::get("http://apilayer.net/api/live?access_key=3502a040cdeb142108c0ae34762f380a¤cies=NGN&source=USD&format=1");
$data = $response->body->quotes; // Parsed body
if($response->code != 200){
echo "error";
}else{
$val=$data->USDNGN;
return view('home',['val'=>$val]);
}
}
}
|
3057ac64b26ae09c8a0b36d1ca9c176187b23e16
|
[
"PHP"
] | 1 |
PHP
|
afinayor/currency
|
f9d1f1bedda43f73be8e3ae70dc46b5bc6342781
|
a5873a120549ed05f5372ebe96228e42f054b2ff
|
refs/heads/master
|
<repo_name>gabrielolferrari/react-marvel-api<file_sep>/src/config/config.js
export const configAPIMarvel = {
publicKey: '8bbee023ea9707d06117988d5205af37',
privateKey: '<KEY>',
baseUrl: 'https://gateway.marvel.com:443/v1/public/',
}<file_sep>/src/components/comics/comicComments.js
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import gql from 'graphql-tag';
import { Mutation, Query } from 'react-apollo';
import Typography from '@material-ui/core/Typography';
import SendIcon from '@material-ui/icons/Send';
import Button from '@material-ui/core/Button';
const ADD_COMMENT = gql`
mutation comment($comicid: String!, $comment: String!) {
addComment(comicid: $comicid, comment: $comment) {
comicid,
comment
}
}
`;
const useStyles = makeStyles(({
commentTitle: {
borderTop: '1px solid #ddd',
marginTop: 20,
marginBottom: 20,
paddingTop: 20,
},
comment: {
borderTop: '1px solid #ddd',
marginTop: 20,
marginBottom: 20,
paddingTop: 20,
width: '100%',
height: 100,
border: 0,
borderBottom: '1px solid #888',
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
fontSize: '12pt',
},
buttonSend: {
float: 'right',
marginTop: 10,
marginBottom: 40,
},
}));
const ComicComments = (props) => {
const classes = useStyles();
const comicid = props.commicid.toString();
let comment;
const GET_COMMENTS = gql`
query comment($comicid: String!){
comments(comicid: $comicid) {
id,
comment
}
}
`;
return (
<React.Fragment>
<Typography variant="h6" className={classes.commentTitle}>
<strong>Comments</strong>
</Typography>
<Query pollInterval={1000} query={GET_COMMENTS} variables={{ comicid }} fetchPolicy="network-only">
{({ loading, error, data }) => {
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return (
data.comments.map(info => (
<div key={info.id}>
<p>{info.comment}</p>
</div>
))
);
}}
</Query>
<Mutation mutation={ADD_COMMENT} onCompleted={() => console.log('Complete')} fetchPolicy="no-cache">
{(addFavorite, { loading, error }) => (
<React.Fragment>
<form onSubmit={(e) => {
e.preventDefault();
addFavorite({ variables: { comicid, comment: comment.value } });
comment.value = '';
}}
>
<textarea
className={classes.comment}
ref={(node) => {
comment = node;
}}
placeholder="Comment"
/>
<Button type="submit" variant="contained" color="primary" className={classes.buttonSend}>
Send
<SendIcon />
</Button>
</form>
{loading && <p>Loading...</p>}
{error && <p>Error :( Please try again</p>}
</React.Fragment>
)}
</Mutation>
</React.Fragment>
);
};
export default ComicComments;
<file_sep>/backend/app.js
const Express = require('express');
const cors = require('cors');
const ExpressGraphQL = require('express-graphql');
const Mongoose = require('mongoose');
const {
GraphQLID,
GraphQLString,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
} = require('graphql');
const app = Express();
Mongoose.connect('mongodb://localhost/marvelapi', { useNewUrlParser: true });
const FavoriteModel = Mongoose.model('favorites', {
comicid: String,
title: String,
image: String,
});
const CommentModel = Mongoose.model('comments', {
comicid: String,
comment: String,
image: String,
});
const FavoriteType = new GraphQLObjectType({
name: 'Favorite',
fields: {
id: { type: GraphQLID },
comicid: { type: GraphQLString },
title: { type: GraphQLString },
image: { type: GraphQLString },
},
});
const CommentType = new GraphQLObjectType({
name: 'Comment',
fields: {
id: { type: GraphQLID },
comicid: { type: GraphQLString },
comment: { type: GraphQLString },
},
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
favorites: {
type: GraphQLList(FavoriteType),
resolve: () => FavoriteModel.find().exec(),
},
favorite: {
type: FavoriteType,
args: {
id: { type: GraphQLNonNull(GraphQLID) },
},
resolve: (root, args) => FavoriteModel.findById(args.id).exec(),
},
comments: {
type: GraphQLList(CommentType),
args: {
comicid: { type: GraphQLNonNull(GraphQLString) },
},
resolve: (root, args) => CommentModel.find({ comicid: args.comicid }).exec(),
},
},
}),
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
addFavorite: {
type: FavoriteType,
args: {
comicid: { type: GraphQLNonNull(GraphQLString) },
title: { type: GraphQLNonNull(GraphQLString) },
image: { type: GraphQLNonNull(GraphQLString) },
},
resolve: (root, args) => {
const favorite = new FavoriteModel(args);
return favorite.save();
},
},
addComment: {
type: CommentType,
args: {
comicid: { type: GraphQLNonNull(GraphQLString) },
comment: { type: GraphQLNonNull(GraphQLString) },
},
resolve: (root, args) => {
const comment = new CommentModel(args);
return comment.save();
},
},
},
}),
});
app.use(cors());
app.use('/graphql', ExpressGraphQL({
schema,
graphiql: true,
}));
app.listen(3001, () => {
console.log('Listening at :3001...');
});
<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';
import CssBaseline from '@material-ui/core/CssBaseline';
import { ThemeProvider } from '@material-ui/styles';
import './index.css';
import App from './App';
import theme from './theme';
const client = new ApolloClient({
uri: 'http://localhost:3001/graphql',
});
ReactDOM.render(
<BrowserRouter>
<ApolloProvider client={client}>
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
</ThemeProvider>
</ApolloProvider>
</BrowserRouter>,
document.getElementById('root'),
);
<file_sep>/src/services/MarvelAPI.js
import axios from 'axios';
import CryptoJS from 'crypto-js';
import moment from 'moment';
import { configAPIMarvel as config } from '../config';
const request = axios.create({
baseURL: `${config.baseUrl}`,
responseType: 'json',
});
const timeStamp = moment().unix();
const generateHash = () => {
const hash = CryptoJS.MD5(timeStamp + config.privateKey + config.publicKey)
.toString(CryptoJS.enc.Hex);
return hash;
};
export const getCharacters = async (character) => {
const URI = '/characters';
let params = `?apikey=${config.publicKey}&ts=${timeStamp}&hash=${generateHash()}`;
if (character) {
params = params.concat(`&name=${character}`);
}
const url = `${URI}${params}`;
return request.get(url);
};
export const getComics = async (page, character) => {
const count = 21;
const currentPage = page || 1;
const currentOffset = currentPage === 1 ? 0 : (count * (page - 1));
const URI = '/comics';
let params = `?limit=${count}&offset=${currentOffset}&apikey=${config.publicKey}&ts=${timeStamp}&hash=${generateHash()}`;
if (character) {
let charInfo = [];
await getCharacters(character).then((result) => {
charInfo = result.data.data.results;
});
if (charInfo[0]) {
params = params.concat(`&characters=${charInfo[0].id}`);
} else {
return null;
}
}
const url = `${URI}${params}`;
return request.get(url);
};
export const getFavoriteComics = async (id) => {
const URI = `/comics/${id}`;
const params = `?apikey=${config.publicKey}&ts=${timeStamp}&hash=${generateHash()}`;
const url = `${URI}${params}`;
return request.get(url);
};
<file_sep>/src/App.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import ListComics from './components/comics/listComics';
import Menu from './components/menu';
import Favorites from './components/favorites';
const App = () => (
<React.Fragment>
<AppBar position="relative" color="primary">
<Toolbar>
<Typography variant="h6" color="inherit" style={{ flex: 1 }} noWrap>
MARVEL
</Typography>
<Menu />
</Toolbar>
</AppBar>
<main>
<Switch>
<Route exact path="/" component={ListComics} />
<Route exact path="/Favorites" component={Favorites} />
</Switch>
</main>
</React.Fragment>
);
export default App;
<file_sep>/src/components/menu/index.js
import React from 'react';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
const useStyles = makeStyles(theme => ({
root: {
float: 'right',
},
link: {
color: '#FFFFFF',
margin: theme.spacing(1),
},
}));
const Menu = () => {
const classes = useStyles();
return (
<React.Fragment>
<div className={classes.root}>
<Typography variant="h6">
<Link to="/" color="secondary" className={classes.link}>
Comics
</Link>
<Link to="/Favorites" color="primary" className={classes.link}>
Favorites
</Link>
</Typography>
</div>
</React.Fragment>
);
};
export default withRouter(Menu);
|
d626927be96a754329b9cf94cce5aa240d8c752f
|
[
"JavaScript"
] | 7 |
JavaScript
|
gabrielolferrari/react-marvel-api
|
877ec53f53d227fbcbeb7544b88bba0fc56f1e16
|
6303336cfd55672fafd81250c832f84be94a0bb4
|
refs/heads/main
|
<file_sep># ProyectoFinalProgramacion
Proyecto final de la tercera evaluación de Programación
|
37753df873640dd1d886099a5bf39f9cdde956a1
|
[
"Markdown"
] | 1 |
Markdown
|
nicorrt/ProyectoFinalProgramacion
|
531249453456e78d8a0eb1f623fb22f2240bedc0
|
47fb321ebe1c5d6c350639a758480264639aaa95
|
refs/heads/master
|
<repo_name>helioferreira/android-pager-animations-demo<file_sep>/README.md
# android-pager-animations-demo
A small project that uses PageTransformer and Shared Element Transition to add some cool behaviours to the ordinary ViewPager.
The project also uses [Picasso](https://github.com/square/picasso) (I shamelessly copied the sample data and used it as placeholder data) and [Picasso Transformations](https://github.com/wasabeef/picasso-transformations).
<file_sep>/app/src/main/java/com/example/pager/ViewPagerAdapter.java
package com.example.pager;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.Stack;
/**
* Created by helio on 17/08/15.
*/
public class ViewPagerAdapter extends PagerAdapter {
private final int transitionItemIndex;
private final Stack<View> recycledViews = new Stack<>();
private boolean startedPostponedEnterTransition = false;
public ViewPagerAdapter(int transitionItemIndex) {
this.transitionItemIndex = transitionItemIndex;
}
@Override
public int getCount() {
return Data.URLS.length;
}
@Override
public Object instantiateItem(ViewGroup collection, int position) {
Context context = collection.getContext();
ViewGroup pagerItemView = (ViewGroup) (recycledViews.empty() ? inflatePageView(collection) : recycledViews.pop());
ImageView imageView = (ImageView) pagerItemView.getChildAt(0);
Picasso.with(context).load(Data.URLS[position]).into(imageView);
collection.addView(pagerItemView, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (position == transitionItemIndex) {
imageView.setTransitionName(context.getString(R.string.transition_picture));
if (!startedPostponedEnterTransition) {
startedPostponedEnterTransition = true;
ActivityCompat.startPostponedEnterTransition((Activity) context);
}
} else {
imageView.setTransitionName(null);
}
}
pagerItemView.setTag(new PageInfo(Data.URLS[position], position < getCount() - 1 ? Data.URLS[position + 1] : null));
return pagerItemView;
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
recycledViews.add((View) view);
}
@Override
public boolean isViewFromObject(final View arg0, final Object arg1) {
return arg0 == arg1;
}
private View inflatePageView(ViewGroup collection) {
return LayoutInflater.from(collection.getContext()).inflate(R.layout.pager_item, collection, false);
}
public PageInfo getPageInfoForPageView(View view) {
return (PageInfo) view.getTag();
}
public static class PageInfo {
public final String pageBgUrl;
public final String rightPageBgUrl;
public PageInfo(String pageBgUrl, String rightPageBgUrl) {
this.pageBgUrl = pageBgUrl;
this.rightPageBgUrl = rightPageBgUrl;
}
}
}
<file_sep>/app/src/main/java/com/example/pager/MainActivity.java
package com.example.pager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Picasso.with(this).setIndicatorsEnabled(true);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(new ListViewAdapter(this));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startDetailsWithSharedElementTransition((ViewGroup) view, position);
}
});
}
private void startDetailsWithSharedElementTransition(ViewGroup itemView, int position) {
Intent intent = new Intent(this, DetailsActivity.class).putExtra(DetailsActivity.EXTRA_URL_INDEX, position);
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this,
new Pair<>(itemView.getChildAt(0), getString(R.string.transition_picture)),
new Pair<>(itemView.getChildAt(1), getString(R.string.transition_label))
);
ActivityCompat.startActivity(this, intent, options.toBundle());
}
}
|
a0164c29a4c024d66ad298cba3a51592d0f0c1a2
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
helioferreira/android-pager-animations-demo
|
59cdc472e7905276d15c41b38d2589301c86572e
|
5f864f10875a9eafa49c543d656842a008b66c05
|
refs/heads/main
|
<repo_name>NeilKulikov/vmfunctions<file_sep>/vmfunctions/common.hpp
#ifndef VMFUNCTIONS_COMMON
#define VMFUNCTIONS_COMMON
#include <type_traits>
namespace vmfunctions::common {
template<typename I>
constexpr I factorial(I arg) {
static_assert(std::is_integral<I>::value);
return arg == 0 ? I(1) : arg * factorial(arg - 1);
}
template<typename F, typename I = int>
constexpr F rfactorial(I deg) {
static_assert(std::is_floating_point<F>::value);
static_assert(std::is_integral<I>::value);
static_assert(std::is_signed<I>::value);
return F(1) / F(factorial<I>(deg));
}
template<typename F, int pow>
constexpr F power(F arg) {
return pow ? arg * power<F, pow - 1>(arg) : F(1);
}
template<typename F>
constexpr F power(F arg, int pow) {
return pow ? arg * power<F>(arg, pow - 1) : F(1);
}
} // vmfunctions::common
#endif // VMFUNCTIONS_COMMON<file_sep>/vmfunctions/constants.hpp
#ifndef VMFUNCTIONS_CONSTANTS
#define VMFUNCTIONS_CONSTANTS
#define __VMF_C_PI 3.141592653589793238462643383279
namespace vmfunctions::constants {
template<typename F>
inline constexpr F pi = F(__VMF_C_PI);
template<typename F>
inline constexpr F dpi = pi<F> * F(2);
template<typename F>
inline constexpr F pih = F(2) / pi<F>;
template<typename F>
inline constexpr F hpi = pi<F> / F(2);
} // vmfunctions::constants
#undef __VMF_C_PI
#endif // VMFUNCTIONS_CONSTANTS<file_sep>/vmfunctions/trigonometry/cos_coefs.hpp
#ifndef VMFUNCTIONS_TRIGINOMETRY_COS_COEFS
#define VMFUNCTIONS_TRIGINOMETRY_COS_COEFS
#include <type_traits>
#include "vmfunctions/common.hpp"
namespace vmfunctions::trigonometry {
template<typename F, typename I = int>
constexpr F cossign(I deg) {
static_assert(std::is_floating_point<F>::value);
static_assert(std::is_integral<I>::value);
static_assert(std::is_signed<I>::value);
return (deg % 4) ? F(-1) : F(1);
}
template<typename F, typename I = int>
constexpr F coseven(I deg) {
static_assert(std::is_floating_point<F>::value);
static_assert(std::is_integral<I>::value);
static_assert(std::is_signed<I>::value);
return (deg % 2) ? F(0) : F(1);
}
template<typename F, typename I = int>
constexpr F coscoef(I deg) {
static_assert(std::is_floating_point<F>::value);
static_assert(std::is_integral<I>::value);
static_assert(std::is_signed<I>::value);
return coseven<F, I>(deg) * cossign<F, I>(deg)
* common::rfactorial<F, I>(deg);
}
} // vmfunctions::trigonometry
#endif // VMFUNCTIONS_TRIGINOMETRY_COS_COEFS<file_sep>/vmfunctions/tests/tests_common.hpp
#ifndef VMFUNCTIONS_TESTS_COMMON
#define VMFUNCTIONS_TESTS_COMMON
#include "catch2/catch.hpp"
#define STD_RTOL 1.e-5
#define STD_ATOL 1.e-7
#define ALMOST_EQUAL_CUSTOM(gtr, res, rtol, atol) check_almost_equal(gtr, res, rtol, atol)
#define ALMOST_EQUAL_REL(gtr, res, rtol) ALMOST_EQUAL_CUSTOM(gtr, res, rtol, decltype(gtr)(STD_ATOL))
#define ALMOST_EQUAL_ABS(gtr, res, atol) ALMOST_EQUAL_CUSTOM(gtr, res, decltype(gtr)(STD_RTOL), atol)
#define ALMOST_EQUAL(gtr, res) ALMOST_EQUAL_CUSTOM(gtr, res, decltype(gtr)(STD_RTOL), decltype(gtr)(STD_ATOL))
template<typename Last>
constexpr auto max(Last l) {
return l;
}
template<typename First, typename Last>
constexpr auto max(First f, Last l) {
return (f >= l) ? f : l;
}
template<typename First, typename... Tail>
constexpr auto max(First f, Tail... t) {
return max(f, max(t...));
}
template<typename T>
constexpr auto abs(T x) {
return (x >= 0) ? x : -x;
}
template<typename T>
void check_almost_equal(const T gt, const T rs,
const T rtol = T(STD_RTOL), const T atol = T(STD_ATOL)) {
CAPTURE(gt, rs, rtol, atol);
if(gt == rs) return;
const T aerr = rs - gt;
CAPTURE(aerr);
if((-atol <= aerr) && (aerr <= +atol)) {
const T div = max(abs(rs), abs(gt), atol);
const T rerr = aerr / div;
CAPTURE(rerr);
REQUIRE(-rtol <= rerr);
REQUIRE(rerr <= +rtol);
} else {
REQUIRE(-atol <= aerr);
REQUIRE(aerr <= +atol);
}
}
#endif // VMFUNCTIONS_TESTS_COMMON<file_sep>/vmfunctions/trigonometry/tests/residue_test.cpp
#ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN
#endif
#include "catch2/catch.hpp"
#include <cmath>
#include "vmfunctions/tests/tests_common.hpp"
#include "vmfunctions/trigonometry/tests/residue.hpp"
using fp_types = std::tuple<float, double>;
TEMPLATE_LIST_TEST_CASE("sin residue 2", "[sin][residue]", fp_types) {
using namespace vmfunctions::trigonometry::tests;
const auto residue =
[](const auto x) { return sin_residue<TestType, 2>(x); };
ALMOST_EQUAL(TestType(-1. / 6.), residue(1.));
ALMOST_EQUAL(TestType(-0.08074551218828077), residue(M_PI_4));
}
TEMPLATE_LIST_TEST_CASE("sin residue 3", "[sin][residue]", fp_types) {
using namespace vmfunctions::trigonometry::tests;
const auto residue =
[](const auto x) { return sin_residue<TestType, 4>(x); };
ALMOST_EQUAL(TestType(+1. / 120.), residue(1.));
ALMOST_EQUAL(TestType(+0.00249039457019272), residue(M_PI_4));
}<file_sep>/vmfunctions/tests/type_manipulations_test.cpp
#include "catch2/catch.hpp"
#include "vmfunctions/type_manipulations.hpp"
using types = std::tuple<
std::tuple<std::int32_t, float>,
std::tuple<std::int64_t, double> >;
TEMPLATE_LIST_TEST_CASE("sign flip via xor", "[xor]", types) {
using namespace vmfunctions::common;
using I = std::tuple_element_t<0, TestType>;
using F = std::tuple_element_t<1, TestType>;
constexpr int shift = sizeof(F);
constexpr I mask = I(1) << (8 * shift - 1);
if constexpr (std::is_same<F, float>::value) {
REQUIRE(mask == std::int32_t(0x80000000));
} else {
REQUIRE(mask == std::int64_t(0x8000000000000000));
}
REQUIRE(XOR(F(-0.1), mask) == F(0.1));
REQUIRE(XOR(F(0.1), mask) == F(-0.1));
REQUIRE(XOR(F(-512.3), mask) == F(512.3));
REQUIRE(XOR(F(512.3), mask) == F(-512.3));
}<file_sep>/vmfunctions/trigonometry/tests/sincos_coefs_test.cpp
#ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN
#endif
#include "catch2/catch.hpp"
#include "vmfunctions/tests/tests_common.hpp"
#include "vmfunctions/trigonometry/cos_coefs.hpp"
#include "vmfunctions/trigonometry/sin_coefs.hpp"
using test_types = std::tuple<
std::tuple<int, float>,
std::tuple<int, double>,
std::tuple<long, float>,
std::tuple<long, double>>;
TEMPLATE_LIST_TEST_CASE("cos coeffients", "[cos][coefs]", test_types) {
using namespace vmfunctions::trigonometry;
using I = std::tuple_element_t<0, TestType>;
using F = std::tuple_element_t<1, TestType>;
const auto ccoef = std::bind(coscoef<F, I>, std::placeholders::_1);
ALMOST_EQUAL(ccoef(0), F(1));
ALMOST_EQUAL(ccoef(1), F(0));
ALMOST_EQUAL(ccoef(2), F(-1. / 2.));
ALMOST_EQUAL(ccoef(3), F(0));
ALMOST_EQUAL(ccoef(4), F(1. / 24.));
ALMOST_EQUAL(ccoef(5), F(0));
ALMOST_EQUAL(ccoef(6), F(-1. / 720.));
}
TEMPLATE_LIST_TEST_CASE("sin coeffients", "[sin][coefs]", test_types) {
using namespace vmfunctions::trigonometry;
using I = std::tuple_element_t<0, TestType>;
using F = std::tuple_element_t<1, TestType>;
const auto scoef = std::bind(sincoef<F, I>, std::placeholders::_1);
ALMOST_EQUAL(scoef(0), F(0.));
ALMOST_EQUAL(scoef(1), F(1.));
ALMOST_EQUAL(scoef(2), F(0.));
ALMOST_EQUAL(scoef(3), F(-1. / 6.));
ALMOST_EQUAL(scoef(4), F(0.));
ALMOST_EQUAL(scoef(5), F(1. / 120.));
ALMOST_EQUAL(scoef(6), F(0.));
}
<file_sep>/vmfunctions/trigonometry/bench/sincos_series_bench.cpp
#ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN
#endif
#ifndef CATCH_CONFIG_ENABLE_BENCHMARKING
#define CATCH_CONFIG_ENABLE_BENCHMARKING
#endif
#include "catch2/catch.hpp"
#include <cmath>
#include <vector>
#include <algorithm>
#include <type_traits>
#include "vmfunctions/trigonometry/sin_series.hpp"
using test_types = std::tuple<float, double>;
#define SINS vmfunctions::trigonometry::sins<TestType>
TEMPLATE_LIST_TEST_CASE("sin series", "[sin][series]", test_types) {
BENCHMARK("Sin Series 1. - 1") {
return SINS(1.);
};
BENCHMARK("Sin Std 1. - 1") {
if constexpr (std::is_same<float, TestType>::value) {
return std::sinf(1.);
}
else {
return std::sin(1.);
}
};
BENCHMARK("Loop Series - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
res += TestType(1.);
}
};
BENCHMARK("Sin Series 1. - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
res += SINS(1.);
}
};
BENCHMARK("Sin Std 1. - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
if constexpr (std::is_same<float, TestType>::value) {
res += std::sinf(1.);
}
if constexpr (std::is_same<double, TestType>::value) {
res += std::sin(1.);
}
}
};
}
TEMPLATE_LIST_TEST_CASE("sin series transform", "[sin][series][wise]", test_types) {
constexpr int nsteps = 1024;
std::vector<TestType> inp(nsteps, TestType(1));
std::vector<TestType> out(nsteps, TestType(1));
BENCHMARK("Sin Series - 1024") {
std::transform(inp.cbegin(), inp.cend(), out.begin(), SINS);
};
BENCHMARK("Sin Series Direct - 1024") {
for(int i = 0; i < nsteps; ++i) {
out[i] = SINS(inp[i]);
}
};
BENCHMARK("Sin Std - 1024") {
constexpr auto sin = [] (auto x) {
if constexpr (std::is_same<float, TestType>::value) {
return std::sinf(1.);
}
else {
return std::sin(1.);
}
};
std::transform(inp.cbegin(), inp.cend(), out.begin(), sin);
};
BENCHMARK("Sin Std Direct - 1024") {
for(int i = 0; i < nsteps; ++i) {
if constexpr (std::is_same<float, TestType>::value) {
out[i] = std::sinf(inp[i]);
}
else {
out[i] = std::sin(inp[i]);
}
}
};
}
#include "vmfunctions/trigonometry/cos_series.hpp"
#define COSS vmfunctions::trigonometry::coss<TestType>
TEMPLATE_LIST_TEST_CASE("cos series", "[cos][series]", test_types) {
BENCHMARK("Cos Series 1. - 1") {
return COSS(1.);
};
BENCHMARK("Cos Std 1. - 1") {
if constexpr (std::is_same<float, TestType>::value) {
return std::cosf(1.);
}
else {
return std::cos(1.);
}
};
BENCHMARK("Loop Series - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
res += TestType(1.);
}
};
BENCHMARK("Cos Series 1. - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
res += COSS(1.);
}
};
BENCHMARK("Cos Std 1. - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
if constexpr (std::is_same<float, TestType>::value) {
res += std::cosf(1.);
}
else {
res += std::cos(1.);
}
}
};
}
TEMPLATE_LIST_TEST_CASE("cos series transform", "[cos][series][wise]", test_types) {
constexpr int nsteps = 1024;
std::vector<TestType> inp(nsteps, TestType(1));
std::vector<TestType> out(nsteps, TestType(1));
BENCHMARK("Cos Series - 1024") {
std::transform(inp.cbegin(), inp.cend(), out.begin(), COSS);
};
BENCHMARK("Cos Series Direct - 1024") {
for(int i = 0; i < nsteps; ++i) {
out[i] = COSS(inp[i]);
}
};
BENCHMARK("Cos Std - 1024") {
constexpr auto cos = [] (auto x) {
if constexpr (std::is_same<float, TestType>::value) {
return std::cosf(1.);
}
else {
return std::cos(1.);
}
};
std::transform(inp.cbegin(), inp.cend(), out.begin(), cos);
};
BENCHMARK("Cos Std Direct - 1024") {
for(int i = 0; i < nsteps; ++i) {
if constexpr (std::is_same<float, TestType>::value) {
out[i] = std::cosf(inp[i]);
}
else {
out[i] = std::cos(inp[i]);
}
}
};
}
<file_sep>/vmfunctions/trigonometry/tests/residue.hpp
#ifndef VMFUNCTIONS_TRIGINOMETRY_TESTS_RESIDUE
#define VMFUNCTIONS_TRIGINOMETRY_TESTS_RESIDUE
#include <cmath>
#include <type_traits>
#include "vmfunctions/common.hpp"
namespace vmfunctions::trigonometry::tests {
//Provides info about upper bound of residue
//in range [0, pi/2]
template<typename F, int deg = sizeof(F)>
constexpr F sin_residue(F arg) {
using namespace vmfunctions::common;
constexpr int ndeg = deg + 1;
constexpr F signs[] = { 1, 1, -1, -1 };
constexpr F sign = signs[ndeg % 4];
return sign
* power<F>(arg, ndeg)
* rfactorial<F>(ndeg);
}
//Provides info about upper bound of residue
//in range [0, pi/2]
template<typename F, int deg = sizeof(F)>
constexpr F cos_residue(F arg) {
using namespace vmfunctions::common;
constexpr int ndeg = deg + 1;
constexpr F signs[] = { -1, -1, 1, 1 };
constexpr F sign = signs[ndeg % 4];
return sign
* power<F>(arg, ndeg)
* rfactorial<F>(ndeg);
}
} // vmfunctions::trigonometry::tests
#endif // VMFUNCTIONS_TRIGINOMETRY_TESTS_RESIDUE<file_sep>/vmfunctions/type_manipulations.hpp
#ifndef VMFUNCTIONS_TYPE_MANIPULATIONS
#define VMFUNCTIONS_TYPE_MANIPULATIONS
#include <cstdint>
namespace vmfunctions::common {
template<typename F>
struct coupled_type;
template<>
struct coupled_type<float> {
typedef std::int32_t type;
static_assert(sizeof(type) == sizeof(float));
};
template<>
struct coupled_type<double> {
typedef std::int64_t type;
static_assert(sizeof(type) == sizeof(double));
};
template<typename F>
using coupled_type_t = typename coupled_type<F>::type;
template<typename F, typename I = coupled_type_t<F> >
union reinterpret {
static_assert(sizeof(F) == sizeof(I));
using this_t = reinterpret<F, I>;
public:
reinterpret(F fval) : fpt_val{fval} {}
reinterpret(I ival) : int_val{ival} {}
operator F () const { return fpt_val; }
F& as_fpt() { return fpt_val; }
operator I () const { return int_val; }
I& as_int() { return int_val; }
auto operator^ (this_t r) const {
return this_t{int_val ^ r.int_val};
}
private:
F fpt_val;
I int_val;
};
template<typename F, typename I>
F XOR(F farg, I iarg) {
using R = reinterpret<F, I>;
return R{farg} ^ R{iarg};
}
} // vmfunctions::common
#endif // VMFUNCTIONS_TYPE_MANIPULATIONS
<file_sep>/vmfunctions/trigonometry/sin_unbalanced.hpp
#ifndef VMFUNCTIONS_TRIGINOMETRY_SIN_UNBALANCED
#define VMFUNCTIONS_TRIGINOMETRY_SIN_UNBALANCED
#include <type_traits>
#include "vmfunctions/constants.hpp"
#include "vmfunctions/type_manipulations.hpp"
#include "vmfunctions/trigonometry/sin_series.hpp"
namespace vmfunctions::trigonometry {
template<typename F, int deg = sizeof(F)>
inline F sinn(F arg) {
using namespace vmfunctions::constants;
return sins<F, deg>(arg * hpi<F>);
}
template<typename F, int deg = sizeof(F)>
inline F sinp(F arg) {
using namespace vmfunctions::common;
using namespace vmfunctions::constants;
constexpr F shifts[] = {0, pi<F>, pi<F>, dpi<F>};
using I = typename coupled_type<F>::type;
// Equals to the following line
// const I aper = I(arg * dpi<F>) % 4;
const I iarg = I(pih<F> * arg);
const I aper = iarg & I(3);
const F argshift = shifts[aper] + F(iarg / 4) * dpi<F>;
constexpr int asshift = 8 * sizeof(F) - 1;
const auto argsign =
reinterpret<F>((aper ^ 1) << asshift);
constexpr int gsshift = 8 * sizeof(F) - 2;
const auto gensign =
reinterpret<F>((aper & 2) << gsshift);
return
XOR(sins<F, deg>(XOR(argshift - arg, argsign)), gensign);
}
template<typename F, int deg = sizeof(F)>
inline F sinu(F arg) {
return arg < F(0) ? -sinp<F, deg>(-arg) : sinp<F, deg>(arg);
}
} // vmfunctions::trigonometry
#endif // VMFUNCTIONS_TRIGINOMETRY_SIN_UNBALANCED<file_sep>/vmfunctions/trigonometry/sin_series.hpp
#ifndef VMFUNCTIONS_TRIGINOMETRY_SIN_SERIES
#define VMFUNCTIONS_TRIGINOMETRY_SIN_SERIES
#include <type_traits>
#include "vmfunctions/trigonometry/sin_coefs.hpp"
namespace vmfunctions::trigonometry {
template<typename F, int deg = sizeof(F)>
inline F sins(F arg) {
F const arg2{arg * arg};
F res{sincoef<F>(2 * deg + 1)};
#pragma unroll(deg)
for(int d = deg; 0 < d; --d) {
res = res * arg2 + sincoef<F>(2 * d - 1);
}
return arg * res;
}
} // vmfunctions::trigonometry
#endif // VMFUNCTIONS_TRIGINOMETRY_SIN_SERIES<file_sep>/vmfunctions/trigonometry/sin_coefs.hpp
#ifndef VMFUNCTIONS_TRIGINOMETRY_SIN_COEFS
#define VMFUNCTIONS_TRIGINOMETRY_SIN_COEFS
#include <type_traits>
#include "vmfunctions/common.hpp"
namespace vmfunctions::trigonometry {
template<typename F, typename I = int>
constexpr F sinsign(I deg) {
static_assert(std::is_floating_point<F>::value);
static_assert(std::is_integral<I>::value);
static_assert(std::is_signed<I>::value);
return ((deg + 1) % 4) ? F(1) : F(-1);
}
template<typename F, typename I = int>
constexpr F sineven(I deg) {
static_assert(std::is_floating_point<F>::value);
static_assert(std::is_integral<I>::value);
static_assert(std::is_signed<I>::value);
return (deg % 2) ? F(1) : F(0);
}
template<typename F, typename I = int>
constexpr F sincoef(I deg) {
static_assert(std::is_floating_point<F>::value);
static_assert(std::is_integral<I>::value);
static_assert(std::is_signed<I>::value);
return sineven<F, I>(deg) * sinsign<F, I>(deg)
* common::rfactorial<F, I>(deg);
}
} // vmfunctions::trigonometry
#endif // VMFUNCTIONS_TRIGINOMETRY_SIN_COEFS<file_sep>/vmfunctions/trigonometry/tests/sincos_unbalanced_test.cpp
#ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN
#endif
#include "catch2/catch.hpp"
#include <cmath>
#include "vmfunctions/tests/tests_common.hpp"
#include "vmfunctions/trigonometry/sin_unbalanced.hpp"
using test_types = std::tuple<float, double>;
TEMPLATE_LIST_TEST_CASE("sin unbalanced", "[sin][unbalanced]", test_types) {
const auto sinu = std::bind(
vmfunctions::trigonometry::sinu<TestType>, std::placeholders::_1);
constexpr int nsteps = 8192;
constexpr TestType atol = 1.e-5;
const TestType from = -11. * M_PI, to = +11. * M_PI;
const TestType step = (to - from) / TestType(nsteps);
for(int i = 0; i < nsteps; ++i) {
const TestType x = from + step * TestType(i);
const TestType sin = std::sin(x);
const TestType res = sinu(x);
const auto diff = res - sin;
REQUIRE(-atol <= diff);
REQUIRE(diff <= +atol);
}
}
<file_sep>/vmfunctions/trigonometry/tests/sincos_series_test.cpp
#ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN
#endif
#include "catch2/catch.hpp"
#include <cmath>
#include "vmfunctions/tests/tests_common.hpp"
#include "vmfunctions/trigonometry/cos_series.hpp"
#include "vmfunctions/trigonometry/sin_series.hpp"
#include "vmfunctions/trigonometry/tests/residue.hpp"
using fp_types = std::tuple<float, double>;
TEMPLATE_LIST_TEST_CASE("cos zero exact", "[cos][series]", fp_types) {
REQUIRE(vmfunctions::trigonometry::coss<TestType>(0) == TestType(1.0));
}
TEMPLATE_LIST_TEST_CASE("cos series", "[cos][series]", fp_types) {
const auto coss = std::bind(
vmfunctions::trigonometry::coss<TestType>, std::placeholders::_1);
const int nsteps = 256;
const TestType from = 0, to = M_PI_2;
const TestType step = (to - from) / TestType(nsteps);
for(int i = 0; i < nsteps; ++i) {
const TestType x = from + step * TestType(i);
const TestType cos = std::cos(x);
const TestType res = coss(x);
ALMOST_EQUAL_CUSTOM(res, cos, TestType(1.e-3), TestType(1.e-5));
}
}
TEMPLATE_LIST_TEST_CASE("sin zero exact", "[sin][series]", fp_types) {
REQUIRE(vmfunctions::trigonometry::sins<TestType>(0) == TestType(0.0));
}
TEMPLATE_LIST_TEST_CASE("sin series", "[sin][series]", fp_types) {
const auto sins = std::bind(
vmfunctions::trigonometry::sins<TestType>, std::placeholders::_1);
const int nsteps = 256;
const TestType from = 0, to = M_PI_2;
const TestType step = (to - from) / TestType(nsteps);
for(int i = 0; i < nsteps; ++i) {
const TestType x = from + step * TestType(i);
const TestType sin = std::sin(x);
const TestType res = sins(x);
ALMOST_EQUAL_CUSTOM(res, sin, TestType(1.e-3), TestType(1.e-5));
}
}
<file_sep>/vmfunctions/tests/common_test.cpp
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
#include "vmfunctions/common.hpp"
#include "vmfunctions/tests/tests_common.hpp"
using int_types = std::tuple<int, long, unsigned int, unsigned long>;
TEMPLATE_LIST_TEST_CASE("factorials", "[factorial]", int_types) {
using namespace vmfunctions::common;
REQUIRE(factorial<TestType>(0) == 1ul);
REQUIRE(factorial<TestType>(1) == 1ul);
REQUIRE(factorial<TestType>(2) == 2ul);
REQUIRE(factorial<TestType>(3) == 6ul);
}
using test_types = std::tuple<
std::tuple<int, float>,
std::tuple<int, double>,
std::tuple<long, float>,
std::tuple<long, double>>;
TEMPLATE_LIST_TEST_CASE("reverse factorials", "[rfactorial]", test_types) {
using namespace vmfunctions::common;
using I = std::tuple_element_t<0, TestType>;
using F = std::tuple_element_t<1, TestType>;
const auto rfact = std::bind(rfactorial<F, I>, std::placeholders::_1);
CAPTURE(F(1.), rfact(0));
ALMOST_EQUAL(F(1.), rfact(0));
CAPTURE(F(1.), rfact(1));
ALMOST_EQUAL(F(1.), rfact(1));
CAPTURE(F(1. / 2.), rfact(2));
ALMOST_EQUAL(F(1. / 2.), rfact(2));
CAPTURE(F(1. / 6.), rfact(3));
ALMOST_EQUAL(F(1. / 6.), rfact(3));
}
using fpt_types = std::tuple<float, double>;
TEMPLATE_LIST_TEST_CASE("power functional", "[power]", fpt_types) {
using namespace vmfunctions::common;
ALMOST_EQUAL(TestType(1), (power<TestType>(1, 0)));
ALMOST_EQUAL(TestType(1), (power<TestType>(1, 10)));
ALMOST_EQUAL(TestType(8), (power<TestType>(2, 3)));
ALMOST_EQUAL(TestType(32), (power<TestType>(2, 5)));
ALMOST_EQUAL(TestType(6.25), (power<TestType>(2.5, 2)));
ALMOST_EQUAL(TestType(39.0625), (power<TestType>(2.5, 4)));
ALMOST_EQUAL(TestType(1), (power<TestType>(3, 0)));
ALMOST_EQUAL(TestType(81), (power<TestType>(3, 4)));
}
<file_sep>/vmfunctions/trigonometry/bench/sincos_unbalanced_bench.cpp
#ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN
#endif
#ifndef CATCH_CONFIG_ENABLE_BENCHMARKING
#define CATCH_CONFIG_ENABLE_BENCHMARKING
#endif
#include "catch2/catch.hpp"
#include <cmath>
#include <type_traits>
#include "vmfunctions/trigonometry/sin_unbalanced.hpp"
using test_types = std::tuple<float, double>;
#define SINU vmfunctions::trigonometry::sinu<TestType>
TEMPLATE_LIST_TEST_CASE("sin unbalanced", "[sin][unbalanced]", test_types) {
BENCHMARK("Sin Unbalanced 1. - 1") {
return SINU(1.);
};
BENCHMARK("Sin Std 1. - 1") {
if constexpr (std::is_same<float, TestType>::value) {
return std::sinf(1.);
}
else {
return std::sin(1.);
}
};
BENCHMARK("Loop Unbalanced - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
res += TestType(1.);
}
};
BENCHMARK("Sin Unbalanced 1. - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
res += SINU(1.);
}
};
BENCHMARK("Sin Std 1. - 1024") {
constexpr int nsteps = 1024;
volatile TestType res = 0.;
for(int i = 0; i < nsteps; ++i) {
if constexpr (std::is_same<float, TestType>::value) {
res += std::sinf(1.);
}
if constexpr (std::is_same<double, TestType>::value) {
res += std::sin(1.);
}
}
};
}
TEMPLATE_LIST_TEST_CASE("sin ynbalanced transform", "[sin][unbalanced][wise]", test_types) {
constexpr int nsteps = 1024;
std::vector<TestType> inp(nsteps, TestType(1));
std::vector<TestType> out(nsteps, TestType(1));
BENCHMARK("Sin Unbalanced - 1024") {
std::transform(inp.cbegin(), inp.cend(), out.begin(), SINU);
};
BENCHMARK("Sin Unbalanced Direct - 1024") {
for(int i = 0; i < nsteps; ++i) {
out[i] = SINU(inp[i]);
}
};
BENCHMARK("Sin Std - 1024") {
constexpr auto sin = [] (auto x) {
if constexpr (std::is_same<float, TestType>::value) {
return std::sinf(1.);
}
else {
return std::sin(1.);
}
};
std::transform(inp.cbegin(), inp.cend(), out.begin(), sin);
};
BENCHMARK("Sin Std Direct - 1024") {
for(int i = 0; i < nsteps; ++i) {
if constexpr (std::is_same<float, TestType>::value) {
out[i] = std::sinf(inp[i]);
}
else {
out[i] = std::sin(inp[i]);
}
}
};
}
<file_sep>/vmfunctions/trigonometry/cos_series.hpp
#ifndef VMFUNCTIONS_TRIGINOMETRY_COS_SERIES
#define VMFUNCTIONS_TRIGINOMETRY_COS_SERIES
#include <type_traits>
#include "vmfunctions/trigonometry/cos_coefs.hpp"
namespace vmfunctions::trigonometry {
template<typename F, int deg = sizeof(F)>
inline F coss(F arg) {
F const arg2{arg * arg};
F res{coscoef<F>(2 * deg + 2)};
#pragma unroll(deg)
for(int d = deg; 0 < d; --d) {
res = res * arg2 + coscoef<F>(2 * d);
}
return res * arg2 + F(1);
}
} // vmfunctions::trigonometry
#endif // VMFUNCTIONS_TRIGINOMETRY_COS_SERIES
|
647dd75b847d68cfcbe2615dc81fc76fec465048
|
[
"C++"
] | 18 |
C++
|
NeilKulikov/vmfunctions
|
6f57e3a36878a4870124deec82aeecd027ebf359
|
1271cb5fcc6db55d3f5b57599a4ed351d77548d6
|
refs/heads/master
|
<repo_name>unicaes-ing/practica-10-reynaldo-martinez<file_sep>/Practica10/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Practica10
{
class Program
{
static void Main(string[] args)
{
int opc = 0;
string seguir = "";
do
{
Console.Clear();
Console.WriteLine("Ejercicios 1-4");
opc = int.Parse(Console.ReadLine());
string contraseña = "";
switch (opc)
{
case 1:
ejer1();
break;
case 2:
ejer2();
break;
case 3:
Console.Write("Coloque la contraseña: ");
contraseña = Console.ReadLine();
ejer3(contraseña);
break;
case 4:
string pass;
for (int i = 3; i > 0; i--)
{
Console.WriteLine("intentos: " + i);
Console.Write("Coloque la contraseña: ");
pass = Console.ReadLine();
if (pass == contraseña)
{
Console.WriteLine("Bienvenido");
i = 1;
}
else
{
Console.WriteLine("siga intentando");
}
Console.ReadKey();
Console.Clear();
}
break;
default:
break;
}
Console.WriteLine("Desea seguir? s/n");
seguir = Console.ReadLine();
} while (seguir == "s");
Console.ReadKey();
}
static void ejer1()
{
int opc = 0;
Console.WriteLine("[1] Agregar pais");
Console.WriteLine("[2] Mostrar paises");
Console.WriteLine("[3] Buscar pais");
opc = int.Parse(Console.ReadLine());
switch (opc)
{
case 1:
try
{
Console.WriteLine("Cuantos paises agregara?");
Console.WriteLine();
int cPaises = int.Parse(Console.ReadLine());
StreamWriter sw = new StreamWriter("./ejer1.txt", false);
string seguir = "";
do
{
Console.Write("Nombre pais :");
string nPais = Console.ReadLine();
sw.WriteLine(nPais);
Console.WriteLine("Agregar otro pais? s/n" );
seguir = Console.ReadLine();
} while (seguir == "s");
sw.Close();
Console.WriteLine();
Console.WriteLine("Paises guardados correctamente");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Se ha producido un error");
}
break;
case 2:
StreamReader sr = new StreamReader("./ejer1.txt");
Console.WriteLine(sr.ReadToEnd());
sr.Close();
break;
case 3:
StreamReader sr1 = new StreamReader("./ejer1.txt");
string paisToFind = "";
Console.WriteLine("Pais a encontrar:");
paisToFind = Console.ReadLine();
string linea = sr1.ReadLine();
Console.WriteLine(sr1.ReadToEnd());
while (linea != null)
{
while (linea == paisToFind)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(paisToFind);
}
linea = sr1.ReadLine();
}
sr1.Close();
break;
default:
break;
}
}
static void ejer2()
{
StreamWriter sw = new StreamWriter("./ejer2.txt", true);
Console.WriteLine("Cuatos paises seran?");
int cPaises = Convert.ToInt32(Console.ReadLine());
string[] paises = new string[cPaises];
Console.WriteLine();
for (int i = 0; i < paises.Length; i++)
{
Console.WriteLine("Pais: ");
paises[i] = Console.ReadLine();
sw.WriteLine(paises[i]);
}
sw.Close();
StreamReader sr = new StreamReader("./ejer2.txt");
Console.WriteLine();
Console.WriteLine("Paises");
Console.WriteLine("----------------");
Console.WriteLine(sr.ReadToEnd());
sr.Close();
}
static void ejer3(string contraseña)
{
string a = contraseña.Replace(contraseña, "0paotolpidgg78");
Stream fs = new FileStream("./ejer03.txt", FileMode.Create, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(a);
sw.Close();
StreamReader sr = new StreamReader("./ejer03.txt");
Console.WriteLine(sr.ReadLine());
fs.Close();
sr.Close();
}
}
}
|
ba4bb85ce848238d92943db5287c876637443d99
|
[
"C#"
] | 1 |
C#
|
unicaes-ing/practica-10-reynaldo-martinez
|
d5484d0336778201d49482f85ff3b3f1c5168b2a
|
c5c8fde14fa4613aa02cf14cd389608e8790d273
|
refs/heads/master
|
<repo_name>ManuelAlanis/Programaci-nC<file_sep>/punteros2.c
#include <stdio.h>
int main(void)
{
int arreglo[5];
int *iPtr;
int i;
arreglo[0]=1;
arreglo[1]=2;
arreglo[2]=3;
arreglo[3]=4;
arreglo[4]=5;
iPtr=&arreglo[0];
for (int i = 0; i < 5; ++i)
{
printf("*iPtr es %d\n",*iPtr );
iPtr++;
}
return 0;
}<file_sep>/structs/practica/funciones.h
//<NAME>
//<NAME>
#ifndef STRUCT_H
#define STRUCT_H
#endif<file_sep>/curprfc.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void buscaconsonantes(char *busca){
int c;
int bandera;
char consonantes[23]="qwrtpsdfghjklzxcvbnmñ";
c=0;
bandera=0;
do{//buscando segunda consonante apellido paterno
for (int i = 0; i < 23; ++i)
if(busca[c]==consonantes[i])
{
bandera++;
if (bandera==2)
{
printf("%c", toupper(consonantes[i]));
}
}
c++;
}while(bandera!=2);
}
void capturaDatos(char *nombre,char *apellidoPaterno,char *apellidoMaterno,char *diaNa,char *mesNa,char *añoNa,char *genero,char *entidad)
{
printf("Escribe tu primer nombre: \n");
gets(nombre);
printf("Escribe tu apellido paterno: \n");
gets(apellidoPaterno);
printf("Escribe tu apellido materno: \n");
gets(apellidoMaterno);
printf("Año de nacimiento: 'ejemplo 1994'\n");
gets(añoNa);
printf("Numero en mes de nacimiento: 'ejemplo 08'\n");
gets(mesNa);
printf("Dia de nacimiento: 'ejemplo 07' \n");
gets(diaNa);
printf("Genero H/M:\n");
gets(genero);
printf("Abreviación de tu entidad federativa: Ejemplo 'BC'\n");
gets(entidad);
}
void generacurp(char *nombre,char *apellidoPaterno,char *apellidoMaterno,char *diaNa,char *mesNa,char *añoNa,char *genero,char *entidad)
{
char *busca[10];
char vocales[5]="aeiou";
int bandera;
int b=1;
int c;
printf("Tu curp es: ");
printf("%c",toupper(apellidoPaterno[0]));
bandera=0;
do{//buscando siguiente vocal
for (int i = 0; i < 5; ++i)
if(apellidoPaterno[b]==vocales[i])
{
printf("%c", toupper(vocales[i]));
bandera=1;
}
b++;
}while(bandera==0);
printf("%c",toupper(apellidoMaterno[0]));
printf("%c",toupper(nombre[0] ));
printf("%c%c",añoNa[2],añoNa[3] );//imprime año en dos digitos
printf("%c%c",mesNa[0],mesNa[1] );
printf("%c%c",diaNa[0],diaNa[1] );
printf("%c",toupper(genero[0] ));
printf("%c%c",toupper(entidad[0]),toupper(entidad[1] ));
buscaconsonantes(apellidoPaterno);
buscaconsonantes(apellidoMaterno);
buscaconsonantes(nombre);
printf("01\n");
}
void generaRFC(char *nombre,char *apellidoPaterno,char *apellidoMaterno,char *diaNa,char *mesNa,char *añoNa)
{
char vocales[5]="aeiou";
int bandera;
int b=1;
int c;
printf("\nTu RFC es: ");
printf("%c",toupper(apellidoPaterno[0]));
bandera=0;
do{//buscando siguiente vocal
for (int i = 0; i < 5; ++i)
if(apellidoPaterno[b]==vocales[i])
{
printf("%c", toupper(vocales[i]));
bandera=1;
}
b++;
}while(bandera==0);
printf("%c",toupper(apellidoMaterno[0]));
printf("%c",toupper(nombre[0] ));
printf("%c%c",añoNa[2],añoNa[3] );//imprime año en dos digitos
printf("%c%c",mesNa[0],mesNa[1] );
printf("%c%c",diaNa[0],diaNa[1] );
printf("011\n");
}
int main()
{
char *busca[10];
char *nombre[50];
char *apellidoPaterno[50];
char *apellidoMaterno[50];
char *diaNa[2];
char *mesNa[2];
char *añoNa[4];
char *genero[1];
char *entidad[2];
printf("Programa para generar CURP y RFC\n");
capturaDatos(nombre,apellidoPaterno,apellidoMaterno,diaNa,mesNa,añoNa,genero,entidad);
generacurp(nombre,apellidoPaterno,apellidoMaterno,diaNa,mesNa,añoNa,genero,entidad);
generaRFC(nombre,apellidoPaterno,apellidoMaterno,diaNa,mesNa,añoNa);
return 0;
}<file_sep>/structs/struct2.c
#include <stdio.h>
struct Libros
{
char *titulo;
char *autor;
char *editorial;
long long int isbn;
};
int main()
{
struct Libros libro1;
libro1.titulo="Programacion";
libro1.autor="<NAME>";
libro1.editorial="<NAME>";
libro1.isbn=3456354634563;
printf("titulo:\t %s\n",libro1.titulo );
printf("autor:\t %s\n",libro1.autor );
printf("editorial:\t%s\n",libro1.editorial );
printf("isbn:\t %lld\n",libro1.isbn );
return 0;
}<file_sep>/matricesdinamicas/milibreria.h
void menu(double **fMat,double **fMatB,int iRenB, int iColB,int iRenA,int iColA);
double** crearMatrizSum(int iRenB, int iColB,int iRenA,int iColA);
void sumMatriz(double **sumfRen,double **fMat,double **fMatB,int iColA,int iRenA);
double** crearMatrizResta(int iRenB, int iColB,int iRenA,int iColA);
void resMatriz(double **resfRen,double **fMat,double **fMatB,int iColA,int iRenA);
double** crearMatrizMulti(int iRenB, int iColB,int iRenA,int iColA);
void multMatriz(double **multfRen,double **fMat,double **fMatB,int iColA,int iRenA);
double** redimencionarMatrizB(double **fRen,int iRenB, int iColB);
double** crearMatrizA(int iRenA, int iColA);
double** crearMatrizB(int iRenB, int iColB);
void llenarMatrizA(double **fMat, int iRenA, int iColA);
void llenarMatrizB(double **fMatB, int iRenB, int iColB);
void imprimirMatrizA(double **fMat, int iRenA, int iColA);
void imprimirMatrizB(double **fMatB, int iRenB, int iColB);
void destruirMatrizA(double **fMat, int iRenA);
void destruirMatrizB(double **fMatB, int iRenA);<file_sep>/punteros4.c
#include <stdio.h>
void func(int *iVar)
{
*iVar = 5;
}
int main(void)
{
int iVar = 1;
printf("El valor de iVar es %d\n",iVar);
func(&iVar); /* Se envía la dirección de la variable iVar */
printf("El valor de iVar es %d\n",iVar);
return 0;
}<file_sep>/ventas/main2.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// int balance[5] = {1000, 2, 3, 17, 50};
int *saborFresa=NULL;
int *saborVainilla=NULL;
int *dias = {saborFresa,saborVainilla};
int opdia;
int i,iTam=0;
int bandera=1;
int opcion;
int opventas;
printf("Hola Pedrito\n");
dias = (int*)malloc(iTam*sizeof(int));
for(i=0;i<iTam;i++)
{
dias[i] = i+1;
}
for(i=0;i<iTam;i++)
{
printf("%d ",dias[i]);
}
do
{
printf("Hay agregado %d dias \n",iTam );
printf("[1] Agregar un dia\n");
printf("[2] Agregar ventas a los dias\n");
scanf("%d",&opcion);
switch(opcion)
{
case 1: //*re *//
iTam++;
dias = (int*)realloc(dias,iTam*sizeof(int));
break;
case 2:
bandera=0; break;
}
} while (bandera!=0);
printf("Dia?\n");
scanf("%d",&opdia);
bandera=1;
do
{
printf("[1]Venta de saborFresa\n");
printf("[2]Venta de saborVainilla\n");
scanf("%d",&opventas);
printf("XXXXX\n");
switch(opventas){
case 1: saborFresa[opdia]++;
printf("Ventas de fresa%d\n",saborFresa[opdia] );
break;
case 2: saborVainilla[opdia]++;
printf("Ventas de vainilla%d\n",saborVainilla[opdia] );
break;
case 3: bandera=0; break;
}
} while (bandera!=0);
printf("\nNuevo tamaño para el arreglo? ");
scanf("%d",&iTam);
dias = (int*)realloc(dias,iTam*sizeof(int));
for(i=0;i<iTam;i++)
{
dias[i] = i+1;
}
for(i=0;i<iTam;i++)
{
printf("%d ",dias[i]);
}
free(dias);
return 0; }<file_sep>/structs/practica/actores.h
//<NAME>
//<NAME>
<file_sep>/memoriadinamica5.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int iTam=7;
int *iArreglo=NULL;
iArreglo=calloc(10,sizeof(int));
for (int i = 0; i <13; ++i)
{
iArreglo[i]=i+1;
printf("%d\n",iArreglo[i]);
}
free(iArreglo);
return 0;
}<file_sep>/memoriadinamica4.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int *iArreglo=NULL;
int i, iTam;
printf("¿Tamaño del arreglo a crear?\n");
scanf("%d",&iTam);
iArreglo=malloc(iTam*sizeof(int));
for (i = 0; i < iTam; i++)
{
iArreglo[i]=i+1;
printf("%d\n",iArreglo[i]);
}
printf("Nuevo tamaño para el arreglo?\n");
scanf("%d",&iTam);
iArreglo=(int*)calloc(iArreglo,iTam*sizeof(int));
for (i = 0; i < iTam; ++i)
{
iArreglo[i]=i+1;
printf("%d\n",iArreglo[i] );
}
free(iArreglo);
return 0;
}<file_sep>/ventas/ventas.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *fresa;
int *vanilla;
int dia;
int bandera=1;
int op;
int opsabo;
int opdia;
int i;
fresa=malloc(dia*sizeof(int));
vanilla=malloc(dia*sizeof(int));
printf("HISTORIAL VENTAS BOLIS\n");
printf("Hay %d dias agregados\n",dia );
do
{
printf("[1] Agregar un día\n");
printf("[2] Capturar ventas\n");
printf("[3] Estadisticas\n");
printf("[4] Salir\n");
scanf("%d",&op);
switch(op){
case 1:
dia++;
fresa=(int*)realloc(fresa,dia*sizeof(int));
vanilla=(int*)realloc(vanilla,dia*sizeof(int));
printf("Hay %d dias agregados\n",dia);
fresa[dia]=0;
vanilla[dia]=0;
printf("%d\n",fresa[dia]);
printf("%d\n",vanilla[dia]);
break;
case 2:
bandera=1;
for (i = 0; i < dia; ++i)
{
printf("[%d] Agregar ventas el dia %d\n",i+1,i+1 );
}
// printf("Dia?\n");
scanf("%d",&opdia);
// do
// {
printf("Dia %d seleccionado\n",opdia);
printf("Cuantos bolis de Fresa vendiste?\n");
scanf("%d",&fresa[opdia]);
printf("Cuantos bolis de Vanilla vendiste?\n");
scanf("%d",&vanilla[opdia]);
printf("[7] Regresar\n" );
scanf("%d",&opsabo);
// switch(opsabo)
// {
// case 5:
// fresa[opdia]++;
// printf("%d Bolis de fresa vendidos\n",fresa[1] );
// break;
// case 7: bandera=10; break;
// }
// } while (bandera!=0);
break;
case 4: bandera=0; break;
}
} while (bandera!=0);
return 0;
}<file_sep>/practican01.c
#include <stdio.h>
void imprimeDatos(char **etiquetas,char *nombre,char *pelicula,char *cancion,char *hobby,char *signo)
{
char **iPtr;
iPtr=&*etiquetas;
printf("Hola nos dijiste que tu %s es %s es un gusto que compartas tu información!\n",*iPtr,nombre);
iPtr++;
printf("Asi que tu %s es %s, es una buena pelicula\n",*iPtr,pelicula);
iPtr++;
printf("Tu %s es %s, esa cancion es movida\n",*iPtr,cancion);
iPtr++;
printf("En tu tiempo libre tienes como %s %s, es divertido\n",*iPtr,hobby);
iPtr++;
printf("%s es un %s muy extraño\n",signo,*iPtr);
}
void capturaDatos(char **etiquetas,char *nombre,char *pelicula,char *cancion,char *hobby,char *signo)
{
char **iPtr;
iPtr=&*etiquetas;
printf("Escribe tu %s :\n",*iPtr);
gets(nombre);
iPtr++;
printf("Escribe tu %s :\n",*iPtr);
gets(pelicula);
iPtr++;
printf("Escribe tu %s :\n",*iPtr);
gets(cancion);
iPtr++;
printf("Escribe tu %s :\n",*iPtr);
gets(hobby);
iPtr++;
printf("Escribe tu %s :\n",*iPtr);
gets(signo);
}
int main()
{
char *etiquetas[]={"nombre completo","pelicula favorita","cancion favorita","hobby","signo zodiacal"};
char nombre[50];
char pelicula[30];
char cancion[30];
char hobby[30];
char signo[30];
printf("Hola! esto un test para conocer tus gustos personales! \n");
capturaDatos(etiquetas,nombre,pelicula,cancion,hobby,signo);
// printf("XXXX\n" );
imprimeDatos(etiquetas,nombre,pelicula,cancion,hobby,signo);
}<file_sep>/memoriadinamica2.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *iArreglo;
int i, iTam=9;
iArreglo=malloc(iTam*sizeof(int));
for (int i = 0; i < iTam; ++i)
{
iArreglo[i]=i+1;
printf("%d ",iArreglo[i] );
}
free(iArreglo);
iArreglo=NULL;
return 0;
}<file_sep>/structs/cap.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *arr;
arr=malloc(3);
scanf("%s",arr);
printf("%s\n",arr);
return 0;
}<file_sep>/matricesdinamicas/matriz.c
#include <stdio.h>
#include <stdlib.h>
float** crearMatriz(int iRen, int iCol);
void llenarMatriz(float **fMat, int iRen, int iCol);
void imprimirMatriz(float **fMat, int iRen, int iCol);
void destruirMatriz(float **fMat, int iRen);
float** modificarMatriz(int iRen, int iCol,int niRen, int niCol);
int main(void)
{
int iRen;
int iCol;
int niRen;
int niCol;
int resp;
printf("Bienvenido al sistema de matrices dinamicas\n");
printf("Creando matriz...\n");
printf("Numero de renglones?\n");
scanf("%d",&iRen);
printf("Numero de Columnas?\n");
scanf("%d",&iCol);
float** fMat = crearMatriz(iRen,iCol);
llenarMatriz(fMat,iRen,iCol);
imprimirMatriz(fMat,iRen,iCol);
printf("Quieres modificarMatriz?\n");
printf("[1] SI\n");
printf("[2] NO\n");
scanf("%d",&resp);
if (resp==1)
{
// int iRen = 4;
// int iCol = 4;
printf("Numero de renglones?\n");
scanf("%d",&niRen);
printf("Numero de Columnas?\n");
scanf("%d",&niCol);
float** fMat = modificarMatriz(iRen,iCol,niRen,niCol);
llenarMatriz(fMat,niRen,niCol);
imprimirMatriz(fMat,niRen,niCol);
printf(" - - - - - - - - - -\n");
printf("Matriz moficada:\n");
printf("%d Columnas \n%d Renglones \n",iRen,iCol );
printf("Good bye\n");
}else
{
printf(" - - - - - - - - - -\n");
printf("Matriz destruida, memoria liberada\n");
printf("Good bye\n");
destruirMatriz(fMat,iRen);
return 0; }
}
float** crearMatriz(int iRen, int iCol)
{
float **fRen = (float**) malloc(iRen*sizeof(float*));
for (int i=0; i<iRen; i++)
{
fRen[i] = (float*) malloc(iCol*sizeof(float));
}
return fRen;
}
void llenarMatriz(float **fMat, int iRen, int iCol)
{ for(int i=0;i<iRen;i++)
for(int j=0;j<iCol;j++)
fMat[i][j] = (i*iCol)+j;
}
void imprimirMatriz(float **fMat, int iRen, int iCol)
{
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
printf("%.2f ",fMat[i][j]);
}
printf("\n");
}
}
float** modificarMatriz(int iRen, int iCol,int niRen, int niCol)
{
if (iRen==niRen&&iCol==niCol)
{
float **fRen = (float**) realloc(fRen,niRen*sizeof(float*));
for (int i=0; i<niRen; i++)
{
fRen[i] = (float*) malloc(niCol*sizeof(float));
}
}
return iRen;
}
void destruirMatriz(float **fMat, int iRen)
{
for(int i=0;i<iRen;i++)
{
free(fMat[i]);
}
free(fMat);
}
<file_sep>/ventas/main.c
#include <stdio.h>
double promedio(int *iArr, int iTam);
int main () {
int balance[5] = {1000, 2, 3, 17, 50};
double prom; prom = promedio( balance, 5 ) ;
printf("El valor promedio es: %f\n", prom );
return 0;
}
double promedio(int *iArr, int iTam)
{
int i, sum = 0; double prom;
for (i = 0; i < iTam; ++i)
{
sum += iArr[i];
}
prom = (double)sum / iTam;
return prom;
}<file_sep>/punteros3.c
#include <stdio.h>
const int MAX = 4;
int main ()
{
char *cNombres[] = { "<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
};
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Contenido de cNombres[%d] = %s\n", i, cNombres[i] );
}
return 0;
}
<file_sep>/README.md
C
========
- Compile C files:
```bash
$ gcc program.c -o program
```
- Run files:
```bash
$ ./programa
```
<file_sep>/structs/practica/peliculas.c
//<NAME>
//<NAME>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Peliculas
{
char *titulo;
char *director;
char **actores;
int *año;
int ID;
int ren;
int col;
};
void capturarActores(char **mat, int iRen, int iCol);
void imprimirActores(char **mat, int iRen, int iCol);
void destruirMatrizActores(char **mat, int iRen);
void capturapelicula(struct Peliculas **producto,int posicionpeliculas,int npeliculas);
void memorianuevapelicula(struct Peliculas **producto,int posicionpeliculas,int npeliculas);
void seleccionapelicula(struct Peliculas **producto,int posicionpeliculas);
void liberarmemoria(struct Peliculas **producto,int npeliculas,int i);
void menuprincipal(struct Peliculas **producto,int npeliculas,int posicionpeliculas,int opcionmenu,int bandera,int i);
int main(void)
{
int i;
int npeliculas=0;
int opcionmenu;
int bandera=0;
int posicionpeliculas=0;
struct Peliculas **producto = NULL;
menuprincipal(producto,npeliculas,posicionpeliculas,opcionmenu,bandera,i);
return 0;
}
char** crearMatrizActores(int iRen, int iCol)
{
char **fRen = (char**) malloc(iRen*sizeof(char*));
//char **fRen = (char**)realloc(fRen,iRen*sizeof(char*));
for (int i=0; i<iRen; i++)
{
fRen[i] = (char*) malloc(iCol*sizeof(char));
}
return fRen;
}
void capturarActores(char **mat, int iRen, int iCol)
{
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
printf("Actor No.%d\n",i+1 );
scanf("%s",mat[i]);
}
}
}
void imprimirActores(char **mat, int iRen, int iCol)
{
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
printf("Actor No.%d: %s\n",i+1,mat[i]);
}
// printf("\n");
}
}
void destruirMatrizActores(char **mat, int iRen)
{
//liberando memoria para el numero total actores
//posicion por posicion
for(int i=0;i<iRen;i++)
{
free(mat[i]);
}
free(mat);
}
void capturapelicula(struct Peliculas **producto,int posicionpeliculas,int npeliculas)
{
//capturando las cadenas con la variable de control 'posicionpeliculas'
printf("Nombre de la Pelicula? ");
scanf("%s",producto[posicionpeliculas]->titulo);
printf("Director? ");
scanf("%s",producto[posicionpeliculas]->director);
printf("Año en que salió la película? ");
scanf("%d",producto[posicionpeliculas]->año);
printf("Cuantos actores hay? ");
//capturando el total deseado de actores;
scanf("%d",&producto[posicionpeliculas]->ren);
producto[posicionpeliculas]->col =1;
//creado una matriz dinamica para el numero total de actores controlada por los renglones de producto[posicionpeliculas]->ren
producto[posicionpeliculas]->actores = crearMatrizActores(producto[posicionpeliculas]->ren, producto[posicionpeliculas]->col);
producto[posicionpeliculas]->ID=npeliculas;
//capturar el numero total de actores deseados por el usuario
//para la posicion de 'posicionpeliculas', posicion peliculas hace que se almacene en el arreglo siguiente
capturarActores(producto[posicionpeliculas]->actores,producto[posicionpeliculas]->ren, producto[posicionpeliculas]->col);
printf("\n");
}
void memorianuevapelicula(struct Peliculas **producto,int posicionpeliculas,int npeliculas)
{
//asignacion de memoria para las nuevas posiciones de la estructura
//con la variable posicion peliculas para controlar las posociones de los arreglos
producto[posicionpeliculas]->titulo=(char*)malloc(10*sizeof(char));
producto[posicionpeliculas]->año=malloc(1);
producto[posicionpeliculas]->director=malloc(10);
producto[posicionpeliculas]->ren=(int)malloc(10*sizeof(int));
producto[posicionpeliculas]->ID=(int)malloc(1*sizeof(int));
capturapelicula(producto,posicionpeliculas,npeliculas);
}
void seleccionapelicula(struct Peliculas **producto,int posicionpeliculas)
{
int bandera2=0;
int op2;
system("clear");
printf("______________________\n");
printf("______PELICULAS_______\n");
do
{
printf("ID\tTITULO\n");
for (int i = 0; i < posicionpeliculas; ++i)
{
printf("[%d]\t%s\n",producto[i]->ID,producto[i]->titulo);
}
scanf("%d",&op2);
op2=op2-1;//se realiza la resta para que la opcion seleccionada
//se convierta en la posicion real del arreglo.
printf("ID: 00%d\n",producto[op2]->ID);
printf("Pelicula : %s\n",producto[op2]->titulo);
printf("año: %d\n",*producto[op2]->año);
printf("director: %s\n",producto[op2]->director);
imprimirActores(producto[op2]->actores,producto[op2]->ren, producto[op2]->col);
printf("______________________\n");
printf("- - - - - - - - - - - \n");
bandera2=1;
} while (bandera2==0);
}
void liberarmemoria(struct Peliculas **producto,int npeliculas,int i)
{
system("clear");
for (int i = 0; i < npeliculas; ++i)
{ //liberando todas las posiciones creadas para la matriz de los actores
//liberacion controlada por el numero de peliculas generadas: npeliculas
destruirMatrizActores(producto[i]->actores,producto[i]->ren);
}
for(i=0;i<npeliculas;i++)
{
free(producto[i]);//liberando las posiciones de la estructura generada
printf("| Pelicula %d liberada | \n",i );
}
free(producto);
printf("\n| %d Peliculas liberadas |\n",npeliculas );
}
void menuprincipal(struct Peliculas **producto,int npeliculas,int posicionpeliculas,int opcionmenu,int bandera,int i)
{
do
{
printf("[1] Agregar Pelicula\n");
printf("[2] Imprimir Peliculas\n");
printf("[3] Salir\n");
scanf("%d",&opcionmenu);
switch(opcionmenu)
{
case 1:
npeliculas++;//para aumentar el numero total de peliculas generadas
producto = (struct Peliculas**)realloc(producto, 10 * sizeof(struct Peliculas*));
producto[posicionpeliculas] = (struct Peliculas*)malloc(sizeof(struct Peliculas));
//asignando memoria para la nueva pelicula
memorianuevapelicula(producto,posicionpeliculas,npeliculas);
//aumentando la posicion de posicionpeliculas, para la posible siguiente vuelta de asignacion
posicionpeliculas++;
break;
case 2:
//menu para imprimir y seleccionar las peliculas capturadas con su ID
seleccionapelicula(producto,posicionpeliculas);
break;
case 3:
bandera=1; break;//bandera de salida
}
} while (bandera==0);
liberarmemoria(producto,npeliculas,i);
}
<file_sep>/structs/struct.c
#include <stdio.h>
struct Libros
{ char *titulo;
char *autor;
char *editorial;
long int isbn;
};
void llenar(struct Libros *libro);
void imprimirInfoLibro(struct Libros libro);
int main(void)
{
struct Libros **libro1=NULL;
llenar(libro1);
imprimirInfoLibro(libro1);
return 0;
}
void llenar(struct Libros *libro){
char *titulo;
printf("Titulo, morro?\n");
scanf("%s",titulo);
libro->titulo =titulo;
libro->autor = "<NAME>";
libro->editorial = "Pepe el toro editoriales";
printf("Cual es el isb, bato?\n");
scanf("%ld",&libro->isbn);
// libro->isbn = variable;
}
void imprimirInfoLibro(struct Libros libro){
printf("Titulo: %s\n",libro.titulo );
printf("Autor: %s\n",libro.autor );
printf("Editorial: %s\n",libro.editorial );
printf("ISBN: %ld\n",libro.isbn);
}
<file_sep>/memoriadinamica3.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *sCadena;
int i;
sCadena=malloc(80);
if (!sCadena)
{
printf("¡ La asignación fallo !\n");
} else printf("Asignación satisfactoria\n");
gets(sCadena);
for (i=0 ; i <strlen(sCadena) ; i++)
{
printf("%c\n",sCadena[i] );
}
sCadena=malloc(100);
if (!sCadena)
{
printf("¡ La asignación fallo !\n");
} else printf("Asignación satisfactoria\n");
gets(sCadena);
for (i=0 ; i <strlen(sCadena) ; i++)
{
printf("%c\n",sCadena[i] );
}
free(sCadena);
return 0;
}<file_sep>/memoriadinamica1.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *iPtr=NULL;
return 0;
}<file_sep>/matricesdinamicas/main.c
#include "milibreria.c"
int main(void)
{
int iRenA;
int iColA;
int iRenB;
int iColB;
printf("------------------------Practica No 2------------------------\n");
printf("Necesitamos generar dos matrices\n");
//Otengo renglones y columnas para matriz A
printf("Matriz A:\n");
printf("¿Numero de Renglones?\n");
scanf("%d",&iRenA);
printf("¿Numero de Columnas?\n");
scanf("%d",&iColA);
printf("- - - - - - - - - -\n");
double** fMat = crearMatrizA(iRenA,iColA);//creo la variable double **fMat con asignacion de memoria de la funcion crearmatrizA
llenarMatrizA(fMat,iRenA,iColA);
//Otengo renglones y columnas para matriz B
printf("Matriz B:\n");
printf("¿Numero de Renglones?\n");
scanf("%d",&iRenB);
printf("¿Numero de Columnas?\n");
scanf("%d",&iColB);
double** fMatB = crearMatrizB(iRenB,iColB);//creo la variable double **fMat con asignacion de memoria de la funcion crearmatrizB
llenarMatrizB(fMatB,iRenB,iColB);
imprimirMatrizA(fMat,iRenA,iColA);
imprimirMatrizB(fMatB,iRenB,iColB);
menu( fMat, fMatB, iRenB, iColB, iRenA, iColA);
// regresando de menu libero la memoria de las matrices
destruirMatrizA(fMat,iRenA);
destruirMatrizB(fMatB,iRenA);
return 0;
}<file_sep>/memoriadinamica6.c
#include <stdio.h>
#include <stdlib.h>
float** crearMatriz(int iRen, int iCol);
void llenarMatriz(float **fMat, int iRen, int iCol);
void imprimirMatriz(float **fMat, int iRen, int iCol);
void destruirMatriz(float **fMat, int iRen);
int main(void)
{
int iRen = 5;
int iCol = 6;
float** fMat = crearMatriz(iRen,iCol);
llenarMatriz(fMat,iRen,iCol);
imprimirMatriz(fMat,iRen,iCol);
destruirMatriz(fMat,iRen);
return 0;
}
float** crearMatriz(int iRen, int iCol)
{
float **fRen = (float**) malloc(iRen*sizeof(float*));
for (int i=0; i<iRen; i++)
{
fRen[i] = (float*) malloc(iCol*sizeof(float));
}
return fRen;
}
void llenarMatriz(float **fMat, int iRen, int iCol)
{
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
fMat[i][j] = (i*iCol)+j;
}
}
}
void imprimirMatriz(float **fMat, int iRen, int iCol)
{
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
printf("%f ",fMat[i][j]);
}
printf("\n");
}
}
void destruirMatriz(float **fMat, int iRen)
{
for(int i=0;i<iRen;i++)
{
free(fMat[i]);
}
free(fMat);
}<file_sep>/punteros.c
#include <stdio.h>
int main()
{
int iVar=20;
int *iPtr=NULL;
iPtr= &iVar;
printf("iPtr = %d\n",*iPtr );
printf("iPtr = %d\n",iPtr );
printf("iPtr = %d\n",&iPtr );
printf("iPtr = %d\n",iVar );
printf("iPtr = %d\n",&iVar );
return 0;
}<file_sep>/matricesdinamicas/milibreria.c
#include <stdio.h>
#include <stdlib.h>
#include "milibreria.h"
void menu(double **fMat,double **fMatB,int iRenB, int iColB,int iRenA,int iColA){
int bandera=1;
int opcion;
int a,b;
do{
printf("----------OPCIONES: \n");
printf("[1] Realizar la multiplicación de matrices\n");
printf("[2] Realizar la suma de matrices\n");
printf("[3] Realizar la resta de matrices\n");
printf("- - - - - - - - - - - \n");
printf("[4] Redimencionar Matriz A\n" );
printf("[5] Redimencionar Matriz A\n" );
printf("- - - - - - - - - - - \n");
printf("[6] Salir\n");
scanf("%d",&opcion);
switch(opcion)
{ //creo un menu seleccionar sumar restar mltiplicar o redimenzionar las matrices
case 1:
printf("Programada multiplicación\n");
double **multfRen=crearMatrizMulti(iRenB,iColB,iRenA,iColA);
if (multfRen==NULL)//validacion por si la función: crearMatrizMulti regresa un valor null imprimir el error
printf("No se puede sumar son de diferente dimensión\n");
else
multMatriz(multfRen,fMat,fMatB,iColA,iRenA);
break;
case 2:
printf("OP 2\n");
double **sumfRen=crearMatrizSum(iRenB,iColB,iRenA,iColA);
if (sumfRen==NULL)//validacion por si la función: crearMatrizSum regresa un valor null imprimir el error
printf("No se puede sumar son de diferente dimensión\n");
else
sumMatriz(sumfRen, fMat, fMatB, iColA, iRenA);
break;
case 3:
printf("\n");
double **resfRen=crearMatrizResta(iRenB,iColB,iRenA,iColA);
if (resfRen==NULL)//validacion por si la función: crearMatrizResta regresa un valor null imprimir el error
printf("No se puede sumar son de diferente dimensión\n");
else
resMatriz(sumfRen, fMat, fMatB, iColA, iRenA);
break;
// case 4 y 5 capturo los nuevos valores para las matrices A y B
case 4:
printf("Matriz B:\n");
printf("¿Numero de Renglones?\n");
scanf("%d",&a);
printf("¿Numero de Columnas?\n");
scanf("%d",&b);
break;
case 5:
printf("Matriz B:\n");
printf("¿Numero de Renglones?\n");
scanf("%d",&a);
printf("¿Numero de Columnas?\n");
scanf("%d",&b);
///
double **fMatB=redimencionarMatrizB(fMatB,a,b);
printf("XXXXX\n");
if (fMatB==NULL)
{
printf("\n");
}else
llenarMatrizB(fMatB,a,b);
break;
//salir del menu
case 6:
printf("\n");
bandera=0;
break;
}
}while(bandera!=0);//bandera para cerrar el menu;
}
//Suma matriz
double** crearMatrizSum(int iRenB, int iColB,int iRenA,int iColA)
{
if(iRenA==iRenB&&iColA==iColB)// comparo que la dimension de las matrices sean iguales
{//comienzo a asignar memoria para la matriz A;
double **sumfRen = (double**) malloc(iRenB*sizeof(double*));
for (int i=0; i<iRenB; i++)
{
sumfRen[i] = (double*) malloc(iColB*sizeof(double));
}
return sumfRen;//regreso la matriz con la memoria asignada;
}
else
{//
printf(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -.\n");
printf("Las matrices no tienen la misma dimensión, no se pueden sumar.\n");
printf(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -.\n");
return 0;
}
}
//como la validacion de la dimension de las matrices ya esta realizada, ahora solo sumo las matrices
void sumMatriz(double **sumfRen,double **fMat,double **fMatB,int iColA,int iRenA)
{
int variable;
printf("\n\n-------SUMANDO LAS MATRICES------\n\n");
for(int i=0;i<iRenA;i++)
{
for(int j=0;j<iColA;j++)
{
// printf("",i+1,j+1 );
variable=fMat[i][j]+fMatB[i][j];//sumo las posiciones de las matrices
sumfRen[i][j] = variable;
}
}
//imprimo la matriz
for(int i=0;i<iRenA;i++)
{
for(int j=0;j<iColA;j++)
{
printf("%.2f ",sumfRen[i][j]);
}
printf("\n");
}
}
//Termina suma matriz;
//RESTA matriz
double** crearMatrizResta(int iRenB, int iColB,int iRenA,int iColA)
{
if(iRenA==iRenB&&iColA==iColB)// comparo que la dimension de las matrices sean iguales
{
double **resfRen = (double**) malloc(iRenB*sizeof(double*));
for (int i=0; i<iRenB; i++)
{
resfRen[i] = (double*) malloc(iColB*sizeof(double));
}
return resfRen;
}
else
{
printf(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -.\n");
printf("Las matrices no tienen la misma dimensión, no se pueden restar.\n");
printf(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -.\n");
return 0;
}
}
void resMatriz(double **resfRen,double **fMat,double **fMatB,int iColA,int iRenA)
{
int variable;
printf("\n\n-------RESTANDO LAS MATRICES------\n\n");
for(int i=0;i<iRenA;i++)
{
for(int j=0;j<iColA;j++)
{
//resto las matrices
variable=fMat[i][j]-fMatB[i][j];
resfRen[i][j] = variable;
}
}
//imprimo la matriz
for(int i=0;i<iRenA;i++)
{
for(int j=0;j<iColA;j++)
{
printf("%.2f ",resfRen[i][j]);
}
printf("\n");
}
}
//Termina resta matriz;
//MULTIPLICACION MATRICES;
//validando la creacion de la matriz multiplicación
double** crearMatrizMulti(int iRenB, int iColB,int iRenA,int iColA)
{
//Dos matrices A y B son multiplicables
//comparando si el número de columnas de A coincide con el número de filas de B.
if(iColA==iRenB)
{
printf("Si son iguales\n");
double **multfRen = (double**) malloc(iRenB*sizeof(double*));
for (int i=0; i<iColA ; i++)
{
multfRen[i] = (double*) malloc(iColB*sizeof(double));
}
return multfRen;
}
else///valicacion si las matrices son deferente dimension
{
printf(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -.\n");
printf("Los reglones y columnas son diferentes entre si, no se puede multiplicar\n");
printf(" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -.\n");
return 0;
}
}
//multiplicando la matriz
void multMatriz(double **multfRen,double **fMat,double **fMatB,int iColA,int iRenA)
{
int i, j,k;
printf("\n\n-------SUMANDO LAS MATRICES------\n\n");
for(i=0;i<iRenA;i++)
for(j=0;j<iColA;j++)
{
multfRen[i][j]=0;
for (k = 0; k < iColA; k++)//MUltiplicando matrices con una variable k para controlar el movimiento
{
multfRen[i][j]+=fMat[i][k]*fMatB[k][j];
}
}
//imprimiendo la matriz
for(int i=0;i<iRenA;i++)
{
for(int j=0;j<iColA;j++)
{
printf("%.2f ",multfRen[i][j]);
}
printf("\n");
}
}
/// END redimencionamiento MATRICES;
double** redimencionarMatrizB(double **fRen,int iRenB, int iColB)
{
double **fRen = (double**) realloc(fRen,iRenB*sizeof(double*));
for (int i=0; i<iRenB; i++)
{
fRen[i] = (double*) realloc(fRen[i],iColB*sizeof(double));
}
if(!fRen)printf("La asignacion fall0\n");
else
{printf("Asignacion completada\n");
// fRen=fRen;
return fRen;
}
return 0;
}
double** crearMatrizB(int iRenB, int iColB)
{
double **fRen = (double**) malloc(iRenB*sizeof(double*));
for (int i=0; i<iRenB; i++)
{
fRen[i] = (double*) malloc(iColB*sizeof(double));
}
return fRen;
}
double** crearMatrizA(int iRenA, int iColA)
{
double **fRen = (double**) malloc(iRenA*sizeof(double*));
for (int i=0; i<iRenA; i++)
{
fRen[i] = (double*) malloc(iColA*sizeof(double));
}
return fRen;
}
void llenarMatrizA(double **fMat, int iRenA, int iColA)
{
int variable;
printf("Vamos a llenar la primera matriz\n");
for(int i=0;i<iRenA;i++)
{
for(int j=0;j<iColA;j++)
{
printf("Valor de renglon %d columna%d :",i+1,j+1 );
scanf("%d",&variable);
fMat[i][j] = variable;
// fMat[i][j] = (i*iColA)+j;
}
}
}
void llenarMatrizB(double **fMatB, int iRenB, int iColB)
{
int variable;
printf("Vamos a llenar la segunda matriz\n");
for(int i=0;i<iRenB;i++)
{
for(int j=0;j<iColB;j++)
{
printf("Valor de renglon %d columna%d :",i+1,j+1 );
scanf("%d",&variable);
fMatB[i][j] = variable;
}
}
}
void imprimirMatrizA(double **fMatB, int iRenA, int iColA)
{
printf("-----MATRIZ A:\n");
for(int i=0;i<iRenA;i++)
{
for(int j=0;j<iColA;j++)
{
printf("%.0f ",fMatB[i][j]);
}
printf("\n");
}
}
void imprimirMatrizB(double **fMat, int iRenB, int iColB)
{
printf("-----MATRIZ B:\n");
for(int i=0;i<iRenB;i++)
{
for(int j=0;j<iColB;j++)
{
printf("%.0f ",fMat[i][j]);
}
printf("\n");
}
}
void destruirMatrizA(double **fMat, int iRenA)
{
for(int i=0;i<iRenA;i++)
{
free(fMat[i]);
}
free(fMat);
}
void destruirMatrizB(double **fMatB, int iRenA)
{
for(int i=0;i<iRenA;i++)
{
free(fMatB[i]);
}
free(fMatB);
}
<file_sep>/structs/struct1.c
#include <stdio.h>
struct estudiante
{
char *nombre;
int matricula;
}estudiante1,estudiante2;
int main()
{
estudiante1.nombre="<NAME>";
estudiante2.matricula=1243445;
printf("Nombre: %s\n",estudiante1.nombre);
printf("Matricula: %d \n",estudiante2.matricula);
return 0;
}<file_sep>/matricesdinamicas/main2.c
#include <stdio.h>
#include <stdlib.h>
double promedio(int npromedios);
int main ()
{
int npromedios;
double prom;
printf("calcula promedio\n");
printf("Cuantos numeros vas a promediar\n");
scanf("%d",&npromedios);
prom = promedio(npromedios);
printf("El valor promedio es: %f\n", prom );
// imprime(npromedios);
return 0;
}
double promedio(int npromedios)
{
int arreglo[npromedios-1];
*arreglo=(int)malloc(npromedios*sizeof(int));
if (arreglo)
{
printf("Asignación de memoria realizada\n");
}
else
{
printf("La Asignación fallo\n");
exit(1);
}
for (int i = 0; i < npromedios; ++i)
{
scanf("%d",&arreglo[i]);
}
int i, sum = 0;
double prom;
for (i = 0; i < npromedios; ++i)
{
sum += arreglo[i];
}
prom = (double)sum / npromedios;
return prom;
}<file_sep>/practica1.c
#include <stdio.h>
void capturaDatos(){
char captura[1];
char *nombre= captura;
printf("Cual es tu nombre?\n");
scanf("%s",nombre);
printf("tu nombre es %s\n",nombre);
char captura2[1];
char *apellidopaterno= captura2;
printf("Cual es tu apellido paterno?\n");
scanf("%s",apellidopaterno);
printf("Tu apellido paterno es %s\n",apellidopaterno);
char captura3[1];
char *apellidomaterno= captura3;
printf("Cual es tu apellido materno?\n");
scanf("%s",apellidomaterno);
printf("Tu apellido materno es %s\n",apellidomaterno);
printf("Tu nombre completo es: %s",nombre);
}
int main()
{
char *nombre;
capturaDatos();
return 0;
}<file_sep>/structs/testpelis.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Peliculas
{
char *titulo;
char *actores;
};
int main()
{ int i;
char *temporal;
int npelicula=0;
int opcion;
int bandera=0;
int nactores;
char *actores;
struct Peliculas *pelicula;
printf("Guardar pelis\n");
// scanf("%d",&npelicula);
do
{
printf("[1] Agregar peli\n");
printf("[2] Ver peli\n");
printf("[3] Salir\n");
scanf("%d",&opcion);
switch(opcion){
case 1:
if (npelicula==0)
{
pelicula=(struct Peliculas*) malloc(sizeof(struct Peliculas));
}else
// pelicula=(struct Peliculas*) realloc(pelicula,(npelicula+1)*sizeof(struct Peliculas));
pelicula[0].titulo = malloc(1*sizeof(char));
pelicula[1].titulo = malloc(1*sizeof(char));
printf("titulo?\n");
scanf("%s",temporal);
printf("temporal: %s\n",temporal);
pelicula[npelicula].titulo=temporal;
printf("%s\n",pelicula[npelicula].titulo);
npelicula++;
// pelicula[0].titulo="Peeeeliiiionee";
// printf("Cuantos actores?\n");
// scanf("%d",&nactores);
// printf("Escribiras %d actores\n",nactores);
// actores=malloc(nactores*sizeof(char));
// for (int i = 0; i < nactores; ++i)
// {
// printf("Actor No.%d\n",i+1);
// scanf("%s",&actores[i]);
// }
// for (int i = 0; i < nactores; ++i)
// {
// // printf("%s\n",actores[i]);
// }
// iArreglo=malloc(iTam*sizeof(int));
break;
case 2:
// for (int i = 0; i < npelicula; ++i)
// {
printf("Pelicula %d: %s\n",i,pelicula[0].titulo);
printf("Pelicula %d: %s\n",i,pelicula[1].titulo);
// }
// printf("%s\n",pelicula[1]->titulo);
// printf("%s\n",pelicula[2]->titulo);
// printf("%s\n",arregloactores[0] );
// printf("%s\n",arregloactores[1] );
// printf("%s\n",arregloactores[2] );
// printf("%s\n",arregloactores[3] );
break;
case 3:
bandera=1;
break;
}
} while (bandera==0);
return 0;
}<file_sep>/structs/memset.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
char *titulo;
char *director;
char **actores;
int *año;
}Peliculas;
int main()
{
char **c = 'F';
char *s;
int i;
Peliculas **producto = NULL;
producto = (Peliculas**)realloc(producto, 1 * sizeof(Peliculas*));
producto[0] = (Peliculas*)malloc(sizeof(Peliculas));
producto[0]->actores=malloc(50);
*producto[0]->actores="Manuel";
printf("%s\n",*producto[0]->actores);
c = (char*)malloc(5*sizeof(char));
// *producto[0]->actores=c;
memset(producto[0]->actores, c, 5 );
for( i=0; i<5; i++ )
// printf( "c[%d]=%c ", i, c );
printf( "\n" );
free(*producto[0]->actores);
return 0;
return 0;
}<file_sep>/structs/peliculas.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char *titulo;
char *director;
char **actores;
int *año;
int ID;
int ren;
int col;
}Peliculas;
char** crearMatriz(int iRen, int iCol)
{
char **fRen = (char**) malloc(iRen*sizeof(char*));
//char **fRen = (char**)realloc(fRen,iRen*sizeof(char*));
for (int i=0; i<iRen; i++)
{
fRen[i] = (char*) malloc(iCol*sizeof(char));
}
return fRen;
}
void llenarMatriz(char **mat, int iRen, int iCol)
{
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
printf("Actor No.%d\n",i+1 );
scanf("%s",mat[i]);
//gets(mat[i]);
//printf("%s\n",mat[i] );
}
}
}
void imprimirMatriz(char **mat, int iRen, int iCol)
{
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
printf("Actor No.%d: %s\n",i+1,mat[i]);
}
// printf("\n");
}
}
void destruirMatriz(char **mat, int iRen)
{
for(int i=0;i<iRen;i++)
{
free(mat[i]);
}
free(mat);
}
int main(void)
{
char *var;
int i;
int npeliculas=0;
int opcionmenu;
int bandera=0;
int posicionpeliculas=0;
int renglones;
int iCol=1;
int iRen=1;
int numeroactores=0;
Peliculas **producto = NULL;//creando mi estructura donde se almacenaran mis peliculas
int bandera2=0;
int op2;
printf("Programa peliculas xd \n");
do
{
printf("[1] Agregar Pelicula\n");
printf("[2] Imprimir Peliculas\n");
printf("[3] Salir\n");
scanf("%d",&opcionmenu);
switch(opcionmenu)
{
case 1:
npeliculas++;//variable para controlar el numero total de peliculas
producto = (Peliculas**)realloc(producto, 10 * sizeof(Peliculas*));
//Asignacion de memoria para las variables de la estructura Peliculas
producto[0] = (Peliculas*)malloc(sizeof(Peliculas));//asignacion de memoria par la nueva pelicula
producto[0]->titulo=(char*)malloc(10*sizeof(char));
producto[0]->año=malloc(1);//asignacion de memoria para las variables del prototipo
producto[0]->director=malloc(10);
producto[0]->ren=(int)malloc(10*sizeof(int));
producto[0]->ID=(int)malloc(1*sizeof(int));
printf("Nombre de la Pelicula? ");
scanf("%s",producto[posicionpeliculas]->titulo);
printf("Director? ");
scanf("%s",producto[posicionpeliculas]->director);
printf("Año en que salió la película? ");
scanf("%d",producto[posicionpeliculas]->año);
printf("Cuantos actores hay? ");
scanf("%d",&producto[posicionpeliculas]->ren);
producto[posicionpeliculas]->col =1;
producto[posicionpeliculas]->actores = crearMatriz(producto[posicionpeliculas]->ren, producto[posicionpeliculas]->col);//creacion de la matriz para actores
producto[posicionpeliculas]->ID=npeliculas;
llenarMatriz(producto[posicionpeliculas]->actores,producto[posicionpeliculas]->ren, producto[posicionpeliculas]->col);
printf("\n");
posicionpeliculas++;//esta variable controla la posicion de las peliculas,
//la mantengo atrasa y la aumento al final para que la primera posicion sea 0
break;
case 2:
printf("______________________\n");
printf("______PELICULAS_______\n");
do
{
printf("ID\tTITULO\n");
for (int i = 0; i < posicionpeliculas; ++i)//posicionpeliculas para imprimir el total de las peliculas guardadas
{
printf("[%d]\t%s\n",producto[i]->ID,producto[i]->titulo);//imprimiento las peliculas almacenadas
}
scanf("%d",&op2);//
op2=op2-1;
printf("ID: 00%d\n",producto[op2]->ID);
printf("Pelicula : %s\n",producto[op2]->titulo);
printf("año: %d\n",*producto[op2]->año);
printf("director: %s\n",producto[op2]->director);
imprimirMatriz(producto[op2]->actores,producto[op2]->ren, producto[op2]->col);
printf("______________________\n");
printf("- - - - - - - - - - - \n");
bandera2=1;
} while (bandera2==0);
break;
case 3:
bandera=1;
break;
}
} while (bandera==0);
destruirMatriz(producto[0]->actores,producto[0]->ren);//liberando memoria de la matriz
for(i=0;i<npeliculas;i++)//ciclo para librerar todas los posiciones que se crearon para las peliculas
{
free(producto[i]);
}
free(producto);
return 0;
}<file_sep>/structs/dynamicstruct.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Matriz
{
char **m;
int ren;
int col;
};
char** crearMatriz(int iRen, int iCol)
{
char **fRen = (char**) malloc(iRen*sizeof(char*));
for (int i=0; i<iRen; i++)
{
fRen[i] = (char*) malloc(iCol*sizeof(char));
}
return fRen;
}
void llenarMatriz(char **mat, int iRen, int iCol)
{
char *nombre="Manuel";
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
printf("Actor No.%d\n",iRen );
scanf("%s",mat[i]);
printf("%s\n",mat[i] );
}
}
}
void imprimirMatriz(char **mat, int iRen, int iCol)
{
for(int i=0;i<iRen;i++)
{
for(int j=0;j<iCol;j++)
{
printf("%s ",mat[i]);
}
printf("\n");
}
}
void destruirMatriz(char **mat, int iRen)
{
for(int i=0;i<iRen;i++)
{
free(mat[i]);
}
free(mat);
}
int main(void)
{
struct Matriz **mat = NULL;
mat = (struct Matriz**)realloc(mat,1*sizeof(struct Matriz*));
mat[0] = (struct Matriz*)malloc(sizeof(struct Matriz));
mat[0]->ren = 1;
mat[0]->col = 1;
mat[0]->m = crearMatriz(mat[0]->ren, mat[0]->col);
llenarMatriz(mat[0]->m,mat[0]->ren, mat[0]->col);
imprimirMatriz(mat[0]->m,mat[0]->ren, mat[0]->col);
destruirMatriz(mat[0]->m,mat[0]->ren);
free(mat[0]);
free(mat);
return 0;
}<file_sep>/structs/hola.c
#include <stdio.h>
int main()
{
char *nombre;
printf("Como te llamas?");
scanf("%s",nombre);
printf("Hola %s\n",nombre );
return 0;
}<file_sep>/structs/practica/funciones.c
//<NAME>
//<NAME>
#include <stdio.h>
#include <stdlib.h>
#include <string.h><file_sep>/structs/struct3.c
#include <stdio.h>
struct Libros
{
char *titulo;
};
int main()
{
struct Libros *libro[2];
libro[0]=(struct Libros*) malloc(sizeof(struct Libros));
libro[0]->titulo="MATE";
printf("titulo: \t %s\n",libro[0]->titulo );
free(libro[0]);
return 0;
}<file_sep>/structs/menu.c
#include <stdio.h>
int main()
{
int opcion;
int bandera=0;
printf("MENu switch\n");
do
{
printf("[1] \n");
printf("[2] \n");
printf("[3] Salir\n");
scanf("%d",&opcion);
switch(opcion)
{
case 1:
printf("Primera opcion :O!\n");
break;
case 2:
printf("Segunda opcion D: \n");
break;
case 3:
printf("Bye :(\n");
bandera=1;
break;
}
} while (bandera==0);
return 0;
}<file_sep>/ventas/main4.c
#include <stdio.h>
#include <stdlib.h>
void promedio(int *total, int p);
void ventaminima(int *total, int p);
void ventamax(int *total, int p);
int main()
{
int *total = NULL, k = 1, s;
total=calloc(1,sizeof(int));
int v, d, t, op, r, u, f, p = 0 , totaldia = 0;
do
{
float prom;
total = (int*)realloc(total,k*sizeof(int));
printf("PALETERIA PEDRITO\nDIA%d\n\n",k);
printf("Cuantos bolis de Vainilla vendiste?\t");
scanf("%d",&v);
printf("Cuantos bolis de Tamarindo vendiste?\t");
scanf("%d",&t);
printf("Cuantos bolis de Rompope vendiste?\t");
scanf("%d",&r);
printf("Cuantos bolis de Uva vendiste?\t");
scanf("%d",&u);
printf("Cuantos bolis de Fresa vendiste?\t");
scanf("%d",&f);
totaldia=v+t+r+u+f;
prom=(float)totaldia/5;
printf("\nVENTA TOTAL DEL DIA\t%d\nPROMEDIO DE VENTA DEL DIA\t %f\n",totaldia,prom);
total[p]=totaldia;
printf("\nDESEA CAPTURAR OTRO DIA DE VENTA PRESIONA 1 PARA CAPTURAR, PRESIONA CUALQUER TECLA PARA CONTINUAR\n ");
scanf("%d",&s);
k++;
p++;
}while(s==1);
promedio(total,p);
ventamax(total,p);
ventaminima(total,p);
return 0;
}
void promedio(int *total,int p)
{
int z,suma=0;
float promedio;
for(z=0; z<p; z++)
{
suma+=total[z];
}
printf("\nEL PROMEDIO DE VENTA DIARIA ES\t");
promedio=(float)suma/z;
printf("%f",promedio);
}
void ventamax(int *total, int p)
{
int aux=0,z;
for(z=0; z<p; z++)
{
if(total[z]>aux)
aux=total[z];
}
printf("\n\nLA VENTA MAXIMA EN ESTOS DIAS FUE\t%d\n",aux);
}
void ventaminima(int *total, int p)
{
int aux=999999,z;
for(z=0; z<p; z++)
{
if(total[z]<aux)
aux=total[z];
}
printf("\nLA VENTA MINIMA EN ESTOS DIAS FUE\t%d\n",aux);
}
|
0f142cfb379aa2c0c512c96ed37b016a26337a65
|
[
"Markdown",
"C"
] | 38 |
C
|
ManuelAlanis/Programaci-nC
|
d91291d814ddbca0bbf6a8c29735c9ed04ab7cc8
|
22c657a332a73a7319cc27571e4fa57b8bd539de
|
refs/heads/master
|
<file_sep>package com.gamerexde.hidemypluginsbungee.Commands;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
public class HideMyPlugins extends Command {
public HideMyPlugins() {
super("hidemyplugins");
}
@Override
public void execute(CommandSender commandSender, String[] args) {
if(commandSender instanceof ProxiedPlayer) {
ProxiedPlayer player = (ProxiedPlayer) commandSender;
if (args.length == 1) {
}
player.sendMessage("§8 [§dHideMyPlugins §bBungee§8]");
player.sendMessage("");
player.sendMessage("§7 - §a/hmpa §8-> §7Shows useful admin commands.");
player.sendMessage("");
}
}
}
|
780655423fbe3081f802181ca886d9f6cc4331d2
|
[
"Java"
] | 1 |
Java
|
meloncafe/HideMyPlugins
|
f8c77f140407451de386205732decfa4ea01a9ca
|
5461f61b8f85c2fe593e43d6af8c099a9dcdb329
|
refs/heads/master
|
<file_sep>// reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main () {
string line;
string location;
string file;
string fullname;
int i=0;
ifstream myfile ("filelist.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
if(!line.empty()) {
if(line.length()>11) {
std::size_t pos = line.find(".");
//std::string root = line.substr (pos);
if(pos==0) {
location=line;
//std::cout<<line<<std::endl;
}
else{
file=line;
i++;
fullname=location+file;
replace(fullname.begin(),fullname.end(),':','/');
cout << fullname<<" "<<i << endl;
}
}
}
}
myfile.close();
}
else cout << "Unable to open file"<<endl;
return 0;
}
<file_sep>#include "TFile.h"
//#include <algorithm> // for std::max
#include <iomanip>
#include "THStack.h"
#include "TCut.h"
#include "TH1.h"
#include "TH2.h"
#include "TFile.h"
#include "TCanvas.h"
#include "TChain.h"
#include "TTree.h"
#include <TROOT.h>
#include <TStyle.h>
#include "TLegend.h"
//#include <iostream>
//#include <fstream>
//#include <string>
#include <ctime>
#include <stdlib.h>
#include "StandardRecord/StandardRecord.h" // Activate DeActivate this line to get rid of the error..!
#include "TApplication.h"
#include "TSystem.h"
#include "TRint.h"
#include "Cintex/Cintex.h"
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
string line;
string location;
string file;
string fullname;
string finalname[1000];
int i = 0;
//#include "StandardRecord.h"
//gSystem->Load("libCintex.so");
//Cintex.Enable()
//gSystem.Load("$SRT_PUBLIC_CONTEXT/lib/Linux2.6-GCC-debug/libStandardRecord_dict.so")
//gInterpreter.AddIncludePath("$SRT_PUBLIC_CONTEXT")
void test01macro()
{
i = 0;
ifstream myfile("filelist.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
if (!line.empty())
{
if (line.length() > 11)
{
std::size_t pos = line.find(".");
//std::string root = line.substr (pos);
if (pos == 0)
{
location = line;
//std::cout<<line<<std::endl;
}
else
{
file = line;
fullname = location + file;
replace(fullname.begin(), fullname.end(), ':', '/');
//fullname.erase(1,1);
fullname.erase(0, 1);
//cout << "/nova/ana/users/mylab/prod/decaf" << fullname << " " << i << endl;
finalname[i] = "/nova/ana/users/mylab/prod/decaf" + fullname;
// std::cout << finalname[i] << std::endl;
i++;
}
}
}
}
myfile.close();
}
else
cout << "Unable to open file" << endl;
i = i - 1;
//file->ls();
//tree->Scan();
TCanvas *c1 = new TCanvas("c1", "X-Vertex position", 1024, 768);
//TCanvas* c2=new TCanvas("c2","Y-Vertex position",1024,768);
TH1F *h0 = new TH1F("h0", "X-Vertex Position", 50, -140, 140);
TH1F *h1 = new TH1F("h1", "Y-Vertex Position", 50, -140, 140);
TH1F *h2 = new TH1F("h2", "Z-Vertex Position", 100, 50, 1200);
TH1F *h3 = new TH1F("h3", "slc.nhit", 50, 20, 250);
TH1F *h4 = new TH1F("h4", "slc.calE", 50, 0, 3.5);
TH1F *h5 = new TH1F("h5", "trk.kalman.len", 100, -20, 420);
caf::StandardRecord *rec;
while (i >= 0)
{
std::cout<<"i value: "<<i<<std::endl;
std::cout<<"file: "<<finalname[i]<<std::endl;
TFile *file = new TFile(finalname[i].c_str(), "read");
TTree *tree = (TTree *)file->Get("recTree");
tree->SetBranchAddress("rec", &rec);
//tree->SetBranchStatus("slc.nhit", 1);
for (int j = 0; j < tree->GetEntries(); ++j)
{
tree->GetEntry(j);
if (rec->trk.nkalman > 0 &&
rec->energy.numusimp.E > 0 &&
rec->sel.remid.pid > 0 &&
rec->vtx.nelastic > 0 &&
rec->slc.nhit > 20 &&
rec->slc.ncontplanes > 4 &&
rec->trk.ncosmic > 0 &&
rec->sel.remid.pid > 0.75 &&
abs(rec->vtx.elastic[0].vtx.fX) < 140 &&
abs(rec->vtx.elastic[0].vtx.fY) < 140 &&
rec->vtx.elastic[0].vtx.fZ < 1200 &&
rec->vtx.elastic[0].vtx.fZ > 50)
{
//std::cout << rec->vtx.elastic[0].vtx.fX << std::endl;
h0->Fill(rec->vtx.elastic[0].vtx.fX);
h1->Fill(rec->vtx.elastic[0].vtx.fY);
h2->Fill(rec->vtx.elastic[0].vtx.fZ);
h3->Fill(rec->slc.nhit);
h4->Fill(rec->slc.calE);
//std::cout<<rec->trk.nkalman<<std::endl;
for (Int_t k = 0; k < rec->trk.nkalman; ++k)
{
h5->Fill(rec->trk.kalman[k + 1].len);
}
//std::cout<<rec->trk.kalman[1].len<<std::endl;
}
//gStyle->SetOptStat(kTRUE);
// TCanvas* c2=new TCanvas("c2","Y-Vertex position",1024,768);
//c2->cd();
//h1->Draw();
//
// //
// }
//std::cout << rec->slc.nhit << std::endl;
}
i--;
}
c1->cd();
h5->Draw();
}
<file_sep>#include <TH2.h>
#include "TFile.h"
#include "TTree.h"
#include "TVector3.h"
#include <TStyle.h>
#include <TCanvas.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include "TLorentzVector.h"
#include <vector>
#include <iomanip>
#include "TMath.h"
#include "TError.h"
#include <math.h>
#include "TApplication.h"
#include "TSystem.h"
#include "TRint.h"
#include "Cintex/Cintex.h"
//gSystem->Load("libCintex.so");
//Cintex::Enable();
//gSystem->Load("$SRT_PUBLIC_CONTEXT/lib/Linux2.6-GCC-debug/libStandardRecord_dict.so");
int main(int argc, char **argv)
{
gSystem->Load("libCintex.so");
Cintex::Enable();
gSystem->Load("$SRT_PUBLIC_CONTEXT/lib/Linux2.6-GCC-debug/libStandardRecord_dict.so");
TApplication theApp("tapp", &argc, argv);
TFile* file = new TFile("/nova/ana/caf/genie_vs_nuwro_nue.root", "READ");
TTree* tree = (TTree*)file->Get("genie");
//tree->Draw("Ev");
TCanvas *c1=new TCanvas("c1");
tree->Draw("Ev:x","","colz");
c1->Update();
theApp.Run();
return 0;
}
|
7b176aba9383169fbd2705d08049a1c8658a1d6b
|
[
"C"
] | 3 |
C
|
chatuu/cafe
|
31a0f735b6ad31a072455ee0f068e311af02b529
|
791664723ba9e314cd458bb4aee88337578b8dda
|
refs/heads/master
|
<file_sep>import requests
import json
def forward_to_api(url,mobile,message,api_key,flash,count):
payload = {'senderId': 'FSTSMS', 'mobile': mobile, 'message': message, 'flash': flash}
headers = {'Authorization': api_key}
print '\n-- Trying to send SMS via API ['+str(count)+'] --'
response = requests.request("POST", url, data=payload, headers=headers)
if response.json()['return'] != True:
return False
print '<< '+response.json()['message']+' >>'
return response.json()['return']
def forward_to_paid_api(url,mobile,message,api_key,flash,count):
headers = {'cache-control': "no-cache"}
querystring = {"authorization":api_key,"sender_id":"FSTSMS","message":message,"language":"english","route":"p","numbers":mobile,"flash":flash}
print '\n-- Trying to send SMS via Paid API ['+str(count)+'] --'
response = requests.request("GET", url, headers=headers, params=querystring)
print '<< '+response.json()['message']+' >>'
return response.json()['return']
def send_sms(sms_data):
phone = sms_data[0]
message = sms_data[1]
allowed_sms_length = 149
#Trim Message length to 160-11 = 149 characters#
if len(message) > allowed_sms_length:
message = message[0:145]
message+='[..]'
print '--> Sending SMS to '+str(phone)
number = str(phone)
api_keys = ["API key1", # Your free msgs API key
"API key2"] # Your paid msgs API key
url = "https://www.fast2sms.com/api/sms/free"
for key in api_keys:
count = api_keys.index(key)+1
if api_keys.index(key)>1:
url = "https://www.fast2sms.com/dev/bulk"
sent_status = forward_to_paid_api(url,number,message,key,0,count)
else:
sent_status = forward_to_api(url,number,message,key,0,count)
if sent_status:
return 'SUCCESS'
else:
print '-- SMS was not sent. Retrying... --'
continue
if sent_status == False:
return 'ERROR'
|
72b1035d1589d3b77c721c7be4e248bce8cde185
|
[
"Python"
] | 1 |
Python
|
marciopocebon/fast2sms
|
617124b86fc46526d8312c43f27cdaa6afaec5f9
|
2632f5c0594392604302b2d9a20f005ddecde58a
|
refs/heads/master
|
<repo_name>RachitKeertiDas/SheetMailScript<file_sep>/script.js
const EMAIL_SENT = 'EMAIL_FORWARDED';
const help_categories = {
'Plumbing' : 1,
'Honeybees' : 2,
'Electricity' : 3,
'Weeds' : 4,
'General Frustration with college life' : 5,
'Snake spotted' : 6,
'Someone broke my wall' : 7
}
function getEmailString(sheet,max,col) {
let description ='';
for(let j=2; j<max;j++){
let currentcell = sheet.getRange(j,col).getValue();
if(currentcell === '')
break;
else
description += ',' + currentcell;
}
return description;
}
function SendResponseEmails() {
let ss = SpreadsheetApp.getActiveSpreadsheet();
let responseSheet = ss.getSheetByName("Form Responses 1");
let blockSheet = ss.getSheetByName("Block Wardens");
let categorySheet = ss.getSheetByName("Help Categories");
const startRow = 2;
const numRows = responseSheet.getLastRow()+1;
const dataRange = responseSheet.getRange(startRow,1,numRows,6);
const data = dataRange.getValues();
for(let i=0; i< data.length; ++i){
let row = data[i];
let isEmailSent = row[6];
if(isEmailSent === EMAIL_SENT)
continue;
const block = row[2];
const senderEmail = row[1];
let cause = row[3];
let wardenlist = '<EMAIL>';
let description = 'Description Of The Problem:\n';
description += "The following complaint was recieved:\n";
let subject = 'Hostel Complaint reagrding : ';
let maxWardenRange = blockSheet.getLastRow();
let maxCategoryRange = categorySheet.getLastRow();
subject += row[3];
description += row[4];
if(block === '')
return;
if(block === 'P'){
wardenlist += getEmailString(blockSheet,maxWardenRange,11);
}
else {
wardenlist += getEmailString(blockSheet,maxWardenRange, block.charCodeAt()-64);
}
wardenlist += getEmailString(categorySheet, maxWardenRange, help_categories[cause] );
description += "This complaint was sent by: ";
description += senderEmail;
MailApp.sendEmail(wardenlist, senderEmail, subject, description);
responseSheet.getRange(startRow + i, 7).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
|
020c302370b96dc79ebffbf567a609b781041453
|
[
"JavaScript"
] | 1 |
JavaScript
|
RachitKeertiDas/SheetMailScript
|
80e9313b72a07bf6a8fad3569e16edd7f6efdc23
|
0556ebcf0d7a84d957e76caa3e01799ebf2dc4bf
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
#encoding: utf-8
import rospy,copy,math
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
from mymouse_ros.msg import MyLightSensorValues
class LineTrace():
def __init__(self):
self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1)
self.s = MyLightSensorValues()
rospy.Subscriber('/lightsensors', MyLightSensorValues, self.callback_lightsensors)
def callback_lightsensors(self,messages):
self.s = messages
def run(self):
rate = rospy.Rate(20)
data = Twist()
while not rospy.is_shutdown():
data.linear.x = 0.2
s1 = (self.s.left_third < 1000)
s2 = (self.s.left_first < 1000)
s3 = (self.s.right_first < 1000)
s4 = (self.s.right_third < 1000)
if (s1+s2+s3+s4)==0:
u = 0.0
else:
u = (2.89*s1 + 1*s2 - 1*s3 - 2.89*s4)/(s1+s2+s3+s4)
delta = math.pi/180*40*u
data.angular.z = delta
self.cmd_vel.publish(data)
rate.sleep()
if __name__ == '__main__':
rospy.init_node('line_trace')
rospy.wait_for_service('/motor_on')
rospy.wait_for_service('/motor_off')
rospy.on_shutdown(rospy.ServiceProxy('/motor_off',Trigger).call)
rospy.ServiceProxy('/motor_on',Trigger).call()
w = LineTrace()
w.run()
|
23428dfe130daf1ad644c3eae9f755a55c8aaedf
|
[
"Python"
] | 1 |
Python
|
IshiguroN/pimouse_run_corridor
|
1de0ca4bdf6e4ac282813df8f24190c651b15856
|
892e1eed6205857437c42bcf9d36e1a9a330d0af
|
refs/heads/master
|
<repo_name>bwmello/TwitterWordCount<file_sep>/twitterWordCount.rb
require 'rubygems'
require 'twitter'
client = Twitter::Streaming::Client.new do |config|
config.consumer_key = "yRDGd1lkfrJzZdB7pXbrCivqc"
config.consumer_secret = "<KEY>"
config.access_token = "<KEY>"
config.access_token_secret = "<KEY>"
end
string = ''
fiveMinuteTimer = Time.now + 300
#client.sample(lang: "en") do |tweet|
client.filter(locations: "-126.75,32.8,-115.75,42.8") do |tweet|
string << tweet.text
break if Time.now > fiveMinuteTimer
end
stopWords = IO.readlines("/RubyProjects/stop_words.txt")
stopWords.each {|a| a.strip! if a.respond_to? :strip! }
wordFrequency = Hash.new(0)
string.gsub!(/[^a-zA-Z' ]/, "")
#puts string
string = string.downcase.split(/\s+/)
string -= stopWords
string.each do |word|
if word !~ /^[0-9]*\.?[0-9]+$/
wordFrequency[word] += 1
end
end
counter = 0
while counter < 10 do
mostCommonWord = wordFrequency.max_by{|k,v| v}
puts "#{mostCommonWord[0]}: #{mostCommonWord[1]} occurrences"
wordFrequency.delete(mostCommonWord[0])
counter += 1
end
|
29d3980f53625be7c3c843c4903ba64c1aaf9b14
|
[
"Ruby"
] | 1 |
Ruby
|
bwmello/TwitterWordCount
|
fbff513f8a9f7c568288e92624b6587c8fccd924
|
09f4dd0ce372e20368aba738db6b2516db93feb9
|
refs/heads/master
|
<repo_name>Benlsc/Go4Lunch<file_sep>/app/src/main/java/com/lescour/ben/go4lunch/controller/fragment/RestaurantListFragment.java
package com.lescour.ben.go4lunch.controller.fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lescour.ben.go4lunch.R;
import com.lescour.ben.go4lunch.model.ParcelableRestaurantDetails;
import com.lescour.ben.go4lunch.model.firestore.User;
import com.lescour.ben.go4lunch.view.RestaurantRecyclerViewAdapter;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class RestaurantListFragment extends BaseFragment {
private RecyclerView.Adapter mRecyclerViewAdapter;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public RestaurantListFragment() {
}
public static RestaurantListFragment newInstance(ParcelableRestaurantDetails mParcelableRestaurantDetails,
ArrayList<User> usersList) {
RestaurantListFragment fragment = new RestaurantListFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_PARCELABLE_RESTAURANTDETAILS, mParcelableRestaurantDetails);
args.putParcelableArrayList(ARG_USERSLIST, usersList);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_restaurant_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setLayoutManager(new LinearLayoutManager(context));
this.mRecyclerViewAdapter = new RestaurantRecyclerViewAdapter(this.mParcelableRestaurantDetails,
this.usersList, context, mListener);
recyclerView.setAdapter(this.mRecyclerViewAdapter);
}
return view;
}
/**
* Notify fragment that the data has changed.
*/
public void notifyFragment() {
this.mRecyclerViewAdapter.notifyDataSetChanged();
}
}
<file_sep>/app/src/main/java/com/lescour/ben/go4lunch/model/ParcelableRestaurantDetails.java
package com.lescour.ben.go4lunch.model;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;
import com.lescour.ben.go4lunch.model.details.PlaceDetailsResponse;
import com.lescour.ben.go4lunch.model.nearby.Result;
import java.util.List;
/**
* Created by benja on 28/03/2019.
*/
public class ParcelableRestaurantDetails implements Parcelable {
private Double currentLat, currentLng;
private List<Result> nearbyResults;
private List<PlaceDetailsResponse> placeDetailsResponses;
private List<Bitmap> mBitmapList;
public ParcelableRestaurantDetails() {
}
protected ParcelableRestaurantDetails(Parcel in) {
if (in.readByte() == 0) {
currentLat = null;
} else {
currentLat = in.readDouble();
}
if (in.readByte() == 0) {
currentLng = null;
} else {
currentLng = in.readDouble();
}
nearbyResults = in.createTypedArrayList(Result.CREATOR);
placeDetailsResponses = in.createTypedArrayList(PlaceDetailsResponse.CREATOR);
mBitmapList = in.createTypedArrayList(Bitmap.CREATOR);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
if (currentLat == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeDouble(currentLat);
}
if (currentLng == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeDouble(currentLng);
}
dest.writeTypedList(nearbyResults);
dest.writeTypedList(placeDetailsResponses);
dest.writeTypedList(mBitmapList);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<ParcelableRestaurantDetails> CREATOR = new Creator<ParcelableRestaurantDetails>() {
@Override
public ParcelableRestaurantDetails createFromParcel(Parcel in) {
return new ParcelableRestaurantDetails(in);
}
@Override
public ParcelableRestaurantDetails[] newArray(int size) {
return new ParcelableRestaurantDetails[size];
}
};
//GETTER\\
public Double getCurrentLat() {
return currentLat;
}
public Double getCurrentLng() {
return currentLng;
}
public List<Result> getNearbyResults() {
return nearbyResults;
}
public List<PlaceDetailsResponse> getPlaceDetailsResponses() {
return placeDetailsResponses;
}
public List<Bitmap> getBitmapList() { return mBitmapList; }
//SETTER\\
public void setCurrentLat(Double currentLat) {
this.currentLat = currentLat;
}
public void setCurrentLng(Double currentLng) {
this.currentLng = currentLng;
}
public void setNearbyResults(List<Result> nearbyResults) {
this.nearbyResults = nearbyResults;
}
public void setPlaceDetailsResponses(List<PlaceDetailsResponse> placeDetailsResponses) { this.placeDetailsResponses = placeDetailsResponses; }
public void setBitmapList(List<Bitmap> bitmapList) { mBitmapList = bitmapList; }
}
<file_sep>/app/src/main/java/com/lescour/ben/go4lunch/controller/fragment/WorkmatesListFragment.java
package com.lescour.ben.go4lunch.controller.fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.lescour.ben.go4lunch.R;
import com.lescour.ben.go4lunch.model.ParcelableRestaurantDetails;
import com.lescour.ben.go4lunch.model.firestore.User;
import com.lescour.ben.go4lunch.view.WorkmatesRecyclerViewAdapter;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class WorkmatesListFragment extends BaseFragment {
private RecyclerView.Adapter mRecyclerViewAdapter;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public WorkmatesListFragment() {
}
public static WorkmatesListFragment newInstance(ParcelableRestaurantDetails mParcelableRestaurantDetails,
ArrayList<User> usersList) {
WorkmatesListFragment fragment = new WorkmatesListFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_PARCELABLE_RESTAURANTDETAILS, mParcelableRestaurantDetails);
args.putParcelableArrayList(ARG_USERSLIST, usersList);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_workmates_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setLayoutManager(new LinearLayoutManager(context));
this.mRecyclerViewAdapter = new WorkmatesRecyclerViewAdapter(mParcelableRestaurantDetails,
usersList, mListener, Glide.with(this), context);
recyclerView.setAdapter(this.mRecyclerViewAdapter);
}
return view;
}
/**
* Notify fragment that the data has changed.
*/
public void notifyFragment() {
this.mRecyclerViewAdapter.notifyDataSetChanged();
}
}
|
98deb2b291f0b4affad1894a29b83f8c14c9d39a
|
[
"Java"
] | 3 |
Java
|
Benlsc/Go4Lunch
|
986e2d956fe8a5c073a4c0c3a6c9614a7caa3bea
|
23590859d145078832798add319438959a93810e
|
refs/heads/master
|
<file_sep>//
// BCOGetGoodsDealsService.swift
// baicaio
//
// Created by JimBo on 15/12/26.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import Alamofire
import RealmSwift
typealias loadGoodsDealsCompletionHandler = (List<BCOGoodsDealInfo>?,NSError?) -> Void
typealias loadGoodsDealInfoCompletionHandler = (BCOGoodsDealInfo?,NSError?) ->Void
class BCOGetGoodsDealsService: NSObject {
//获取商品优惠列表
static func getGoodsDetalList(urlString:String, pageOfCagegoty page:Int, category:String, completionHandler:loadGoodsDealsCompletionHandler){
var url:String = urlString
if page>1 {
if url.hasPrefix("http://www.baicaio.com/?s="){
let searchString:String = url.stringByReplacingOccurrencesOfString("http://www.baicaio.com/?s=", withString: "")
url = "http://www.baicaio.com/page/" + String(stringInterpolationSegment: page) + "?s=" + searchString
}else{
url = url + "page/" + String(stringInterpolationSegment: page)
}
}
url = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
Alamofire.request(.GET, url)
.responseData { response in
if response.result.isSuccess {
let goodsDealArray = self.goodsDealArrayWithHtmlData(response.data!,category: category)
if goodsDealArray.count>0 {
let realm = try! Realm()
try! realm.write{
//添加新的数据
realm.add(goodsDealArray, update: true)
}
}
completionHandler(goodsDealArray,nil)
}else{
let error = NSError(domain: "加载失败", code: 40004, userInfo: nil)
let list = List<BCOGoodsDealInfo>()
if page == 1 {
let realm = try! Realm()
let result = realm.objects(BCOGoodsDealInfo.self).filter("category = '\(category)'")
for item in result {
list.append(item)
}
}
completionHandler(list,error)
}
}
}
//获取商品详情
static func getGoodsDealInfo(urlStr : String , completionHandler : loadGoodsDealInfoCompletionHandler){
//判断本地是否已缓存,如果已缓存,则直接取本地
if let goodsDealInfo = self.getGoodsDealInfoFormDBWithUrl(urlStr) {
completionHandler(goodsDealInfo,nil)
}else {
Alamofire.request(.GET, urlStr)
.responseData { response in
if response.result.isSuccess {
let goodsDealInfo = self.goodsDealInfoWithHtmlData(response.data!, introUrl: urlStr)
completionHandler(goodsDealInfo,nil)
}else{
let error = NSError(domain: "加载失败", code: 40004, userInfo: nil)
completionHandler(nil,error)
}
}
}
}
//根据分类获取所有商品详情【已收藏的除外】
static func getGoodsDealExceptCollectedWithCategory(category:String) -> [BCOGoodsDealInfo]{
let realm = try! Realm()
let collectedResult = realm.objects(BCOGoodsDealCollected.self)
if collectedResult.count>0 {
let willDeleteArray = realm.objects(BCOGoodsDealInfo).filter("category = '\(category)'").filter({ (goodsDealInfo) -> Bool in
if let _ = collectedResult.filter("infoUrl = '\(goodsDealInfo.infoUrl)'").first{
return false
}
return true
})
return willDeleteArray
}else{
return realm.objects(BCOGoodsDealInfo.self).reverse()
}
}
//获取所有没收藏的数据【已收藏的除外】
static func getGoodsDealExceptCollected() -> [BCOGoodsDealInfo]{
let realm = try! Realm()
let collectedResult = realm.objects(BCOGoodsDealCollected.self)
if collectedResult.count>0 {
let willDeleteArray = realm.objects(BCOGoodsDealInfo).filter({ (goodsDealInfo) -> Bool in
if let _ = collectedResult.filter("infoUrl = '\(goodsDealInfo.infoUrl)'").first{
return false
}
return true
})
return willDeleteArray
}else{
return realm.objects(BCOGoodsDealInfo.self).reverse()
}
}
//根据data,解析出商品优惠的列表
private static func goodsDealArrayWithHtmlData(data:NSData,category:String) -> List<BCOGoodsDealInfo>{
let goodsDealArray = List<BCOGoodsDealInfo>()
let html = TFHpple(HTMLData: data)
let ulElements = html.searchWithXPathQuery("//ul[@class='post-list']")
for ulElement in ulElements {
let liElements = ulElement.childrenWithTagName("li")
// 这里是同一个对象
for liElement in liElements {
let goodsDetail = BCOGoodsDealInfo()
//日期
let divDateElements = liElement.searchWithXPathQuery("//div[@class='date']")
if let divDateElement = divDateElements.first as? TFHppleElement {
goodsDetail.date = divDateElement.content
}
//时间
let divTimeElements = liElement.searchWithXPathQuery("//div[@class='time']")
if let divTimeElement = divTimeElements.first as? TFHppleElement {
goodsDetail.time = divTimeElement.content
}
let divThumbElements = liElement.searchWithXPathQuery("//div[@class='thumb']")
if let divThumbElement = divThumbElements.first as? TFHppleElement {
//图片地址
let imgElements = divThumbElement.searchWithXPathQuery("//img")
if let imgElement = imgElements.first as? TFHppleElement {
goodsDetail.imageUrl = imgElement.objectForKey("src")
}
//商城
let spanElements = divThumbElement.searchWithXPathQuery("//span")
if let spanElement = spanElements.first as? TFHppleElement {
goodsDetail.source = spanElement.content
}
}
let h2Elements = liElement.searchWithXPathQuery("//h2[@class='title']")
let h2Element = h2Elements.first
if let aElements = h2Element?.searchWithXPathQuery("//a") {
if let aElement = aElements.first {
goodsDetail.title = aElement.text.description
goodsDetail.infoUrl = aElement.objectForKey("href")
}
}
//设置分类
goodsDetail.category = category
goodsDealArray.append(goodsDetail)
}
}
return goodsDealArray
}
//根据data 解析商品优惠详细信息
private static func goodsDealInfoWithHtmlData(data:NSData,introUrl:String) -> BCOGoodsDealInfo {
let realm = try! Realm()
let goodsDealInfo = realm.objectForPrimaryKey(BCOGoodsDealInfo.self, key: introUrl)
let html = TFHpple(HTMLData: data)
let ulElements = html.searchWithXPathQuery("//ul[@class='post-list post-content']")
//内容所在的ul
let ulElement = ulElements.first as! TFHppleElement
let divContentElements = ulElement.searchWithXPathQuery("//div[@class='content']")
//内容所在的div
let divContentElement = divContentElements.first as! TFHppleElement
//获取内容
let pContentElements = divContentElement.searchWithXPathQuery("//p")
//所有content
let elementArray = List<BCOGoodsDealContentElement>()
//单独存储Image的
let imageElementArray = List<BCOGoodsDealContentElement>()
let imgElements = divContentElement.searchWithXPathQuery("//img")
let srcDict = NSMutableDictionary()
for imageElement in imgElements {
let imageHppleElement = imageElement as! TFHppleElement
let contentElement = BCOGoodsDealContentElement()
//只拿没有添加过的图片地址
let src = imageHppleElement.objectForKey("src")
if let _ = srcDict.objectForKey(src) {
print("已包含该图片")
}else{
contentElement.elementType = BCOGoodsDealContentElementType.Image.rawValue
contentElement.imgUrl = (imageHppleElement.objectForKey("src"))!
imageElementArray.append(contentElement)
srcDict.setValue("", forKey: src)
}
}
//获取直达链接
var linkUrl = ""
let buyLinkDivElements = divContentElement.searchWithXPathQuery("//a[@rel='nofollow external']")
if buyLinkDivElements.count>0{
if let buyLinkElement = buyLinkDivElements.first as? TFHppleElement {
linkUrl = buyLinkElement.objectForKey("href")
}
}
//获取内容
for pContentElement in pContentElements! {
//分解每个内容
if(pContentElement.hasChildren()){
if let pContentHppleElement = pContentElement as? TFHppleElement {
let elements = pContentHppleElement.children
for newElement in elements {
let contentElement = BCOGoodsDealContentElement()
if(newElement.tagName == "a"){
contentElement.elementType = BCOGoodsDealContentElementType.Link.rawValue
contentElement.text = newElement.content
contentElement.linkUrl = (newElement.objectForKey("href"))
}else if(newElement.tagName == "img"){
contentElement.elementType = BCOGoodsDealContentElementType.Image.rawValue
contentElement.imgUrl = (newElement.objectForKey("src"))
}else if(newElement.tagName == "strong"){
if let hppleElement = newElement as? TFHppleElement {
if hppleElement.hasChildren(){
let subElement = hppleElement.firstChild
if(subElement.tagName == "a"){
contentElement.elementType = BCOGoodsDealContentElementType.Link.rawValue
contentElement.text = subElement.content
contentElement.linkUrl = (subElement.objectForKey("href"))
}else{
contentElement.elementType = BCOGoodsDealContentElementType.Text.rawValue
contentElement.text = subElement.content
}
}else{
if let hppleElement = newElement as? TFHppleElement {
contentElement.elementType = BCOGoodsDealContentElementType.Text.rawValue
contentElement.text = hppleElement.content
}
}
}
}else{
if let hppleElement = newElement as? TFHppleElement {
contentElement.elementType = BCOGoodsDealContentElementType.Text.rawValue
contentElement.text = hppleElement.content
}
}
elementArray.append(contentElement)
}
}
}else{
let contentElement = BCOGoodsDealContentElement()
contentElement.elementType = BCOGoodsDealContentElementType.Text.rawValue
contentElement.text = pContentElement.text.description
elementArray.append(contentElement)
}
//每个p标签最后,都需要添加换行
let contentElement = BCOGoodsDealContentElement()
contentElement.elementType = BCOGoodsDealContentElementType.Text.rawValue
contentElement.text = "\n\n"
elementArray.append(contentElement)
}
try! realm.write { () -> Void in
goodsDealInfo?.imageElementList.removeAll()
goodsDealInfo?.contentElementList.removeAll()
goodsDealInfo?.imageElementList.appendContentsOf(imageElementArray)
goodsDealInfo?.contentElementList.appendContentsOf(elementArray)
goodsDealInfo?.directLink = linkUrl
}
return goodsDealInfo!
}
//从本地数据库获取详情
private static func getGoodsDealInfoFormDBWithUrl(infoUrl:String) -> BCOGoodsDealInfo? {
let realm = try! Realm()
let goodsDealInfoList = realm.objects(BCOGoodsDealInfo.self).filter("infoUrl = %@", infoUrl).filter { (goodsDealInfo:BCOGoodsDealInfo) -> Bool in
if goodsDealInfo.contentElementList.count>0 {
return true
}
return false
}
return goodsDealInfoList.first;
}
//清除数据
static func removeData(){
let realm = try! Realm()
try! realm.write { () -> Void in
let willDeleteArray = self.getGoodsDealExceptCollected()
realm.delete(willDeleteArray)
}
}
}
<file_sep>//
// BCOGoodsDealCollectionService.swift
// baicaio
//
// Created by JimBo on 15/12/29.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import RealmSwift
class BCOGoodsDealCollectionService: NSObject {
static func isCollected(infoUrl:String) -> Bool {
let realm = try! Realm()
if let _ = realm.objectForPrimaryKey(BCOGoodsDealCollected.self, key: infoUrl) {
return true
}
return false
}
static func doCollection(infoUrl:String){
let item = BCOGoodsDealCollected()
item.infoUrl = infoUrl
item.collectedDate = NSDate()
let realm = try! Realm()
try! realm.write { () -> Void in
realm.add(item, update: true)
}
}
static func removeCollection(infoUrl:String){
let item = BCOGoodsDealCollected()
item.infoUrl = infoUrl
let realm = try! Realm()
if let item = realm.objectForPrimaryKey(BCOGoodsDealCollected.self, key: infoUrl) {
try! realm.write { () -> Void in
realm.delete(item)
}
}
}
static func getCollectedGoodDealList() -> List<BCOGoodsDealInfo> {
let realm = try! Realm()
let collectedGoodsDealList = realm.objects(BCOGoodsDealCollected).sorted("collectedDate",ascending:false)
let sqlStr = NSMutableString()
sqlStr.appendString("infoUrl in {")
for item in collectedGoodsDealList {
sqlStr.appendString("'\(item.infoUrl)'")
if collectedGoodsDealList.last != item {
sqlStr.appendString(",")
}
}
sqlStr.appendString("}")
let result = realm.objects(BCOGoodsDealInfo.self).filter(sqlStr as String)
//倒叙
let resultArray = result.reverse()
let list = List<BCOGoodsDealInfo>()
list.appendContentsOf(resultArray)
return list;
}
}
<file_sep>//
// BCOUtil.swift
// baicaio
//
// Created by JimBo on 16/1/4.
// Copyright © 2016年 JimBo. All rights reserved.
//
import UIKit
import RealmSwift
import Kingfisher
class BCOUtil: NSObject {
static func cacheSize() -> Int {
var imageCacheSize = 0
do {
let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(KingfisherManager.sharedManager.cache.diskCachePath)
if let _attr = attr {
imageCacheSize = Int(_attr.fileSize())
}
} catch {
}
let realm = try! Realm()
let fileManager = NSFileManager.defaultManager()
let fileAttributes = try! fileManager.attributesOfItemAtPath(realm.path)
let realmSize = fileAttributes["NSFileSize"] as! Int
return imageCacheSize+realmSize
}
static func clearCache(){
KingfisherManager.sharedManager.cache.clearDiskCache()
// let realm = try! Realm()
// try! realm.write { () -> Void in
// realm.delete(realm.objects(BCOSearchHistory.self))
// }
}
}
<file_sep>//
// BCOGoodsTableViewCell
// baicaio
//
// Created by JimBo on 15/12/26.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import Kingfisher
class BCOGoodsTableViewCell: UITableViewCell {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var goodsImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var soureLabel: UILabel!
var goodsDealInfo = BCOGoodsDealInfo()
override func awakeFromNib() {
super.awakeFromNib()
self.containerView.layer.cornerRadius = 4
self.containerView.layer.masksToBounds = true
self.selectedBackgroundView = UIView(frame: self.containerView.frame)
}
func setupCellWithGoodsDealInfo(goodsDealInfo:BCOGoodsDealInfo){
self.goodsImageView.kf_cancelDownloadTask()
self.goodsDealInfo = goodsDealInfo
if goodsDealInfo.imageUrl.hasPrefix("http://") {
self.goodsImageView.kf_setImageWithURL(NSURL(string: goodsDealInfo.imageUrl)!, placeholderImage: nil)
}else {
self.goodsImageView.image = nil
}
titleLabel.text = goodsDealInfo.title
soureLabel.text = goodsDealInfo.source + " | " + goodsDealInfo.date + " " + goodsDealInfo.time
}
}
<file_sep>//
// UIImage+Color.swift
// baicaio
//
// Created by JimBo on 15/12/25.
// Copyright © 2015年 JimBo. All rights reserved.
//
import Foundation
public extension UIImage{
public static func imageWithColor(color:UIColor,withFrame frame:CGRect)->UIImage{
UIGraphicsBeginImageContext(frame.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, frame)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
public static func imageWithColor(color:UIColor)->UIImage{
return UIImage.imageWithColor(color, withFrame: CGRectMake(0, 0, 1, 1))
}
}<file_sep>//
// BCOHomeViewController.swift
// baicaio
//
// Created by JimBo on 15/12/25.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
class BCOHomeViewController: YZDisplayViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setUpAllViewController()
self.setUpTitleView()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.dd(self.view)
}
func setUpTitleView(){
self.titleFont = UIFont.systemFontOfSize(15)
self.setUpTitleGradient { (isShowTitleGradient:UnsafeMutablePointer<ObjCBool>,titleColorGradientStyle:UnsafeMutablePointer<YZTitleColorGradientStyle>,startR:UnsafeMutablePointer<CGFloat>,startG:UnsafeMutablePointer<CGFloat>,startB:UnsafeMutablePointer<CGFloat>,endR:UnsafeMutablePointer<CGFloat>,endG:UnsafeMutablePointer<CGFloat>,endB:UnsafeMutablePointer<CGFloat>) -> Void in
titleColorGradientStyle.initialize(YZTitleColorGradientStyleRGB)
isShowTitleGradient.initialize(true)
startR.initialize(0.76)
startG.initialize(0.76)
startB.initialize(0.76)
endR.initialize(0.29)
endG.initialize(0.63)
endB.initialize(0.27)
}
self.setUpTitleScale { (isShowTitleScale:UnsafeMutablePointer<ObjCBool>,titleScale:UnsafeMutablePointer<CGFloat>) -> Void in
isShowTitleScale.initialize(true)
titleScale.initialize(1.13)
}
}
func setUpAllViewController(){
let homeViewController = Storyboards.Main.instantiateGoodsTableViewController()
homeViewController.title = "首页"
homeViewController.requestURLString = "http://www.baicaio.com/"
homeViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(homeViewController)
let ghhzViewController = Storyboards.Main.instantiateGoodsTableViewController()
ghhzViewController.title = "个护化妆"
ghhzViewController.requestURLString = "http://www.baicaio.com/topics/ghhz/"
ghhzViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(ghhzViewController)
let bjysViewController = Storyboards.Main.instantiateGoodsTableViewController()
bjysViewController.title = "保健养生"
bjysViewController.requestURLString = "http://www.baicaio.com/topics/bjys/"
bjysViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(bjysViewController)
let smjdViewController = Storyboards.Main.instantiateGoodsTableViewController()
smjdViewController.title = "数码家电"
smjdViewController.requestURLString = "http://www.baicaio.com/topics/smjd/"
smjdViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(smjdViewController)
let fzxhViewController = Storyboards.Main.instantiateGoodsTableViewController()
fzxhViewController.title = "服装鞋帽"
fzxhViewController.requestURLString = "http://www.baicaio.com/topics/fzxm/"
fzxhViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(fzxhViewController)
let xbsdViewController = Storyboards.Main.instantiateGoodsTableViewController()
xbsdViewController.title = "箱包手袋"
xbsdViewController.requestURLString = "http://www.baicaio.com/topics/xbsd/"
xbsdViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(xbsdViewController)
let zbssViewController = Storyboards.Main.instantiateGoodsTableViewController()
zbssViewController.title = "钟表首饰"
zbssViewController.requestURLString = "http://www.baicaio.com/topics/zbss/"
zbssViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(zbssViewController)
let mywjViewController = Storyboards.Main.instantiateGoodsTableViewController()
mywjViewController.title = "母婴玩具"
mywjViewController.requestURLString = "http://www.baicaio.com/topics/mywj/"
mywjViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(mywjViewController)
let rybhViewController = Storyboards.Main.instantiateGoodsTableViewController()
rybhViewController.title = "日用百货"
rybhViewController.requestURLString = "http://www.baicaio.com/topics/rybh/"
rybhViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(rybhViewController)
let spjyViewController = Storyboards.Main.instantiateGoodsTableViewController()
spjyViewController.title = "食品酒饮"
spjyViewController.requestURLString = "http://www.baicaio.com/topics/spjy/"
spjyViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(spjyViewController)
let tsyxViewController = Storyboards.Main.instantiateGoodsTableViewController()
tsyxViewController.title = "图书音像"
tsyxViewController.requestURLString = "http://www.baicaio.com/topics/tsyx/"
tsyxViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoList
self.addChildViewController(tsyxViewController)
}
func dd(view:UIView){
for subView in view.subviews {
self.dd(subView)
if subView.isKindOfClass(UIScrollView) && (subView as! UIScrollView).scrollsToTop{
print(subView)
}
}
}
}
<file_sep>//
// TipViewController.swift
// baicaio
//
// Created by JimBo on 16/1/11.
// Copyright © 2016年 JimBo. All rights reserved.
//
import UIKit
import MessageUI
enum TipViewActionType:Int {
case None = 0
case Error = 1999
}
class TipViewController: UIViewController,MFMailComposeViewControllerDelegate {
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var contentLabel: UILabel!
var content:String? = ""
var actionType:TipViewActionType = .None
override func viewDidLoad() {
super.viewDidLoad()
self.contentLabel.text = self.content;
guard self.actionType == .Error else{
self.actionButton.titleLabel?.text = "申请使用测试版"
self.actionButton.hidden = true
return
}
self.actionButton.hidden = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
self.setNeedsStatusBarAppearanceUpdate()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
self.setNeedsStatusBarAppearanceUpdate()
}
func setup(content:String?,actionType:TipViewActionType){
self.content = content;
self.actionType = actionType
}
@IBAction func actionButtonTouched(sender: AnyObject) {
if MFMailComposeViewController.canSendMail() {
let mailComposeVC = MFMailComposeViewController()
mailComposeVC.mailComposeDelegate = self
mailComposeVC.setToRecipients(["<EMAIL>"])
mailComposeVC.setSubject("[白菜哦] 反馈")
self.presentViewController(mailComposeVC, animated:true, completion: nil)
}
}
@IBAction func closeButtonTouched(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
//MARK - 邮件代理
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
return
}
}
<file_sep>//
// BCOGoodsDealContentElement.swift
// baicaio
//
// Created by JimBo on 15/12/27.
// Copyright © 2015年 JimBo. All rights reserved.
//
import Foundation
import RealmSwift
enum BCOGoodsDealContentElementType:Int{
case Text = 0,Link,Image
}
class BCOGoodsDealContentElement: Object {
dynamic var elementType = 0
dynamic var text = ""
dynamic var linkUrl = ""
dynamic var imgUrl = ""
dynamic var width = 0
dynamic var height = 0
}
<file_sep>//
// BCOGoodsDealCollectedGoodsDeal.swift
// baicaio
//
// Created by JimBo on 15/12/29.
// Copyright © 2015年 JimBo. All rights reserved.
//
import Foundation
import RealmSwift
class BCOGoodsDealCollected: Object {
dynamic var infoUrl = ""
dynamic var collectedDate:NSDate = NSDate()
override static func primaryKey() -> String? {
return "infoUrl"
}
}
<file_sep>//
// UIView+ViewController.swift
// baicaio
//
// Created by JimBo on 15/12/29.
// Copyright © 2015年 JimBo. All rights reserved.
//
import Foundation
public extension UIView{
func findViewController() -> UIViewController? {
for(var next = self.superview;(next != nil);next=next?.superview){
let nextResponder = next?.nextResponder()
if nextResponder!.isKindOfClass(UIViewController.self) {
return nextResponder as? UIViewController
}
}
return nil
}
}<file_sep>//
// BCOSearchViewController.swift
// baicaio
//
// Created by JimBo on 15/12/30.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import RealmSwift
class BCOSearchViewController: UIViewController,UISearchBarDelegate{
var searchBar:UISearchBar = UISearchBar()
var searchHistoryList = List<BCOSearchHistory>()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
self.tableView.tableHeaderView = UIView()
self.searchBar = UISearchBar(frame: CGRectMake(0,0,BCOConfig.screenWidth-30,20))
searchBar.placeholder = "请输入"
searchBar.setValue("取消", forKeyPath: "_cancelButtonText")
searchBar.showsCancelButton = true
searchBar.delegate = self
searchBar.tintColor = UIColor.blackColor()
self.searchBar.becomeFirstResponder()
self.navigationItem.titleView = searchBar
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.searchHistoryList = BCOSearchHistoryService.getSearchHistory()
self.tableView.reloadData()
self.searchBar.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
//查询
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
self.search(searchBar.text!)
}
func search(searchString:String!){
self.searchBar.setValue(searchString, forKeyPath: "text")
BCOSearchHistoryService.saveSearchHistory(searchString)
let homeViewController = Storyboards.Main.instantiateGoodsTableViewController()
homeViewController.title = searchString
homeViewController.requestURLString = "http://www.baicaio.com/?s=\(searchString)"
homeViewController.viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoListForSearch
self.navigationController?.pushViewController(homeViewController, animated: true)
}
}
extension BCOSearchViewController:UITableViewDelegate,UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchHistoryList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SearchCellIdentifier", forIndexPath: indexPath)
let searchHistory = self.searchHistoryList[indexPath.row]
cell.textLabel?.text = searchHistory.search
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let searchHistory = self.searchHistoryList[indexPath.row]
self.search(searchHistory.search)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "搜索历史"
}
}
<file_sep>//
// BCOFeedbackViewController.swift
// baicaio
//
// Created by JimBo on 16/1/11.
// Copyright © 2016年 JimBo. All rights reserved.
//
import UIKit
import MessageUI
class BCOFeedbackViewController: UIViewController,MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func feedbackButtonTouched(sender: UIButton) {
if MFMailComposeViewController.canSendMail() {
let mailComposeVC = MFMailComposeViewController()
mailComposeVC.mailComposeDelegate = self
mailComposeVC.setToRecipients(["<EMAIL>"])
mailComposeVC.setSubject("[白菜哦] 反馈")
self.presentViewController(mailComposeVC, animated:true, completion: nil)
}
}
//MARK - 邮件代理
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
return
}
}
<file_sep>//
// BCOGoodsTableViewController.swift
// baicaio
//
// Created by JimBo on 15/12/25.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import RealmSwift
import MJRefresh
import JDStatusBarNotification
enum BCOGoodsTableViewControllerShowType:Int{
case GoodsDealInfoCollectedList = 0, GoodsDealInfoList,GoodsDealInfoListForSearch
}
class BCOGoodsTableViewController: UITableViewController {
var goodsDealArray = List<BCOGoodsDealInfo>()
var requestURLString = "http://www.baicaio.com/"
var willLoadPage = 1
var viewType = BCOGoodsTableViewControllerShowType.GoodsDealInfoCollectedList
override func viewDidLoad() {
super.viewDidLoad()
self.setupTableView()
if self.viewType == .GoodsDealInfoListForSearch {
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.scrollsToTop = true
if self.viewType == BCOGoodsTableViewControllerShowType.GoodsDealInfoCollectedList {
self.tableView.mj_header.beginRefreshing()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.tableView.scrollsToTop = false
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.goodsDealArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let goodsCell = tableView.dequeueReusableCell(BCOGoodsTableViewController.Reusable.GoodsTableViewCellIdentifier, forIndexPath: indexPath) as! BCOGoodsTableViewCell
goodsCell.setupCellWithGoodsDealInfo(self.goodsDealArray[indexPath.row])
return goodsCell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
//如果是收藏界面,则允许删除
if self.viewType == .GoodsDealInfoCollectedList {
return true
}else {
return false
}
}
override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
return "删除"
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
//移除收藏,删除这一行
let goodsDealInfo = self.goodsDealArray[indexPath.row]
BCOGoodsDealCollectionService.removeCollection(goodsDealInfo.infoUrl)
self.goodsDealArray.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 120
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.5
}
//segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == BCOGoodsTableViewController.Segue.ShowGoodsDealInfoSegue {
let viewController = segue.destinationViewController as! BCOGoodsInfoViewController
let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell)
let goodsDealInfo = self.goodsDealArray[indexPath!.row]
viewController.goodsDealIntroUrl = goodsDealInfo.infoUrl
}
}
//MARK - load data
func loadData(){
//默认,从网络获取
if (self.viewType == BCOGoodsTableViewControllerShowType.GoodsDealInfoList||self.viewType == BCOGoodsTableViewControllerShowType.GoodsDealInfoListForSearch){
var category = self.title!
if self.viewType == BCOGoodsTableViewControllerShowType.GoodsDealInfoListForSearch {
category = "搜索"
}
BCOGetGoodsDealsService.getGoodsDetalList(self.requestURLString, pageOfCagegoty: self.willLoadPage,category: category) { (goodsDealArray:List<BCOGoodsDealInfo>?, error:NSError?) -> Void in
if let newGoodsDealArray = goodsDealArray {
if self.willLoadPage == 1 {
self.goodsDealArray.removeAll()
}
self.willLoadPage++
self.goodsDealArray.appendContentsOf(newGoodsDealArray)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
if (error != nil) {
self.tableView.mj_footer.removeFromSuperview();
JDStatusBarNotification.showWithStatus(error?.domain, dismissAfter: 1.0, styleName: JDStatusBarStyleSuccess)
}else{
self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadData")
}
})
}
}
}else{
//查看收藏夹
self.goodsDealArray = BCOGoodsDealCollectionService.getCollectedGoodDealList()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
self.tableView.mj_footer.removeFromSuperview()
})
}
}
// MARK - scroll view delegate
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.tableView.showsVerticalScrollIndicator = true
}
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.tableView.showsVerticalScrollIndicator = false
}
//MARK - setup tableView
func setupTableView(){
self.tableView.separatorStyle = .None
self.tableView.showsVerticalScrollIndicator = false
self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadData")
self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadData")
self.tableView.mj_header.beginRefreshing()
}
}
<file_sep>#!/usr/bin/env xcrun -sdk macosx swift
//
// Natalie - Storyboard Generator Script
//
// Generate swift file based on storyboard files
//
// Usage:
// natalie.swift Main.storyboard > Storyboards.swift
// natalie.swift path/toproject/with/storyboards > Storyboards.swift
//
// Licence: MIT
// Author: <NAME> http://blog.krzyzanowskim.com
//
//MARK: SWXMLHash
//
// SWXMLHash.swift
//
// Copyright (c) 2014 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
//MARK: Extensions
private extension String {
func trimAllWhitespacesAndSpecialCharacters() -> String {
let invalidCharacters = NSCharacterSet.alphanumericCharacterSet().invertedSet
let x = self.componentsSeparatedByCharactersInSet(invalidCharacters)
return x.joinWithSeparator("")
}
}
private func SwiftRepresentationForString(string: String, capitalizeFirstLetter: Bool = false, doNotShadow: String? = nil) -> String {
var str = string.trimAllWhitespacesAndSpecialCharacters()
if capitalizeFirstLetter {
str = String(str.uppercaseString.unicodeScalars.prefix(1) + str.unicodeScalars.suffix(str.unicodeScalars.count - 1))
}
if str == doNotShadow {
str = str + "_"
}
return str
}
//MARK: Parser
let rootElementName = "SWXMLHash_Root_Element"
/// Simple XML parser.
public class SWXMLHash {
/**
Method to parse XML passed in as a string.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(xml: String) -> XMLIndexer {
return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
/**
Method to parse XML passed in as an NSData instance.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(data: NSData) -> XMLIndexer {
let parser = XMLParser()
return parser.parse(data)
}
class public func lazy(xml: String) -> XMLIndexer {
return lazy((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
class public func lazy(data: NSData) -> XMLIndexer {
let parser = LazyXMLParser()
return parser.parse(data)
}
}
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
mutating func removeAll() {
items.removeAll(keepCapacity: false)
}
func top() -> T {
return items[items.count - 1]
}
}
class LazyXMLParser: NSObject, NSXMLParserDelegate {
override init() {
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
var elementStack = Stack<String>()
var data: NSData?
var ops: [IndexOp] = []
func parse(data: NSData) -> XMLIndexer {
self.data = data
return XMLIndexer(self)
}
func startParsing(ops: [IndexOp]) {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
root = XMLElement(name: rootElementName)
parentStack.push(root)
self.ops = ops
let parser = NSXMLParser(data: data!)
parser.delegate = self
parser.parse()
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) {
elementStack.push(elementName)
if !onMatch() {
return
}
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if !onMatch() {
return
}
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
let match = onMatch()
elementStack.pop()
if match {
parentStack.pop()
}
}
func onMatch() -> Bool {
// we typically want to compare against the elementStack to see if it matches ops, *but*
// if we're on the first element, we'll instead compare the other direction.
if elementStack.items.count > ops.count {
return elementStack.items.startsWith(ops.map { $0.key })
}
else {
return ops.map { $0.key }.startsWith(elementStack.items)
}
}
}
/// The implementation of NSXMLParserDelegate and where the parsing actually happens.
class XMLParser: NSObject, NSXMLParserDelegate {
override init() {
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
func parse(data: NSData) -> XMLIndexer {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
parentStack.push(root)
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.parse()
return XMLIndexer(root)
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) {
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
parentStack.pop()
}
}
public class IndexOp {
var index: Int
let key: String
init(_ key: String) {
self.key = key
self.index = -1
}
func toString() -> String {
if index >= 0 {
return key + " " + index.description
}
return key
}
}
public class IndexOps {
var ops: [IndexOp] = []
let parser: LazyXMLParser
init(parser: LazyXMLParser) {
self.parser = parser
}
func findElements() -> XMLIndexer {
parser.startParsing(ops)
let indexer = XMLIndexer(parser.root)
var childIndex = indexer
for op in ops {
childIndex = childIndex[op.key]
if op.index >= 0 {
childIndex = childIndex[op.index]
}
}
ops.removeAll(keepCapacity: false)
return childIndex
}
func stringify() -> String {
var s = ""
for op in ops {
s += "[" + op.toString() + "]"
}
return s
}
}
/// Returned from SWXMLHash, allows easy element lookup into XML data.
public enum XMLIndexer: SequenceType {
case Element(XMLElement)
case List([XMLElement])
case Stream(IndexOps)
case Error(NSError)
/// The underlying XMLElement at the currently indexed level of XML.
public var element: XMLElement? {
get {
switch self {
case .Element(let elem):
return elem
case .Stream(let ops):
let list = ops.findElements()
return list.element
default:
return nil
}
}
}
/// All elements at the currently indexed level
public var all: [XMLIndexer] {
get {
switch self {
case .List(let list):
var xmlList = [XMLIndexer]()
for elem in list {
xmlList.append(XMLIndexer(elem))
}
return xmlList
case .Element(let elem):
return [XMLIndexer(elem)]
case .Stream(let ops):
let list = ops.findElements()
return list.all
default:
return []
}
}
}
/// All child elements from the currently indexed level
public var children: [XMLIndexer] {
get {
var list = [XMLIndexer]()
for elem in all.map({ $0.element! }) {
for elem in elem.children {
list.append(XMLIndexer(elem))
}
}
return list
}
}
/**
Allows for element lookup by matching attribute values.
- parameter attr: should the name of the attribute to match on
- parameter _: should be the value of the attribute to match on
- returns: instance of XMLIndexer
*/
public func withAttr(attr: String, _ value: String) -> XMLIndexer {
let attrUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"]"]
let valueUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"]
switch self {
case .Stream(let opStream):
opStream.stringify()
let match = opStream.findElements()
return match.withAttr(attr, value)
case .List(let list):
if let elem = list.filter({ $0.attributes[attr] == value }).first {
return .Element(elem)
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo))
case .Element(let elem):
if let attr = elem.attributes[attr] {
if attr == value {
return .Element(elem)
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo))
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo))
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo))
}
}
/**
Initializes the XMLIndexer
- parameter _: should be an instance of XMLElement, but supports other values for error handling
- returns: instance of XMLIndexer
*/
public init(_ rawObject: AnyObject) {
switch rawObject {
case let value as XMLElement:
self = .Element(value)
case let value as LazyXMLParser:
self = .Stream(IndexOps(parser: value))
default:
self = .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: nil))
}
}
/**
Find an XML element at the current level by element name
- parameter key: The element name to index by
- returns: instance of XMLIndexer to match the element (or elements) found by key
*/
public subscript(key: String) -> XMLIndexer {
get {
let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect key [\"\(key)\"]"]
switch self {
case .Stream(let opStream):
let op = IndexOp(key)
opStream.ops.append(op)
return .Stream(opStream)
case .Element(let elem):
let match = elem.children.filter({ $0.name == key })
if match.count > 0 {
if match.count == 1 {
return .Element(match[0])
}
else {
return .List(match)
}
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
}
}
/**
Find an XML element by index within a list of XML Elements at the current level
- parameter index: The 0-based index to index by
- returns: instance of XMLIndexer to match the element (or elements) found by key
*/
public subscript(index: Int) -> XMLIndexer {
get {
let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect index [\"\(index)\"]"]
switch self {
case .Stream(let opStream):
opStream.ops[opStream.ops.count - 1].index = index
return .Stream(opStream)
case .List(let list):
if index <= list.count {
return .Element(list[index])
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
case .Element(let elem):
if index == 0 {
return .Element(elem)
}
else {
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
}
}
typealias GeneratorType = XMLIndexer
public func generate() -> IndexingGenerator<[XMLIndexer]> {
return all.generate()
}
}
/// XMLIndexer extensions
extension XMLIndexer: BooleanType {
/// True if a valid XMLIndexer, false if an error type
public var boolValue: Bool {
get {
switch self {
case .Error:
return false
default:
return true
}
}
}
}
extension XMLIndexer: CustomStringConvertible {
public var description: String {
get {
switch self {
case .List(let list):
return list.map { $0.description }.joinWithSeparator("\n")
case .Element(let elem):
if elem.name == rootElementName {
return elem.children.map { $0.description }.joinWithSeparator("\n")
}
return elem.description
default:
return ""
}
}
}
}
/// Models an XML element, including name, text and attributes
public class XMLElement {
/// The name of the element
public let name: String
/// The inner text of the element, if it exists
public var text: String?
/// The attributes of the element
public var attributes = [String:String]()
var children = [XMLElement]()
var count: Int = 0
var index: Int
/**
Initialize an XMLElement instance
- parameter name: The name of the element to be initialized
- returns: a new instance of XMLElement
*/
init(name: String, index: Int = 0) {
self.name = name
self.index = index
}
/**
Adds a new XMLElement underneath this instance of XMLElement
- parameter name: The name of the new element to be added
- parameter withAttributes: The attributes dictionary for the element being added
- returns: The XMLElement that has now been added
*/
func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement {
let element = XMLElement(name: name, index: count)
count++
children.append(element)
for (keyAny,valueAny) in attributes {
let key = keyAny as! String
let value = valueAny as! String
element.attributes[key] = value
}
return element
}
}
extension XMLElement: CustomStringConvertible {
public var description:String {
get {
var attributesStringList = [String]()
if !attributes.isEmpty {
for (key, val) in attributes {
attributesStringList.append("\(key)=\"\(val)\"")
}
}
var attributesString = attributesStringList.joinWithSeparator(" ")
if (!attributesString.isEmpty) {
attributesString = " " + attributesString
}
if children.count > 0 {
var xmlReturn = [String]()
xmlReturn.append("<\(name)\(attributesString)>")
for child in children {
xmlReturn.append(child.description)
}
xmlReturn.append("</\(name)>")
return xmlReturn.joinWithSeparator("\n")
}
if text != nil {
return "<\(name)\(attributesString)>\(text!)</\(name)>"
} else {
return "<\(name)\(attributesString)/>"
}
}
}
}
//MARK: - Natalie
//MARK: Objects
enum OS: String, CustomStringConvertible {
case iOS = "iOS"
case OSX = "OSX"
static let allValues = [iOS, OSX]
enum Runtime: String {
case iOSCocoaTouch = "iOS.CocoaTouch"
case MacOSXCocoa = "MacOSX.Cocoa"
init(os: OS) {
switch os {
case iOS:
self = .iOSCocoaTouch
case OSX:
self = .MacOSXCocoa
}
}
}
enum Framework: String {
case UIKit = "UIKit"
case Cocoa = "Cocoa"
init(os: OS) {
switch os {
case iOS:
self = .UIKit
case OSX:
self = .Cocoa
}
}
}
init(targetRuntime: String) {
switch (targetRuntime) {
case Runtime.iOSCocoaTouch.rawValue:
self = .iOS
case Runtime.MacOSXCocoa.rawValue:
self = .OSX
case "iOS.CocoaTouch.iPad":
self = iOS
default:
fatalError("Unsupported")
}
}
var description: String {
return self.rawValue
}
var framework: String {
return Framework(os: self).rawValue
}
var targetRuntime: String {
return Runtime(os: self).rawValue
}
var storyboardType: String {
switch self {
case iOS:
return "UIStoryboard"
case OSX:
return "NSStoryboard"
}
}
var storyboardSegueType: String {
switch self {
case iOS:
return "UIStoryboardSegue"
case OSX:
return "NSStoryboardSegue"
}
}
var storyboardControllerTypes: [String] {
switch self {
case iOS:
return ["UIViewController"]
case OSX:
return ["NSViewController", "NSWindowController"]
}
}
var storyboardControllerReturnType: String {
switch self {
case iOS:
return "UIViewController"
case OSX:
return "AnyObject" // NSViewController or NSWindowController
}
}
var storyboardControllerSignatureType: String {
switch self {
case iOS:
return "ViewController"
case OSX:
return "Controller" // NSViewController or NSWindowController
}
}
var storyboardInstantiationInfo: [(String /* Signature type */, String /* Return type */)] {
switch self {
case iOS:
return [("ViewController", "UIViewController")]
case OSX:
return [("WindowController", "NSWindowController"), ("ViewController", "NSViewController")]
}
}
var viewType: String {
switch self {
case iOS:
return "UIView"
case OSX:
return "NSView"
}
}
var resuableViews: [String]? {
switch self {
case iOS:
return ["UICollectionReusableView", "UITableViewCell"]
case OSX:
return nil
}
}
func controllerTypeForElementName(name: String) -> String? {
switch self {
case iOS:
switch name {
case "viewController":
return "UIViewController"
case "navigationController":
return "UINavigationController"
case "tableViewController":
return "UITableViewController"
case "tabBarController":
return "UITabBarController"
case "splitViewController":
return "UISplitViewController"
case "pageViewController":
return "UIPageViewController"
case "collectionViewController":
return "UICollectionViewController"
case "exit", "viewControllerPlaceholder":
return nil
default:
assertionFailure("Unknown controller element: \(name)")
return nil
}
case OSX:
switch name {
case "viewController":
return "NSViewController"
case "windowController":
return "NSWindowController"
case "pagecontroller":
return "NSPageController"
case "tabViewController":
return "NSTabViewController"
case "splitViewController":
return "NSSplitViewController"
case "exit", "viewControllerPlaceholder":
return nil
default:
assertionFailure("Unknown controller element: \(name)")
return nil
}
}
}
}
class XMLObject {
let xml: XMLIndexer
let name: String
init(xml: XMLIndexer) {
self.xml = xml
self.name = xml.element!.name
}
func searchAll(attributeKey: String, attributeValue: String? = nil) -> [XMLIndexer]? {
return searchAll(self.xml, attributeKey: attributeKey, attributeValue: attributeValue)
}
func searchAll(root: XMLIndexer, attributeKey: String, attributeValue: String? = nil) -> [XMLIndexer]? {
var result = Array<XMLIndexer>()
for child in root.children {
for childAtLevel in child.all {
if let attributeValue = attributeValue {
if let element = childAtLevel.element where element.attributes[attributeKey] == attributeValue {
result += [childAtLevel]
}
} else if let element = childAtLevel.element where element.attributes[attributeKey] != nil {
result += [childAtLevel]
}
if let found = searchAll(childAtLevel, attributeKey: attributeKey, attributeValue: attributeValue) {
result += found
}
}
}
return result.count > 0 ? result : nil
}
func searchNamed(name: String) -> [XMLIndexer]? {
return self.searchNamed(self.xml, name: name)
}
func searchNamed(root: XMLIndexer, name: String) -> [XMLIndexer]? {
var result = Array<XMLIndexer>()
for child in root.children {
for childAtLevel in child.all {
if let elementName = childAtLevel.element?.name where elementName == name {
result += [child]
}
if let found = searchNamed(childAtLevel, name: name) {
result += found
}
}
}
return result.count > 0 ? result : nil
}
func searchById(id: String) -> XMLIndexer? {
return searchAll("id", attributeValue: id)?.first
}
}
class Scene: XMLObject {
lazy var viewController: ViewController? = {
if let vcs = self.searchAll("sceneMemberID", attributeValue: "viewController"), vc = vcs.first {
return ViewController(xml: vc)
}
return nil
}()
lazy var segues: [Segue]? = {
return self.searchNamed("segue")?.map { Segue(xml: $0) }
}()
lazy var customModule: String? = self.viewController?.customModule
lazy var customModuleProvider: String? = self.viewController?.customModuleProvider
}
class ViewController: XMLObject {
lazy var customClass: String? = self.xml.element?.attributes["customClass"]
lazy var customModuleProvider: String? = self.xml.element?.attributes["customModuleProvider"]
lazy var storyboardIdentifier: String? = self.xml.element?.attributes["storyboardIdentifier"]
lazy var customModule: String? = self.xml.element?.attributes["customModule"]
lazy var reusables: [Reusable]? = {
if let reusables = self.searchAll(self.xml, attributeKey: "reuseIdentifier"){
return reusables.map { Reusable(xml: $0) }
}
return nil
}()
}
class Segue: XMLObject {
let kind: String
let identifier: String?
lazy var destination: String? = self.xml.element?.attributes["destination"]
override init(xml: XMLIndexer) {
self.kind = xml.element!.attributes["kind"]!
if let id = xml.element?.attributes["identifier"] where id.characters.count > 0 {self.identifier = id}
else {self.identifier = nil}
super.init(xml: xml)
}
}
class Reusable: XMLObject {
let kind: String
lazy var reuseIdentifier: String? = self.xml.element?.attributes["reuseIdentifier"]
lazy var customClass: String? = self.xml.element?.attributes["customClass"]
override init(xml: XMLIndexer) {
kind = xml.element!.name
super.init(xml: xml)
}
}
class Storyboard: XMLObject {
let version: String
lazy var os:OS = {
guard let targetRuntime = self.xml["document"].element?.attributes["targetRuntime"] else {
return OS.iOS
}
return OS(targetRuntime: targetRuntime)
}()
lazy var initialViewControllerClass: String? = {
if let initialViewControllerId = self.xml["document"].element?.attributes["initialViewController"],
let xmlVC = self.searchById(initialViewControllerId)
{
let vc = ViewController(xml: xmlVC)
if let customClassName = vc.customClass {
return customClassName
}
if let controllerType = self.os.controllerTypeForElementName(vc.name) {
return controllerType
}
}
return nil
}()
lazy var scenes: [Scene] = {
guard let scenes = self.searchAll(self.xml, attributeKey: "sceneID") else {
return []
}
return scenes.map { Scene(xml: $0) }
}()
lazy var customModules: [String] = self.scenes.filter{ $0.customModule != nil && $0.customModuleProvider == nil }.map{ $0.customModule! }
override init(xml: XMLIndexer) {
self.version = xml["document"].element!.attributes["version"]!
super.init(xml: xml)
}
func processStoryboard(storyboardName: String, os: OS) {
print("")
print(" struct \(storyboardName): Storyboard {")
print("")
print(" static let identifier = \"\(storyboardName)\"")
print("")
print(" static var storyboard: \(os.storyboardType) {")
print(" return \(os.storyboardType)(name: self.identifier, bundle: nil)")
print(" }")
if let initialViewControllerClass = self.initialViewControllerClass {
let cast = (initialViewControllerClass == os.storyboardControllerReturnType ? (os == OS.iOS ? "!" : "") : " as! \(initialViewControllerClass)")
print("")
print(" static func instantiateInitial\(os.storyboardControllerSignatureType)() -> \(initialViewControllerClass) {")
print(" return self.storyboard.instantiateInitial\(os.storyboardControllerSignatureType)()\(cast)")
print(" }")
}
for (signatureType, returnType) in os.storyboardInstantiationInfo {
let cast = (returnType == os.storyboardControllerReturnType ? "" : " as! \(returnType)")
print("")
print(" static func instantiate\(signatureType)WithIdentifier(identifier: String) -> \(returnType) {")
print(" return self.storyboard.instantiate\(signatureType)WithIdentifier(identifier)\(cast)")
print(" }")
print("")
print(" static func instantiateViewController<T: \(returnType) where T: IdentifiableProtocol>(type: T.Type) -> T? {")
print(" return self.storyboard.instantiateViewController(type)")
print(" }")
}
for scene in self.scenes {
if let viewController = scene.viewController, storyboardIdentifier = viewController.storyboardIdentifier {
let controllerClass = (viewController.customClass ?? os.controllerTypeForElementName(viewController.name)!)
print("")
print(" static func instantiate\(SwiftRepresentationForString(storyboardIdentifier, capitalizeFirstLetter: true))() -> \(controllerClass) {")
print(" return self.storyboard.instantiate\(os.storyboardControllerSignatureType)WithIdentifier(\"\(storyboardIdentifier)\") as! \(controllerClass)")
print(" }")
}
}
print(" }")
}
func processViewControllers() {
for scene in self.scenes {
if let viewController = scene.viewController {
if let customClass = viewController.customClass {
print("")
print("//MARK: - \(customClass)")
if let segues = scene.segues?.filter({ return $0.identifier != nil })
where segues.count > 0 {
print("extension \(os.storyboardSegueType) {")
print(" func selection() -> \(customClass).Segue? {")
print(" if let identifier = self.identifier {")
print(" return \(customClass).Segue(rawValue: identifier)")
print(" }")
print(" return nil")
print(" }")
print("}")
print("")
}
if let storyboardIdentifier = viewController.storyboardIdentifier {
print("extension \(customClass): IdentifiableProtocol { ")
if viewController.customModule != nil {
print(" var storyboardIdentifier: String? { return \"\(storyboardIdentifier)\" }")
} else {
print(" public var storyboardIdentifier: String? { return \"\(storyboardIdentifier)\" }")
}
print(" static var storyboardIdentifier: String? { return \"\(storyboardIdentifier)\" }")
print("}")
print("")
}
if let segues = scene.segues?.filter({ return $0.identifier != nil })
where segues.count > 0 {
print("extension \(customClass) { ")
print("")
print(" enum Segue: String, CustomStringConvertible, SegueProtocol {")
for segue in segues {
if let identifier = segue.identifier
{
print(" case \(SwiftRepresentationForString(identifier)) = \"\(identifier)\"")
}
}
print("")
print(" var kind: SegueKind? {")
print(" switch (self) {")
var needDefaultSegue = false
for segue in segues {
if let identifier = segue.identifier {
print(" case \(SwiftRepresentationForString(identifier)):")
print(" return SegueKind(rawValue: \"\(segue.kind)\")")
} else {
needDefaultSegue = true
}
}
if needDefaultSegue {
print(" default:")
print(" assertionFailure(\"Invalid value\")")
print(" return nil")
}
print(" }")
print(" }")
print("")
print(" var destination: \(self.os.storyboardControllerReturnType).Type? {")
print(" switch (self) {")
var needDefaultDestination = false
for segue in segues {
if let identifier = segue.identifier, destination = segue.destination,
destinationElement = searchById(destination)?.element,
destinationClass = (destinationElement.attributes["customClass"] ?? os.controllerTypeForElementName(destinationElement.name))
{
print(" case \(SwiftRepresentationForString(identifier)):")
print(" return \(destinationClass).self")
} else {
needDefaultDestination = true
}
}
if needDefaultDestination {
print(" default:")
print(" assertionFailure(\"Unknown destination\")")
print(" return nil")
}
print(" }")
print(" }")
print("")
print(" var identifier: String? { return self.description } ")
print(" var description: String { return self.rawValue }")
print(" }")
print("")
print("}")
}
if let reusables = viewController.reusables?.filter({ return $0.reuseIdentifier != nil })
where reusables.count > 0 {
print("extension \(customClass) { ")
print("")
print(" enum Reusable: String, CustomStringConvertible, ReusableViewProtocol {")
for reusable in reusables {
if let identifier = reusable.reuseIdentifier {
print(" case \(SwiftRepresentationForString(identifier, doNotShadow: reusable.customClass)) = \"\(identifier)\"")
}
}
print("")
print(" var kind: ReusableKind? {")
print(" switch (self) {")
var needDefault = false
for reusable in reusables {
if let identifier = reusable.reuseIdentifier {
print(" case \(SwiftRepresentationForString(identifier, doNotShadow: reusable.customClass)):")
print(" return ReusableKind(rawValue: \"\(reusable.kind)\")")
} else {
needDefault = true
}
}
if needDefault {
print(" default:")
print(" preconditionFailure(\"Invalid value\")")
print(" break")
}
print(" }")
print(" }")
print("")
print(" var viewType: \(self.os.viewType).Type? {")
print(" switch (self) {")
needDefault = false
for reusable in reusables {
if let identifier = reusable.reuseIdentifier, customClass = reusable.customClass {
print(" case \(SwiftRepresentationForString(identifier, doNotShadow: reusable.customClass)):")
print(" return \(customClass).self")
} else {
needDefault = true
}
}
if needDefault {
print(" default:")
print(" return nil")
}
print(" }")
print(" }")
print("")
print(" var storyboardIdentifier: String? { return self.description } ")
print(" var description: String { return self.rawValue }")
print(" }")
print("")
print("}\n")
}
}
}
}
}
}
class StoryboardFile {
let data: NSData
let storyboardName: String
let storyboard: Storyboard
init(filePath: String) {
self.data = NSData(contentsOfFile: filePath)!
self.storyboardName = ((filePath as NSString).lastPathComponent as NSString).stringByDeletingPathExtension
self.storyboard = Storyboard(xml:SWXMLHash.parse(self.data))
}
}
//MARK: Functions
func findStoryboards(rootPath: String, suffix: String) -> [String]? {
var result = Array<String>()
let fm = NSFileManager.defaultManager()
if let paths = fm.subpathsAtPath(rootPath) {
let storyboardPaths = paths.filter({ return $0.hasSuffix(suffix)})
// result = storyboardPaths
for p in storyboardPaths {
result.append((rootPath as NSString).stringByAppendingPathComponent(p))
}
}
return result.count > 0 ? result : nil
}
func processStoryboards(storyboards: [StoryboardFile], os: OS) {
print("//")
print("// Autogenerated by Natalie - Storyboard Generator Script.")
print("// http://blog.krzyzanowskim.com")
print("//")
print("")
print("import \(os.framework)")
let modules = storyboards.flatMap{ $0.storyboard.customModules }
for module in Set<String>(modules) {
print("import \(module)")
}
print("")
print("//MARK: - Storyboards")
print("")
print("extension \(os.storyboardType) {")
for (signatureType, returnType) in os.storyboardInstantiationInfo {
print(" func instantiateViewController<T: \(returnType) where T: IdentifiableProtocol>(type: T.Type) -> T? {")
print(" let instance = type.init()")
print(" if let identifier = instance.storyboardIdentifier {")
print(" return self.instantiate\(signatureType)WithIdentifier(identifier) as? T")
print(" }")
print(" return nil")
print(" }")
print("}")
print("")
}
print("")
print("protocol Storyboard {")
print(" static var storyboard: \(os.storyboardType) { get }")
print(" static var identifier: String { get }")
print("}")
print("")
print("struct Storyboards {")
for file in storyboards {
file.storyboard.processStoryboard(file.storyboardName, os: os)
}
print("}")
print("")
print("//MARK: - ReusableKind")
print("enum ReusableKind: String, CustomStringConvertible {")
print(" case TableViewCell = \"tableViewCell\"")
print(" case CollectionViewCell = \"collectionViewCell\"")
print("")
print(" var description: String { return self.rawValue }")
print("}")
print("")
print("//MARK: - SegueKind")
print("enum SegueKind: String, CustomStringConvertible { ")
print(" case Relationship = \"relationship\" ")
print(" case Show = \"show\" ")
print(" case Presentation = \"presentation\" ")
print(" case Embed = \"embed\" ")
print(" case Unwind = \"unwind\" ")
print(" case Push = \"push\" ")
print(" case Modal = \"modal\" ")
print(" case Popover = \"popover\" ")
print(" case Replace = \"replace\" ")
print(" case Custom = \"custom\" ")
print("")
print(" var description: String { return self.rawValue } ")
print("}")
print("")
print("//MARK: - IdentifiableProtocol")
print("")
print("public protocol IdentifiableProtocol: Equatable {")
print(" var storyboardIdentifier: String? { get }")
print("}")
print("")
print("//MARK: - SegueProtocol")
print("")
print("public protocol SegueProtocol {")
print(" var identifier: String? { get }")
print("}")
print("")
print("public func ==<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {")
print(" return lhs.identifier == rhs.identifier")
print("}")
print("")
print("public func ~=<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {")
print(" return lhs.identifier == rhs.identifier")
print("}")
print("")
print("public func ==<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {")
print(" return lhs.identifier == rhs")
print("}")
print("")
print("public func ~=<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {")
print(" return lhs.identifier == rhs")
print("}")
print("")
print("public func ==<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {")
print(" return lhs == rhs.identifier")
print("}")
print("")
print("public func ~=<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {")
print(" return lhs == rhs.identifier")
print("}")
print("")
print("//MARK: - ReusableViewProtocol")
print("public protocol ReusableViewProtocol: IdentifiableProtocol {")
print(" var viewType: \(os.viewType).Type? { get }")
print("}")
print("")
print("public func ==<T: ReusableViewProtocol, U: ReusableViewProtocol>(lhs: T, rhs: U) -> Bool {")
print(" return lhs.storyboardIdentifier == rhs.storyboardIdentifier")
print("}")
print("")
print("//MARK: - Protocol Implementation")
print("extension \(os.storyboardSegueType): SegueProtocol {")
print("}")
print("")
if let reusableViews = os.resuableViews {
for reusableView in reusableViews {
print("extension \(reusableView): ReusableViewProtocol {")
print(" public var viewType: UIView.Type? { return self.dynamicType }")
print(" public var storyboardIdentifier: String? { return self.reuseIdentifier }")
print("}")
print("")
}
}
for controllerType in os.storyboardControllerTypes {
print("//MARK: - \(controllerType) extension")
print("extension \(controllerType) {")
print(" func performSegue<T: SegueProtocol>(segue: T, sender: AnyObject?) {")
print(" if let identifier = segue.identifier {")
print(" performSegueWithIdentifier(identifier, sender: sender)")
print(" }")
print(" }")
print("")
print(" func performSegue<T: SegueProtocol>(segue: T) {")
print(" performSegue(segue, sender: nil)")
print(" }")
print("}")
print("")
}
if os == OS.iOS {
print("//MARK: - UICollectionView")
print("")
print("extension UICollectionView {")
print("")
print(" func dequeueReusableCell<T: ReusableViewProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> UICollectionViewCell? {")
print(" if let identifier = reusable.storyboardIdentifier {")
print(" return dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: forIndexPath)")
print(" }")
print(" return nil")
print(" }")
print("")
print(" func registerReusableCell<T: ReusableViewProtocol>(reusable: T) {")
print(" if let type = reusable.viewType, identifier = reusable.storyboardIdentifier {")
print(" registerClass(type, forCellWithReuseIdentifier: identifier)")
print(" }")
print(" }")
print("")
print(" func dequeueReusableSupplementaryViewOfKind<T: ReusableViewProtocol>(elementKind: String, withReusable reusable: T, forIndexPath: NSIndexPath!) -> UICollectionReusableView? {")
print(" if let identifier = reusable.storyboardIdentifier {")
print(" return dequeueReusableSupplementaryViewOfKind(elementKind, withReuseIdentifier: identifier, forIndexPath: forIndexPath)")
print(" }")
print(" return nil")
print(" }")
print("")
print(" func registerReusable<T: ReusableViewProtocol>(reusable: T, forSupplementaryViewOfKind elementKind: String) {")
print(" if let type = reusable.viewType, identifier = reusable.storyboardIdentifier {")
print(" registerClass(type, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)")
print(" }")
print(" }")
print("}")
print("//MARK: - UITableView")
print("")
print("extension UITableView {")
print("")
print(" func dequeueReusableCell<T: ReusableViewProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> UITableViewCell? {")
print(" if let identifier = reusable.storyboardIdentifier {")
print(" return dequeueReusableCellWithIdentifier(identifier, forIndexPath: forIndexPath)")
print(" }")
print(" return nil")
print(" }")
print("")
print(" func registerReusableCell<T: ReusableViewProtocol>(reusable: T) {")
print(" if let type = reusable.viewType, identifier = reusable.storyboardIdentifier {")
print(" registerClass(type, forCellReuseIdentifier: identifier)")
print(" }")
print(" }")
print("")
print(" func dequeueReusableHeaderFooter<T: ReusableViewProtocol>(reusable: T) -> UITableViewHeaderFooterView? {")
print(" if let identifier = reusable.storyboardIdentifier {")
print(" return dequeueReusableHeaderFooterViewWithIdentifier(identifier)")
print(" }")
print(" return nil")
print(" }")
print("")
print(" func registerReusableHeaderFooter<T: ReusableViewProtocol>(reusable: T) {")
print(" if let type = reusable.viewType, identifier = reusable.storyboardIdentifier {")
print(" registerClass(type, forHeaderFooterViewReuseIdentifier: identifier)")
print(" }")
print(" }")
print("}")
print("")
}
for file in storyboards {
file.storyboard.processViewControllers()
}
}
//MARK: MAIN()
if Process.arguments.count == 1 {
print("Invalid usage. Missing path to storyboard.")
exit(1)
}
let argument = Process.arguments[1]
var filePaths:[String] = []
let storyboardSuffix = ".storyboard"
if argument.hasSuffix(storyboardSuffix) {
filePaths = [argument]
} else if let s = findStoryboards(argument, suffix: storyboardSuffix) {
filePaths = s
}
let storyboardFiles = filePaths.map { StoryboardFile(filePath: $0) }
for os in OS.allValues {
let storyboardsForOS = storyboardFiles.filter({ $0.storyboard.os == os })
if !storyboardsForOS.isEmpty {
if storyboardsForOS.count != storyboardFiles.count {
print("#if os(\(os.rawValue))")
}
processStoryboards(storyboardsForOS, os: os)
if storyboardsForOS.count != storyboardFiles.count {
print("#endif")
}
}
}
exit(0)
<file_sep>//
// BCOShareViewController.swift
// baicaio
//
// Created by JimBo on 15/12/31.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import MonkeyKing
class BCOShareViewController: UIViewController {
var goodsDealInfo = BCOGoodsDealInfo()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func qqShareButtonTouched(sender: AnyObject) {
//分享
let message = MonkeyKing.Message.QQ(.Friends(info: (
title: self.goodsDealInfo.title,
description: self.goodsDealInfo.title,
thumbnail: UIImage(named: "icon"),
media: .URL(NSURL(string: self.goodsDealInfo.infoUrl)!)
)))
MonkeyKing.shareMessage(message) { success in
print("shareURLToQQSession success: \(success)")
}
}
@IBAction func weChatSareButtonTouched(sender: AnyObject) {
//分享
let message = MonkeyKing.Message.WeChat(.Session(info: (
title: self.goodsDealInfo.title,
description: self.goodsDealInfo.title,
thumbnail: UIImage(named: "icon"),
media: .URL(NSURL(string: self.goodsDealInfo.infoUrl)!)
)))
MonkeyKing.shareMessage(message) { success in
print("shareURLToWeChatSession success: \(success)")
}
}
}
<file_sep>//
// BCOGoodsInfoContentCell.swift
// baicaio
//
// Created by JimBo on 15/12/26.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import YYText
import Kingfisher
let KGoodsDealImageLoadedNotificationName = "BCOGoodsDealImageLoadedNotificationName"
let KGoodsDealLinkedTouchedNotificationName = "BCOGoodsDealLinkedTouchedNotificationName"
let KGoodsDealImageTouchedNotificationName = "BCOGoodsDealImageTouchedNotificationName"
let KGoodsInfoContentImageBaseTag = 400
class BCOGoodsInfoContentCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var contentTextView: YYLabel!
var goodsDealInfo = BCOGoodsDealInfo()
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .None
self.setupContentTextView()
}
func setupContentTextView(){
self.contentTextView.numberOfLines = 0
self.contentTextView.userInteractionEnabled = true
}
func setupGoodsDealInfo(goodsDealInfo:BCOGoodsDealInfo,attributedString:NSMutableAttributedString){
self.goodsDealInfo = goodsDealInfo
self.dateLabel.text = goodsDealInfo.source + " | " + goodsDealInfo.date + " " + goodsDealInfo.time
self.titleLabel.text = goodsDealInfo.title
self.contentTextView.attributedText = attributedString
}
static func heightAndContentAttStringWithGoodsDealInfo(goodsDealInfo:BCOGoodsDealInfo) -> (height:CGFloat,attributeString:NSMutableAttributedString){
var imageIndex = 0
let text = NSMutableAttributedString()
let elementList = goodsDealInfo.contentElementList
//遍历Element
for element in elementList {
let defaultTextFontAttributes = [NSForegroundColorAttributeName:UIColor(hex: "777777"),NSFontAttributeName:UIFont.systemFontOfSize(14)]
let defaultLinkFontAttributes = [NSForegroundColorAttributeName:UIColor(hex: "156BC5"),NSFontAttributeName:UIFont.systemFontOfSize(14)]
if element.elementType == BCOGoodsDealContentElementType.Text.rawValue {
let textAttributedString = NSMutableAttributedString(string: element.text, attributes: defaultTextFontAttributes)
text.appendAttributedString(textAttributedString)
}else if element.elementType == BCOGoodsDealContentElementType.Link.rawValue {
let textAttributedString = NSMutableAttributedString(string: element.text, attributes: defaultLinkFontAttributes)
let textHightlight = YYTextHighlight()
textHightlight.setColor(UIColor(hex: "9AC2E8"))
textHightlight.tapAction = { (_,_,_,_) -> Void in
NSNotificationCenter.defaultCenter().postNotificationName(KGoodsDealLinkedTouchedNotificationName, object: element.linkUrl)
}
textAttributedString.yy_setTextHighlight(textHightlight, range: textAttributedString.yy_rangeOfAll())
text.appendAttributedString(textAttributedString)
}else if element.elementType == BCOGoodsDealContentElementType.Image.rawValue {
var imageWidth = BCOConfig.screenWidth-20
var imageHeight = (BCOConfig.screenWidth-20)/1.6
let imageView = UIImageView()
imageView.contentMode = UIViewContentMode.ScaleAspectFit
//判断是否已缓存该图片
if let image = KingfisherManager.sharedManager.cache.retrieveImageInDiskCacheForKey(element.imgUrl){
if image.size.width > imageWidth {
//对image进行缩放
let scale = image.size.width/imageWidth
imageHeight = image.size.height/scale
}else{
imageWidth = image.size.width
imageHeight = image.size.height
}
imageView.frame = CGRectMake(0, 0, imageWidth, imageHeight)
imageView.image = image
//处理图片点击事件
imageView.userInteractionEnabled = true
imageView.tag = KGoodsInfoContentImageBaseTag+imageIndex;
let tapGesture = UITapGestureRecognizer(target: self, action: "goodsInfoContentImageTaped:")
imageView.addGestureRecognizer(tapGesture);
imageIndex++;
}else{
//下载图片
KingfisherManager.sharedManager.downloader.downloadImageWithURL(NSURL(string: element.imgUrl)!, progressBlock: nil, completionHandler: { (image, error, imageURL, originalData) -> () in
if let image = image {
KingfisherManager.sharedManager.cache.storeImage(image, forKey: element.imgUrl)
NSNotificationCenter.defaultCenter().postNotificationName(KGoodsDealImageLoadedNotificationName, object: nil)
}
})
}
let imageAttributedString = NSMutableAttributedString.yy_attachmentStringWithContent(imageView, contentMode: UIViewContentMode.ScaleAspectFit, attachmentSize: CGSizeMake(imageWidth, imageHeight), alignToFont: UIFont.systemFontOfSize(14), alignment: YYTextVerticalAlignment.Center)
text.appendAttributedString(imageAttributedString)
}
}
text.yy_setLineSpacing(2, range: NSMakeRange(0, text.length))
let contentTextLayout = YYTextLayout(containerSize: CGSizeMake(BCOConfig.screenWidth-20, CGFloat.max), text: text)
let titleTextFontAttributes = [NSFontAttributeName:UIFont.boldSystemFontOfSize(16)]
let titleText = NSMutableAttributedString(string: goodsDealInfo.title, attributes: titleTextFontAttributes)
let titleTextLayout = YYTextLayout(containerSize: CGSizeMake(BCOConfig.screenWidth-20, CGFloat.max), text: titleText)
let height = 10+16+13+titleTextLayout!.textBoundingSize.height+15+contentTextLayout!.textBoundingSize.height+1
return (height,text)
}
static func goodsInfoContentImageTaped(tapGestureRecognizer:UITapGestureRecognizer){
let view = tapGestureRecognizer.view
let index = view!.tag-KGoodsInfoContentImageBaseTag
NSNotificationCenter.defaultCenter().postNotificationName(KGoodsDealImageTouchedNotificationName, object: index)
}
}
<file_sep>//
// BCOConfig.swift
// baicaio
//
// Created by JimBo on 15/12/25.
// Copyright © 2015年 JimBo. All rights reserved.
//
import Spring
import MonkeyKing
import Fabric
import Crashlytics
import RealmSwift
public struct BCOConfig{
static let mainColor = "4AA345"
static let screenWidth = UIScreen.mainScreen().bounds.width
static func configUI(){
UINavigationBar.appearance().setBackgroundImage(UIImage.imageWithColor(UIColor(hex: mainColor)), forBarMetrics: UIBarMetrics.Default)
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
}
static func registerThirdParty(){
Fabric.with([Crashlytics.self])
MonkeyKing.registerAccount(.WeChat(appID: "***********", appKey: ""))
MonkeyKing.registerAccount(.QQ(appID: "********"))
}
static func realmConfig(){
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
// enumerate(_:_:) 方法遍历了存储在 Realm 文件中的每一个“BCOGoodsDealInfo”对象
migration.enumerate(BCOGoodsDealInfo.className()) { oldObject, newObject in
// 将名字进行合并,存放在 fullName 域中
newObject!["category"] = "首页"
}
}
})
}
}
<file_sep>//
// BCOPersonTableViewController.swift
// baicaio
//
// Created by JimBo on 16/1/4.
// Copyright © 2016年 JimBo. All rights reserved.
//
import UIKit
import JDStatusBarNotification
class BCOPersonTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "设置"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(BCOPersonTableViewController.Reusable.disclosureCellIdentifier, forIndexPath: indexPath) as! BCOPersonDetailCell
if indexPath.row == 0 {
cell.titleLabel.text = "清除缓存"
cell.detailLabel.text = String(format: "%.1fMB", Double(BCOUtil.cacheSize())/1024.0/1024.0)
}else{
cell.titleLabel.text = "意见反馈"
cell.detailLabel.text = ""
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == 0 {
self.showAlertControllerForClean()
}else {
self.performSegue(BCOPersonTableViewController.Segue.showFeedbackViewController)
}
}
//MARK - alert
func showAlertControllerForClean(){
let alertController = UIAlertController(title: "提示", message: "将清除所有图片缓存,确认删除?", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel) { (_) -> Void in
}
let OKAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default) { (_) -> Void in
BCOUtil.clearCache()
self.tableView.reloadData()
JDStatusBarNotification.showWithStatus("操作成功", dismissAfter: 1.0, styleName: JDStatusBarStyleSuccess)
}
alertController.addAction(cancelAction)
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
class BCOPersonDetailCell:UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
}
<file_sep>//
// BCOGoodsInfoViewController.swift
// baicaio
//
// Created by JimBo on 15/12/26.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import AMScrollingNavbar
import SafariServices
import MJRefresh
import JBImageBrowserViewController
import JDStatusBarNotification
class BCOGoodsInfoViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var goodsDealIntroUrl = ""
var goodsDealInfo = BCOGoodsDealInfo()
var goodsPhotoArray = [JBImage]()
var goodsDealCollected = false
var goodsLayoutInfo = (height:CGFloat.min,attributeString:NSMutableAttributedString())
@IBOutlet weak var bannerView: CyclePictureView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var collectingButton: UIButton!
@IBOutlet weak var actionButtonsContainerView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
self.setupBannerView()
self.setupTableView()
self.title = "优惠详情"
let backItem = UIBarButtonItem(image: UIImage(named: "nav_back_icon"), style: UIBarButtonItemStyle.Plain, target: self, action: "navigationBack")
self.navigationItem.leftBarButtonItem = backItem
self.actionButtonsContainerView.userInteractionEnabled = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
self.setNeedsStatusBarAppearanceUpdate()
if let navigationController = self.navigationController as? ScrollingNavigationController {
navigationController.followScrollView(tableView, delay: 0.0)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contentImageLoaded", name: KGoodsDealImageLoadedNotificationName, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contentLinkTouched:", name: KGoodsDealLinkedTouchedNotificationName, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contentImageTouched:", name: KGoodsDealImageTouchedNotificationName, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if let navigationController = self.navigationController as? ScrollingNavigationController {
navigationController.stopFollowingScrollView()
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let goodsContentCell = tableView.dequeueReusableCell(BCOGoodsInfoViewController.Reusable.GoodsContentInfoCellIdentifier, forIndexPath: indexPath) as! BCOGoodsInfoContentCell
goodsContentCell.setupGoodsDealInfo(self.goodsDealInfo, attributedString: self.goodsLayoutInfo.attributeString)
return goodsContentCell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
self.goodsLayoutInfo = BCOGoodsInfoContentCell.heightAndContentAttStringWithGoodsDealInfo(self.goodsDealInfo)
return goodsLayoutInfo.height
}
// MARK - load Data
func refreshData(){
BCOGetGoodsDealsService.getGoodsDealInfo(self.goodsDealIntroUrl) { (goodsDealInfo:BCOGoodsDealInfo?, error:NSError?) -> Void in
if error == nil{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.goodsDealInfo = goodsDealInfo!
self.tableView.reloadData()
self.resetBannerView()
self.tableView.mj_header.removeFromSuperview()
//收藏
self.goodsDealCollected = BCOGoodsDealCollectionService.isCollected(self.goodsDealInfo.infoUrl)
if self.goodsDealCollected {
self.collectingButton.setImage(UIImage(named: "info_shoucang_selected_icon"), forState: UIControlState.Normal)
self.collectingButton.setTitle("取消收藏", forState: UIControlState.Normal)
}else{
self.collectingButton.setImage(UIImage(named: "info_shoucang_icon"), forState: UIControlState.Normal)
self.collectingButton.setTitle("收藏", forState: UIControlState.Normal)
}
self.actionButtonsContainerView.userInteractionEnabled = true
})
}else{
}
self.tableView.mj_header.endRefreshing()
}
}
// reset banner
func resetBannerView(){
var imageURLArray: [String] = []
for element in self.goodsDealInfo.imageElementList {
imageURLArray.append(element.imgUrl)
}
if imageURLArray.count>0 {
bannerView.imageURLArray = imageURLArray
}
}
//MARK - action
func contentImageLoaded(){
self.tableView.reloadData()
}
func contentImageTouched(notification: NSNotification){
let index = notification.object as! UInt
self.pushPhotoBrowserViewController(index)
}
func contentLinkTouched(notification: NSNotification){
let link = notification.object as! String
let safariViewCoroller = SFSafariViewController(URL: NSURL(string: link)!, entersReaderIfAvailable: true)
safariViewCoroller.delegate = self
self.navigationController?.presentViewController(safariViewCoroller, animated: true, completion: { () -> Void in
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
self.setNeedsStatusBarAppearanceUpdate()
})
}
@IBAction func collectingButtonDidTouch(sender: UIButton) {
//收藏
self.goodsDealCollected = !BCOGoodsDealCollectionService.isCollected(self.goodsDealInfo.infoUrl)
if self.goodsDealCollected {
BCOGoodsDealCollectionService.doCollection(self.goodsDealInfo.infoUrl)
self.collectingButton.setImage(UIImage(named: "info_shoucang_selected_icon"), forState: UIControlState.Normal)
self.collectingButton.setTitle("取消收藏", forState: UIControlState.Normal)
}else{
BCOGoodsDealCollectionService.removeCollection(self.goodsDealInfo.infoUrl)
self.collectingButton.setImage(UIImage(named: "info_shoucang_icon"), forState: UIControlState.Normal)
self.collectingButton.setTitle("收藏", forState: UIControlState.Normal)
}
JDStatusBarNotification.showWithStatus("操作成功", dismissAfter: 1.0, styleName: JDStatusBarStyleSuccess)
}
@IBAction func linkButtonDidTouch(sender: UIButton) {
//点击直达链接
let link = self.goodsDealInfo.directLink
if link.length>0 {
let safariViewCoroller = SFSafariViewController(URL: NSURL(string: link)!, entersReaderIfAvailable: true)
safariViewCoroller.delegate = self
self.navigationController?.presentViewController(safariViewCoroller, animated: true, completion: { () -> Void in
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
self.setNeedsStatusBarAppearanceUpdate()
})
}
}
//MARK - notification
func navigationBack(){
self.navigationController?.popViewControllerAnimated(true)
}
//MARK - setup
func setupBannerView(){
bannerView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetWidth(self.view.frame)/1.66)
self.tableView.tableHeaderView = bannerView
bannerView.backgroundColor = UIColor.clearColor()
bannerView.autoScroll = false
bannerView.pictureContentMode = .ScaleAspectFit
bannerView.currentDotColor = UIColor(hex: BCOConfig.mainColor)
bannerView.delegate = self
}
func setupTableView(){
self.tableView.separatorStyle = .None
self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "refreshData")
self.tableView.mj_header.beginRefreshing()
}
//MARK - sugue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == BCOGoodsInfoViewController.Segue.shareSegue {
let viewController = segue.destinationViewController as! BCOShareViewController
viewController.goodsDealInfo = self.goodsDealInfo
}
}
}
extension BCOGoodsInfoViewController:SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(controller: SFSafariViewController) {
controller.dismissViewControllerAnimated(true) { () -> Void in
}
}
}
extension BCOGoodsInfoViewController: CyclePictureViewDelegate {
func cyclePictureView(cyclePictureView: CyclePictureView, didSelectItemAtIndexPath indexPath: NSIndexPath){
self.pushPhotoBrowserViewController(UInt(indexPath.row))
}
}
extension BCOGoodsInfoViewController {
func pushPhotoBrowserViewController(currentIndex:UInt){
if self.goodsPhotoArray.count == 0 {
for element in self.goodsDealInfo.imageElementList {
let photo = JBImage(url:NSURL(string: element.imgUrl))
self.goodsPhotoArray.append(photo)
}
}
let photoBrowser = JBImageBrowserViewController(imageArray: self.goodsPhotoArray, failedPlaceholderImage: nil)
self.presentViewController(photoBrowser, animated: true, completion: nil)
}
}
<file_sep>//
// NSString+SubstringWithRange.swift
// baicaio
//
// Created by JimBo on 15/12/26.
// Copyright © 2015年 JimBo. All rights reserved.
//
import Foundation
extension String
{
func substringWithRange(start: Int, end: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if end < 0 || end > self.characters.count
{
print("end index \(end) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end))
return self.substringWithRange(range)
}
func substringWithRange(start: Int, location: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if location < 0 || start + location > self.characters.count
{
print("end index \(start + location) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + location))
return self.substringWithRange(range)
}
}<file_sep>//
// BCOSearchHistory.swift
// baicaio
//
// Created by JimBo on 15/12/31.
// Copyright © 2015年 JimBo. All rights reserved.
//
import Foundation
import RealmSwift
class BCOSearchHistory: Object {
dynamic var search = ""
dynamic var date = NSDate()
override static func primaryKey() -> String? {
return "search"
}
}
<file_sep>//
// BCOGoodsDealInfo.swift
// baicaio
//
// Created by JimBo on 15/12/26.
// Copyright © 2015年 JimBo. All rights reserved.
//
import Foundation
import RealmSwift
class BCOGoodsDealInfo: Object {
dynamic var title = ""
//白菜哦的详细页
dynamic var infoUrl = ""
dynamic var imageUrl = ""
dynamic var date = ""
dynamic var time = ""
dynamic var source = ""
dynamic var category = ""
//直达链接
dynamic var directLink = ""
var contentElementList = List<BCOGoodsDealContentElement>()
var imageElementList = List<BCOGoodsDealContentElement>()
override static func primaryKey() -> String? {
return "infoUrl"
}
}
<file_sep>//
// BCOSearchHistoryService.swift
// baicaio
//
// Created by JimBo on 15/12/31.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import RealmSwift
class BCOSearchHistoryService: NSObject {
static func saveSearchHistory(searchString:String!){
let searchHistrory = BCOSearchHistory()
searchHistrory.search = searchString
searchHistrory.date = NSDate()
let realm = try! Realm()
try! realm.write { () -> Void in
realm.add(searchHistrory, update: true)
}
}
static func getSearchHistory() -> List<BCOSearchHistory>{
let realm = try! Realm()
let sortedItems = realm.objects(BCOSearchHistory.self).sorted("date", ascending: false)
let list = List<BCOSearchHistory>()
list.appendContentsOf(sortedItems)
return list;
}
}
<file_sep>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
inhibit_all_warnings!
use_frameworks!
target 'baicaio' do
pod 'Spring', :git => 'https://github.com/MengTo/Spring.git', :branch => 'swift2'
pod 'Alamofire', '~> 3.0'
pod 'RealmSwift'
pod 'YYText'
pod 'AMScrollingNavbar', '~> 2.0.1'
pod 'JBImageBrowserViewController'
pod 'MonkeyKing', '~> 0.8'
pod 'MJRefresh'
pod 'FDFullscreenPopGesture', '1.1'
pod 'JDStatusBarNotification'
end<file_sep>#baicaio
<figure class="half">
<img src="http://7xjcm6.com1.z0.glb.clouddn.com/Simulator%20Screen%20Shot%202016%E5%B9%B47%E6%9C%8810%E6%97%A5%20%E4%B8%8A%E5%8D%889.59.52.png?imageView/2/w/200">
<img src="http://7xjcm6.com1.z0.glb.clouddn.com/Simulator%20Screen%20Shot%202016%E5%B9%B47%E6%9C%8810%E6%97%A5%20%E4%B8%8A%E5%8D%8810.00.36.png?imageView/2/w/200">
</figure>
>白菜哦,是一款比价购物推荐类APP,类似于什么值得买。
个人swift练手项目,用了两周的业余时间,进行开发。[半年前做的,其中引用了很多OC的三方库,并且代码很乱,大家请勿模仿]
# 项目实现
1. 所有数据,均是通过request请求[白菜哦](http//:www.baicaio.com)网站,来获得
2. 数据返回后,通过[hpple](https://github.com/topfunky/hpple)进行html解析,并转化为我们需要的model对象
3. 不同的功能,只是模拟相应的网站请求操作,来完成
# 框架接口
主要是用MVCS结构
```
M:瘦Model,主要是构造方法
V:负责View的配置+数据显示
C:Controller,主要负责调用Service里面的业务方法,获取数据,然后将数据赋予View,并组织相关逻辑
S:业务逻辑方法,该模块会调用API+Model+DB层,进行数据获取,存储,Parse。
```
## License
This code is distributed under the terms and conditions of the MIT license.
```
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
<file_sep>//
// AppDelegate.swift
// baicaio
//
// Created by JimBo on 15/12/24.
// Copyright © 2015年 JimBo. All rights reserved.
//
import UIKit
import MonkeyKing
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
BCOConfig.configUI()
BCOConfig.registerThirdParty()
BCOConfig.realmConfig()
//注册推送
APService.registerForRemoteNotificationTypes(UIUserNotificationType.Badge.union(.Alert).union(.Badge).rawValue, categories: nil)
APService.setupWithOption(launchOptions)
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if MonkeyKing.handleOpenURL(url) {
return true
}
return false
}
func applicationDidBecomeActive(application: UIApplication) {
application.applicationIconBadgeNumber = 0
}
func applicationWillTerminate(application: UIApplication) {
BCOGetGoodsDealsService.removeData()
}
}
//MARK - 推送
extension AppDelegate {
//注册成功
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
APService.registerDeviceToken(deviceToken)
}
//接收到推送
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
APService.handleRemoteNotification(userInfo)
//获取content
let content = ((userInfo["aps"] as? NSDictionary) ?? ["alert":""]).objectForKey("alert")
//如果error为1999,则表示网站改版了,需要重新编码
if let error = (userInfo["error"] as? String) {
if let rootVC = application.keyWindow?.rootViewController {
rootVC.modalPresentationStyle = UIModalPresentationStyle.OverFullScreen
let controller = Storyboards.Main.instantiateTipViewController()
if let errorCode = Int(error) {
controller.setup(content as? String, actionType: TipViewActionType(rawValue: errorCode)!)
rootVC.presentViewController(controller, animated: true, completion: nil)
}
}
}
completionHandler(UIBackgroundFetchResult.NewData)
}
}
|
081113eb8827e510151d50cf5937b002b725b1c5
|
[
"Swift",
"Ruby",
"Markdown"
] | 26 |
Swift
|
XGBCCC/baicaio
|
f222d26fde86bc88ae0948d95a1fdbd4e8da71e8
|
8fcfd4a19499f8c76f0a443144edcfe47035e01b
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$','website.app_views.home'),
url(r'^set_points/(?P<id>\d+)/(?P<puntos>\d+)/$','website.app_views.set_points'),
)
<file_sep># -*- coding: utf-8 -*-
import hashlib
import json
import urllib
import urlparse
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
import tweepy
from comentarios.models import Comentarios
from dalero.settings import TWITTER, FACEBOOK
from usuarios.forms import FormEstacionamiento
from usuarios.models import Estacionamiento, UsuarioBase, Cliente
from usuarios.permisos import *
def twitter_connect(request):
"""
Inicio del proceso oauth de Twitter
Se obtiene el request_token para luego redireccionar al usuario a la página para solicitar permiso de acceso
Libreria tweepy
"""
try:
auth = tweepy.OAuthHandler(TWITTER['KEY'], TWITTER['SECRET'], TWITTER["CALLBACK"])
redirect_url = auth.get_authorization_url()
rkey = auth.request_token.key
rsecret = auth.request_token.secret
request.session['tw_rt'] = "%s::%s"%(rkey, rsecret)
return HttpResponseRedirect(redirect_url)
except:
return HttpResponseRedirect('/?error_twitter')
def twitter_callback(request):
"""
Una vez el usuario permise o no el acceso a su cuenta de Twitter esta vista revisa si concedio permisos o no
En caso afirmativo busca a un usuario con ese id de Twitter para crear la sesion, de no existir crea al usuario
"""
retorno = HttpResponseRedirect('/')
try:
s = request.session['tw_rt']
tokens = s.split('::')
request_token = tokens[0]
request_secret = tokens[1]
if 'oauth_token' in request.GET and 'oauth_verifier' in request.GET:
oauth_verifier = request.GET['oauth_verifier']
oauth = tweepy.OAuthHandler(TWITTER['KEY'], TWITTER['SECRET'])
oauth.set_request_token(request_token, request_secret)
oauth.get_access_token(oauth_verifier)
api = tweepy.API(oauth)
tw_user = api.verify_credentials()
try:
cliente = Cliente.objects.get(twitter_id=tw_user.id)
cliente.login(request)
except Cliente.DoesNotExist:
accesstoken = oauth.access_token.key
secret = oauth.access_token.secret
cliente = Cliente(nombre_usuario="%s_tc"%tw_user.screen_name,
twitter_id=tw_user.id,
twitter_accesstoken=accesstoken,
twitter_secrettoken=secret)
cliente.save()
cliente.login(request)
retorno = HttpResponseRedirect('/app/')
except:
retorno = HttpResponseRedirect('/?error_twitter')
del request.session['tw_rt']
return retorno
def facebook_connect(request):
"""
Inicio del proceso oauth de Facebook
Se obtiene el request_token para luego redireccionar al usuario a la página para solicitar permiso de acceso
"""
facebook_oauth = "https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=email,publish_stream,offline_access"\
%(FACEBOOK["KEY"],
FACEBOOK["CALLBACK"])
return HttpResponseRedirect(facebook_oauth)
def facebook_callback(request):
"""
Una vez el usuario permise o no el acceso a su cuenta de Facebook esta vista revisa si concedio permisos o no
En caso afirmativo busca a un usuario con ese id de Facebook para crear la sesion, de no existir crea al usuario
"""
code = None if 'code' not in request.GET else request.GET['code']
retorno = HttpResponseRedirect('/?error_facebook')
try:
if code is not None:
args = dict(client_id=FACEBOOK["KEY"],
redirect_uri=FACEBOOK["CALLBACK"],
client_secret=FACEBOOK["SECRET"],
code=code)
response = urlparse.parse_qs(urllib.urlopen("https://graph.facebook.com/oauth/access_token?%s"%urllib.urlencode(args)).read())
access_token = response["access_token"][-1]
if access_token is not None:
fb_user = json.load(urllib.urlopen("https://graph.facebook.com/me?%s"%urllib.urlencode(dict(access_token=access_token))))
if 'id' in fb_user:
try:
cliente = Cliente.objects.get(facebook_id=fb_user['id'])
cliente.login(request)
except Cliente.DoesNotExist:
cliente = Cliente(nombre_usuario="%s_fb"%(fb_user['username'] if 'username' in fb_user else fb_user['id']),
facebook_id=fb_user['id'],
facebook_accesstoken=access_token,
facebook_code=code)
cliente.save()
cliente.login(request)
request.session['tipo'] = 'cliente'
retorno = HttpResponseRedirect('/app/')
except:
pass
return retorno
@user_passes_test(es_administrador, login_url='/users/login/')
def crear_estacionamiento(request):
"""
Vista para crear estacionamiento
Se valida si existe un UsuarioBase con el email y nombre_usuario pasado (deben ser unicos)
Se crea el password tipo <PASSWORD>
"""
errors = {}
if request.method != 'POST':
form = FormEstacionamiento()
else:
form = FormEstacionamiento(data=request.POST)
if form.is_valid():
clean_data = form.cleaned_data
if UsuarioBase.objects.all().filter(nombre_usuario=clean_data['nombre_usuario']).exists():
errors = {'nombre_usuario' : {'as_text':'* Nombre de usuario usado'}}
elif UsuarioBase.objects.all().filter(correo=clean_data['correo']).exists():
errors = {'correo' : {'as_text':'* Correo electrónico usado'}}
else:
password = __<PASSWORD>(user=clean_data['nombre_usuario'])
estacionamiento = Estacionamiento(
nombre_usuario=clean_data['nombre_usuario'],
password=<PASSWORD>,
correo=clean_data['correo'],
descripcion=clean_data['descripcion'],
nombre=clean_data['nombre'],
latitud=clean_data['latitud'],
longitud=clean_data['longitud'],
motos=clean_data['motos'],
camiones=clean_data['camiones'],
sin_techo=clean_data['sin_techo'])
estacionamiento.save()
return HttpResponseRedirect('/users/admin/listar_estacionamientos/')
else:
errors = form.errors
return render_to_response('usuarios/crear_editar_estacionamiento.html', {'form' : form, 'errors' : errors, 'crear' : True}, context_instance=RequestContext(request))
@user_passes_test(es_administrador, login_url='/users/login/')
def listar_estacionamientos(request, page=1):
"""
Vista para mostrar los estacionamientos registrados con paginacion
"""
estacionamientos = Estacionamiento.objects.all()
paginator = Paginator(estacionamientos, 20)
try:
page = int(page)
except:
page = 1
try:
pagina = paginator.page(page)
except (EmptyPage, InvalidPage):
pagina = paginator.page(paginator.num_pages)
pagination = {'object_list': [x.to_dict(admin=True) for x in pagina.object_list],
'has_prev': pagina.has_previous(),
'has_next': pagina.has_next(),
'prev_page': pagina.previous_page_number() if pagina.has_previous() else None,
'next_page': pagina.next_page_number() if pagina.has_next() else None,
'page': pagina.number,
'num_pages': pagina.paginator.num_pages,
}
return render_to_response('usuarios/listar_estacionamientos.html', {'pagination' : pagination,}, context_instance=RequestContext(request))
@user_passes_test(es_estacionamiento, login_url='/users/login/')
def editar_estacionamiento(request, id=None):
"""
Vista para editar estacionamiento
Podran usar esta vista tanto estacionamientos como administrador
"""
errors = {}
es_estac = Estacionamiento.objects.all().filter(usuariobase_ptr_id=request.user.id).exists()
try:
if es_estac:
estacionamiento = request.user.estacionamiento
else:
estacionamiento = Estacionamiento.objects.get(pk=id)
if request.method != 'POST':
initial = {'nombre' : estacionamiento.nombre,
'nombre_usuario' : estacionamiento.nombre_usuario,
'correo' : estacionamiento.correo,
'descripcion' : estacionamiento.descripcion,
'motos' : estacionamiento.motos,
'camiones' : estacionamiento.camiones,
'sin_techo' : estacionamiento.sin_techo,
'id' : estacionamiento.id}
if not es_estac:
initial.update({'latitud' : estacionamiento.latitud,
'longitud' : estacionamiento.longitud,})
form = FormEstacionamiento(initial=initial,
edit=True,
parking=es_estac)
else:
form = FormEstacionamiento(data=request.POST, edit=True, parking=es_estac)
if form.is_valid():
clean_data = form.cleaned_data
if Estacionamiento.objects.all().exclude(pk=estacionamiento.id).filter(correo=clean_data['correo']).exists():
errors = {'correo' : {'as_text':'* Correo electrónico usado'}}
else:
estacionamiento.descripcion = clean_data['descripcion']
estacionamiento.nombre = clean_data['nombre']
estacionamiento.motos = clean_data['motos']
estacionamiento.camiones = clean_data['camiones']
estacionamiento.sin_techo = clean_data['sin_techo']
if not es_estac:
estacionamiento.latitud = clean_data['latitud']
estacionamiento.longitud = clean_data['longitud']
estacionamiento.save()
else:
errors = form.errors
return render_to_response('usuarios/crear_editar_estacionamiento.html',
{'form' : form, 'errors' : errors, 'es_estacionamiento' : es_estac, 'estacionamiento' : estacionamiento},
context_instance=RequestContext(request))
except Estacionamiento.DoesNotExist:
raise Http404()
@user_passes_test(es_administrador, login_url='/users/login/')
def eliminar_estacionamiento(request, id):
"""
Vista para el soft delete de estacionamientos
La misma permitira desactivar y activar
"""
try:
estacionamiento = Estacionamiento.objects.get(pk=id)
estacionamiento.activo = not estacionamiento.activo
estacionamiento.save()
return HttpResponseRedirect('/users/admin/listar_estacionamientos/')
except Estacionamiento.DoesNotExist:
raise Http404()
@user_passes_test(es_estacionamiento, login_url='/users/login/')
def listar_comentarios(request, park, page=1):
"""
Vista para listar los comentarios de un estacionamiento
La misma podra ser usada por estacionamiento como por administrador
"""
try:
estacionamiento = Estacionamiento.objects.get(pk=park, activo=True)
comments = Comentarios.objects.all().filter(estacionamiento__id=estacionamiento.id, cliente__activo=True)
es_estac = Estacionamiento.objects.all().filter(usuariobase_ptr_id=request.user.id).exists()
if es_estac and request.user.estacionamiento.id != estacionamiento.id:
raise Http404()
paginator = Paginator(comments, 20)
try:
page = int(page)
except:
page = 1
try:
comentarios = paginator.page(page)
except (EmptyPage, InvalidPage):
comentarios = paginator.page(paginator.num_pages)
next_page = comentarios.next_page_number() if comentarios.has_next() else 0
pagination = {'object_list': [x.to_dict(admin=True) for x in comentarios.object_list],
'has_prev': comentarios.has_previous(),
'has_next': comentarios.has_next(),
'prev_page': comentarios.previous_page_number() if comentarios.has_previous() else None,
'next_page': next_page if comentarios.has_next() else None,
'page': comentarios.number,
'num_pages': comentarios.paginator.num_pages,
}
return render_to_response('usuarios/listar_comentarios.html', {'pagination' : pagination,
'es_estacionamiento' : es_estac,
'estacionamiento' : estacionamiento},
context_instance=RequestContext(request))
except Estacionamiento.DoesNotExist:
raise Http404()
@user_passes_test(es_administrador, login_url='/users/login/')
def eliminar_comentario(request, id, id_comentario):
"""
Vista para elimiar comentarios
"""
try:
comment = Comentarios.objects.get(pk=id_comentario)
comment.delete()
except Comentarios.DoesNotExist:
raise Http404()
return HttpResponseRedirect('/users/admin/listar_comentarios/%s/'%comment.estacionamiento_id)
@user_passes_test(es_administrador, login_url='/users/login/')
def listar_usuarios(request, page=1):
"""
Vista para listar Clientes registrados
"""
try:
clientes = Cliente.objects.all()
paginator = Paginator(clientes, 20)
try:
page = int(page)
except:
page = 1
try:
clientes = paginator.page(page)
except (EmptyPage, InvalidPage):
clientes = paginator.page(paginator.num_pages)
pagination = {'object_list': [x.to_dict() for x in clientes.object_list],
'has_prev': clientes.has_previous(),
'has_next': clientes.has_next(),
'prev_page': clientes.previous_page_number() if clientes.has_previous() else None,
'next_page': clientes.next_page_number() if clientes.has_next() else None,
'page': clientes.number,
'num_pages': clientes.paginator.num_pages,
}
return render_to_response('usuarios/listar_usuarios.html', {'pagination' : pagination}, context_instance=RequestContext(request))
except Cliente.DoesNotExist:
raise Http404()
@user_passes_test(es_administrador, login_url='/users/login/')
def eliminar_usuario(request, id):
"""
Vista para hacer soft deletede clientes registrados
"""
try:
cliente = Cliente.objects.get(pk=id)
cliente.activo = not cliente.activo
cliente.save()
except Cliente.DoesNotExist:
raise Http404()
return HttpResponseRedirect('/users/admin/listar_usuarios/')
@user_passes_test(es_estacionamiento, login_url='/users/login/')
def denunciar_comentario(request, id):
"""
Vista para que el estacionamiento marque como spam a uncomentario
"""
try:
comment = Comentarios.objects.get(pk=id, estacionamiento=request.user.estacionamiento)
comment.spam = not comment.spam
comment.save()
except Comentarios.DoesNotExist:
raise Http404()
return HttpResponseRedirect('/users/admin/listar_comentarios/%s/'%comment.estacionamiento_id)
def __new_password(user):
"""
Generador de passwords
"""
new_pass = <PASSWORD>("%<PASSWORD>"%user).<PASSWORD>()
return new_pass
def login(request):
"""
Vista para loguear usuarios (estacionamientos y admin)
"""
'''(admin, nuevo) = UsuarioBase.objects.get_or_create(nombre_usuario='admin')
if nuevo:
admin.password = <PASSWORD>('<PASSWORD>').<PASSWORD>()
admin.administrador = True
admin.save()'''
errors = None
if request.method == 'POST':
if 'username' not in request.POST or 'password' not in request.POST:
errors = 'Debe llenar todos los campos'
else:
try:
user = UsuarioBase.objects.get(nombre_usuario = request.POST['username'],
password = hashlib.sha512(request.POST['password']).hexdigest())
except:
user = None
if user is None or not user.activo:
errors = u'Nombre de usuario o contraseña no coinciden'
else:
existe_estacionmiento = Estacionamiento.objects.all().filter(usuariobase_ptr_id=user.id).exists()
if existe_estacionmiento or user.administrador:
user.login(request)
if 'next' in request.GET:
return HttpResponseRedirect(request.GET['next'])
else:
if existe_estacionmiento:
return HttpResponseRedirect('/users/park/editar_estacionamiento/')
else:
return HttpResponseRedirect('/users/admin/listar_estacionamientos/')
else:
errors = u'Nombre de usuario o contraseña no coinciden'
return render_to_response('login.html', {'errors' : errors}, context_instance=RequestContext(request))
def logout(request):
"""
Vista para desloguear usuario (cualquier tipo)
"""
del request.session['SESSION_KEY']
return HttpResponseRedirect("/")<file_sep># -*- coding: utf-8 -*-
from django.db.models import Avg
from django.shortcuts import render_to_response
from django.template import RequestContext
from comentarios.models import Puntos
from usuarios.permisos import *
from django.core.context_processors import csrf
@user_passes_test(es_cliente, login_url='/')
def home(request):
"""
Vista del home de le aplicación en la que se muestra el mapa
"""
data = {}
data.update(csrf(request))
retorno = render_to_response("app/index.html", data, context_instance=RequestContext(request))
return retorno
@user_passes_test(es_cliente, login_url='/')
def set_points(request, id, puntos):
"""
Servicio para puntear los estacionamientos
"""
puntos = int(puntos)
if puntos > 5 or puntos < 1:
return HttpResponse(json.dumps({'success' : False, 'cause' : 'puntaje de 1-5'}), mimetype='application/json')
try:
estacionamiento = Estacionamiento.objects.get(pk=id)
existe_puntos = Puntos.objects.all().filter(estacionamiento=estacionamiento, cliente=request.user.cliente).exists()
if not existe_puntos:
punto = Puntos(estacionamiento=estacionamiento,
cliente=request.user.cliente,
puntos=puntos)
punto.save()
puntos_avg = Puntos.objects.all().filter(estacionamiento=estacionamiento).aggregate(Avg('puntos'))['puntos__avg']
return HttpResponse(json.dumps({'success' : True,
'puntos' : int(round(puntos_avg, 2)) if puntos_avg is not None else 0}),
mimetype='application/json')
else:
return HttpResponse(json.dumps({'success' : False, 'cause' : 'exist'}), mimetype='application/json')
except:
pass
return HttpResponse(json.dumps({'success' : False, 'cause' : 'error inesperado'}), mimetype='application/json')<file_sep>__author__ = '<NAME>'
<file_sep>var list_parkings = [];
var timout;
var map;
function show_parking(id){
var estacionamiento = localStorage.getItem(id);
if(estacionamiento != null){
var json_est = JSON.parse(estacionamiento);
var get_comments = function(){
$.get('/comentarios/get_comments/' + json_est.id,
{},
function(data){
var retorno = '';
if(data.success && data.comentarios.length > 0){
retorno += '<strong>Comentarios</strong>';
$.each(data.comentarios, function(i, v){
retorno += '<div class="commets-box">' +
'<p>' + v.contenido + '</p>' +
'</div>';
});
}
$('#wrapper_comment').html(retorno);
}
);
}
var datos_meta = function(){
var meta = '';
if(json_est.motos){
meta += '<li>Motos</li>';
}
if(json_est.camiones){
meta += '<li>Camiones</li>';
}
if(!json_est.sin_techo){
meta += '<li>Techado</li>';
}else{
meta += '<li>Sin techo</li>';
}
return meta;
}
var set_points = function(data_puntos){
$('.wrapper-points').html('');
var puntos = '';
for(var i=1; i < 6; i++){
if(data_puntos < i){
puntos += '<i class="icon-star-empty point" data-point="' + i + '"></i>';
}else{
puntos += '<i class="icon-star point" data-point="' + i + '"></i>';
}
}
$('.wrapper-points').html(puntos);
}
var datos_html = '<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h3 id="myModalLabel">' + json_est.nombre + '</h3>' +
'</div>' +
'<div class="modal-body">' +
'<span><strong>Puntaje</strong></span> ' +
'<span class="wrapper-points"></span><br>' +
'<strong>Descripcion:</strong>' +
'<p>' + json_est.descripcion + '</p>' +
'<ul>' +
datos_meta() +
'</ul>' +
'</div>' +
'<div class="modal-footer">' +
'<div id="wrapper_comment"></div>' +
'<div class="wrapper-comment-form">' +
'<form class="navbar-form pull-left" style="width: 100%;">' +
'<strong>¿Tienes algún comentario?</strong><br>' +
'<textarea class="area_comment" style="width: 98%;"></textarea>' +
'<small>140 caractéres máximo<small><br>' +
'<button type="submit" class="btn_send_comment">Enviar</button>' +
'</form>' +
'</div>' +
'<div class="wrapper-comments"></div>' +
'</div>';
$('#wrapper_detalles').html(datos_html);
get_comments();
set_points(json_est.puntos);
$('#wrapper_detalles').modal('show');
$('.area_comment').keyup(function(){
if($('.area_comment').val().length > 140) {
$('.area_comment').val($('.area_comment').val().substring(0, 140))
}
});
$('.point').click(function(){
$this = $(this);
$.post('/app/set_points/' + json_est.id + '/' + $this.data('point') + '/',
{'csrfmiddlewaretoken' : csr},
function(data){
if(data.success){
set_points(data.puntos);
}
});
});
$('.navbar-form').submit(function(e){
e.preventDefault();
$this = $(this);
if($this.find('textarea').val() == '')return false;
$.post('/comentarios/set_comment/' + json_est.id + '/',
{'csrfmiddlewaretoken' : csr, 'contenido' : $this.find('textarea').val()},
function(data){
if(data.success){
var retorno = '';
if($('#wrapper_comment strong').length > 0){
retorno += '<strong>Comentarios</strong>';
}
$('#wrapper_comment').prepend(
'<div class="commets-box">' +
'<p>' + data.comentario.contenido + '</p>' +
'</div>'
);
$this.find('textarea').val('');
}
}
);
});
}
}
function get_parkings(recarga){
window.clearTimeout(timout);
navigator.geolocation.getCurrentPosition(function (position) {
var $lat = position.coords.latitude.toFixed(5);
var $long = position.coords.longitude.toFixed(5);
if(typeof recarga != "undefined" && localStorage.getItem('position') == $lat + '/' + $long){
timout = setTimeout('get_parkings(true)', 30000);
}else{
localStorage.setItem('position', $lat + '/' + $long);
var point = new google.maps.LatLng($lat, $long);
var mapOptions = {
center: point,
zoom: 16,
styles:[
{ featureType: "road", stylers: [{hue: "#006Eee"}]}
],
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: point,
map: map
});
var data = {'lat' : $lat, 'long' : $long}
if(typeof recarga != 'undefined'){data['recarga'] = true;}
$.get(
'/geo/buscar_estacionmientos/',
data,
function(data){
$.each(data.parkings, function(i, v){
if(list_parkings.indexOf(v.latitud + v.longitud) == -1){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(v.latitud, v.longitud),
map: map,
icon: new google.maps.MarkerImage("/static/img/taxi.png"),
title:v.name
});
localStorage.setItem(v.id, JSON.stringify(v));
console.log(v.id, v);
google.maps.event.addListener(marker, "click", function() {
show_parking(v.id);
});
}
});
google.maps.event.addListener(map, 'center_changed', function() {
get_parkings(true, true);
});
timout = setTimeout('get_parkings(true)', 30000);
}
);
}
},
function(){alert('Error al obtener posición');},
{ enableHighAccuracy:true }
);
}
$(document).ready(function(){
var $lat = false;
var $long = false;
$('#map_canvas').height($('#map_canvas').height() - 60);
var useragent = navigator.userAgent;
if (useragent.indexOf('iPhone') == -1 && useragent.indexOf('Android') == -1 ) {
$('#map_canvasd').css({'width':'600px'});
}
get_parkings();
window.onorientationchange = function(){}
});
<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from usuarios.permisos import usuario_autenticado
def home(request):
"""
Home de la aplicacion
"""
data = {}
if usuario_autenticado(request):
data['usuario'] = request.user
retorno = render_to_response("index.html", data, context_instance=RequestContext(request))
return retorno
<file_sep># -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
from comentarios.models import Comentarios
from usuarios.models import Estacionamiento
from usuarios.permisos import user_passes_test
from usuarios.permisos import *
@user_passes_test(es_cliente, login_url='/')
def set_comentario(request, id):
try:
if 'contenido' not in request.POST or request.POST['contenido'] == '':
return HttpResponse(json.dumps({'success' : False, 'cause' : 'contenido vacio'}), mimetype='application/json')
estacionamiento = Estacionamiento.objects.get(pk=id)
comentario = Comentarios(estacionamiento=estacionamiento,
cliente=request.user.cliente,
contenido=request.POST['contenido'])
comentario.save()
return HttpResponse(json.dumps({'success' : True, 'comentario' : comentario.to_dict(cliente=request.user.cliente)}), mimetype='application/json')
except:
pass
return HttpResponse(json.dumps({'success' : False, 'cause' : 'error inesperado'}), mimetype='application/json')
@user_passes_test(es_cliente, login_url='/')
def get_comentarios(request, id):
if 0==0:
offset = 0 if 'offset' not in request.GET else int(request.GET['offset'])
limit = 5
comentarios = [x.to_dict(admin=False, cliente=request.user.cliente) for x in Comentarios.objects.all().filter(estacionamiento=id)[offset:limit + offset]]
return HttpResponse(json.dumps({'success' : True, 'comentarios' : comentarios}), mimetype='application/json')
'''except:
return HttpResponse(json.dumps({'success' : False}), mimetype='application/json')'''<file_sep># -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$','usuarios.views.login'),
url(r'^logout/$','usuarios.views.logout'),
url(r'^twitter_connect/$','usuarios.views.twitter_connect'),
url(r'^twitter_callback/$','usuarios.views.twitter_callback'),
url(r'^facebook_connect/$','usuarios.views.facebook_connect'),
url(r'^facebook_callback/$','usuarios.views.facebook_callback'),
url(r'^admin/crear_estacionamiento/$','usuarios.views.crear_estacionamiento'),
url(r'^admin/listar_estacionamientos/(?P<page>\d+)?','usuarios.views.listar_estacionamientos'),
url(r'^admin/editar_estacionamiento/(?P<id>\d+)/$','usuarios.views.editar_estacionamiento'),
url(r'^admin/eliminar_estacionamiento/(?P<id>\d+)/$','usuarios.views.eliminar_estacionamiento'),
url(r'^admin/listar_comentarios/(?P<park>\d+)/(?P<page>\d+)?','usuarios.views.listar_comentarios'),
url(r'^admin/eliminar_comentario/(?P<id>\d+)/(?P<id_comentario>\d+)/$','usuarios.views.eliminar_comentario'),
url(r'^admin/listar_usuarios/(?P<page>\d+)?','usuarios.views.listar_usuarios'),
url(r'^admin/eliminar_usuario/(?P<id>\d+)/$','usuarios.views.eliminar_usuario'),
url(r'^admin/editar_estacionamiento/(?P<id>\d+)/$','usuarios.views.editar_estacionamiento'),
url(r'^park/editar_estacionamiento/$','usuarios.views.editar_estacionamiento'),
url(r'^park/listar_comentarios/(?P<park>\d+)/(?P<page>\d+)?','usuarios.views.listar_comentarios'),
url(r'^park/denunciar_comentario/(?P<id>\d+)/$','usuarios.views.denunciar_comentario'),
)
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from usuarios.models import Cliente, Estacionamiento
class Comentarios(models.Model):
cliente = models.ForeignKey(Cliente)
fecha = models.DateTimeField(auto_now=False, auto_now_add=True, db_index=True)
spam = models.BooleanField(default=False, db_index=True)
contenido = models.TextField(max_length=140)
estacionamiento = models.ForeignKey(Estacionamiento)
def to_dict(self, admin=False, cliente=None):
data = {'fecha' : self.fecha.strftime("%d/%m/%Y H:M"),
'spam' : self.spam,
'contenido' : self.contenido}
if cliente:
data.update({'cliente' : True if self.cliente.id == cliente.id else False,
'id' : self.id})
if admin:
data.update({'estacionamiento' : self.estacionamiento.to_dict(admin=True),
'id' : self.id,
'cliente' : self.cliente.to_dict()})
return data
class Meta:
ordering = ['-fecha']
class Puntos(models.Model):
cliente = models.ForeignKey(Cliente)
fecha = models.DateTimeField(auto_now=False, auto_now_add=True)
puntos = models.IntegerField(default=0)
estacionamiento = models.ForeignKey(Estacionamiento)
class Meta:
unique_together = ('cliente', 'estacionamiento')<file_sep># -*- coding: utf-8 -*-
from django import forms
class FormEstacionamiento(forms.Form):
nombre_usuario = forms.RegexField(label = u'Nombre de usuario',
regex=r'^[^\ ]+$',
max_length=30,
widget=forms.TextInput(attrs={'placeholder':'No se permiten espacios'}))
nombre = forms.CharField(label='Nombre del estacionamiento',
max_length=100,
widget=forms.TextInput())
correo = forms.EmailField(label = u'Correo Electrónico',
max_length=75,
widget= forms.TextInput(attrs={'placeholder':u'Correo electrónico válido'}))
descripcion = forms.CharField(label = u'Descripción',
max_length=200,
widget= forms.Textarea())
latitud = forms.DecimalField(label = u'Latitude',
max_digits= 17,
decimal_places=15,
widget= forms.TextInput(attrs={'placeholder':'12.123456789012345'}))
longitud = forms.DecimalField(label = u'Longitude',
max_digits= 17,
decimal_places=15,
widget= forms.TextInput(attrs={'placeholder':'12.123456789012345'}))
motos = forms.BooleanField(label='Aceptan motos',
required= False,
widget= forms.CheckboxInput())
camiones = forms.BooleanField(label='Aceptan camiones',
required= False,
widget= forms.CheckboxInput())
sin_techo = forms.BooleanField(label='Sin techo',
required= False,
widget= forms.CheckboxInput())
id = forms.IntegerField(required=True, widget=forms.HiddenInput())
def __init__(self, edit=False, parking=False, *args, **kwargs):
super(FormEstacionamiento, self).__init__(*args, **kwargs)
if not edit:
del self.fields['id']
else:
self.fields['nombre_usuario'].widget = forms.TextInput(attrs={'readonly':'true'})
if parking:
del self.fields['latitud']
del self.fields['longitud']<file_sep># -*- coding: utf-8 -*-
from django.db import models
# Create your models here.
from django.db.models import Avg
class UsuarioBase(models.Model):
nombre_usuario = models.CharField(max_length=100)
password = models.CharField(max_length=128, null=True, blank=True)
creacion = models.DateTimeField(auto_now=False, auto_now_add=True)
ultimo_acceso = models.DateTimeField(auto_now=True, auto_now_add=True)
administrador = models.BooleanField(default=False)
activo = models.BooleanField(default=True)
correo = models.EmailField(null=True, blank=True)
def login(self, request):
request.session['SESSION_KEY'] = self.id
self.save()
return True
class IntentosIngreso(models.Model):
ip = models.IPAddressField(blank=False, null=False, db_index=True)
fecha = models.DateTimeField(auto_created=True)
class Cliente(UsuarioBase):
facebook_id = models.CharField(max_length=100, blank=True, null=True)
facebook_accesstoken = models.CharField(max_length=200, blank=True, null=True)
facebook_code = models.CharField(max_length=400, blank=True, null=True)
twitter_id = models.CharField(max_length=100, blank=True, null=True)
twitter_accesstoken = models.CharField(max_length=200, blank=True, null=True)
twitter_secrettoken = models.CharField(max_length=200, blank=True, null=True)
def to_dict(self):
data = {'nombre_usuario' : self.nombre_usuario,
'facebook' : self.facebook_id is not None,
'id' : self.id,
'activo' : self.activo,
'twitter' : self.twitter_id is not None}
return data
class Estacionamiento(UsuarioBase):
nombre = models.CharField(max_length=100)
descripcion = models.TextField(max_length=200)
latitud = models.FloatField(db_index=True, max_length=25)
longitud = models.FloatField(db_index=True, max_length=25)
motos = models.BooleanField(default=False)
camiones = models.BooleanField(default=False)
sin_techo = models.BooleanField(default=False)
def to_dict(self, admin=False):
puntos = self.puntos_set.all().aggregate(Avg('puntos'))['puntos__avg']
data = {
'nombre' : self.nombre,
'descripcion' : self.descripcion,
'latitud' : str(self.latitud),
'longitud' : str(self.longitud),
'puntos' : int(round(puntos, 2)) if puntos is not None else 0,
'motos' : self.motos,
'camiones' : self.camiones,
'sin_techo' : self.sin_techo,
'id' : self.id,
'comentarios' : self.comentarios_set.all().count()
}
if admin:
data.update({'correo' : self.correo,
'nombre_usuario' : self.nombre_usuario,
'activo' : self.activo})
return data<file_sep># -*- coding: utf-8 -*-
from django.db import models
from usuarios.models import Cliente
class PosicionCliente(models.Model):
cliente = models.ForeignKey(Cliente)
latitud = models.FloatField(db_index=True, max_length=25)
longitud = models.FloatField(db_index=True, max_length=25)
fecha = models.DateTimeField(auto_now=False, auto_now_add=True)
primero = models.BooleanField(default=True)<file_sep># -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^set_comment/(?P<id>\d+)/$', 'comentarios.views.set_comentario'),
url(r'^get_comments/(?P<id>\d+)', 'comentarios.views.get_comentarios'),
)
<file_sep># -*- coding: utf-8 -*-
import json
from django.db import connection
from django.http import HttpResponse
from geo.models import PosicionCliente
from usuarios.models import Estacionamiento
from usuarios.permisos import *
@user_passes_test(es_cliente, login_url='/')
def buscar_estacionmientos(request):
lat = float(request.GET['lat'])
long = float(request.GET['long'])
radio = 10
unidad_distancia = 6371
posicion_cliente = PosicionCliente(cliente=request.user.cliente,
latitud=lat,
longitud=long)
posicion_cliente.primero = True if 'recarga' not in request.GET else False
posicion_cliente.save()
cursor = connection.cursor()
sql = """SELECT usuariobase_ptr_id AS id, latitud, longitud
FROM usuarios_estacionamiento WHERE (%f * acos( cos( radians(%f) ) * cos( radians( latitud ) ) *
cos( radians( longitud ) - radians(%f) ) + sin( radians(%f) ) * sin( radians( latitud ) ) ) ) < %d
""" % (unidad_distancia, lat, long, lat, int(radio))
cursor.execute(sql)
ids = [row[0] for row in cursor.fetchall()]
parkings =[x.to_dict() for x in Estacionamiento.objects.all().filter(id__in=ids, activo=True)]
return HttpResponse(json.dumps({'success' : True, 'parkings' : parkings}), mimetype='application/json')<file_sep># -*- coding: utf-8 -*-
from functools import wraps
import json
import urlparse
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse
from django.utils.decorators import available_attrs
from dalero import settings
from usuarios.models import UsuarioBase, Estacionamiento
def usuario_autenticado(request):
if 'SESSION_KEY' in request.session and request.session['SESSION_KEY']:
try:
user = UsuarioBase.objects.get(pk=request.session['SESSION_KEY'])
request.user = user
return True
except:
pass
return False
def es_cliente(request):
return usuario_autenticado(request) and (request.user.cliente or request.user.administrador)
def es_administrador(request):
return usuario_autenticado(request) and request.user.administrador
def es_estacionamiento(request):
return usuario_autenticado(request) and (Estacionamiento.objects.all().filter(usuariobase_ptr_id=request.user.id).exists() or request.user.administrador)
def user_passes_test(test_func, login_url=None, login_json=False, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = request.build_absolute_uri()
login_scheme, login_netloc = urlparse.urlparse(login_url or
settings.LOGIN_URL)[:2]
current_scheme, current_netloc = urlparse.urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
if login_json:
return HttpResponse(json.dumps({'success':False,'cause':'403'}))
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(path, login_url, redirect_field_name)
return _wrapped_view
return decorator<file_sep>from django.conf.urls import patterns, include, url
from dalero import settings
# Uncomment the next two lines to enable the admin:
#from django.contrib import admin
#admin.autodiscover()
from dalero.settings import STATIC_ROOT
urlpatterns = patterns('',
# Examples:
url(r'^$', 'website.views.home', name='home'),
url(r'^users/', include('usuarios.urls')),
url(r'^app/', include('website.app_urls')),
url(r'^geo/', include('geo.urls')),
url(r'^comentarios/', include('comentarios.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
#url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
#url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': STATIC_ROOT,
'show_indexes': True}),
)<file_sep># Django settings for dalero project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
ADMINS = (
# ('<NAME>', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dalero_db', # Or path to database file if using sqlite3.
'USER': 'dalerouser', # Not used with sqlite3.
'PASSWORD': '<PASSWORD>', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
TIME_ZONE = 'America/Caracas'
LANGUAGE_CODE = 'es-la'
SITE_ID = 1
USE_I18N = False
USE_L10N = False
USE_TZ = True
MEDIA_ROOT = os.path.join(ROOT_PATH, '../media/')
MEDIA_URL = "/media/"
STATIC_ROOT = os.path.join(ROOT_PATH, '../static/')
STATIC_URL = '/static/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = 'w&<KEY>(dgut^)gl#)7qa#g4ad'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
)
ROOT_URLCONF = 'dalero.urls'
WSGI_APPLICATION = 'dalero.wsgi.application'
TEMPLATE_DIRS = (os.path.join(ROOT_PATH, '../templates/'),)
LOGIN_URL = '/login/'
INSTALLED_APPS = (
'django.contrib.sessions',
'website',
'usuarios',
'geo',
'comentarios'
)
TWITTER = {'KEY' : '<KEY>',
'SECRET' : 'mIJlwd8UlUCD2jIMBr00mEaNVJc6Xfwg2qfOeKLP6A',
'CALLBACK' : 'http://dalero.net/users/twitter_callback/'}
FACEBOOK = {'KEY' : '437709029599876',
'SECRET' : 'aae3a045a95c8296770d37001b027ee9',
'CALLBACK' : 'http://dalero.net/users/facebook_callback/'}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
|
b268b5cd471cb6e12f8a9281092c6f0b3565d0d6
|
[
"JavaScript",
"Python"
] | 17 |
Python
|
elreychagi/parkero
|
878ff24709c6d7157f07c3112269103ca2dc4d3d
|
77136237ad49f0483b0b628c817007acca7c3e24
|
refs/heads/main
|
<file_sep>from PIL import Image, ImageFilter
import os
# 해당 파일이 없다면 => 특정 파일을 생성하기 (os를 쓰지 않음)
# 일단 파일을 open => 예외 처리
# https://pillow.readthedocs.io/en/stable/reference/Image.html
targetRoot = "./target/"
sourceRoot = "./source/"
fileList = os.listdir(sourceRoot)
for fileName in fileList:
sourceImg = Image.open(sourceRoot + fileName).convert("RGB")
fName = fileName[:-len(fileName.split('.')[-1]) - 1]
fileNum = 0
width = sourceImg.width
height = sourceImg.height
widt = sourceImg.width
heigh = sourceImg.height
widthDiff = width * 20 // 100
heighthDiff = height * 20 // 100
widthDif = widt * 30 // 100
heighthDif = heigh * 30 // 100
os.mkdir(targetRoot + fName)
targetDirectory = targetRoot + fName + "/"
# targetDirectory = "./target/imageName/"
for degree in range(-20, 21, 4):
targetImg = sourceImg.rotate(degree, fillcolor=(255, 255, 255, 255))
targetImg = targetImg.convert("RGB")
targetImg.save(targetDirectory + f'{fileNum}.jpg', "JPEG")
fileNum += 1
targetImgBlur = targetImg.filter(filter=ImageFilter.BLUR)
targetImgBlur.save(targetDirectory + f'{fileNum}.jpg', "JPEG")
fileNum += 1
targetImgCrop = targetImg.crop((widthDiff, heighthDiff, width-widthDiff, height-heighthDiff))
targetImgCrop.save(targetDirectory + f'{fileNum}.jpg', "JPEG")
fileNum += 1
targetImgCrop = targetImg.crop((widthDif, heighthDif, widt-widthDif, heigh-heighthDif))
targetImgCrop.save(targetDirectory + f'{fileNum}.jpg', "JPEG")
fileNum += 1
|
40de6c692be0af40354b85622243abb375f51385
|
[
"Python"
] | 1 |
Python
|
dhkdl/test
|
832dad530c8e77e6886a15e0c0daf9bb7566772e
|
3382df009b81f496e230ba0986a872eb148d91b6
|
refs/heads/master
|
<file_sep># HNSWGO
This is a golang interface of [hnswlib](https://github.com/nmslib/hnswlib). For more information, please follow [hnswlib](https://github.com/nmslib/hnswlib) and [Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs.](https://arxiv.org/abs/1603.09320).
# Compile (Optional)
```bash
git clone github.com/evan176/hnswgo.git
cd hnswgo && make
sudo cp libhnsw.so /usr/local/lib
ldconfig
```
# Usages
1. Download shared library
```bash
sudo wget https://github.com/evan176/hnswgo/releases/download/v1/libhnsw.so -P /usr/local/lib/
ldconfig
```
2. Export CGO variable
```
export CGO_CXXFLAGS=-std=c++11
```
3. Go get
```
go get github.com/evan176/hnswgo
```
| argument | type | |
| -------------- | ---- | ----- |
| dim | int | vector dimension |
| M | int | see[ALGO_PARAMS.md](https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md) |
| efConstruction | int | see[ALGO_PARAMS.md](https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md) |
| randomSeed | int | random seed for hnsw |
| maxElements | int | max records in data |
| spaceType | str | |
| spaceType | distance |
| --------- |:-----------------:|
| ip | inner product |
| cosine | cosine similarity |
| l2 | l2 |
```go
package main
import (
"fmt"
"math/rand"
"github.com/evan176/hnswgo"
)
func randVector(dim int) []float32 {
vec := make([]float32, dim)
for j := 0; j < dim; j++ {
vec[j] = rand.Float32()
}
return vec
}
func main() {
var dim, M, efConstruction int = 128, 32, 300
// Maximum elements need to construct index
var maxElements uint32 = 1000
// Define search space: l2 or ip (innder product)
var spaceType, indexLocation string = "l2", "hnsw_index.bin"
// randomSeed int = 100
// Init new index with 1000 vectors in l2 space
h := hnswgo.New(dim, M, efConstruction, randomSeed, maxElements, spaceType)
// Insert 1000 vectors to index. Label type is uint32.
var i uint32
for ; i < maxElements; i++ {
h.AddPoint(randVector(dim), i)
}
h.Save(indexLocation)
h = hnswgo.Load(indexLocation, dim, spaceType)
// Search vector with maximum 10 nearest neighbors
h.setEf(15)
searchVector := randVector(dim)
labels, dists := h.SearchKNN(searchVector, 10)
for i, l := range labels {
fmt.Printf("Nearest label: %d, dist: %f\n", l, dists[i])
}
}
```
# References
<NAME>., and <NAME>. "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs." TPAMI, preprint: [https://arxiv.org/abs/1603.09320]
<file_sep>// hnsw_wrapper.h
#ifdef __cplusplus
extern "C" {
#endif
typedef void* HNSW;
HNSW initHNSW(int dim, unsigned long int max_elements, int M, int ef_construction, int rand_seed, char stype);
HNSW loadHNSW(char *location, int dim, char stype);
HNSW saveHNSW(HNSW index, char *location);
void freeHNSW(HNSW index);
void addPoint(HNSW index, float *vec, unsigned long int label);
int searchKnn(HNSW index, float *vec, int N, unsigned long int *label, float *dist);
void setEf(HNSW index, int ef);
#ifdef __cplusplus
}
#endif
<file_sep>//hnsw_wrapper.cpp
#include <iostream>
#include "hnswlib/hnswlib.h"
#include "hnsw_wrapper.h"
#include <thread>
#include <atomic>
HNSW initHNSW(int dim, unsigned long int max_elements, int M, int ef_construction, int rand_seed, char stype) {
hnswlib::SpaceInterface<float> *space;
if (stype == 'i') {
space = new hnswlib::InnerProductSpace(dim);
} else {
space = new hnswlib::L2Space(dim);
}
hnswlib::HierarchicalNSW<float> *appr_alg = new hnswlib::HierarchicalNSW<float>(space, max_elements, M, ef_construction, rand_seed);
return (void*)appr_alg;
}
HNSW loadHNSW(char *location, int dim, char stype) {
hnswlib::SpaceInterface<float> *space;
if (stype == 'i') {
space = new hnswlib::InnerProductSpace(dim);
} else {
space = new hnswlib::L2Space(dim);
}
hnswlib::HierarchicalNSW<float> *appr_alg = new hnswlib::HierarchicalNSW<float>(space, std::string(location), false, 0);
return (void*)appr_alg;
}
HNSW saveHNSW(HNSW index, char *location) {
((hnswlib::HierarchicalNSW<float>*)index)->saveIndex(location);
return ((hnswlib::HierarchicalNSW<float>*)index);
}
void freeHNSW(HNSW index) {
hnswlib::HierarchicalNSW<float>* ptr = (hnswlib::HierarchicalNSW<float>*) index;
delete ptr;
}
void addPoint(HNSW index, float *vec, unsigned long int label) {
((hnswlib::HierarchicalNSW<float>*)index)->addPoint(vec, label);
}
int searchKnn(HNSW index, float *vec, int N, unsigned long int *label, float *dist) {
std::priority_queue<std::pair<float, hnswlib::labeltype>> gt;
try {
gt = ((hnswlib::HierarchicalNSW<float>*)index)->searchKnn(vec, N);
} catch (const std::exception& e) {
return 0;
}
int n = gt.size();
std::pair<float, hnswlib::labeltype> pair;
for (int i = n - 1; i >= 0; i--) {
pair = gt.top();
*(dist+i) = pair.first;
*(label+i) = pair.second;
gt.pop();
}
return n;
}
void setEf(HNSW index, int ef) {
((hnswlib::HierarchicalNSW<float>*)index)->ef_ = ef;
}
<file_sep>package hnswgo
// #cgo CFLAGS: -I./
// #cgo LDFLAGS: -lhnsw
// #include <stdlib.h>
// #include "hnsw_wrapper.h"
import "C"
import (
"math"
"unsafe"
)
type HNSW struct {
index C.HNSW
spaceType string
dim int
normalize bool
}
func New(dim, M, efConstruction, randSeed int, maxElements uint32, spaceType string) *HNSW {
var hnsw HNSW
hnsw.dim = dim
hnsw.spaceType = spaceType
if spaceType == "ip" {
hnsw.index = C.initHNSW(C.int(dim), C.ulong(maxElements), C.int(M), C.int(efConstruction), C.int(randSeed), C.char('i'))
} else if spaceType == "cosine" {
hnsw.normalize = true
hnsw.index = C.initHNSW(C.int(dim), C.ulong(maxElements), C.int(M), C.int(efConstruction), C.int(randSeed), C.char('i'))
} else {
hnsw.index = C.initHNSW(C.int(dim), C.ulong(maxElements), C.int(M), C.int(efConstruction), C.int(randSeed), C.char('l'))
}
return &hnsw
}
func Load(location string, dim int, spaceType string) *HNSW {
var hnsw HNSW
hnsw.dim = dim
hnsw.spaceType = spaceType
pLocation := C.CString(location)
if spaceType == "ip" {
hnsw.index = C.loadHNSW(pLocation, C.int(dim), C.char('i'))
} else if spaceType == "cosine" {
hnsw.normalize = true
hnsw.index = C.loadHNSW(pLocation, C.int(dim), C.char('i'))
} else {
hnsw.index = C.loadHNSW(pLocation, C.int(dim), C.char('l'))
}
C.free(unsafe.Pointer(pLocation))
return &hnsw
}
func (h *HNSW) Save(location string) {
pLocation := C.CString(location)
C.saveHNSW(h.index, pLocation)
C.free(unsafe.Pointer(pLocation))
}
func (h *HNSW) Free() {
C.freeHNSW(h.index)
}
func normalizeVector(vector []float32) []float32 {
var norm float32
for i := 0; i < len(vector); i++ {
norm += vector[i] * vector[i]
}
norm = 1.0 / (float32(math.Sqrt(float64(norm))) + 1e-15)
for i := 0; i < len(vector); i++ {
vector[i] = vector[i] * norm
}
return vector
}
func (h *HNSW) AddPoint(vector []float32, label uint32) {
if h.normalize {
vector = normalizeVector(vector)
}
C.addPoint(h.index, (*C.float)(unsafe.Pointer(&vector[0])), C.ulong(label))
}
func (h *HNSW) SearchKNN(vector []float32, N int) ([]uint32, []float32) {
Clabel := make([]C.ulong, N, N)
Cdist := make([]C.float, N, N)
if h.normalize {
vector = normalizeVector(vector)
}
numResult := int(C.searchKnn(h.index, (*C.float)(unsafe.Pointer(&vector[0])), C.int(N), &Clabel[0], &Cdist[0]))
labels := make([]uint32, N)
dists := make([]float32, N)
for i := 0; i < numResult; i++ {
labels[i] = uint32(Clabel[i])
dists[i] = float32(Cdist[i])
}
return labels[:numResult], dists[:numResult]
}
func (h *HNSW) SetEf(ef int) {
C.setEf(h.index, C.int(ef))
}
<file_sep>CXX=g++
INCLUDES=-I.
CXXFLAGS=-fPIC -pthread -Wall -std=c++0x -std=c++11 -O2 -march=native $(INCLUDES)
LDFLAGS=-shared
OBJS=hnsw_wrapper.o
TARGET=libhnsw.so
all: $(TARGET)
$(OBJS): hnsw_wrapper.h hnsw_wrapper.cc hnswlib/*.h
$(CXX) $(CXXFLAGS) -c hnsw_wrapper.cc
$(TARGET): $(OBJS)
$(CXX) $(LDFLAGS) -o $(TARGET) $(OBJS)
clean:
rm -rf $(OBJS) $(TARGET)
|
61b434b11b980ae2695b3043d46baebe628d07d6
|
[
"Markdown",
"Makefile",
"C",
"Go",
"C++"
] | 5 |
Markdown
|
evan176/hnswgo
|
39253a76f9e49934fc483b54ce96a937f0618804
|
de96790bada6a496a3fef24fdfb552ab3f7d65a0
|
refs/heads/master
|
<file_sep>#include <iostream>
#include "oracle_operator.h"
OracleOperator::OracleOperator(std::string user, std::string password, std::string dburl)
{
env = oracle::occi::Environment::createEnvironment(oracle::occi::Environment::DEFAULT);
try {
conn = env->createConnection(user, password, dburl);
} catch (oracle::occi::SQLException& ex) {
std::cout << "code: " << ex.getErrorCode() << " message: " << ex.getMessage() << std::endl;
}
}
OracleOperator::~OracleOperator()
{
env->terminateConnection(conn);
oracle::occi::Environment::terminateEnvironment(env);
}
void* OracleOperator::select(const std::string& sql, oracleCallBack callBack)
{
void* result = nullptr;
try {
stmt = conn->createStatement(sql);
oracle::occi::ResultSet* resultSet = stmt->executeQuery();
if (callBack != nullptr) {
result = callBack(resultSet);
}
stmt->closeResultSet(resultSet);
conn->terminateStatement(stmt);
} catch (oracle::occi::SQLException& ex) {
std::cout << "code: " << ex.getErrorCode() << " message: " << ex.getMessage() << std::endl;
}
return result;
}
unsigned int OracleOperator::executeUpdate(const std::string& sql)
{
unsigned int result;
stmt = conn->createStatement();
result = stmt->executeUpdate(sql);
conn->commit();
conn->terminateStatement(stmt);
return result;
}
<file_sep>#pragma once
#include <windows.h>
#include <functional>
#include "oracle_operator.h"
//typedef void (*toolCallBack)(const std::string path, const std::string filename, WIN32_FIND_DATA* findData, void* para);
typedef std::function <void (const std::string, const std::string, const WIN32_FIND_DATA*, void*)> toolCallBack;
class WinTools {
private:
UINT m_uElapse;
static std::string sm_srcdir;
static toolCallBack sm_callBack;
static OracleOperator* sm_orclOper;
static void iteratorDir(const std::string subdir);
public:
WinTools(UINT uElapse);
void start();
static void setCallBack(toolCallBack callBack);
static void setSrcdir(std::string srcdir);
static void setOracOper(OracleOperator* orclOper);
static OracleOperator* getOrclOper();
};
<file_sep>#include "tool.h"
#include "oracle_operator.h"
#include <iostream>
#include <fstream>
#include "tinyxml2.h"
std::string getTodayLogFileName()
{
SYSTEMTIME now;
GetLocalTime(&now);
char ct[18];
std::snprintf(ct, 18, "logs\\%4d%02d%02d.log", now.wYear, now.wMonth, now.wDay);
return ct;
}
std::string getCurrentTime()
{
SYSTEMTIME now;
GetLocalTime(&now);
char ct[24];
std::snprintf(ct, 24, "%4d-%02d-%02d %02d:%02d:%02d.%03d", now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond, now.wMilliseconds);
return ct;
}
int main(int argc, char* argv[])
{
if (argc < 6) {
std::cout << "usage:" << argv[0] << " <user> <password> <dburl> <srcdir> <interval>\n";
exit(1);
}
std::string user = argv[1];
std::string password = argv[2];
std::string dburl = argv[3];
std::string srcdir = argv[4];
int interval = std::atoi(argv[5]);
OracleOperator *oracleOper = new OracleOperator(user, password, dburl);
/*oracleOper->select("select login_name from user_user", [user](void* rs) -> void* {
oracle::occi::ResultSet* resultSet = (oracle::occi::ResultSet*) rs;
while (resultSet->next()) {
std::cout << user << "--login_name: " << resultSet->getString(1) << std:: endl;
}
return nullptr;
});*/
std::string preLogFileName = getTodayLogFileName();
std::ofstream logFile = std::ofstream(getTodayLogFileName());
WinTools::setSrcdir(srcdir);
WinTools::setCallBack([&preLogFileName, &logFile, &oracleOper](const std::string srcdir, const std::string filename, const WIN32_FIND_DATA* findData, void* para) {
//std::cout << "filename: [" << filename << "]\n";
tinyxml2::XMLDocument doc;
std::string path = srcdir + "\\" + filename;
doc.LoadFile(path.c_str());
tinyxml2::XMLElement* rootElement = doc.FirstChildElement("InventoryStatus");
if (rootElement == nullptr) {
std::cout << "not input invt, not handle!!!\n";
return;
}
std::string ebcCode(rootElement->FirstChildElement("ebcCode")->GetText());
std::string copNo(rootElement->FirstChildElement("copNo")->GetText());
std::string newInvtNo(rootElement->FirstChildElement("invtNo")->GetText());
std::string cusStatus(rootElement->FirstChildElement("returnStatus")->GetText());
std::cout << "ebcCode: [" << ebcCode << "] copNo: [" << copNo << "] cusStatus: [" << cusStatus << "]\n";
oracleOper->select("select t.app_status, t.invt_no from ceb2_invt_head t where t.ebc_code = '"
+ ebcCode + "' and t.cop_no = '" + copNo + "'", [&preLogFileName, &logFile, &ebcCode, &copNo, &cusStatus, &newInvtNo, &oracleOper](void* rs) -> void* {
oracle::occi::ResultSet* resultSet = (oracle::occi::ResultSet*) rs;
if (resultSet->next()) {
std::string appStatus = resultSet->getString(1);
std::string invtNo = resultSet->getString(2);
std::cout << "ent-> ebcCode: [" << ebcCode << "] copNo: [" << copNo << "] appStatus: [" << appStatus
<< "] invtNo: [" << invtNo << "]\n";
if (invtNo == "" && appStatus != "100" && appStatus != "800" && appStatus != "899" && cusStatus == "26") {
std::string updateInvt = "update ceb2_invt_head t set t.invt_no = '" + newInvtNo + "', t.app_status='800' where t.ebc_code = '" + ebcCode
+ "' and t.cop_no = '" + copNo + "'";
oracleOper->executeUpdate(updateInvt);
std::string newFileName = getTodayLogFileName();
if (newFileName != preLogFileName) {
logFile.close();
logFile = std::ofstream(newFileName);
preLogFileName = newFileName;
}
logFile << "[" << getCurrentTime() << "] update ebcCode: [" << ebcCode << "] copNo: [" << copNo << "] appStatus: [800] invtNo: [" << newInvtNo << "] success!\n";
logFile.flush();
}
return nullptr;
}
return nullptr;
});
});
WinTools::setOracOper(oracleOper);
WinTools tool = WinTools(interval);
tool.start();
delete oracleOper;
logFile.close();
return 0;
}<file_sep>#pragma once
#include <string>
#include <functional>
#include <occi.h>
//typedef void* (*oracleCallBack)(void* para);
typedef std::function<void* (void*)> oracleCallBack;
class OracleOperator
{
private:
oracle::occi::Environment* env;
oracle::occi::Connection* conn;
oracle::occi::Statement* stmt;
public:
OracleOperator(std::string user, std::string password, std::string dburl);
~OracleOperator();
void* select(const std::string& sql, oracleCallBack callBack);
unsigned int executeUpdate(const std::string& sql = "");
};
<file_sep>#include "tool.h"
#include <iostream>
#include <cstdio>
#include <ctime>
std::string WinTools::sm_srcdir = "";
toolCallBack WinTools::sm_callBack = nullptr;
OracleOperator* WinTools::sm_orclOper = nullptr;
void WinTools::iteratorDir(const std::string subdir)
{
HANDLE hFind;
WIN32_FIND_DATA findData;
std::string dirNew = WinTools::sm_srcdir + "\\" + subdir;
std::string dirSearch = dirNew + "\\*.*";
hFind = FindFirstFile(dirSearch.c_str(), &findData);
if (hFind == INVALID_HANDLE_VALUE) {
std::cout << "Failed to find first file!\n";
return;
}
do {
if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0)
continue;
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
std::cout << "dir not handle\n";
continue;
}
else {
std::cout << "find file is: " << findData.cFileName << "\n";
WinTools::sm_callBack(dirNew, findData.cFileName, &findData, nullptr);
}
} while (FindNextFile(hFind, &findData));
FindClose(hFind);
}
WinTools::WinTools(UINT uElapse): m_uElapse(uElapse * 1000)
{
}
void WinTools::start()
{
BOOL bRet;
MSG msg;
UINT timerid = SetTimer(NULL, 0, m_uElapse, [](HWND hWnd, UINT message, UINT_PTR idTimer, DWORD dwTime) {
std::time_t today = std::time(nullptr) - 60 * 60;
std::tm ttoday;
std::tm* tmtoday = &ttoday;
localtime_s(&ttoday, &today);
char ctoday[11];
std::snprintf(ctoday, 15, "%4d%02d%02d%02d", tmtoday->tm_year + 1900, tmtoday->tm_mon + 1, tmtoday->tm_mday,
tmtoday->tm_hour);
SYSTEMTIME now;
GetLocalTime(&now);
char ct[15];
std::snprintf(ct, 15, "%4d%02d%02d%02d%02d%02d", now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond);
std::cout << "start... time: [" << ct << "] subdir: [" << ctoday << "]\n";
WinTools::iteratorDir(ctoday);
});
while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0) {
if (bRet == -1) {
}
else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
void WinTools::setCallBack(toolCallBack callBack)
{
sm_callBack = callBack;
}
void WinTools::setSrcdir(std::string srcdir)
{
sm_srcdir = srcdir;
}
void WinTools::setOracOper(OracleOperator* orclOper)
{
sm_orclOper = orclOper;
}
OracleOperator* WinTools::getOrclOper()
{
return sm_orclOper;
}
|
a5b784db9aecf6273646ebb5554f5853d35adc85
|
[
"C++"
] | 5 |
C++
|
zhaopei8948/modify-invt-cusstatus
|
6b87f59629ab9ecb04a9e95efeea2037548b48b5
|
989aab37996c56d9dfca9220ea5e27e071c453b8
|
refs/heads/master
|
<file_sep>#Task notes
This is just a summary of my thoughts while doing the test.
##Usage
There are 3 endpoints to the given API:
1) `convert` will take a variable `integer` and return the provided integer and a roman numeral.
2) `recent` will list all recently converted integers. You can pass through a `period` variable of day, week or month to
change the time limit.
3) `common` will list the 10 most commonly converted integers. You can send `timestamps = true` to view when these were
most recently converted.
##Thoughts
For the database I only created the one "conversions" table, and used an index to make finding rows based on the integers
easy. I considered using multiple tables for this - one to act as a cache of converted integers (with the most recently
converted date) and another to store the counts, but realised this would fail to show an accurate history if the same integer
were converted multiple times.
I set the number of characters for the "numeral" field to 32, but did cheat a bit and find that the longest possible
conversion was from 3888 with 15 characters at MMMDCCCLXXXVIII. It might then have made more sense to set the limit for
the numeral column to '15', however I didn't really think it was a necessary optimisation.
When I had everything set up the biggest questions were ones of which route to take, which to be fair is almost always the case.
I opted to not have 2 tables for storing the conversion and most recent date time and probably made several other decisions
not for optimisation but to actually have something to work from.
##Where I struggled
The most challenging aspect of this test was actually not the development itself, but rather setting up the environment.
Due to some misunderstandings of the Laravel/Homestead vagrant box and then some strange issues with windows well over half
the time spent was on getting something set up for testing in the first place.
IDE support for laravel isn't excellent, so another big time sink was sorting out which functions did and didn't exist in
each class. I ended up getting a composer package which solved most of the issues.
In general it was tricky for me to decide where bits of logic should go. I tried to go with leaving all models in the "app"
folder as is Laravel's default, but I did find it harder to decide what was worthy of being a model (if I were to do it again
I would probably namespace models and place them in folders e.g. Entities, Validation, Responses folders).
Eloquent's way of working with models is actually very different to what I expected, and I found myself pausing a lot while
working with the models. This was due to the lack of field definitions, and ways of interacting with the data when you
retrieve it from the model. This is quite easily solved with phpdoc blocks/experience, however, and likely a matter of inexperience.
##What I would do differently if starting over
* I would most definitely not name the conversion totals table "total" and give the column name "total". It just made naming
unnecessarily complex.
* Create more 'services' and put less logic in the controller.
* In a similar vein, create either a dedicated validation Model or just have clearer validation functions. I avoided
changing the provided interface as much as possible, which lead to the validation being in strange places.
* Probably make separate transformers for timestamps, as the current method places it inside another array - good if it
were expanded into more generic "metadata", but not good for the current API endpoints
* When creating the endpoints I would probably make use of the ability to take variables from URLs in routes, e.g. `Route::get('/convert/{integer}', "ConvertController@convert")->where('integer', '[0-9]+');`
* Create a 'unique' option when listing recent transactions, to select from the Totals table instead of the conversions.
* Make use of pagination/variable limits for the common and recent endpoints.
* Use branches in git, I didn't due to the size of the test but should have done to keep better track of changes.
##Running commentary
This is a list of thoughts and comments done while writing the test, initially imported from OneNote.
The first half is a long list of failures, with some more constructive thoughts later on.
* My available options are:
* Host remotely, set up my git repo there and push to it.
* Use a bare repo and a clone that's used to display the site?
* Set up Vagrant box or php in windows and run locally - may be an issue with sorting out db things.
* Decided to use virtualbox and laravel\homestead to spin up a remote box.
* After creating vagrant box was unable to retrieve a response from the server, this was due to laravel not being installed
in the vendor folder. (composer issue)
* Installed composer on windows due to ease of use in future, sadly not compatible with the remote interpreter in PHPStorm.
* Installed PHP 7.1 interpreter, added PHP to the PATH and enabled extensions with some edits to the php.ini
* When running composer discovered an error where Symfony's HttpKernel was not installed correctly - it exists in
vendor/composer/b037c860/symfony-http-kernel-c830387/HttpKernelInterface.php but not in vendor/symfony.
* This was due to an issue I thought was solved earlier where running php artisan optimize failed (php not defined). I
thought this was fixed by adding php to the PATH since retrying composer did not fail again, but evidently not. Attempted
solution: restart computer.
* Solution did not work, turns out I messed up when adding php to the PATH. Composer now installs fine.
* discovered I had not yet enabled virtualization in my BIOS, changed motherboards since the last time working with VMs.
* I used the Homestead/Laravel composer component to generate a vagrantfile, and the app is accessible via SSH using localhost:2222
* _At this point I didn't realise I hadn't actually got the server running and thought the issue may have been to do with
there not being a default landing page_ Currently working on which class is needed for Route, since there are many possible answers.
Here is where I gave up on Laravel/Homestead. I didn't write anything in the log on tuesday while working this out.
* Tuesday 01/08/17 21:25pm Finally got a server running that shows something! Gave up on homestead/laravel completely, tried
running with php artisan serve
* Ran into an issue where everything was returning "not found" errors, found laravel.log and it was pointing to index.php then to the compiled files
```
[2017-08-0120:21:26]production.ERROR:RuntimeException:TheonlysupportedciphersareAES-128-CBCandAES-256-CBCwiththecorrectkeylengths.inD:\Documents\Projects\RomanNumerals-API\bootstrap\cache\compiled.php:13520
Stacktrace:
#0D:...\RomanNumerals-API\bootstrap\cache\compiled.php(7927):Illuminate\Encryption\Encrypter->__construct('','AES-256-CBC')
#1D:...\RomanNumerals-API\bootstrap\cache\compiled.php(1477):Illuminate\Encryption\EncryptionServiceProvider->Illuminate\Encryption\{closure}(Object(Illuminate\Foundation\Application),Array)
#2D:...\RomanNumerals-API\bootstrap\cache\compiled.php(1433):Illuminate\Container\Container->build(Object(Closure),Array)
#3D:...\RomanNumerals-API\bootstrap\cache\compiled.php(2011):Illuminate\Container\Container->make('encrypter',Array)
#4D:...\RomanNumerals-API\bootstrap\cache\compiled.php(1534):Illuminate\Foundation\Application->make('encrypter')
#5D:...\RomanNumerals-API\bootstrap\cache\compiled.php(1511):Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#6D:...\RomanNumerals-API\bootstrap\cache\compiled.php(1497):Illuminate\Container\Container->getDependencies(Array,Array)
#7D:...\RomanNumerals-API\bootstrap\cache\compiled.php(1433):Illuminate\Container\Container->build('App\\Http\\Middle...',Array)
#8D:...\RomanNumerals-API\bootstrap\cache\compiled.php(2011):Illuminate\Container\Container->make('App\\Http\\Middle...',Array)
#9D:...\RomanNumerals-API\bootstrap\cache\compiled.php(2529):Illuminate\Foundation\Application->make('App\\Http\\Middle...')
#10D:...\RomanNumerals-API\public\index.php(58):Illuminate\Foundation\Http\Kernel->terminate(Object(Illuminate\Http\Request),Object(Illuminate\Http\Response))
#11D:...\RomanNumerals-API\server.php(21):require_once('D:\\Documents\\Pr...')
#12{main}
```
* Did the obvious and googled the exception, discovered that this was likely due to a lack of an application key, and ran `php artisan key:generate`
* Created a home template in blade, it was refreshingly simple to do.
* Installed fractal using composer as it wasn't pre-installed. Not updated the composer.json or composer.lock files though.
* Created a numerals table using artisan migrate, I had to change the environment to work on root though (no changes required for other things).
* In implementing the Roman Numeral conversion, I would have placed the type checking of the value in the function arguments
using scalar type hinting, but decided to obey the interface as given.
* I was initially going to have the Numerals table use an "index" on the integer column. This would have interfered with
the requirement to view the most recently stored integers, and so was removed.
* I also initially created the "Numerals" table using `php artisan make:migration create_numerals_table --table=numerals`
instead of using php `model:make model Numerals -m`. This wasn't really a mistake, just inefficient.
* Realised that effective use of Fractal resources would make it much easier to work with a `totals` table, so going to make one now.
* Now using the Fractal Transformers to return data - the ConversionTransformer works better just returning the integer
and roman numerals, but the client may want to view the "most recent" data as well. It looks like this would be best dealt
with using the "includes" method from Fractal\Transformer.
* Created a TimestampTransformer that can work for any Eloquent model - gated by the Parent Transformers at the moment.
* After adding the ability to specify a time period for the recent conversions, I've had a look at the controller and really
don't like how messy the code is. I'm not sure whether to create a service for recent conversions, or to try and leave it as it is.
* Left the time period logic in the controller, it's definitely the worst code there - should probably use something in the
constants to help with the logic and either have a foreach() loop over valid time periods or use an associative array and just find the index.
* Removed blade templates as everything is now working using JSON.
* Decided to look up Exception Handling and found a much nicer way using Laravel - tried to implement that<file_sep><?php
/** This route is used to convert an integer.
* Not currently using the "/convert/{$id}" syntax as wanted to use Request objects.
*/
Route::get('/convert', "ConvertController@convert");
Route::get("/recent", "ConvertController@recent");
Route::get('/common', "ConvertController@common");<file_sep><?php
namespace App;
use League\Fractal;
class TotalTransformer extends Fractal\TransformerAbstract
{
protected $availableIncludes = ["timestamps"];
public function transform(Total $total) {
return [
'integer' => (int) $total->integer,
'total' => (int) $total->total
];
}
/**
* @param Total $total
* @return Fractal\Resource\Item
*/
public function includeTimestamps(Total $total) {
return $this->item($total, new TimestampTransformer);
}
}<file_sep><?php
namespace App;
use League\Fractal;
/**
* Used to generate a Fractal Resource friendly array, to ease creating JSON responses.
* Class ConversionTransformer
* @package App
*/
class ConversionTransformer extends Fractal\TransformerAbstract
{
protected $availableIncludes = [
'timestamps'
];
public function transform(Conversion $conversion) {
return [
'integer' => (int) $conversion->integer,
'numeral' => $conversion->numeral
];
}
/**
* @param Conversion $conversion
* @return Fractal\Resource\Item
*/
public function includeTimestamps(Conversion $conversion) {
return $this->item($conversion, new TimestampTransformer);
}
}<file_sep><?php
namespace App;
interface IntegerConversionInterface
{
/** convert a given integer to roman numerals.
* @param $integer
* @return string a Roman Numeral
*/
public function toRomanNumerals($integer);
}<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* App\Total
*
* @mixin \Eloquent
*/
class Total extends Model
{
/** @var string column for primary key */
public $primaryKey = "integer";
/** @var bool let the model builder know not to increment the primary key */
public $incrementing = false;
/** @var array which fields can be set */
protected $fillable = array("integer", "total");
}
<file_sep><?php
namespace App;
use InvalidArgumentException;
/**
* This class exists to perform integer conversions to various formats.
* Class IntegerConversion
* @package App
*/
class IntegerConversion implements IntegerConversionInterface
{
/**
* @var array Map of roman numerals with their values.
*/
private $numeralValues = [
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1
];
/**
* @param $integer
* @return string
*/
public function toRomanNumerals($integer) {
if(!is_int($integer)) {
//passing a non-integer to IntegerConversion is just wrong.
throw new InvalidArgumentException("Non-integer passed for conversion", 400);
}
if($integer < 1 || $integer > 3999) {
throw new InvalidArgumentException("Invalid integer passed for conversion", 400);
}
$romanNumeral = "";
foreach($this->numeralValues as $numeral => $value) {
//how many times current numeral goes into the integer
$matches = intval($integer/$value);
//Add the numeral to the string that many times
$romanNumeral.= str_repeat($numeral, $matches);
//remove that factor from the integer before continuing. Variables are mutable!
$integer = $integer % $value;
}
return $romanNumeral;
}
}<file_sep><?php
namespace App;
use League\Fractal\TransformerAbstract;
use Illuminate\Database\Eloquent\Model;
/**
* This may be cheating and insecure if we wish to hide dates for future requests, however right now it allows the user
* to optionally include the timestamps for any Transformer provided that Transformer supports it.
* @package App
*/
class TimestampTransformer extends TransformerAbstract
{
/**
* Take any Eloquent Model and create a timestamp field for use in other Transformers.
* @param Model $model
* @return array
*/
public function transform(Model $model) {
return [
'last_converted' => $model->updated_at->toDateTimeString()
];
}
}<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* App\Conversion
*
* @mixin \Eloquent
*/
class Conversion extends Model
{
//Say which attributes are mass assignable
protected $fillable = array("integer", "numeral");
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
* Date: 01/08/2017
* Time: 22:27
*/
namespace App\Http\Controllers;
use App\Conversion;
use App\ConversionTransformer;
use App\IntegerConversion;
use App\Total;
use App\TotalTransformer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
class ConvertController extends Controller
{
/** @var Manager manager used to present responses */
protected $fractal;
/** @const int number of records to retrieve for a "common" request */
const COMMON_LIMIT = 10;
const PERIOD_DAY = "day";
const PERIOD_WEEK = "week";
const PERIOD_MONTH = "month";
/** @const array valid time periods for "recent" call */
const ALLOWED_PERIODS = [self::PERIOD_DAY, self::PERIOD_WEEK, self::PERIOD_MONTH];
public function __construct(){
$this->fractal = new Manager();
}
/**
* Take an integer and convert it into a roman numeral, storing the conversion.
*
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function convert(Request $request) {
$integer = $request->input('integer');
$integerConverter = new IntegerConversion();
if(empty($integer)){
throw new \InvalidArgumentException("No integer given to convert. Please pass any value to be converted using 'integer' in your request", 400);
}
$romanNumeral = $integerConverter->toRomanNumerals(intval($integer));
//store conversion
$conversion = Conversion::create([
"integer" => $integer,
"numeral" => $romanNumeral
]);
//update Conversion Totals
$total = Total::firstOrNew(["integer" => $integer]);
$total->total++;
$total->save();
//create Resource to return
$resource = new Item($conversion, new ConversionTransformer());
return response($this->fractal->createData($resource)->toJson())->header("Content-Type", "application/json");
}
/**
* Get the most recent Conversions and show them to the end user
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function recent(Request $request) {
$timePeriod = $request->get("period", self::PERIOD_WEEK);
$startDate = $this->getStartDate($timePeriod);
$recentConversions = Conversion::whereDate('updated_at', '>', $startDate)->orderBy('updated_at', 'DESC')->get();
//Always include timestamps for most recent conversions
$this->fractal->parseIncludes("timestamps");
$resource = new Collection($recentConversions, new ConversionTransformer());
return response($this->fractal->createData($resource)->toJson())->header("Content-Type", "application/json");
}
/**
* Return the top 10 most commonly requested integer conversions
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function common(Request $request) {
$commonConversions = Total::orderBy('total', 'DESC')->limit(self::COMMON_LIMIT)->get();
if($request->get("timestamps", false)){
$this->fractal->parseIncludes("timestamps");
}
$resource = new Collection($commonConversions, new TotalTransformer());
return response($this->fractal->createData($resource)->toJson())->header("Content-Type", "application/json");
}
/**
* Retrieve a date string a set period of time before now
*
* @param $timePeriod string period of time to search
* @return string
*/
private function getStartDate($timePeriod) {
if(!in_array($timePeriod, self::ALLOWED_PERIODS)) {
throw new \InvalidArgumentException("Invalid time period specified", 400);
}
$currentDate = Carbon::today();
//Check available options and change date accordingly.
// This is not nicely done right now as it doesn't work nicely with added options.
if($timePeriod === self::PERIOD_DAY) {
$startDate = $currentDate->copy()->subDay();
} else if($timePeriod === self::PERIOD_WEEK) {
$startDate = $currentDate->copy()->subWeek();
} else {
$startDate = $currentDate->copy()->subMonth();
}
return $startDate->toDateString();
}
}
|
d4118fcddcc4833ab637232ad08b9875a6fad8f6
|
[
"Markdown",
"PHP"
] | 10 |
Markdown
|
Hobohodo/RomanNumerals-API
|
de87958679bb143e73b7c678f650f5ce916154c8
|
28b22a27f6623cda8a500d3725ae4531f95ffe30
|
refs/heads/main
|
<repo_name>tenmugi/ScriptTest<file_sep>/Assets/Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boss
{
private int hp = 100;
private int power = 20;
private int mp = 53;
public void Attack()
{
Debug.Log(this.power + "のダメージを与えた");
}
public void Defence(int damage)
{
if (hp >= 5)
{
this.hp -= damage;
Debug.Log(damage + "のダメージを受けた");
}
else
{
Debug.Log("負けた");
}
}
public void Magic()
{
if (mp >= 5)
{
this.mp -= 5;
Debug.Log("魔法攻撃をした。残りMPは" + this.mp);
}
else
{
Debug.Log("MPが足りないため、魔法が使えない");
}
}
}
public class Test : MonoBehaviour
{
void Start()
{
Boss midboss = new Boss();
midboss.Attack();
midboss.Defence(5);
midboss.Magic();
for (int i = 0; i < 10; i++)
{
midboss.Magic();
}
for(int i = 0; i < 20; i++)
{
midboss.Defence(5);
}
int[] array = new int[5];
array[0] = 1;
array[1] = 3;
array[2] = 5;
array[3] = 7;
array[4] = 9;
for (int i = 0; i < 5; i++)
{
Debug.Log(array[i]);
}
for (int i = 4; i >= 0; i--)
{
Debug.Log(array[i]);
}
}
private void Update()
{
}
}
|
ae5f98d87f0859d5d88f58d79d55ade95fa962f1
|
[
"C#"
] | 1 |
C#
|
tenmugi/ScriptTest
|
9b19467bafd7dd1c120712d42c66537ef5ac3aae
|
4c2cd57ad2e6ff389a8e9ef0d09101dd9dbbfb7b
|
refs/heads/master
|
<repo_name>dev-vadym/gorpc<file_sep>/server.go
package gorpc
import (
"net/http"
"reflect"
"fmt"
"encoding/json"
"github.com/valyala/fasthttp"
)
type Server struct {
Secret string
services *serviceMap
OnExecute func(action string, req interface{}, res interface{})
OnError func(err error)
}
type Contexter interface {
Method() string
RequestUrl()string
RequestHeader(key string) string
RequestBody() ([]byte, error)
ResponseHeader(key, value string)
ResponseWrite(statusCode int, body []byte) error
}
func NewServer(secret string) *Server {
return &Server{Secret: secret, services: new(serviceMap)}
}
func (serv *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
ctx := NewHttpContext(writer, request)
serv.Execute(ctx)
}
func (serv *Server) ServeFastHTTP(httpCtx *fasthttp.RequestCtx) {
ctx := NewFastContext(httpCtx)
serv.Execute(ctx)
}
func (serv *Server) Execute(ctx Contexter) {
defer func() {
if rerr := recover(); rerr != nil{
if serv.OnError != nil{
serv.OnError(fmt.Errorf("rpc panic: %v", rerr))
}
}
}()
reply, err := serv.paserAndExecute(ctx)
wErr := serv.write(ctx, reply, err)
if wErr != nil && serv.OnError != nil{
serv.OnError(fmt.Errorf("rpc write error: %v", err))
}
}
func (serv *Server) Register(services ...interface{}) error {
for _, service := range services {
err := serv.RegisterWithName(service, "")
if err != nil {
return err
}
}
return nil
}
func (serv *Server) RegisterWithName(service interface{}, name string) error {
return serv.services.register(service, name)
}
func (serv *Server) paserAndExecute(ctx Contexter) (interface{}, error) {
if ctx.Method() != "POST" {
return nil, ErrURLInvalid
}
sign := ctx.RequestHeader("sign")
timestamp := ctx.RequestHeader("timestamp")
action := ctx.RequestHeader("action")
if sign == "" || timestamp == "" || action == "" {
return nil, ErrURLInvalid
}
byteBody, err := ctx.RequestBody()
if err != nil {
return nil, err
}
if serv.Secret != "" {
reqSign := makeSign(timestamp + string(byteBody), serv.Secret)
if reqSign != sign {
return nil, ErrPasswordIncorrect
}
}
serviceSpec, methodSpec, errGet := serv.services.get(action)
if errGet != nil {
return nil, fmt.Errorf("rpc found action %v error %v", action, errGet)
}
refArgs := reflect.New(methodSpec.argsType)
args := refArgs.Interface()
if len(byteBody) > 0 {
err := json.Unmarshal(byteBody, &args)
if err != nil {
return nil, err
}
}
// Call the service method.
refReply := reflect.New(methodSpec.replyType)
reply := refReply.Interface()
// omit the HTTP request if the service method doesn't accept it
var errValue []reflect.Value
errValue = serv.callFuc(methodSpec.method, []reflect.Value{
serviceSpec.rcvr,
refArgs,
refReply,
})
// Cast the result to error if needed.
var errResult error
errInter := errValue[0].Interface()
if errInter != nil {
errResult = errInter.(error)
}
if serv.OnExecute != nil{
if errResult != nil{
serv.OnExecute(action, args, errResult)
}else{
serv.OnExecute(action, args, reply)
}
}
return reply, errResult
}
func (serv *Server) callFuc(method reflect.Method, in []reflect.Value) (out []reflect.Value){
defer func() {
if err := recover(); err != nil{
out = []reflect.Value{reflect.ValueOf(err)}
}
}()
out = method.Func.Call(in)
return
}
func (serv *Server) write(ctx Contexter, reply interface{}, err error) error{
var body []byte
if err == nil && reply != nil {
body, err = json.Marshal(reply)
}
ctx.ResponseHeader("Content-Type", "application/json; charset=utf-8")
if err != nil {
ctx.ResponseHeader("msg", err.Error())
}
return ctx.ResponseWrite(http.StatusOK, body)
}
<file_sep>/readme.md
gorpc is a lightweight RPC over HTTP services, use password sign for security, providing access to the exported methods of an object through HTTP requests.
Features
--------
* Lightweight RPC
* Http service
* Password for security
Usage
---------
Install:
go get github.com/foolin/gorpc
Example
---------
## Service
```go
package rpcvo
type UserService struct {}
func (this *UserService) Say(name *string, reply *string) error {
*reply = "Hello, " + *name + "!"
return nil
}
```
## Server
```go
package main
import (
"net/http"
"log"
"github.com/foolin/gorpc"
"github.com/foolin/gorpc/example/rpcvo"
)
func main() {
log.SetFlags(log.Lshortfile|log.LstdFlags)
secrect := "<PASSWORD>" //password
server := gorpc.NewServer(secrect)
//=========== register rpc service =======//
//Register batch
err := server.Register(
new(rpcvo.UserService),
)
if err != nil {
log.Panicf("register error %v", err)
}
//=========== create http server =======//
mux := http.NewServeMux()
mux.Handle("/rpc", server)
log.Println("listen: 5080")
log.Print(http.ListenAndServe(":5080", mux))
}
```
## Client
```go
package main
import (
"github.com/foolin/gorpc"
"log"
"github.com/foolin/gorpc/example/rpcvo"
)
func main() {
//log.SetFlags(log.Lshortfile|log.LstdFlags)
client := gorpc.NewClient("http://127.0.0.1:5080/rpc", "1q2w3e")
var err error
//============= user service =============//
var sayReply string
err = client.Call("UserService.Say", "Foolin", &sayReply)
if err != nil {
log.Printf("UserService.Say error: %v", err)
}else{
log.Printf("UserService.Say result: %v", sayReply)
}
}
```
## Result
2016/04/14 10:25:58 UserService.Say result: Hello, Foolin!
## About
Reference [gorilla/rpc](https://github.com/gorilla/rpc)
<file_sep>/example/server/server.go
package main
import (
"net/http"
"log"
"github.com/foolin/gorpc"
"github.com/foolin/gorpc/example/rpcvo"
)
func main() {
log.SetFlags(log.Lshortfile|log.LstdFlags)
secrect := "<PASSWORD>" //password
server := gorpc.NewServer(secrect)
//=========== register rpc service =======//
//Register batch
err := server.Register(
new(rpcvo.UserService),
new(rpcvo.CalculatorService),
)
if err != nil {
log.Panicf("register error %v", err)
}
//Register with name
err = server.RegisterWithName(new(rpcvo.CalculatorService), "Cal")
if err != nil {
log.Panicf("register error %v", err)
}
//=========== create http server =======//
mux := http.NewServeMux()
mux.Handle("/rpc", server)
/*
//other way handler
mux.HandleFunc("/rpc", func(w http.ResponseWriter, req *http.Request) {
//befor handler, write code here!!!
server.ServeHTTP(w, req)
//after handler, write code here!!!
})
*/
log.Println("listen: 5080")
log.Print(http.ListenAndServe(":5080", mux))
}
<file_sep>/nethttp.go
package gorpc
import (
"net/http"
"io/ioutil"
"fmt"
)
type HttpContext struct {
request *http.Request
response http.ResponseWriter
}
func NewHttpContext(writer http.ResponseWriter, req *http.Request) *HttpContext {
return &HttpContext{request: req, response: writer}
}
func (ctx *HttpContext) Method() string{
return ctx.request.Method
}
func (ctx *HttpContext) RequestUrl() string{
return ctx.request.RequestURI
}
func (ctx *HttpContext) RequestHeader(key string) string{
return ctx.request.Header.Get(key)
}
func (ctx *HttpContext) RequestBody() ([]byte, error){
return ioutil.ReadAll(ctx.request.Body)
}
func (ctx *HttpContext) ResponseHeader(key, value string){
ctx.response.Header().Set(key, value)
}
func (ctx *HttpContext) ResponseWrite(statusCode int, body []byte) error{
//header必须在后面
ctx.response.WriteHeader(http.StatusOK)
_, err := fmt.Fprint(ctx.response, string(body))
return err
}<file_sep>/example/readme.md
Exmaple for gorpc
Structure
---------
rpcvo --service
client --rpc client
server --rpc server
Usage
---------
# Server:
cd server
go run server.go
# Client:
cd client
go run client.go
<file_sep>/fasthttp.go
package gorpc
import (
"github.com/valyala/fasthttp"
"net/http"
)
type FastContext struct {
*fasthttp.RequestCtx
}
func NewFastContext(ctx *fasthttp.RequestCtx) *FastContext {
return &FastContext{RequestCtx: ctx}
}
func (ctx *FastContext) Method() string{
return string(ctx.Request.Header.Method())
}
func (ctx *FastContext) RequestUrl() string{
return string(ctx.RequestURI())
}
func (ctx *FastContext) RequestHeader(key string) string{
return string(ctx.Request.Header.Peek(key))
}
func (ctx *FastContext) RequestBody() ([]byte, error){
return ctx.Request.Body(), nil
}
func (ctx *FastContext) ResponseHeader(key, value string){
ctx.Response.Header.Set(key, value)
}
func (ctx *FastContext) ResponseWrite(statusCode int, body []byte) error{
//header必须在后面
ctx.SetStatusCode(http.StatusOK)
_, err := ctx.Write(body)
return err
}
<file_sep>/example/rpcvo/user.go
package rpcvo
type UserService struct {}
func (this *UserService) Say(name *string, reply *string) error {
*reply = "Hello, " + *name + "!"
return nil
}
<file_sep>/client.go
package gorpc
import (
"net/http"
"bytes"
"fmt"
"time"
"errors"
"io/ioutil"
"encoding/json"
"log"
)
type Client struct {
BaseUrl string
Secret string
Log *log.Logger
}
func NewClient(baseUrl, secret string) *Client {
return &Client{BaseUrl: baseUrl, Secret: secret}
}
func (this *Client) SetLog(log *log.Logger) {
this.Log = log
}
func (this *Client) Call(name string, args interface{}, reply interface{}) error {
err := this.doCall(name, args, reply)
if this.Log != nil {
if err != nil {
this.Log.Printf("rpc call url: %v, action: %v, error: %v", this.BaseUrl, name, err)
} else {
this.Log.Printf("rpc call url: %v, action: %v, success.", this.BaseUrl, name)
}
}
return err
}
func (this *Client) doCall(name string, args interface{}, reply interface{}) error {
//request header
reqParams, err := json.Marshal(args)
if err != nil {
return err
}
reqTimestmap := fmt.Sprintf("%v", time.Now().Unix())
reqSign := "rpc"
if this.Secret != "" {
reqSign = makeSign(reqTimestmap + string(reqParams), this.Secret)
}
url := this.BaseUrl
//request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqParams))
if err != nil {
return err
}
req.Header.Set("sign", reqSign)
req.Header.Set("timestamp", reqTimestmap)
req.Header.Set("action", name)
//client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
//response header
msg := resp.Header.Get("msg")
if msg != "" {
return errors.New(msg)
}
//如果不需要返回数据
if reply == nil {
return nil
}
byteBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Rpc read response body error: %v", err)
}
if len(byteBody) <= 0{
return fmt.Errorf("Rpc reponse empty content.")
}
err = json.Unmarshal(byteBody, reply)
if err != nil {
return fmt.Errorf("Rpc Unmarshal json error: %v, content: %s", err, byteBody)
}
return nil
}
<file_sep>/example/rpcvo/calculator.go
package rpcvo
import "errors"
type CalculatorService struct {}
type CalculatorArgs struct {
A, B int
}
type CalculatorReply struct {
Result int
}
func (this *CalculatorService) Div(args *CalculatorArgs, reply *CalculatorReply) error {
if args.B == 0{
return errors.New("B is zero.")
}
reply.Result = args.A * args.B
return nil
}
func (h *CalculatorService) Multiply(args *CalculatorArgs, reply *CalculatorReply) error {
reply.Result = args.A * args.B
return nil
}
<file_sep>/example/client/client.go
package main
import (
"github.com/foolin/gorpc"
"log"
"github.com/foolin/gorpc/example/rpcvo"
)
func main() {
//log.SetFlags(log.Lshortfile|log.LstdFlags)
client := gorpc.NewClient("http://127.0.0.1:5080/rpc", "1q2w3e")
var err error
//============= user service =============//
var sayReply string
err = client.Call("UserService.Say", "Foolin", &sayReply)
if err != nil {
log.Printf("UserService.Say error: %v", err)
}else{
log.Printf("UserService.Say result: %v", sayReply)
}
//============= calculator service =============//
mutiArgs := &rpcvo.CalculatorArgs{
A: 15,
B: 100,
}
var mutiResult rpcvo.CalculatorReply
err = client.Call("CalculatorService.Multiply", mutiArgs, &mutiResult)
if err != nil {
log.Printf("CalculatorService.Multiply error: %v", err)
}else{
log.Printf("CalculatorService.Multiply result: %v", mutiResult.Result)
}
//============= calculator service with name =============//
divArgs := &rpcvo.CalculatorArgs{
A: 15,
B: 0,
}
var divResult rpcvo.CalculatorReply
err = client.Call("Cal.Div", divArgs, &divResult)
if err != nil {
log.Printf("Cal.Div error: %v", err)
}else{
log.Printf("Cal.Div result: %v", divResult.Result)
}
}
<file_sep>/errors.go
package gorpc
import (
"errors"
)
var (
ErrPasswordIncorrect = errors.New("Password incorrect!")
ErrURLInvalid = errors.New("URL error!")
)<file_sep>/sign.go
package gorpc
import (
"fmt"
"crypto/sha1"
"crypto/hmac"
)
func makeSign(value, secret string) string {
mac := hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(value))
hash := mac.Sum(nil)
return fmt.Sprintf("%x", hash)
}
|
3bfda77b1f88fab1a674171b245d3ff022cd8b54
|
[
"Markdown",
"Go"
] | 12 |
Go
|
dev-vadym/gorpc
|
2599e2ebbc4cbbbd8d291d383de38d472e5f92cc
|
f2ea8562be2a0bda385b5c9d63209f6a1520a418
|
refs/heads/master
|
<repo_name>vigensahakyan/Algorithms<file_sep>/Algorithms/src/com/data/structure/BPlusTree.java
package com.data.structure;
import com.data.structure.RedBlackTree.RedBlackNode;
public class BPlusTree<T extends Comparable<T>> implements Set<T> {
// max children per B-tree node = M
// (must be even and greater than 2)
private static final int M = 4;
private BPlusTreeNode root; // root of the B-tree
private int height; // height of the B-tree
private int N; // number of key-value pairs in the B-tree
// helper B-tree node data type
// M number of reference your key_size(M-1) + reference_size*M <= block_size
// E.g key is integer(4 byte) reference is (6 byte) and block size is 4kbyte hence 4*(M-1) + 6*M <=4096 ==> your M<=500
// Root of B+ tree has minimum 1 key up to (M-1) keys, and it has [2,M] children node
// Internal nodes store up to M-1 key, and have between floor(M/2) and M children.
// Every non-leaf, non-root hence inner node has at least floor(M / 2) children.
// Every key from the table appears in a leaf, in left-to-right sorted order.
private static final class BPlusTreeNode {
private int m; // number of children
private KeyValueElement[] childs = new KeyValueElement[M]; // the array of childs
private BPlusTreeNode left = null;
private BPlusTreeNode right = null;
// create a node with k childs
private BPlusTreeNode(int k) {
m = k;
}
}
// internal nodes: only use key and next
// external nodes: only use key and value
private static class KeyValueElement {
private Comparable key;
private Object val;
private BPlusTreeNode next; // helper field to iterate over array entries
public KeyValueElement(Comparable key, Object val, BPlusTreeNode next) {
this.key = key;
this.val = val;
this.next = next;
}
}
public BPlusTree() {
root = new BPlusTreeNode(0);
}
public boolean isEmpty() {
return size() == 0;
}
public int size() {
return N;
}
public int height() {
return height;
}
@Override
public boolean Insert(T obj) {
if (obj == null) throw new NullPointerException("obj must not be null");
BPlusTreeNode u = insert(root, obj, obj, height);
N++;
if (u == null) return true;
// need to split root
BPlusTreeNode t = new BPlusTreeNode(2); // change 2 to 1;
t.childs[0] = new KeyValueElement(root.childs[0].key, null, root);
t.childs[1] = new KeyValueElement(u.childs[0].key, null, u);
root = t;
root.childs[0].next.right = root.childs[1].next;
root.childs[1].next.left = root.childs[0].next;
height++;
return true;
}
@Override
public boolean Search(T obj) {
if (obj == null) throw new NullPointerException("obj must not be null");
return searchInternal(root, obj, height)!=null;
}
@Override
public boolean Remove(T obj) {
// TODO Auto-generated method stub
return false;
}
@Override
public IteratorInterface Iterator() {
IteratorInterface<T> it = new IteratorInterface<T>(){
int i = 0;
private BPlusTreeNode currentNode = minKey(root);
@Override
public boolean hasNext() {
boolean hasNext = false;
if(currentNode!=null){
if(i< currentNode.m){
hasNext = true;
}
}
return hasNext;
}
@Override
public T Next() {
// TODO Auto-generated method stub
T obj = null;
if(hasNext()){
obj = (T) currentNode.childs[i].key;
i++;
}
if (i >= currentNode.m){
currentNode = currentNode.right;
i=0;
}
return obj;
}
@Override
public boolean remove(T rm) {
// TODO Auto-generated method stub
return false;
}
};
return it;
}
private T searchInternal(BPlusTreeNode x, T key, int ht) {
KeyValueElement[] childs = x.childs;
// external node
if (ht == 0) {
for (int j = 0; j < x.m; j++) {
if (keyeq(key, childs[j].key)) return (T) childs[j].val;
}
}
// internal node
else {
for (int j = 0; j < x.m; j++) {
if (j+1 == x.m || lessthan(key, childs[j+1].key))
return searchInternal(childs[j].next, key, ht-1);
}
}
return null;
}
public void put(T key, T val) {
if (key == null) throw new NullPointerException("key must not be null");
BPlusTreeNode u = insert(root, key, val, height);
N++;
if (u == null) return;
// need to split root
BPlusTreeNode t = new BPlusTreeNode(2);
t.childs[0] = new KeyValueElement(root.childs[0].key, null, root);
t.childs[1] = new KeyValueElement(u.childs[0].key, null, u);
root = t;
height++;
}
private BPlusTreeNode insert(BPlusTreeNode h, T key, T val, int ht) {
int j;
KeyValueElement t = new KeyValueElement(key, val, null);
// leaf node
if (ht == 0) {
for (j = 0; j < h.m; j++) {
if (lessthan(key, h.childs[j].key)) break;
}
}
// internal node
else {
for (j = 0; j < h.m; j++) {
if ((j+1 == h.m) || lessthan(key, h.childs[j+1].key)) {
BPlusTreeNode u = insert(h.childs[j++].next, key, val, ht-1);
if (u == null){
return null;
// if leaf has been split
}else if((ht-1)== 0){
u.right = h.childs[j-1].next.right;
h.childs[j-1].next.right = u;
u.left = h.childs[j-1].next;
//break;
}
// if split
t.key = u.childs[0].key;
t.next = u;
break;
}
}
}
for (int i = h.m; i > j; i--)
h.childs[i] = h.childs[i-1];
h.childs[j] = t;
h.m++;
if (h.m < M) return null;
else return split(h);
}
// split node in half
private BPlusTreeNode split(BPlusTreeNode h) {
BPlusTreeNode t = new BPlusTreeNode(M/2);
h.m = M/2;
for (int j = 0; j < M/2; j++)
t.childs[j] = h.childs[M/2+j];
return t;
}
public String toString() {
return toString(root, height, "") + "\n";
}
private String toString(BPlusTreeNode h, int ht, String indent) {
StringBuilder s = new StringBuilder();
KeyValueElement[] childs = h.childs;
if (ht == 0) {
for (int j = 0; j < h.m; j++) {
s.append(indent + childs[j].key + " " + childs[j].val + "\n");
}
}
else {
for (int j = 0; j < h.m; j++) {
if (j > 0) s.append(indent + "(" + childs[j].key + ")\n");
s.append(toString(childs[j].next, ht-1, indent + " "));
}
}
return s.toString();
}
// comparison functions - make Comparable instead of Key to avoid casts
private boolean lessthan(Comparable k1, Comparable k2) {
return k1.compareTo(k2) < 0;
}
private boolean keyeq(Comparable k1, Comparable k2) {
return k1.compareTo(k2) == 0;
}
private BPlusTreeNode minKey(BPlusTreeNode x){
BPlusTreeNode min = x;
while(min.childs[0].next != null){
min = min.childs[0].next;
}
return min;
}
}
<file_sep>/Algorithms/src/com/data/structure/PriorityQueue.java
package com.data.structure;
public interface PriorityQueue<T> {
boolean Insert(T obj);
T Minimum();
T ExtractMin();
void DecreaseKey(T key, int m);
boolean Delete(T obj);
}
<file_sep>/Algorithms/src/com/data/structure/RedBlackTree.java
package com.data.structure;
import java.sql.Blob;
// Properties of Red Black Tree
// 1. Every node is either red or black.
// 2. The root is black.
// 3. Every leaf (NIL) is black.
// 4. If a node is red, then both its children are black.
// 5. For each node, all simple paths from the node to descendant leaves contain the
// same number of black nodes.
public class RedBlackTree<T extends Comparable<T>> implements Set<T> {
class RedBlackNode<T extends Comparable<T>> {
// Possible color for this node
public static final boolean BLACK = true;
// Possible color for this node
public static final boolean RED = false;
// the key of each node
public T data;
// Parent of node
RedBlackNode<T> parent;
// Left child
RedBlackNode<T> left;
// Right child
RedBlackNode<T> right;
// the color of a node
public boolean color;
RedBlackNode() {
color = BLACK;
parent = null;
left = null;
right = null;
}
// Constructor which sets key to the argument.
RedBlackNode(T ndata) {
this();
this.data = ndata;
}
}
private RedBlackNode<T> nil = new RedBlackNode<T>();
private RedBlackNode<T> root = nil;
public RedBlackTree() {
root.left = nil;
root.right = nil;
root.parent = nil;
}
@Override
public boolean Insert(T obj) {
boolean inserted = false;
RedBlackNode<T> NodeY = nil;
RedBlackNode<T> NodeX = this.root;
RedBlackNode<T> NodeZ = new RedBlackNode<T>();
NodeZ.data = obj;
NodeZ.left = nil;
NodeZ.right = nil;
NodeZ.parent = nil;
while (NodeX != nil) {
NodeY = NodeX;
if (0 > (NodeZ.data).compareTo(NodeX.data)) {
NodeX = NodeX.left;
} else {
NodeX = NodeX.right;
}
}
NodeZ.parent = NodeY;
if (NodeY == nil) {
this.root = NodeZ;
NodeZ.parent = nil;
this.root = NodeZ;
inserted = true;
} else if (0 > (NodeZ.data).compareTo(NodeY.data)) {
NodeY.left = NodeZ;
inserted = true;
} else {
NodeY.right = NodeZ;
inserted = true;
}
NodeZ.color = RedBlackNode.RED;
RedBlacTreeInsertFixUp(NodeZ);
return false;
}
@Override
public boolean Search(T obj) {
boolean found = false;
RedBlackNode<T> ro = root;
if (SearchInternal(obj) != nil && SearchInternal(obj) != null) {
found = true;
}
return found;
}
private RedBlackNode<T> SearchInternal(T obj) {
boolean found = false;
RedBlackNode<T> ro = root;
while (ro != nil) {
if (ro.data.equals(obj)) {
found = true;
break;
} else if (0 > (obj).compareTo(ro.data)) {
ro = ro.left;
} else {
ro = ro.right;
}
}
return ro;
}
@Override
public boolean Remove(T obj) {
boolean removed = false;
RedBlackNode<T> y;
RedBlackNode<T> z = SearchInternal(obj);
if (z != nil && z != null) {
if ((z.left != nil) || (z.right != nil)) {
RedBlackNode<T> fixUpNode = null;
y = z;
boolean yOriginalColor = y.color;
if (z.left == nil) {
fixUpNode = z.right;
Transplant(z, z.right);
} else if (z.right == nil) {
fixUpNode = z.left;
Transplant(z, z.left);
} else {
y = MinElement(z.right);
yOriginalColor = y.color;
fixUpNode = y.right;
if (y.parent == z) {
fixUpNode.parent = y;
} else {
Transplant(y, y.right);
y.right = z.right;
y.right.parent = y;
}
Transplant(z, y);
y.left = z.left;
y.left.parent = y;
y.color = z.color;
}
if (yOriginalColor == RedBlackNode.BLACK) {
RedBlacTreeRemoveFixUp(fixUpNode);
}
} else {
if (z == z.parent.left) {
z.parent.left = nil;
} else {
z.parent.right = nil;
}
}
}
return removed;
}
@Override
public IteratorInterface Iterator() {
IteratorInterface<T> it = new IteratorInterface<T>() {
int i = 0;
private RedBlackNode<T> currentNode = MinElement(root);
@Override
public boolean hasNext() {
if (i == 0) {
return true;
}
return (TreeSuccessor(currentNode) != null && TreeSuccessor(currentNode) != nil) ? true : false;
}
@Override
public T Next() {
// TODO Auto-generated method stub
if (i == 0) {
i++;
return currentNode.data;
}
T obj = null;
RedBlackNode<T> tmpCurrentNode = TreeSuccessor(currentNode);
obj = tmpCurrentNode.data;
currentNode = tmpCurrentNode;
return obj;
}
@Override
public boolean remove(T rm) {
// TODO Auto-generated method stub
return false;
}
};
// TODO
return it;
}
public RedBlackNode<T> MaxElement(RedBlackNode<T> node) {
RedBlackNode<T> tmpNode = node;
while (tmpNode.right.data != null) {
tmpNode = tmpNode.right;
}
return tmpNode;
}
public RedBlackNode<T> MinElement(RedBlackNode<T> node) {
RedBlackNode<T> tmpNode = node;
while (tmpNode.left.data != null) {
tmpNode = tmpNode.left;
}
return tmpNode;
}
// Natural order
public void InorderTreeWalking(RedBlackNode<T> node) {
if (node != nil) {
InorderTreeWalking(node.left);
System.out.print(node.data);
System.out.print(" ");
InorderTreeWalking(node.right);
if (node == root) {
System.out.println();
}
}
}
public void PreorderTreeWalking(RedBlackNode<T> node) {
if (node != nil) {
System.out.print(node.data);
System.out.print(" ");
InorderTreeWalking(node.left);
InorderTreeWalking(node.right);
if (node == root) {
System.out.println();
}
}
}
public void PostOrderTreeWalking(RedBlackNode<T> node) {
if (node != nil) {
InorderTreeWalking(node.left);
InorderTreeWalking(node.right);
System.out.print(node.data);
System.out.print(" ");
if (node == root) {
System.out.println();
}
}
}
public boolean IterativeTreeSearch(T obj) {
return false;
}
public RedBlackNode<T> GetRoot() {
return root;
}
// Tree Successor in ordered tree
public RedBlackNode<T> TreeSuccessor(RedBlackNode<T> obj) {
if (obj.right != nil) {
return MinElement(obj.right);
}
RedBlackNode<T> y = obj.parent;
while (y != nil && obj == y.right) {
obj = y;
y = y.parent;
}
return y;
}
public RedBlackNode<T> TreePredecessor(RedBlackNode<T> obj) {
if (obj.left != nil) {
return MaxElement(obj.right);
}
RedBlackNode<T> y = obj.parent;
while (y != nil && obj == y.left) {
obj = y;
y = y.parent;
}
return y;
}
private void Transplant(RedBlackNode<T> y, RedBlackNode<T> x) {
if (y.parent == nil) {
root = x;
} else if (y == y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
x.parent = y.parent;
}
}
private void LeftRotate(RedBlackNode<T> NodeX) {
if (NodeX != nil) {
RedBlackNode<T> NodeY = NodeX.right;
NodeX.right = NodeY.left;
if (NodeY.left != nil) {
NodeY.left.parent = NodeX;
}
NodeY.parent = NodeX.parent;
if (NodeX.parent == nil) {
root = NodeY;
} else if (NodeX == NodeX.parent.left) {
NodeX.parent.left = NodeY;
} else {
NodeX.parent.right = NodeY;
}
NodeY.left = NodeX;
NodeX.parent = NodeY;
}
}
private void RightRotate(RedBlackNode<T> NodeY) {
if (NodeY != nil) {
RedBlackNode<T> NodeX = NodeY.left;
NodeY.left = NodeX.right;
if (NodeX.right != nil) {
NodeX.right.parent = NodeY;
}
NodeX.parent = NodeY.parent;
if (NodeY.parent == nil) {
root = NodeX;
} else if (NodeY == NodeY.parent.right) {
NodeY.parent.right = NodeX;
} else {
NodeY.parent.left = NodeX;
}
NodeX.right = NodeY;
NodeY.parent = NodeX;
}
}
private void RedBlacTreeInsertFixUp(RedBlackNode<T> Node) {
// Node.parent is never null because we have nil root which is black.
while (Node.parent.color == RedBlackNode.RED) {
// Case when node parent is left child of his parent(grandfather of
// node)
if (Node.parent == Node.parent.parent.left) {
RedBlackNode<T> uncle = Node.parent.parent.right;
// Case 1 uncle is RED, we will pain parent and uncle to BLACK
// and grandfather to RED and then iterate again on grandfather
if (uncle.color == RedBlackNode.RED) {
uncle.color = RedBlackNode.BLACK;
Node.parent.color = RedBlackNode.BLACK;
Node.parent.parent.color = RedBlackNode.RED;
Node = Node.parent.parent;
// Case 2 uncle is black and node is right child of parent
// node
} else if (Node == Node.parent.right && uncle.color == RedBlackNode.BLACK) {
Node = Node.parent;
LeftRotate(Node); // After this rotation we get the case 3
// because of specific of this case
// Case 3 uncle is black and node is left child of parent
// node
} else if (Node == Node.parent.left && uncle.color == RedBlackNode.BLACK) {
Node.parent.color = RedBlackNode.BLACK;
Node.parent.parent.color = RedBlackNode.RED;
Node = Node.parent.parent;
RightRotate(Node);
}
// Case when node parent is right child of his
// parent(grandfather of node)
} else if (Node.parent == Node.parent.parent.right) {
RedBlackNode<T> uncle = Node.parent.parent.left;
// Case 1 uncle is RED, we will pain parent and uncle to BLACK
// and grandfather to RED and then iterate again on grandfather
if (uncle.color == RedBlackNode.RED) {
uncle.color = RedBlackNode.BLACK;
Node.parent.color = RedBlackNode.BLACK;
Node.parent.parent.color = RedBlackNode.RED;
Node = Node.parent.parent;
} else if (Node == Node.parent.left && uncle.color == RedBlackNode.BLACK) {
Node = Node.parent;
RightRotate(Node); // After this rotation we get the case 3
// because of specific of this case
// Case 3 uncle is black and node is left child of parent
// node
} else if (Node == Node.parent.right && uncle.color == RedBlackNode.BLACK) {
Node.parent.color = RedBlackNode.BLACK;
Node.parent.parent.color = RedBlackNode.RED;
Node = Node.parent.parent;
LeftRotate(Node);
}
}
}
root.color = RedBlackNode.BLACK;
}
private void RedBlacTreeRemoveFixUp(RedBlackNode<T> x) {
while (x != root && x.color == RedBlackNode.BLACK) {
// Case when node is left child of his parent
if (x == x.parent.left) {
RedBlackNode<T> brother = x.parent.right;
// Case 1 when brother has RED color. Since Brother must have
// black children, we can switch the
// colors of Brother and x.parent and then perform a
// left-rotation on x.parent
// The new Brother of x, which is one of Brothers children
// prior to the rotation, is now black, and thus we have
// converted case 1 into case 2,
// 3, or 4.
if (brother.color == RedBlackNode.RED) {
brother.color = RedBlackNode.BLACK;
x.parent.color = RedBlackNode.RED;
LeftRotate(x.parent);
// We get new brother
brother = x.parent.right;
// Cases 2, 3, and 4 occur when node Brother is black; they
// are distinguished by the
// colors of Brothers children.
// Case 1 xs sibling Brother is black, and both of
// Brothers children are black
}
if (brother.color == RedBlackNode.BLACK && brother.left.color == RedBlackNode.BLACK
&& brother.right.color == RedBlackNode.BLACK) {
brother.color = RedBlackNode.RED;
x = x.parent;
// Case 3 xs sibling Brother is black, Brothers left child
// is red, and Brothers right child is black
} else if (brother.color == RedBlackNode.BLACK && brother.left.color == RedBlackNode.RED
&& brother.right.color == RedBlackNode.BLACK) {
brother.left.color = RedBlackNode.BLACK;
brother.color = RedBlackNode.RED;
RightRotate(brother);
brother = x.parent.right;
// Case 4 xs sibling Brother is black, and Brothers right
// child is red
brother.color = x.parent.color;
x.parent.color = RedBlackNode.BLACK;
brother.right.color = RedBlackNode.BLACK;
LeftRotate(x.parent);
x = root;
}
// Case when node is right child of his parent
} else if (x == x.parent.right) {
RedBlackNode<T> brother = x.parent.left;
// Case 1 when brother has RED color. Since Brother must have
// black children, we can switch the
// colors of Brother and x.parent and then perform a
// right-rotation on x.parent
// The new Brother of x, which is one of Brothers children
// prior to the rotation, is now black, and thus we have
// converted case 1 into case 2,
// 3, or 4.
if (brother.color == RedBlackNode.RED) {
brother.color = RedBlackNode.BLACK;
x.parent.color = RedBlackNode.RED;
RightRotate(x.parent);
// We get new brother
brother = x.parent.left;
// Cases 2, 3, and 4 occur when node Brother is black; they
// are distinguished by the
// colors of Brothers children.
// Case 1 xs sibling Brother is black, and both of
// Brothers children are black
}
if (brother.color == RedBlackNode.BLACK && brother.left.color == RedBlackNode.BLACK
&& brother.right.color == RedBlackNode.BLACK) {
brother.color = RedBlackNode.RED;
x = x.parent;
// Case 3 xs sibling Brother is black, Brothers right
// child is red, and Brothers left child is black
} else if (brother.color == RedBlackNode.BLACK && brother.right.color == RedBlackNode.RED
&& brother.left.color == RedBlackNode.BLACK) {
brother.right.color = RedBlackNode.BLACK;
brother.color = RedBlackNode.RED;
LeftRotate(brother);
brother = x.parent.right;
// Case 4 xs sibling Brother is black, and Brothers left
// child is red
brother.color = x.parent.color;
x.parent.color = RedBlackNode.BLACK;
brother.left.color = RedBlackNode.BLACK;
RightRotate(x.parent);
x = root;
}
}
}
x.color = RedBlackNode.BLACK;
}
}
<file_sep>/Algorithms/src/com/data/structure/TestCollections.java
package com.data.structure;
import java.util.ArrayList;
import java.util.Iterator;
//import java.util.LinkedList;
import java.util.List;
public class TestCollections {
public static void main(String[] args) {
// TestCollections.StackTest();
// LinkedListTest();
// VectorListTest();
// OAHashSetTest();
// ChainedHastTableTest();
// RedBlackTreeTest();
// BPlusTreeTest();
FibonacciHeapTreeTest();
List<Integer> ss;
ArrayList<Integer> arl = new ArrayList<>();
}
public static void FibonacciHeapTreeTest() {
FibonacciHeap<Integer> st = new FibonacciHeap<Integer>();
st.insert(80, 80);
st.insert(50, 50);
st.insert(120, 120);
st.insert(45, 45);
st.insert(130, 45);
st.insert(47, 47);
st.insert(45, 45);
System.out.println(st.size());
}
public static void BPlusTreeTest() {
Set<Integer> st = new BPlusTree<Integer>();
st.Insert(80);
st.Insert(50);
st.Insert(120);
st.Insert(45);
st.Insert(130);
st.Insert(47);
st.Insert(45);
st.Insert(180);
st.Insert(137);
st.Insert(45);
st.Insert(180);
st.Insert(137);
st.Insert(80);
st.Insert(50);
st.Insert(120);
st.Insert(45);
st.Insert(130);
st.Insert(47);
st.Insert(45);
st.Insert(180);
st.Insert(137);
st.Insert(45);
st.Insert(180);
st.Insert(137);
IteratorInterface<Integer> it = st.Iterator();
while (it.hasNext()) {
System.out.println(it.Next());
}
}
public static void RedBlackTreeTest() {
Set<Integer> st = new RedBlackTree<Integer>();
st.Insert(80);
st.Insert(50);
st.Insert(120);
st.Insert(45);
st.Insert(130);
st.Insert(47);
st.Insert(45);
st.Insert(180);
st.Insert(137);
st.Remove(50);
st.Remove(45);
st.Remove(120);
st.Remove(137);
System.out.println(st.Search(45));
IteratorInterface<Integer> it = st.Iterator();
while (it.hasNext()) {
System.out.println(it.Next());
}
}
public static void ChainedHastTableTest() {
Set<String> st = new ChainedHashTable<String>();
st.Insert("1");
st.Insert("1");
st.Insert("1");
st.Insert("2");
st.Insert("2");
st.Insert("3");
st.Insert("4");
st.Remove("2");
st.Search("3");
st.Remove("5");
IteratorInterface<Integer> it = st.Iterator();
while (it.hasNext()) {
System.out.println(it.Next());
}
}
public static void OAHashSetTest() {
Set<String> st = new HashSetOpenAddressed<String>();
st.Insert("1");
st.Insert("1");
st.Insert("1");
st.Insert("2");
st.Insert("2");
st.Insert("3");
st.Insert("4");
st.Remove("2");
st.Search("3");
st.Remove("5");
IteratorInterface<Integer> it = st.Iterator();
while (it.hasNext()) {
System.out.println(it.Next());
}
}
public static void VectorListTest() {
ListInterface<Integer> list = new VectorList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.set(5, 22);
System.out.println(list.get(0));
System.out.println(list.get(5));
System.out.println(list.get(6));
System.out.println(list.get(7));
list.remove(1);
System.out.println("=============================================");
IteratorInterface<Integer> it = list.Iterator();
while (it.hasNext()) {
System.out.println(it.Next());
}
}
public static void LinkedListTest() {
ListInterface<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.set(5, 22);
System.out.println(list.get(0));
System.out.println(list.get(5));
System.out.println(list.get(6));
System.out.println(list.get(7));
list.remove(1);
System.out.println("=============================================");
IteratorInterface<Integer> it = list.Iterator();
while (it.hasNext()) {
System.out.println(it.Next());
}
}
public static void StackTest() {
DynamicStack<Integer> sk = new DynamicStack<Integer>();
sk.Push(1);
sk.Push(2);
sk.Push(2);
sk.Push(2);
sk.Push(2);
sk.Push(2);
sk.Push(2);
sk.Push(2);
sk.Push(2);
sk.Push(10);
IteratorInterface<Integer> it = sk.Iterator();
while (it.hasNext()) {
System.out.println(it.Next());
}
sk.Pop();
sk.Pop();
sk.Pop();
sk.Pop();
sk.Pop();
System.out.println("=============================================");
it = sk.Iterator();
while (it.hasNext()) {
System.out.println(it.Next());
}
}
}
<file_sep>/Algorithms/src/com/cormen/sorting/MergeSort.java
package com.cormen.sorting;
import java.util.ArrayList;
public class MergeSort<T extends Comparable<T>> implements SortInterface {
static public int numOperation = 0;
@Override
public void Sort(ArrayList array) {
// TODO Auto-generated method stub
Merge_Sort(array, 0, (array.size() - 1));
}
private void Merge_Sort(ArrayList<T> array, int p, int r) {
if (p < r) {
int q = (int) Math.floor((p + r) / 2);
Merge_Sort(array, p, q);
Merge_Sort(array, q + 1, r);
Merge(array, p, q, r);
}
}
private void Merge(ArrayList<T> array, int p, int q, int r) {
int n1 = (q - p) + 1;
int n2 = r - q;
T[] left = (T[]) new Comparable[n1 + 1];
T[] right = (T[]) new Comparable[n2 + 1];
for (int i = 0; i < n1; i++) {
left[i] = array.get(p + i);
}
for (int i = 0; i < n2; i++) {
right[i] = array.get(q + i + 1);
}
int i = 0;
int j = 0;
for (int z = p; z <= r; z++) {
if (i == n1) {
array.set(z, right[j]);
j++;
} else if (j == n2) {
array.set(z, left[i]);
i++;
} else if (left[i].compareTo(right[j]) <= 0) {
array.set(z, left[i]);
i++;
} else {
array.set(z, right[j]);
j++;
}
}
}
public static void main(String[] args) {
MergeSort<Integer> in = new MergeSort<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>() {
{
add(4);
add(1);
add(3);
add(2);
add(16);
add(9);
add(10);
add(14);
add(8);
add(7);
add(6);
add(5);
add(17);
add(14);
add(15);
add(16);
}
};
System.out.println(list.toString());
in.Sort(list);
System.out.println(list.toString() + "Cost : " + in.numOperation);
}
}
<file_sep>/Algorithms/src/com/dynamic/programming/CutRod.java
package com.dynamic.programming;
public class CutRod {
int[] p = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
public static int numOper = 0;
// recursive it has exponential time as it decide each of overlapping
// subproblems several time
public int cutRod(int n) {
numOper++;
if (n == 0) {
return 0;
}
int q = Integer.MIN_VALUE;
for (int i = 1; i <= (n); i++) {
q = Math.max(q, p[i] + cutRod((n) - i));
}
return q;
}
public int MemorizedCutRod(int n) {
int[] r = new int[n + 1];
for (int i = 0; i <= n; i++) {
r[i] = Integer.MIN_VALUE;
}
return MemorizeCutRodAux(n, r);
}
private int MemorizeCutRodAux(int n, int[] r) {
numOper++;
if (r[n] >= 0) {
return r[n];
}
if (n == 0) {
return 0;
}
int q = Integer.MIN_VALUE;
for (int i = 1; i <= (n); i++) {
q = Math.max(q, p[i] + MemorizeCutRodAux((n) - i, r));
}
r[n] = q;
return q;
}
public int BottomUpCutRod(int n) {
int[] r = new int[n + 1];
int[] s = new int[n + 1];
r[0] = 0;
for (int j = 1; j <= (n); j++) {
int q = Integer.MIN_VALUE;
for (int i = 1; i <= (j); i++) {
numOper++;
if (q < (p[i] + r[j - i])) {
q = p[i] + r[j - i];
s[j] = i;
}
// q = Math.max(q, p[i] +r[j-i]);
}
r[j] = q;
}
int k = n;
while (n > 0) {
System.out.println(s[n]);
n = n - s[n];
}
return r[k];
}
public static void main(String[] args) {
System.out.println(new CutRod().BottomUpCutRod(9) + " " + CutRod.numOper);
}
}
<file_sep>/Algorithms/src/com/cormen/sorting/InsertionSort.java
package com.cormen.sorting;
import java.util.ArrayList;
import java.util.Collections;
public class InsertionSort<T extends Comparable<T>> implements SortInterface {
static public int numOperation = 0;
public void Sort(ArrayList array) {
Insertion_Sort(array);
}
private void Insertion_Sort(ArrayList<T> array) {
for (int j = 1; j < array.size(); j++) {
T key = array.get(j);
int i = j - 1;
while (i >= 0 && (array.get(i).compareTo(key) > 0)) {
array.set(i + 1, array.get(i));
i--;
}
array.set(i + 1, key);
}
}
public static void main(String[] args) {
InsertionSort<Integer> in = new InsertionSort<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>() {
{
add(4);
add(1);
add(3);
add(2);
add(16);
add(9);
add(10);
add(14);
add(8);
add(7);
add(6);
add(5);
add(17);
add(14);
add(15);
add(16);
}
};
System.out.println(list.toString());
in.Sort(list);
System.out.println(list.toString() + "Cost : " + in.numOperation);
}
}
<file_sep>/Algorithms/src/com/data/structure/ListInterface.java
package com.data.structure;
public interface ListInterface<T> {
T get(int i);
boolean add(T obj);
boolean remove(T obj);
boolean set(int i, T obj);
IteratorInterface Iterator();
}
<file_sep>/Algorithms/src/com/data/structure/ChainedHashTable.java
package com.data.structure;
import java.util.TreeSet;
public class ChainedHashTable<T> implements Set<T> {
private int size = 37;
// to get the better speed we use TreeSet instead of LinkedList, that
// guarantee log(n) cost for finding element in chain
private TreeSet<T>[] table = new TreeSet[size];
@Override
public boolean Insert(T obj) {
boolean inserted = false;
int hash = hash(obj.hashCode());
if (table[hash] != null) {
if (table[hash].add(obj)) {
inserted = true;
}
} else {
table[hash] = new TreeSet<T>();
table[hash].add(obj);
inserted = true;
}
return inserted;
}
@Override
public boolean Search(T obj) {
boolean found = false;
int hash = hash(obj.hashCode());
if (table[hash] != null) {
if (table[hash].contains(obj)) {
found = true;
}
}
return found;
}
@Override
public boolean Remove(T obj) {
boolean removed = false;
int hash = hash(obj.hashCode());
if (table[hash] != null) {
if (table[hash].remove(obj)) {
removed = true;
}
}
return removed;
}
@Override
public IteratorInterface Iterator() {
return null;
}
private int hash(int k) {
return k % size;
}
}
<file_sep>/Algorithms/src/com/cormen/sorting/QuickSort.java
package com.cormen.sorting;
import java.util.ArrayList;
import java.util.Collections;
public class QuickSort<T extends Comparable<T>> implements SortInterface {
static public int numOperation = 0;
@Override
public void Sort(ArrayList array) {
Quick_Sort(array, 0, array.size() - 1);
}
private void Quick_Sort(ArrayList<T> array, int p, int r) {
if (p < r) {
int q = Randomized_Partition(array, p, r);
Quick_Sort(array, p, q - 1);
Quick_Sort(array, q + 1, r);
}
}
private int Randomized_Partition(ArrayList<T> array, int p, int r) {
// Math.random() return value form uniform distribution within 0-1 then
// we transform it into range [p,r]
int rR = (int) (Math.random() * (r - p)) + p;
Collections.swap(array, r, rR);
int i = p - 1;
T obj = array.get(r);
for (int j = p; j <= (r - 1); j++) {
if (obj.compareTo(array.get(j)) > 0) {
i++;
Collections.swap(array, i, j);
numOperation++;
}
}
Collections.swap(array, i + 1, r);
numOperation++;
return i + 1;
}
private int Partition(ArrayList<T> array, int p, int r) {
int i = p - 1;
T obj = array.get(r);
for (int j = p; j <= (r - 1); j++) {
if (obj.compareTo(array.get(j)) > 0) {
i++;
Collections.swap(array, i, j);
numOperation++;
}
}
Collections.swap(array, i + 1, r);
numOperation++;
return i + 1;
}
public static void main(String[] args) {
QuickSort<Integer> in = new QuickSort<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>() {
{
add(4);
add(1);
add(3);
add(2);
add(16);
add(9);
add(10);
add(14);
add(8);
add(7);
add(6);
add(5);
add(17);
add(14);
add(15);
add(16);
}
};
System.out.println(list.toString());
in.Sort(list);
System.out.println(list.toString() + "Cost : " + in.numOperation);
}
}
<file_sep>/Algorithms/src/com/cormen/sorting/HeapSort.java
package com.cormen.sorting;
import java.util.ArrayList;
import java.util.Collections;
public class HeapSort<T extends Comparable<T>> implements SortInterface {
static public int numOperation = 0;
public void Sort(ArrayList array) {
Heap_Sort(array);
}
private void Heap_Sort(ArrayList<T> array) {
int heap_size = array.size();
BuildMaxHeap(array);
for (int i = (array.size() - 1); i >= 1; i--) {
Collections.swap(array, 0, i);
heap_size--;
MaxHeapIFY(array, heap_size, 0);
}
}
private void BuildMaxHeap(ArrayList<T> array) {
int middleOfArray = (int) Math.floor((array.size()) / 2) - 1;
for (int i = middleOfArray; i >= 0; i--) {
MaxHeapIFY(array, array.size(), i);
}
}
private void MaxHeapIFY(ArrayList<T> array, int heap_size, int i) {
int largest = 0;
int l = Left(i);
int r = Right(i);
if (l <= heap_size - 1 && array.get(l).compareTo(array.get(i)) > 0) {
largest = l;
} else {
largest = i;
}
if (r <= heap_size - 1 && array.get(r).compareTo(array.get(largest)) > 0) {
largest = r;
}
if (largest != i) {
Collections.swap(array, i, largest);
numOperation++;
MaxHeapIFY(array, heap_size, largest);
}
}
private int Parent(int i) {
return (int) Math.floor(i / 2);
}
private int Left(int i) {
// original is 2*i, but because of indexing of array start with 0, we
// had to modify it to (2*(i+1)-1)
return (2 * (i + 1)) - 1;
}
private int Right(int i) {
// original is (2*i + 1), but beacuse o indexing of array start with 0,
// we had to modify it to (2*(i+1))
return (2 * (i + 1));
}
public static void main(String[] args) {
HeapSort<Integer> in = new HeapSort<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>() {
{
add(4);
add(1);
add(3);
add(2);
add(16);
add(9);
add(10);
add(14);
add(8);
add(7);
add(6);
add(5);
add(17);
add(14);
add(15);
add(16);
}
};
System.out.println(list.toString());
in.Sort(list);
System.out.println(list.toString() + "Cost : " + in.numOperation);
}
}
|
e7e95269f86f5305db2a261e13e63dec9ce0ffa8
|
[
"Java"
] | 11 |
Java
|
vigensahakyan/Algorithms
|
1b40644a82efad1043a9c76e54d6d0990391b3d0
|
5324e865b48225c2310f594b189e6505ea98c06f
|
refs/heads/master
|
<file_sep>from microbit import *
import radio
import random
import microbit
#setup radio
radio.config(length=251, channel=53, power=4)
sending = 1
def
<file_sep># TeamNetwork
Tasks:
Research
Network without data loss
Test
Decide data format
Code the microbits to pass the data
Work on battery life
Microbit protection network
Priority Queue:
Research
Code
Get Locations of Microbits
Test battery life
Figure out microbit protection
Network
Test
Data format
|
fe223075b7012cb60daefbf1e9c0463aad77e7c9
|
[
"Markdown",
"Python"
] | 2 |
Python
|
afillipi/TeamNetwork
|
bf305da751474ff27c6b706e6127a6c73e5df202
|
1a8a6b09111b025b3657704dd51793e20f718ab2
|
refs/heads/main
|
<file_sep>import React, {useState, useEffect} from 'react'
import styled from "styled-components"
import {useHistory} from "react-router-dom"
import {projectState } from "./projectState"
import {motion} from "framer-motion"
import {pageAnimation} from "../animation"
import GitHubIcon from '@material-ui/icons/GitHub';
import PublicIcon from '@material-ui/icons/Public';
const ProjectDetail = () => {
const history = useHistory();
const url = history.location.pathname;
const [projects, setProjects]=useState(projectState);
const [project, setProject] = useState(null);
useEffect(()=>{
const currentProject=projects.filter((stateProject)=>stateProject.url===url);
setProject(currentProject[0]);
console.log(setProjects)
},[projects,url])
return (
<div>
{project && (
<Detail exit="exit" variants={pageAnimation} initial="hidden" animate="show">
<HeadLine>
<h2>{project.title}</h2>
<img src={project.secondaryImg} alt="project" />
</HeadLine>
<Details>
{project.details.map((detail)=>(
<Single
title={detail.title}
description={detail.description}
key={detail.title}
/>
))}
<Links
github={project.github}
deployed={project.deployed}
/>
</Details>
</Detail>
)}
</div>
)
}
const Detail = styled(motion.div)`
color: white;
`;
const HeadLine = styled.div`
padding-top: 20vh;
position: relative;
h2 {
position: absolute;
top: 10%;
left: 50%;
transform: translate(-50%, -10%);
}
img {
margin:auto;
display:block;
width: 90%;
height: 90%;
object-fit: cover;
}
`;
const Details = styled.div`
min-height: 60vh;
display: block;
margin: 5rem 10rem;
align-items: center;
justify-content: space-around;
@media (max-width: 1500px) {
display: block;
margin: 2rem 2rem;
}
`;
const DetailStyle = styled.div`
padding: 1rem;
h3 {
font-size: 2rem;
}
.line {
width: 100%;
background: #156D75;
height: 0.5rem;
margin: 1rem 0rem;
}
p {
padding: 1rem 0rem;
}
a{
display:inline-block;
text-decoration: none;
color: white;
padding:0rem 2rem 0rem 0rem;
&:hover{
background-color: #156D75;
color: black;
}
`;
//Detail Component
const Single = ({ title, description }) => {
return (
<DetailStyle>
<h3>{title}</h3>
<div className="line"></div>
<p>{description}</p>
</DetailStyle>
);
};
const Links = ({github, deployed})=>{
return (
<DetailStyle>
<a href={github} target="_blank" rel="noreferrer" ><GitHubIcon fontSize='large' />Repo</a>
<a href={deployed} target="_blank" rel="noreferrer" ><PublicIcon fontSize='large' />Website</a>
</DetailStyle>
)
};
export default ProjectDetail
<file_sep>import React from 'react'
import BioSection from '../components/BioSection'
import BackgroundSection from '../components/BackgroundSection'
import BackgroundExpand from '../components/BackgroundExpand'
import {motion} from "framer-motion"
import { pageAnimation } from '../animation'
import ScrollTop from '../components/ScrollTop'
const Bio = () => {
return (
<motion.div exit="exit" variants={pageAnimation} initial="hidden" animate="show">
<BioSection />
<BackgroundSection />
<BackgroundExpand />
<ScrollTop />
</motion.div>
)
}
export default Bio
<file_sep>import React from 'react'
import ucdavis from "../img/ucdavis.png"
import codingdojo from "../img/codingdojo.png"
import apple from "../img/apple.png"
import oracle from "../img/oracle.png"
import code from "../img/code.jpg"
import {Bio, Description, Image} from "../styles"
import styled from "styled-components"
import {scrollReveal} from "../animation"
import {useScroll} from "./useScroll"
const BackgroundSection = () => {
const [element, controls]=useScroll()
return (
<Background
variants={scrollReveal}
animate={controls}
initial="hidden"
ref={element}
>
<Description>
<h2><span>Background</span></h2>
<Cards>
<Card>
<div className="pic">
<img src={ucdavis} alt="pic" />
<h3>UC Davis</h3>
</div>
</Card>
<Card>
<div className="pic">
<img src={codingdojo} alt="pic" />
<h3>Coding Dojo</h3>
</div>
</Card>
<Card>
<div className="pic">
<img src={apple} alt="pic" />
<h3>Apple </h3>
</div>
</Card>
<Card>
<div className="pic">
<img src={oracle} alt="pic" />
<h3>Oracle</h3>
</div>
</Card>
</Cards>
</Description>
<Image>
<img src={code} alt="code" />
</Image>
</Background>
)
}
const Background = styled(Bio)`
h2 {
padding-bottom: 5rem;
}
p {
width: 70%;
padding: 2rem 0rem 4rem 0rem;
}
`;
const Cards = styled.div`
display: flex;
flex-wrap: wrap;
@media (max-width: 1300px) {
justify-content: center;
}
`;
const Card = styled.div`
flex-basis: 20rem;
margin: 1rem 0rem;
.pic {
display: flex;
align-items: center;
img{
width:50px;
height:auto;
}
h3 {
margin: 1rem;
background: white;
color: black;
padding: 1rem;
width:60%;
}
}
`;
export default BackgroundSection
<file_sep>import React from 'react'
import {motion} from "framer-motion"
import {pageAnimation, titleAnim} from "../animation"
import styled from "styled-components"
import LinkedInIcon from '@material-ui/icons/LinkedIn';
import GitHubIcon from '@material-ui/icons/GitHub';
import MailOutlineIcon from '@material-ui/icons/MailOutline';
import AssignmentIcon from '@material-ui/icons/Assignment';
import pdf from "../img/GabrielFernandezResume.pdf"
const Contact = () => {
return (
<ContactStyle exit="exit" variants={pageAnimation} initial="hidden" animate="show" style={{background:"#D3D3D3"}}>
<Title>
<Hide>
<motion.h2 variants={titleAnim}>Get in Touch</motion.h2>
</Hide>
</Title>
<div>
<Hide>
<Social variants={titleAnim}>
<Circle />
<h2>Send Me an Email</h2>
<a href="mailto:<EMAIL>"><MailOutlineIcon fontSize='large' /><EMAIL></a>
</Social>
</Hide>
<Hide>
<Social variants={titleAnim}>
<Circle />
<h2>Connect on LinkedIn</h2>
<a href="https://www.linkedin.com/in/gabriel-antonio-fernandez/" rel="noreferrer" target="_blank" ><LinkedInIcon fontSize='large' />gabriel-antonio-fernandez</a>
</Social>
</Hide>
<Hide>
<Social variants={titleAnim}>
<Circle />
<h2>View my GitHub</h2>
<a href="https://github.com/gabrfernandez" rel="noreferrer" target="_blank" ><GitHubIcon fontSize='large' />gabrfernandez</a>
</Social>
</Hide>
<Hide>
<Social variants={titleAnim}>
<Circle />
<h2>View my Resume</h2>
<a href={pdf} rel="noreferrer" target="_blank" ><AssignmentIcon fontSize='large' />resume</a>
</Social>
</Hide>
</div>
</ContactStyle>
)
}
const ContactStyle = styled(motion.div)`
padding: 5rem 10rem;
color: #353535;
min-height: 90vh;
@media (max-width: 1500px) {
padding: 2rem;
font-size: 1rem;
}
`;
const Title = styled.div`
margin-bottom: 4rem;
color: black;
@media (max-width: 1500px) {
margin-top: 5rem;
}
`;
const Hide = styled.div`
overflow: hidden;
`;
const Circle = styled.div`
border-radius: 50%;
width: 1.5rem;
height: 1.5rem;
background: #353535;
`;
const Social = styled(motion.div)`
display: flex;
align-items: center;
h2 {
margin: 2rem;
}
a{
text-decoration: none;
color: black;
&:hover{
background-color: black;
color: white;
}
}
`;
export default Contact
<file_sep>import React from 'react'
import Bio from './views/Bio'
import GlobalStyle from "./components/GlobalStyle"
import Nav from './components/Nav';
import { Route , Switch, useLocation} from 'react-router-dom';
import Contact from './views/Contact';
import Projects from './views/Projects'
import ProjectDetail from "./views/ProjectDetail";
import { AnimatePresence } from 'framer-motion';
function App() {
const location= useLocation();
return (
<div className="App">
<GlobalStyle />
<Nav />
<AnimatePresence exitBeforeEnter>
<Switch location={location} key={location.pathname}>
<Route path="/" component={Bio} exact />
<Route path="/projects" component={Projects} exact/>
<Route path="/projects/:id" component={ProjectDetail} />
<Route path="/contact" component={Contact} />
</Switch>
</AnimatePresence>
</div>
);
}
export default App;
<file_sep>import blogger from "../img/blogger.png"
import bloggerGif from "../img/bloggerGif.gif"
import myshop from "../img/myshop.png"
import myshopGif from "../img/myshopGif.gif"
import moviedb from "../img/moviedb.png"
import moviedbGif from "../img/moviedbGif.gif"
export const projectState = () => {
return [
{
title:"Blogger",
mainImg: blogger,
secondaryImg: bloggerGif,
url: "/projects/blogger",
github:"https://github.com/gabrfernandez/blogger_django",
deployed:"http://3.19.241.54/",
details:[
{
title:"OVERVIEW",
description:
"This is a blog app where users can post and view blog posts about certain categories. Users have full CRUD functionality on their posts. Implemented user login/registration. Users can also interact with each other by leaving comments on specific posts. The app displays feature posts/categories. App also includes admin functionality. "
},
{
title:"TECHNOLOGIES",
description:
"Built with Django, MySQL, Bootstrap, Crispy Forms, Pillow, FontAwesome, & Recaptcha."
},
{
title:"DEPLOYMENT",
description:
"This application is deployed on AWS EC2. Click on the link to see application or on the GitHub link to see code."
},
],
},
{
title:"MyShop",
mainImg: myshop,
secondaryImg: myshopGif,
url: "/projects/myshop",
github:"https://github.com/gabrfernandez/myshop",
deployed:"https://myshopgabe.herokuapp.com/",
details:[
{
title:"OVERVIEW",
description:
"This is a full functional eCommerce app built using the MERN STACK. Customers can purchase items and checkout with PayPal or with Credit/Debt Card. Customers can leave a review on a product. Admin can upload/edit products and manage orders."
},
{
title:"TECHNOLOGIES",
description:
"Built with: React, Redux, MongoDB Atlas, Mongoose, Express, Node, Bcrypt, JSONWebToken, Bootstrap, & PayPal. "
},
{
title:"DEPLOYMENT",
description:
"This application is deployed on Heroku. Click on the link to see application or on the GitHub link to see code."
},
],
},
{
title:"MovieDB API",
mainImg: moviedb,
secondaryImg: moviedbGif,
url: "/projects/moviedb",
github:"https://github.com/gabrfernandez/moviedb_api",
deployed:"https://moviedb-8ae2d.web.app/",
details:[
{
title:"OVERVIEW",
description:
"Users can search movies by utilizing MovieDB API. The detail page displays key details about the movie, including poster backdrops and a trailer. The Home page loads popular, upcoming, and new movies."
},
{
title:"TECHNOLOGIES",
description:
"Built with React, Redux, Axios, Framer Motion, Styled Components, & MovieDB API. "
},
{
title:"DEPLOYMENT",
description:
"This application is deployed on Firebase. Click on the link to see application or on the GitHub link to see code."
},
],
},
]
}
<file_sep>import React from 'react'
import styled from "styled-components"
const Nav = () => {
return (
<StyledNav>
<h1>
<a id="logo" href="/"><NAME></a>
</h1>
<ul>
<li>
<a href="/">Bio</a>
</li>
<li>
<a href="/projects">My Projects</a>
</li>
<li>
<a href="/contact">Contact Me</a>
</li>
</ul>
</StyledNav>
)
}
const StyledNav = styled.nav`
min-height: 10vh;
display: flex;
margin: auto;
justify-content: space-between;
align-items: center;
padding: 1rem 10rem;
background: #282828;
position: sticky;
top:0;
z-index:10;
a {
color: white;
text-decoration: none;
}
ul {
display: flex;
list-style: none;
}
#logo {
font-size: 2rem;
font-family: "Oswald", sans-serif;
font-weight: lighter;
}
li {
padding-left: 10rem;
position: relative;
}
@media (max-width: 1300px) {
flex-direction: column;
padding: 2rem 1rem;
#logo {
display: inline-block;
margin: 1rem;
}
ul {
padding: 2rem;
justify-content: space-around;
width: 100%;
li {
padding: 0;
}
}
}
`;
export default Nav
<file_sep>import React from 'react'
import styled from "styled-components"
import {Link} from "react-router-dom"
import myshop from "../img/myshop.png"
import moviedb from "../img/moviedb.png"
import blogger from "../img/blogger.png"
import {motion} from "framer-motion"
import {lineAnim, pageAnimation, slider, sliderContainer, fade} from "../animation"
import {useScroll} from "../components/useScroll"
import ScrollTop from '../components/ScrollTop'
const Projects = () => {
const [element, controls]= useScroll();
const [element2, controls2]=useScroll();
return (
<Work style={{background:"#D3D3D3"}} exit="exit" variants={pageAnimation} initial="hidden" animate="show">
<motion.div variants={sliderContainer}>
<Frame1 variants={slider}></Frame1>
<Frame2 variants={slider}></Frame2>
<Frame3 variants={slider}></Frame3>
<Frame4 variants={slider}></Frame4>
</motion.div>
<Project>
<Link to ="/projects/blogger">
<Hide>
<motion.h2 variants={fade}>Blogger</motion.h2>
<motion.div variants={lineAnim} className="line"></motion.div>
<motion.img src={blogger} alt="blogger" />
</Hide>
</Link>
</Project>
<Project ref={element} variants={fade} animate={controls} initial="hidden" >
<Link to="projects/myshop">
<h2>MyShop</h2>
<motion.div variants={lineAnim} className="line"></motion.div>
<img src={myshop} alt="myshop" />
</Link>
</Project>
<Project ref={element2} variants={fade} animate={controls2} initial="hidden">
<Link to="/projects/moviedb">
<h2>MovieDB API</h2>
<motion.div variants={lineAnim} className="line"></motion.div>
<img src={moviedb} alt="moviedb" />
</Link>
</Project>
<ScrollTop />
</Work>
)
}
const Work = styled(motion.div)`
min-height: 100vh;
overflow: hidden;
padding: 5rem 10rem;
@media (max-width: 1300px) {
padding: 2rem 2rem;
}
h2 {
padding: 1rem 0rem;
}
`;
const Project = styled(motion.div)`
padding-bottom: 10rem;
.line {
height: 0.5rem;
background: #156D75;
margin-bottom: 3rem;
}
img {
width: 90%;
height: 90%;
object-fit: contain;
}
a{
text-decoration:none;
color:#156D75;
}
h2:hover{
color:#EA7200;
font-size:400%;
}
`;
const Hide = styled.div`
overflow: hidden;
`;
const Frame1 = styled(motion.div)`
position: fixed;
left: 0;
top: 10%;
width: 100%;
height: 100vh;
background: #156D75;
z-index: 2;
`;
const Frame2 = styled(Frame1)`
background: #FFFFFF;
`;
const Frame3 = styled(Frame1)`
background: #EA7200;
`;
const Frame4 = styled(Frame1)`
background: #000000;
`;
export default Projects
|
fc91d1630a38d72e0b84cc87a246098bc27d20f8
|
[
"JavaScript"
] | 8 |
JavaScript
|
gabrfernandez/portfolio
|
344f573cdc4b9dbfe76fcbd4387701f43067ef73
|
02375e930d83ad449654cefb5648e03014f88356
|
refs/heads/master
|
<file_sep>const electron = require("electron");
const ipc = electron.ipcRenderer;
const remote = require("remote");
const settings = remote.getGlobal("settings");
import css from "./setup.css";
const types = [
"discord",
"flowdock",
"gitter",
"slack",
"twitter",
];
// Redraw on tab changes
ipc.on("tab-update", () => m.redraw);
const editor = {
controller : function(args) {
var ctrl = this;
ctrl.tab = {};
ctrl.url = (url) => { ctrl.tab.url = url; };
ctrl.type = (pos) => { ctrl.tab.type = types[pos]; };
ctrl.add = () => {
ipc.send("tab-add", ctrl.tab);
ctrl.tab = {};
};
ctrl.remove = (pos) => ipc.send("tab-del", pos);
},
view : (ctrl, args) => m("div", { class : css.tab },
m("div", { class : css.type },
m("label", "Type ",
m("select", {
value : args.tab.type || ctrl.tab.type,
onchange : m.withAttr("selectedIndex", ctrl.type)
},
types.map((type) => m("option", { value : type }, type))
)
)
),
m("div", { class : css.url },
m("label", "URL ",
m("input", {
type : "url",
class : css.urlinput,
value : args.tab.url || ctrl.tab.url || "",
oninput : m.withAttr("value", ctrl.url)
})
)
),
m("div", { class : css.actions },
args.tab.url ?
m("button", {
onclick : ctrl.remove.bind(ctrl, args.idx)
}, "Remove") :
m("button", {
onclick : ctrl.add
}, "Add")
)
)
};
export function view() {
return m("div", { class : css.content },
settings.tabs.map((tab, idx) => m(editor, { tab, idx })),
m(editor, { tab : false })
);
}
<file_sep>C:tophat:
=======
It's a chat thing I dunno.

## Install
1. `git clone https://github.com/tivac/c-hat.git`
2. `npm i`
3. `npm start`
4. Follow terrible instructions to modify your settings file to add services
<file_sep>const fs = require("fs");
const path = require("path");
const electron = require("electron");
const app = electron.app;
const ipc = electron.ipcMain;
// Default to local appdata only, because it's more correct
// Has to be done asap or it won't take
// https://github.com/electron/electron/issues/1404
if(process.platform === "win32") {
app.setPath("appData", process.env.LOCALAPPDATA);
app.setPath("userData", path.join(process.env.LOCALAPPDATA, app.getName()));
}
const argv = require("minimist")(process.argv.slice(2));
const json = path.join(app.getPath("userData"), "settings.json");
let window;
let tray;
let settings;
function syncPosition() {
settings = Object.assign(settings, window.getBounds());
}
function createWindow() {
window = new electron.BrowserWindow({
width : settings.width,
height : settings.height,
x : settings.x,
y : settings.y,
icon : path.join(__dirname, "./icon.png"),
title : require("./package.json").productName,
autoHideMenuBar : true
});
// Remove the default menu, it isn't very useful
window.setMenu(null);
window.loadURL(`file://${__dirname}/index.html`);
window.on("resize", syncPosition);
window.on("move", syncPosition);
if(argv.devtools) {
window.webContents.openDevTools();
}
window.on("closed", () => {
window = null;
});
}
app.on("ready", () => {
try {
settings = JSON.parse(fs.readFileSync(json));
} catch(e) {
settings = JSON.parse(fs.readFileSync(path.join(__dirname, "./settings.json")));
}
// So it's easily accessible anywhere
global.settings = settings;
createWindow();
// Create Tray icon
tray = new electron.Tray(path.join(__dirname, "./icon.png"));
tray.on("double-click", () => window.show());
});
// Quit when all windows are closed.
app.on("window-all-closed", () => {
// Except on OSX
if(process.platform === "darwin") {
return;
}
app.quit();
});
app.on("will-quit", () => {
// Save out settings before quitting
fs.writeFileSync(json, JSON.stringify(settings, null, 4));
});
app.on("activate", () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if(window === null) {
createWindow();
}
});
// Settings hooks
ipc.on("tab-add", (e, tab) => {
settings.tabs.push(tab);
e.sender.send("tab-updated");
});
ipc.on("tab-del", (e, pos) => {
settings.tabs.splice(pos, 1);
e.sender.send("tab-updated");
});
<file_sep>"use strict";
var rollup = require("rollup").rollup,
argv = require("minimist")(process.argv.slice(2));
function noop() { }
rollup({
entry : "./app/renderer.js",
plugins : [
require("rollup-plugin-node-resolve")({
browser : true
}),
require("modular-css/rollup")({
css : "./app/gen/c-hat.css",
namer : argv.compress ? require("modular-css-namer")() : undefined,
done : [
argv.compress ? require("cssnano")() : noop
]
}),
require("rollup-plugin-buble")(),
argv.compress ? require("mithril-objectify/rollup")() : noop,
argv.compress ? require("rollup-plugin-uglify")() : noop
]
})
.then((bundle) => bundle.write({
format : "iife",
dest : "./app/gen/c-hat.js"
}))
.catch((error) => console.error(error.stack));
<file_sep>/* eslint no-console:0 */
"use strict";
var packager = require("electron-packager"),
humanize = require("humanize-duration"),
zipdir = require("zip-dir"),
size = require("filesize"),
pkg = require("../package.json"),
start = Date.now();
packager({
platform : "win32,linux",
arch : "all",
asar : true,
dir : "./app",
icon : "./logo/hat",
out : "./packages",
overwrite : true,
prune : true,
download : {
cache : "./packages/cache"
},
"app-copyright" : "Copyright (C) 2016 <NAME>. All rights reserved.",
"app-version" : pkg.version,
"version-string" : {
CompanyName : "<NAME>",
FileDescription : "Tabbed web chat clients are fun.",
ProductName : pkg.productName
}
}, (error, paths) => {
if(error) {
console.error(error);
return process.exit(1);
}
console.log(`\nBuilt ${paths.length} package(s) in ${humanize(Date.now() - start)}:\n\t${paths.join("\n\t")}\n`);
start = Date.now();
console.log("Zipping packages...");
return Promise.all(paths.map((dir) => {
var out = `${dir}.zip`;
return new Promise((resolve, reject) => {
zipdir(dir, {
saveTo : out
}, (err, buffer) => {
if(err) {
return reject(err);
}
console.log(`Zipped ${out} (${size(buffer.length)}) in ${humanize(Date.now() - start)}`);
return resolve(out);
});
});
}))
.catch((err) => {
console.error(err);
return process.exit(1);
});
});
|
0adf8e4b31a7b7ca83138962f22d8e3e5bb7f2a3
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
stffrd/c-hat
|
3d415f84ccfaee37071d23c621c30276f42e86c5
|
13565bd69a7c9e86f9db5f8d1afe6c9045988267
|
refs/heads/main
|
<file_sep>from random import randint
from numba import njit, np
from numba.typed import List
f = open('1.txt', 'w', encoding='utf8')
def start():
print('--------------------------------')
print('Для начала работы нажмите Enter.')
input()
print('Это программа для генирации случайных чисел.')
start()
@njit(fastmath=True)
def gen_A(leng, r1, r2):
A = [randint(r1, r2) for i in range(leng)]
typed_a = List(A)
# [typed_a.append(x) for x in A]
return A, typed_a
@njit(fastmath=True)
def get_best(A, n):
j = -1
h = 10000
index1 = 0
index2 = 0
result = 0
last = A[0]
best = 0
for i in range(1, len(A)):
if A[i] == last:
last = A[i]
index2 += 1
else:
r1 = index2 - index1 + 1
r2 = A[index1]
if j <= r1 <= h and r2 == n:
result += 1
if r1 > best:
best = r1
index2 += 1
index1 = index2
last = A[i]
if A[-1] == n:
index2 += 1
r1 = index2 - index1 + 1
r2 = A[index1]
if j <= r1 <= h and r2 == n:
result += 1
if r1 > best:
best = r1
return best
@njit(fastmath=True)
def user_ask(n, j, h, A):
index1 = 0
index2 = 0
result = 0
last = A[0]
for i in range(1, len(A)):
if A[i] == last:
last = A[i]
index2 += 1
else:
r1 = index2 - index1 + 1
r2 = A[index1]
if j <= r1 <= h and r2 == n:
result += 1
index2 += 1
index1 = index2
last = A[i]
if A[-1] == n:
index2 += 1
r1 = index2 - index1 + 1
r2 = A[index1]
if j <= r1 <= h and r2 == n:
result += 1
return result
def main_program():
while True:
print('Введите диапозон чисел')
range1 = input().split(' ')
if len(range1) != 2:
print('Вы указали интервал неверно!')
start()
continue
else:
try:
range1[0] = int(range1[0])
range1[1] = int(range1[1])
except:
print('Промежутки интервала должны быть целыми числами!')
start()
continue
if range1[1] < range1[0]:
print('Неправильно указаны граници интервала. 1 число должно быть не больше 2')
start()
continue
print('Введите длину последовательности')
try:
leng = int(input())
if leng < 1:
print('Минамальное значение длины последовательности это - 1')
start()
continue
except:
print('Длина последовательности должна быть целым числом!')
start()
continue
# A = [0] * leng
print('Генерация последовательности:')
print()
# A = [randint(range1[0], range1[1]) for i in range(leng)]
A, typed_a = gen_A(leng, range1[0], range1[1])
print('Генерация последовательности готова')
# typed_a = List(A)
# [typed_a.append(x) for x in A]
print()
s = '\n'
f.write(s)
# number_of_repet = [0] * (leng + 1)
# best = [0] * (leng + 1)
# typed_number_of_repet = List()
# [typed_a.append(x) for x in number_of_repet]
#
# typed_best = List()
# [typed_a.append(x) for x in best]
# best = get_best(A, range1[0], range1[1], leng, number_of_repet, best)
# print(best, '------')
print()
s = '\n'
f.write(s)
for i in range(range1[0], range1[1] + 1):
res1 = get_best(typed_a, i)
print('Максимальная длина ряда из', i, '-', res1)
s = 'Максимальная длина ряда из ' + str(i) + ' - ' + str(res1) + '\n'
f.write(s)
s = '\n'
f.write(s)
print()
return A, typed_a
A, typed_a= main_program()
s = '\n'
f.write(s)
print(r'Запросы, для завершения прграммы введите -1')
print()
# print(r'Сколька последовательносте из числа n, в которых число n повторилось в промежетке от j до h (числа n j h укажите через пробел)')
z = 1
while z is not None:
z = input(
r'Сколько последовательностей из числа n, в которых число n повторилось в промежутке от j до h (числа n j h укажите через пробел)')
if z == '-1':
break
try:
n, j, h = z.split()
n, j, h = int(n), int(j), int(h)
except:
print('Вы указали данные неверно')
continue
result = user_ask(n, j, h, typed_a)
print()
print(f'Существует {result} промежутков из числа {n} длиной от {j} до {h}')
print()
s = f'Существует {result} промежутков из числа {n} длиной от {j} до {h}' + '\n'
f.write(s)
f.close()
|
92a6e63d967efff8e10688cbc80aca75ebab8047
|
[
"Python"
] | 1 |
Python
|
Ser4ey/nuitka
|
b96ba342a7bb63b8c5961d0280c099f747fbbb22
|
d9c94678b797b6d1993bfec57fb018893a16d5d8
|
refs/heads/master
|
<repo_name>ISBITX/isbit_android_client<file_sep>/isbit/src/main/java/com/isbit/m/RefreshOrdersInformation.java
package com.isbit.m;
/**
* Created by Sebastian on 14/01/2017.
*/
public interface RefreshOrdersInformation {
public void refresh();
}
<file_sep>/isbit/build.gradle
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
}
}
apply plugin: 'com.android.application'
repositories {
mavenCentral()
jcenter()
}
android {
compileSdkVersion 25
// buildToolsVersion '21.1.2'
buildToolsVersion '23.0.2' // Older versions may give compile errors
signingConfigs{
config{
keyAlias 'isbit'
keyPassword '<PASSWORD>'
storePassword '<PASSWORD>'
storeFile file('C:\\Users\\Sebastian\\isbit_android_certs\\isbit_android_isbit_sa_de_cv_2017_keystore.jks')
}
}
defaultConfig {
minSdkVersion 14
targetSdkVersion 25
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.0.13'
compile group: 'com.alibaba', name: 'fastjson', version: '1.1.36'
compile group: 'org.jsoup', name: 'jsoup', version: '1.7.3'
compile group: 'com.google.guava', name: 'guava', version: '18.0'
compile group: 'junit', name: 'junit', version: '4.11'
// compile fileTree(dir: 'libs', include: ['*.jar'])
// testCompile 'junit:junit:4.12'
// compile 'com.android.support:appcompat-v7:19.0.3'
//compile 'com.android.support:recyclerview-v7:19.+'
compile 'org.java-websocket:Java-WebSocket:1.3.0'
// compile 'com.android.support:support-v4:19.1.0'
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.google.zxing:core:3.2.1'
compile 'com.journeyapps:zxing-android-embedded:3.4.0@aar'
compile 'net.danlew:android.joda:2.9.5.1'
}
<file_sep>/isbit/src/main/java/com/isbit/m/DepositFragment.java
package com.isbit.m;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import org.bitcoin.market.IsbitMXNApi;
import org.bitcoin.market.bean.AppAccount;
import org.bitcoin.market.bean.Symbol;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link DepositFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link DepositFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class DepositFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public DepositFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment DepositFragment.
*/
// TODO: Rename and change types and number of parameters
public static DepositFragment newInstance(String param1, String param2) {
DepositFragment fragment = new DepositFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_deposit, container, false);
final Activity activity = getActivity();
final ImageView qriv = (ImageView) rootView.findViewById(R.id.qrImageView);
final TextView addr_tv = (TextView) rootView.findViewById(R.id.addr);
new Thread(new Runnable() {
@Override
public void run() {
IsbitMXNApi api = new IsbitMXNApi(rootView.getContext());
AppAccount appAccount = new AppAccount();
DS ds = new DS(activity);
ds.open();
appAccount.setSecretKey(ds.query_secret_key());
appAccount.setAccessKey(ds.query_access_key());
ds.close();
final JSONObject resp = api.getDepositAddress(appAccount,Symbol.btc);
final String address = resp.getString("address");
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix = multiFormatWriter.encode(address, BarcodeFormat.QR_CODE,200,200);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
qriv.setImageBitmap(bitmap);
addr_tv.setText(address);
qriv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String shareBody = ""+address;
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "DIRECCION DEPOSITO");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_using)));
}
});
}catch (WriterException e){
e.printStackTrace();
Log.e("DepositFragment",e.toString());
}
}
});
}
}).start();
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Activity context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
<file_sep>/isbit/src/main/java/com/isbit/m/RunningOrdersArrayAdapter.java
package com.isbit.m;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONException;
import org.bitcoin.market.bean.BitOrder;
import org.bitcoin.market.bean.OrderSide;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
/**
* Created by Sebastian on 01/01/2017.
*/
class RunningOrdersArrayAdapter extends ArrayAdapter<BitOrder> {
private Context context;
HashMap<BitOrder, Integer> mIdMap = new HashMap<BitOrder, Integer>();
public RunningOrdersArrayAdapter(Context context, int textViewResourceId,
List<BitOrder> objects) {
super(context, textViewResourceId, objects);
this.context = context;
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
@Override
public long getItemId(int position) {
BitOrder item = getItem(position);
return mIdMap.get(item);
}
@Override
public boolean hasStableIds() {
return true;
}
@SuppressLint("SetTextI18n")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);
TextView datetime = new TextView(context);
TextView precio = new TextView(context);
precio.setPadding(0,0,8,0);
LinearLayout hl1 = new LinearLayout(context);
hl1.setOrientation(LinearLayout.HORIZONTAL);
TextView volumen = new TextView(context);
// BitOrder ord = getItem(position);
ll.addView(datetime);
ll.addView(hl1);
hl1.addView(precio);
hl1.addView(volumen);
try {
if((OrderSide.buy).equals(getItem(position).getOrderSide())){
precio.setTextColor(Color.GREEN);
}else{
precio.setTextColor(Color.RED);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
precio.setText(String.format(Locale.getDefault(),"%.8f",getItem(position).getOrderMxnPrice()));
} catch (JSONException e) {
e.printStackTrace();
}
try {
volumen.setText(String.format(Locale.getDefault(),"%.8f",getItem(position).getOrderAmount()));
} catch (JSONException e) {
e.printStackTrace();
}
try {
android.text.format.DateFormat df = new android.text.format.DateFormat();
//datetime.setText(df.format("MM/dd hh:mm a", getItem(position).getDatetime()));
datetime.setText(getItem(position).getCreateTime()+"");
}catch (Exception e){
e.printStackTrace();
Log.e("RunningOrdersArray","problem printing running order date ---"+e.toString());
}
return ll;
// return super.getView(position, convertView, parent);
}
}
<file_sep>/isbit/src/main/java/com/isbit/m/MainActivity.java
package com.isbit.m;
import android.app.ActionBar;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends FragmentActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, FundsFragment.OnFragmentInteractionListener, DepositFragment.OnFragmentInteractionListener, TradeFragment.OnFragmentInteractionListener, SetActionbarInformation {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.funds_activity);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
int number = position+1;
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
switch (number){
case 1:
fragmentManager.beginTransaction().replace(R.id.container, FundsFragment.newInstance(position + 1)).commit();
break;
case 2:
fragmentManager.beginTransaction().replace(R.id.container, TradeFragment.newInstance("one","two change this")).commit();
break;
case 3:
fragmentManager.beginTransaction().replace(R.id.container, DepositFragment.newInstance("","")).commit();
break;
case 4:
DS ds = new DS(MainActivity.this);
ds.open();
ds.erase();
ds.close();
finish();
break;
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = "Salir";
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public void onFragmentInteraction(Uri uri) {
}
@Override
public void setActionbarTitle(String tile) {
ActionBar ab = getActionBar();
ab.setTitle(tile);
}
@Override
public void setActionbarSubtitle(String subtitle) {
ActionBar ab = getActionBar();
ab.setSubtitle(subtitle);
}
}
<file_sep>/settings.gradle
include ':isbit'
<file_sep>/isbit/src/main/java/com/isbit/m/CancelOrderDialogFragment.java
package com.isbit.m;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.DialogFragment;
import org.bitcoin.market.IsbitMXNApi;
import org.bitcoin.market.bean.AppAccount;
import org.bitcoin.market.bean.BitOrder;
import org.bitcoin.market.bean.OrderSide;
import org.bitcoin.market.bean.Symbol;
import org.bitcoin.market.bean.SymbolPair;
public class CancelOrderDialogFragment extends DialogFragment {
private BitOrder ord;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
String msg = "";
String title = "CANCELAR orden de ";
if(OrderSide.sell.equals(ord.getOrderSide())){
title += "VENTA?";
}else {
title += "COMPRA?";
}
msg+="Precio: "+ord.getOrderMxnPrice()+" MXN";
msg+="\n";
msg+="Volumen: "+ord.getOrderAmount()+" BTC";
msg+="\n";
builder.setTitle(title);
builder.setMessage(msg)
.setPositiveButton("Sí",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
new Thread(new Runnable() {
@Override
public void run() {
Context context = getContext();
if(context!=null) {
IsbitMXNApi api = new IsbitMXNApi(context);
AppAccount appAccount = new AppAccount();
DS ds = new DS(context);
ds.open();
appAccount.setAccessKey(ds.query_access_key());
appAccount.setSecretKey(ds.query_secret_key());
ds.close();
SymbolPair symbol_pair = new SymbolPair(Symbol.btc, Symbol.mxn);
api.cancel(appAccount, ord.getOrderId(), symbol_pair);
}
new Handler(Looper.getMainLooper()).post(new Runnable(){
@Override
public void run() {
Intent broadcast = new Intent();
broadcast.setAction(RealTimeMarketData.ACTION_ORDERBOOK_CHANGED);
broadcast.putExtra(RealTimeMarketData.EXTRA_PAYLOAD_STRING,"{}");
Context context = getContext();
if (context!=null) {
context.sendBroadcast(broadcast);
// getActivity().sendBroadcast(broadcast);
}
}
});
}
}).start();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
public BitOrder getOrder() {
return ord;
}
public void setOrder(BitOrder ord) {
this.ord = ord;
}}
<file_sep>/isbit/src/main/java/com/isbit/m/Tablero.java
package com.isbit.m;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegratorISBIT;
import com.google.zxing.integration.android.IntentResultISBIT;
import org.bitcoin.market.IsbitMXNApi;
import org.bitcoin.market.bean.AppAccount;
import org.bitcoin.market.bean.Asset;
import org.json.JSONException;
import org.json.JSONObject;
public class Tablero extends FragmentActivity {
public static final String TAG = "Tablero";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.isbit.m.R.layout.activity_tablero);
final Context context = getApplicationContext();
/*
new Thread(new Runnable() {
@Override
public void run() {
String url_str = DS.get_isbit_url(context)+"//api/v2/order_book.json?market=btcmxn&asks_limit=10&bids_limit=10";
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(url_str);
urlConnection = (HttpURLConnection) url.openConnection();
// urlConnection.setDoOutput(true);
// urlConnection.setChunkedStreamingMode(0);
//
// OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
// writeStream(out);
// out.write("hola".getBytes());
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
final String respuesta= readStream(in);
JSONObject orderbook = new JSONObject(respuesta);
final JSONArray asks_json = orderbook.getJSONArray("asks");
final JSONArray bids_json = orderbook.getJSONArray("bids");
Tablero.this.runOnUiThread(new Runnable() {
@Override
public void run() {
final ListView listview = (ListView) findViewById(android.R.id.list);
final ArrayList<JSONObject> list = new ArrayList<JSONObject>();
for (int i = asks_json.length()-1; i >= 0; --i) {
try {
if(asks_json.getJSONObject(i).getDouble("remaining_volume")>0) {
list.add(asks_json.getJSONObject(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < bids_json.length(); ++i) {
try {
if(asks_json.getJSONObject(i).getDouble("remaining_volume")>0) {
list.add(bids_json.getJSONObject(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final StableArrayAdapter adapter = new StableArrayAdapter(Tablero.this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
//TextView ticker_tv = (TextView) findViewById(R.id.ticker_tv);
//ticker_tv.setText(respuesta);
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
}).start();
*/
View tablero = (View) findViewById(R.id.tablero);
initIsbit(tablero,Tablero.this);
Button button = (Button) findViewById(com.isbit.m.R.id.button_acceder);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Intent login_activity_intent = new Intent(Tablero.this, LoginActivity.class);
// startActivity(login_activity_intent);
//Intent intent = new Intent("com.google.zxing.client.android.SCAN");
IntentIntegratorISBIT i = new IntentIntegratorISBIT(Tablero.this);
i.setCaptureActivity(ToolbarCaptureActivity.class);
i.initiateScan();
// startActivity(new Intent(Tablero.this,ToolbarCaptureActivity.class));
//intent.putExtra("SCAN_MODE", "QR_CODE_MODE");//for Qr code, its "QR_CODE_MODE" instead of "PRODUCT_MODE"
//intent.putExtra("SAVE_HISTORY", false);//this stops saving ur barcode in barcode scanner app's history
//startActivityForResult(intent, 0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResultISBIT result = IntentIntegratorISBIT.parseActivityResult(requestCode, resultCode, data);
Log.i(TAG, "onActivityResult(requestCode="+requestCode+", resultCode, data="+data+")");
if (result != null) {
String contents = result.getContents();
if (result.getContents()!=null){
try {
JSONObject yeison = new JSONObject(contents);
String access_key = yeison.getString("access_key");
String secret_key = yeison.getString("secret_key");
String url_host = yeison.getString("url_host");
String url_schema = yeison.getString("url_schema");
DS ds = new DS(Tablero.this);
ds.open();
ds.save_key_value_pair( DS.access_key, access_key);
ds.save_key_value_pair( com.isbit.m.DS.secret_key, secret_key);
ds.save_key_value_pair( com.isbit.m.DS.url_host, url_host);
ds.save_key_value_pair( com.isbit.m.DS.url_schema, url_schema);
ds.close();
Intent intent = new Intent(Tablero.this, MainActivity.class);
startActivity(intent);
//Log.d("api", secret_key + " " + access_key);
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("shit", "La respuesta fue " + contents);
} else {
// do something else
}
}
public void initIsbit(final View rootView, final Activity activity){
final ProgressBar pb = (ProgressBar) rootView.findViewById(R.id.progressBar);
final Button access_button = (Button) findViewById(com.isbit.m.R.id.button_acceder);
DS ds = new DS(activity);
ds.open();
final String access_key = ds.query_access_key();
final String secret_key = ds.query_secret_key();
ds.close();
pb.setVisibility(View.VISIBLE);
access_button.setVisibility(View.GONE);
if(access_key!=null && !access_key.isEmpty() && secret_key!=null && !secret_key.isEmpty()){
access_button.setVisibility(View.GONE);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
final AppAccount app_account = new AppAccount();
app_account.setAccessKey(access_key);
app_account.setSecretKey(secret_key);
IsbitMXNApi api = new IsbitMXNApi(activity);
try{
final Asset asset = api.getInfo(app_account);
Log.i("MainActivity", asset.toString());
final Long member_id = asset.getAppAccountId();
DS ds = new DS(activity);
ds.open();
final String email_str = ds.query_database_key( "email");
final String sn_str = ds.query_database_key( "sn");
ds.close();
rootView.post(new Runnable() {
@Override
public void run() {
//boolean active = Boolean.parseBoolean(DS.query_database_key(activity, "activated"));
if(email_str.length()>0 && sn_str.length()>0) {
Toast.makeText(activity, "Miembro " + member_id + " Autenticado", Toast.LENGTH_LONG);
Intent intent = new Intent(Tablero.this, MainActivity.class);
startActivity(intent);
finish();
}else{
AlertDialogFragment adf = new AlertDialogFragment();
adf.setMsg("MIEMBRO NO AUTENTICADO ");
adf.show(getSupportFragmentManager(),"adf_member_not_aut");
pb.setVisibility(View.GONE);
access_button.setVisibility(View.VISIBLE);
}
}
});
}catch (final RuntimeException re){
rootView.post(new Runnable() {
@Override
public void run() {
//boolean active = Boolean.parseBoolean(DS.query_database_key(activity, "activated"));
AlertDialogFragment adf = new AlertDialogFragment();
adf.setMsg("FRACASO DE AUTENTICACION "+ re.getMessage());
adf.show(getSupportFragmentManager(),"adf_aut_failure");
pb.setVisibility(View.GONE);
}
});
}
}
}).start();
}else{
pb.setVisibility(View.GONE);
access_button.setVisibility(View.VISIBLE);
}
}
}
<file_sep>/isbit/src/main/java/com/isbit/m/RealTimeMarketData.java
package com.isbit.m;
import android.app.Activity;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Mac;
public class RealTimeMarketData extends Activity {
public static final String ACTION_ORDERBOOK_CHANGED = "ACTION_ORDERBOOK_CHANGED" ;
public static final String EXTRA_PAYLOAD_STRING = "EXTRA_PAYLOAD_STRING";
private WebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.isbit.m.R.layout.activity_main);
connectWebSocket();
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(com.isbit.m.R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(com.isbit.m.R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case com.isbit.m.R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(com.isbit.m.R.layout.fragment_main, container, false);
return rootView;
}
}
private void connectWebSocket() {
URI uri;
try {
DS ds = new DS(RealTimeMarketData.this);
ds.open();
String host = ds.query_url_host();
ds.close();
uri = new URI("ws://"+host+":8080");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView)findViewById(com.isbit.m.R.id.messages);
textView.setText(textView.getText() + "\n" + message);
try {
JSONObject msg_json = new JSONObject(message);
String challenge = msg_json.getString("challenge");
DS ds = new DS(RealTimeMarketData.this);
ds.open();
String access_key = ds.query_access_key();
String private_key = ds.query_secret_key();
ds.close();
String payload = access_key + challenge;
textView.setText(textView.getText() + "\n challenge = " + challenge + "\n");
textView.setText(textView.getText() + "\n payload = " + payload + "\n");
String signature = hmacsha256_encode(private_key,payload);
textView.setText(textView.getText() + "\n signature = " + signature + "\n");
JSONObject auth_json = new JSONObject();
auth_json.put("access_key",access_key);
auth_json.put("answer", signature);
JSONObject reply_json = new JSONObject();
reply_json.put("auth", auth_json);
textView.setText(textView.getText() + "\n Mensaje autenticación = " + reply_json.toString() + "\n");
mWebSocketClient.send(auth_json.toString());
JSONObject orderbook_msg = new JSONObject();
orderbook_msg.put("orderbook",new JSONObject().put("action","update"));
mWebSocketClient.send(orderbook_msg.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
public void sendMessage(View view) {
EditText editText = (EditText)findViewById(com.isbit.m.R.id.message);
mWebSocketClient.send(editText.getText().toString());
editText.setText("");
}
public String hmacsha256_encode(String key, String data) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return str2Hex(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}
public String convertStringToHex(String str){
char[] chars = str.toCharArray();
StringBuffer hex = new StringBuffer();
for(int i = 0; i < chars.length; i++){
hex.append(Integer.toHexString((int)chars[i]));
}
return hex.toString();
}
public String str2Hex(byte[] bytes) {
StringBuffer hash = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hash.append('0');
}
hash.append(hex);
}
return hash.toString();
}
}
<file_sep>/README.md
# isbit_android_client
Android Client for https://isbit.co API. The library inside this app can also be used for SE JAVA apps.
Any questions pls contact <NAME> at the following address <EMAIL>
|
ddd0beca5f4634efa6823229450eefd129b40502
|
[
"Markdown",
"Java",
"Gradle"
] | 10 |
Java
|
ISBITX/isbit_android_client
|
90d74fdfe1ac330d9c19ea1b260aaf97cefd4fc5
|
5b6644efbc2135a835318df6da9cad8f5b1e395e
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import TableTitle from '../Common/TableTitle';
import AddressDetail from '../Common/AddressDetail';
class PrAddress extends Component {
constructor() {
super();
this.state = {
expandedRows: null
};
}
rowExpansionTemplate(data) {
return (
<AddressDetail data={data} />
);
}
render() {
return (
<div>
<TableTitle />
<div>
<DataTable
value={this.props.addressList}
expandedRows={this.state.expandedRows}
onRowToggle={(e) => this.setState({ expandedRows: e.data })}
rowExpansionTemplate={this.rowExpansionTemplate}>
<Column expander={true} style={{ width: '4em' }} />
<Column field='username' header='Nick' style={{ width: '10em' }} />
<Column field='name' header='Name' style={{ width: '10em' }} />
<Column field='email' header='E-Mail' style={{ width: '15em' }} />
<Column field='phone' header='Phone' style={{ width: '10em' }} />
<Column field='website' header='Web Address' style={{ width: '10em' }} />
</DataTable>
</div>
</div>
);
}
}
export default PrAddress;<file_sep>import React from 'react';
import classes from './Header.css'
const header = (props) => {
return (
<thead className={classes.Header}>
<tr >
<th></th>
<th>Nick</th>
<th>Name</th>
<th>E-Mail</th>
<th>Phone</th>
<th>Web Address</th>
</tr>
</thead>
);
}
export default header;<file_sep>import React, { Component } from 'react'
import 'primereact/resources/themes/nova-light/theme.css';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import { SelectButton } from 'primereact/selectbutton';
import Auxiliary from '../hoc/Auxiliary';
import PrAddress from '../Components/PrimeComponents/PrAddress';
import AddressList from '../Components/NativeComponents/AddressList';
import MdAddressList from '../Components/ReactMDComponents/MdAddressList';
import SuiAddressList from '../Components/SymanticUIComponents/SuiAddressList';
import { AddressService } from '../Services/AddressServices';
import AdAddressList from '../Components/AntDesignComponents/AdAddressList';
class Layout extends Component {
constructor() {
super();
this.state = {
mode: 'nt',
addressList: []
};
this.addressService = new AddressService();
}
componentDidMount() {
this.addressService.getAllAddresses()
.then(response => {
this.setState({
addressList: response
})
}).catch(error => {
console.log(error);
});
}
render() {
const options = [
{ label: 'Native', value: 'nt' },
{ label: 'PrimeReact', value: 'pr' },
{ label: 'React MD', value: 'md' },
{ label: 'Semantic UI', value: 'sui' },
{ label: 'Ant Design', value: 'ad' }
];
let dataTable = "";
if (this.state.mode === 'nt') {
dataTable =
<div>
<AddressList addressList={this.state.addressList} />
</div>
} else if (this.state.mode === 'pr') {
dataTable =
<div >
<PrAddress addressList={this.state.addressList} />
</div>
} else if (this.state.mode === 'md') {
dataTable =
<div>
<MdAddressList addressList={this.state.addressList} />
</div>
} else if (this.state.mode === 'sui') {
dataTable =
<div>
<SuiAddressList addressList={this.state.addressList} />
</div>
} else if (this.state.mode === 'ad') {
dataTable =
<div>
<AdAddressList addressList={this.state.addressList} />
</div>
}
return (
<Auxiliary>
<div>
<SelectButton
style={{ width: '600px' }}
value={this.state.mode}
options={options}
checked={this.state.primeMode}
onChange={(e) => this.setState({ mode: e.value })} />
</div>
{
dataTable
}
</Auxiliary>
);
}
}
export default Layout;<file_sep>import React, { Component } from 'react';
import {
DataTable,
TableBody, CardTitle, CardText, Card,
Button, DialogContainer
} from 'react-md';
import Auxiliary from '../../hoc/Auxiliary';
import MdAddress from './Address/MdAddress';
import MdHeader from './Address/MdHeader';
import TableTitle from '../Common/TableTitle';
import AddressDetail from '../Common/AddressDetail';
class MdAddressList extends Component {
state = { visible: false, data: null };
show = (i) => {
this.setState({
visible: true,
data: this.props.addressList[i]
});
};
hide = () => {
this.setState({ visible: false, data: null });
};
handleKeyDown = (e) => {
const key = e.which || e.keyCode;
if (key === 13 || key === 32) {
// also close on enter or space keys
this.hide();
}
};
render() {
const { visible } = this.state;
return (
<Auxiliary>
<TableTitle />
<div>
<DialogContainer
id="simple-list-dialog"
title=""
visible={visible}
onHide={this.hide} >
<Card style={{ maxWidth: 800 }} className="md-block-centered">
<CardTitle title='Address Card' />
<CardText>
<AddressDetail data={this.state.data} />
</CardText>
</Card>
<Button raised onClick={this.hide}>
close
</Button>
</DialogContainer>
</div>
<DataTable plain>
<MdHeader />
<TableBody>
{
this.props.addressList.map((addr, i) => (
<MdAddress key={i} index={i} address={addr} showDialogClicked={this.show} />
))
}
</TableBody>
</DataTable>
</Auxiliary >
);
}
}
export default MdAddressList;<file_sep>import React from 'react';
import {configure, shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import AddressList from './AddressList';
import Address from './Address/Address';
configure({adapter: new Adapter()});
describe ('<AddressList/> ', () => {
it ('should return no <Address/> when addressList is empty! ', ()=>{
const wrapper = shallow(<AddressList addressList = {[]}/>);
expect(wrapper.find(Address)).toHaveLength(0);
});
});<file_sep>import React from 'react';
import classes from './Detail.css';
import AddressDetail from '../../Common/AddressDetail';
const detail = (props) => {
if (props.data === null) {
return null;
}
return (
<div className={classes.Detail}>
<AddressDetail data={props.data} />
<div>
<button onClick={props.hideDetail} >close</button>
</div>
</div>
);
}
export default detail;<file_sep>### `npm instal`
to install node in your local
### `npm start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.<file_sep>import React from 'react'
import {
TableHeader,
TableRow,
TableColumn,
} from 'react-md';
const mdHeader = (props) => {
return (
<TableHeader>
<TableRow>
<TableColumn>Nick</TableColumn>
<TableColumn>Name</TableColumn>
<TableColumn>E-Mail</TableColumn>
<TableColumn>Phone</TableColumn>
<TableColumn>Web Address</TableColumn>
</TableRow>
</TableHeader>
);
};
export default mdHeader;
|
7de49d79bbcac1655c81a021ce287412a61551c7
|
[
"JavaScript",
"Markdown"
] | 8 |
JavaScript
|
sedpol/react-contact-address
|
086f80951dafd840f502de3618528b0bc97535cd
|
f391ec8229cfea5780d29ae9df5fadcde6d2cd69
|
refs/heads/master
|
<repo_name>PSAScapstone2014/TestingFramework<file_sep>/valgrind/vgTest.py
import socket
import time
import subprocess
import csv
import thread
class valgrindTest:
def runValgrind(testFile, outFilename)
testfile = "vc"
outFilename = "logvg.txt"
subprocess.call("valgrind./", file, stderr=outFilename,shell=True)
print "name of test file",testFile
def echo_test(self, data, fileName):
dataString = ""
file = open(fileName,"rb")
file = csv.reader(file, delimiter = '\t')
fileContent = ""
for row in file:
fileContent += row[0]
for dataChunk in data['SD1_IO']:
dataString += dataChunk
if not fileContent == dataString:
raise AssertionError("Data sent did not match data received")
else:
print "Test passed!"
<file_sep>/README.md
TestingFramework
================
<file_sep>/gps_example/SendReceiveLibrary.py
import socket
import time
import subprocess
import csv
import thread
import itertools
import shlex
import threading
from collections import defaultdict
# This is a helper funtion that formats data for the ChibiOS protocol
# @param lld The name of the low-level driver that the data is being sent to
# @param data The data to be sent to the driver
# @return A string formatted for the protocol
def sim_format(lld, data):
return '%s\t%s\n' % (lld , data.encode('hex'))
# This method reads a TSV file and sends the contents to a socket that
# represents the IO interface for a low-level driver. The TSV file should have the format:
# data<tab>time
# The data is what will be sent to the driver and the time is the time stamp of the data.
# This method will delay its sends to the socket to simulate the time elapse represented
# by the difference of the time stamps.
# @param fileName The name of the TSV file to be read from
# @param fileDesc The file descriptor to create the socket from
# @param driver The name of the low-level driver to send the data to
def send_to_driver(fileName, fileDesc, driver):
conn = socket.fromfd(fileDesc, socket.AF_INET, socket.SOCK_STREAM)
tsvFile = open(fileName,"rb")
tsvFile = csv.reader(tsvFile, delimiter = '\t')
lastTime = 0.0 # The time stamp of the last data point
for row in tsvFile:
newTime = float(row[1]) # The time stamp of the new data point
if ((newTime - lastTime) > 0.0): # Delay if there was a tim eelapse between data points
print "time to wait: ", (newTime - lastTime), " seconds"
time.sleep(newTime - lastTime)
conn.sendall(sim_format(driver, row[0]))
lastTime = newTime
print "sent: ", row[0], " to ", driver
#Class that represents keywords usable in the test table.
class SendReceiveLibrary:
# This method represents a keyword that can be used in the test table. This keyword starts up a
# chibiOS application, sends data to the app, receives data that the app outputs, and finally
# closes the app. The file in dataFiles must have the same index as the driver it needs to be
# sent to in drivers.
# @param simioPort The port used for ChibiOS input and output simulation
# @param drivers A list of the drivers used in the application that receive data
# @param dataFiles A list of data files to be sent to drivers that receive data
# @param arguments The arguments used to execute the ChibiOs application
# @return A dictionary that associates the names of low-level drivers to the data they sent
def send_and_receive(self, simioPort, drivers, dataFiles, arguments):
args = shlex.split(arguments)
HOST = ''
PORT = int(simioPort)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
activeApps = []
data = defaultdict(list)
dataBuffer = ""
sendThread = []
activeApps.append(subprocess.Popen(args, stdout=subprocess.PIPE))
conn, addr = s.accept()
print "connection accepted on: ", addr
for driver, dataFile in itertools.izip(drivers, dataFiles):
newThread = threading.Thread(target=send_to_driver, args=(dataFile, conn.fileno(), driver))
newThread.start()
sendThread.append(newThread)
while (1):
dataBuffer += conn.recv(1024)
if (threading.activeCount() <= 1):
break
lines = dataBuffer.split('\n')
for line in lines:
try:
header, code = line.strip().split('\t', 1)
except:
break
dataChunk = code.decode('hex')
data[header].append(dataChunk)
print "received: ", dataChunk, " from ", header
for app in activeApps:
app.terminate()
conn.close()
s.close()
return data
# This method is the same as send_and_receive except is collects data from an outgoing lwip
# connection as well as that from the drivers.
# @param simioPort The port used for ChibiOS input and output simulation
# @param drivers A list of the drivers used in the application that receive data
# @param dataFiles A list of data files to be sent to drivers that receive data
# @param lwipPort The port being connected to by the ChibiOS for outgoing lwip data
# @param lwipAddress The address being connected to by ChibiOS for outgoing lwip data
# @param arguments The arguments used to execute the ChibiOs application
# @return A dictionary that associates the names of low-level drivers to the data they sent
def send_and_receive_with_lwip(self, simioPort, drivers, dataFiles, lwipPort, lwipAddress, arguments):
args = shlex.split(arguments)
HOST = ''
PORT = int(simioPort)
LWIPPORT = int(lwipPort)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
lwipSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
lwipSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
lwipSocket.bind((lwipAddress, LWIPPORT))
activeApps = []
data = defaultdict(list)
dataBuffer = ""
lwipDataBuffer = ""
sendThread = []
activeApps.append(subprocess.Popen(args, stdout=subprocess.PIPE))
conn, addr = s.accept()
print "connection accepted on: ", addr
for driver, dataFile in itertools.izip(drivers, dataFiles):
newThread = threading.Thread(target=send_to_driver, args=(dataFile, conn.fileno(), driver))
newThread.start()
sendThread.append(newThread)
while (1):
dataBuffer += conn.recv(1024)
lwipDataBuffer += lwipSocket.recv(1024) + "\n"
if (threading.activeCount() <= 1):
break
lines = dataBuffer.split('\n')
for line in lines:
try:
header, code = line.strip().split('\t', 1)
except:
break
dataChunk = code.decode('hex')
data[header].append(dataChunk)
print "received: ", dataChunk, " from ", header
lines = lwipDataBuffer.split('\n')
for line in lines:
data['lwip'].append(line)
print "received: ", line, " from lwip"
for app in activeApps:
app.terminate()
conn.close()
s.close()
return data
# *** USER DEFINED TESTS DEFINED BELOW ***
# Here you can define keywords to be used to test the data returned from
# the send_and_receive keyword.
# An example user defined test is provided.
# The keyword echo_test will take the dictionary returned from send_and_received and check that the
# data sent from the serial driver matches the data in a provided TSV data file.
def echo_test(self, data, fileName):
dataString = ""
tsvFile = open(fileName,"rb")
tsvFile = csv.reader(tsvFile, delimiter = '\t')
fileContent = ""
for row in tsvFile:
fileContent += row[0]
for dataChunk in data['SD1_IO']:
dataString += dataChunk
if not fileContent == dataString:
raise AssertionError("Data sent did not match data received")
else:
print "Test passed!"
def gps_echo_test(self, data, fileName):
tsvFile = open(fileName,"rb")
tsvFile = csv.reader(tsvFile, delimiter = '\t')
for output, original in itertools.izip(data['lwip'], tsvFile):
prepend, data = output.strip().split('$', 1)
data = '$' + data
print "output: ", data
print "original: ", original[0]
print "--------------"
if not (data == original[0]):
raise AssertionError("Data sent did not match data received")
print "Test passed!"
<file_sep>/serial_test_example/README.md
To run this example you need to compile the serial unit test in ChibiOS-RT/testhal/Posix/SERIAL, then rename the executable to serialTest and move it to this directory.
<file_sep>/gps_example/README.md
To run this example echo test on the flight gps application you need to build the flight-gps app in stm32/projects/flight-gps and move the ch.elf to this directory.
|
63e2d3da7bf2b891bd1cef213ab4e237f4837dba
|
[
"Markdown",
"Python"
] | 5 |
Python
|
PSAScapstone2014/TestingFramework
|
b34d5d37e37caf74455e715cb2c4e03cb119f648
|
0172768aef061954e043c74def1f29e85373abdf
|
refs/heads/master
|
<file_sep>def is_palindrome(s):
#if s is palindrome return True, else return False
for i in range(0,len(s)/2):
if s[i] != s[-(i+1)]:
return False
return True
print is_palindrome('aha')
print is_palindrome('abcd')
print is_palindrome('able was i ere i saw elba')<file_sep>#paper,rock, scissors
player1 = raw_input('player1?')
player2 = raw_input("player2?")
VALID_INPUT = ['paper','rock','scissors']
WINNING_COMBO = [['paper','rock'],['rock','scissors'],['scissors','paper']]
def valid_input(inp):
if inp in VALID_INPUT:
return True
else:
return False
def rps(player1,player2):
if valid_input(player1) and valid_input(player2):
if player1 == player2:
return 'Tie game'
elif ([player1,player2] in WINNING_COMBO):
return 'player1 win'
else:
return 'player2 win'
else:
print "enter a valid option"
print rps(player1,player2)<file_sep>from graphics import *
class Wheel():
def __init__(self, center, wheel_radius, tire_radius):
self.tire_circle = Circle(center, tire_radius)
self.wheel_circle = Circle(center, wheel_radius)
def draw(self, win):
self.tire_circle.draw(win)
self.wheel_circle.draw(win)
def move(self, dx, dy):
self.tire_circle.move(dx, dy)
self.wheel_circle.move(dx, dy)
def set_color(self, wheel_color, tire_color):
self.tire_circle.setFill(tire_color)
self.wheel_circle.setFill(wheel_color)
def undraw(self):
self.tire_circle .undraw()
self.wheel_circle .undraw()
def get_size(self):
return self.tire_circle.getRadius()
def get_center(self):
return self.tire_circle.getCenter()
def animate(self, win, dx, dy, n):
if n > 0:
self.move(dx, dy)
win.after(100, self.animate, win, dx, dy, n-1)
# Define a main function; if you want to display graphics, run main()
# after you load code into your interpreter
def main():
# create a window with width = 700 and height = 500
new_win = GraphWin('Wheel', 700, 500)
# What we'll need for the wheel...
wheel_center = Point(200, 200) # The wheel center is a Point at (200, 200)
tire_radius = 100 # The radius of the outer tire is 100
# Make a wheel object
new_wheel = Wheel(wheel_center, 0.6*tire_radius, tire_radius)
# Set its color
new_wheel.set_color('red', 'black')
# And finally, draw it
new_wheel.draw(new_win)
# Run the window loop (must be the *last* line in your code)
new_win.mainloop()
# Comment this call to main() when you import this code into
# your car.py file - otherwise the Wheel will pop up when you
# try to run your car code.
main()<file_sep>print "example1: make a list of letters in a string"
print [letter for letter in "hello, wolrd"]
print [letter+"!" for letter in "hello world"]
print [letter for letter in "hello world" if letter != 'o']<file_sep>
def print_guessed():
'''
Prints out the characters you have guessed in the secret word so far
'''
secret_word = 'claptrap'
letters_guessed = ['p']
character_list = []
####### YOUR CODE HERE ######
for i in secret_word:
if i in letters_guessed:
character_list.append(i)
else:
character_list.append('-')
return ''.join(character_list)
print print_guessed()<file_sep># Name:
# Section:
# hw2.py
##### Template for Homework 2, exercises 2.0 - 2.5 ######
# ********** Exercise 2.0 **********
def f1(x):
print x + 1
def f2(x):
return x + 1
print f1(3) #print 4, and return None
print f2(3) #reuturn 4
#print f1(3)+1 # failed because unsupported operand type for 'int'+'str' 1+None
print f2(3)+1 # 5
# ********** Exercise 2.1 **********
# Define your function here
##### YOUR CODE HERE #####
#paper,rock, scissors
def rps(player1,player2):
if player1 == player2:
print "Tie game"
elif (player1 == 'scissors' and player2 == 'paper' or
player1 == 'rock' and player2 == 'scissors' or
player1 == 'paper' and player2 == 'rock'):
print "player1 wins"
else:
print "player2 wins"
# Test Cases for Exercise 2.1
##### YOUR CODE HERE #####
rps("scissors","paper")
rps("paper","rock")
rps("rock","scissors")
rps('paper','scissors')
rps('scissors','rock')
rps('rock','paper')
rps('scissors','scissors')
rps('paper','paper')
rps('rock','rock')
# ********** Exercise 2.2 **********
# Define is_divisible function here
##### YOUR CODE HERE #####
def is_divisible(m,n):
if n != 0:
if m%n == 0:
return True
else:
return False
else:
print 'can not be divisibe by zero'
# Test cases for is_divisible
## Provided for you... uncomment when you're done defining your function
print is_divisible(10, 5) # This should return True
print is_divisible(18, 7) # This should return False
print is_divisible(42, 0) # What should this return?
# Define not_equal function here
##### YOUR CODE HERE #####
def not_equal(m,n):
if m > n or m < n:
return True
else:
return False
# Test cases for not_equal
##### YOUR CODE HERE #####
not_equal(2,2)
not_equal(2,3)
# ********** Exercise 2.3 **********
import math
import random
## 1 - multadd function
##### YOUR CODE HERE #####
def multadd(a,b,c):
return a*b+c
## 2 - Equations
##### YOUR CODE HERE #####
a = math.sin(math.pi/4)
b = 1
c = math.cos(math.pi/4)/2
print multadd(a,b,c)
# Test Cases
# angle_test =
# print "sin(pi/4) + cos(pi/4)/2 is:"
# print angle_test
# ceiling_test =
# print "ceiling(276/19) + 2 log_7(12) is:"
# print ceiling_test
## 3 - yikes function
##### YOUR CODE HERE #####
# Test Cases
# x = 5
# print "yikes(5) =", yikes(x)
# ********** Exercise 2.4 **********
## 1 - rand_divis_3 function
##### YOUR CODE HERE #####
def rand_divis_3():
if random.randint(0,100)%3 == 0:
return True
else:
return False
# Test Cases
##### YOUR CODE HERE #####
print rand_divis_3()
print rand_divis_3()
## 2 - roll_dice function - remember that a die's lowest number is 1;
#its highest is the number of sides it has
##### YOUR CODE HERE #####
def roll_dice(n,m):
for i in range(0,m):
print random.randint(1,n)
# Test Cases
##### YOUR CODE HERE #####
roll_dice(6,3)
# ********** Exercise 2.5 **********
# code for roots function
##### YOUR CODE HERE #####
# Test Cases
##### YOUR CODE HERE #####<file_sep># Name:
# Section:
# 6.189 Project 1: Hangman template
# hangman_template.py
# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
from string import *
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
# Import hangman words
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = split(line)
print " ", len(wordlist), "words loaded."
print 'Enter play_hangman() to play a game of hangman!'
return wordlist
# actually load the dictionary of words and point to it with
# the words_dict variable so that it can be accessed from anywhere
# in the program
words_dict = load_words()
# Run get_word() within your program to generate a random secret word
# by using a line like this within your program:
# secret_word = get_word()
def get_word():
"""
Returns a random word from the word list
"""
word=words_dict[randrange(0,len(words_dict))]
return word
# end of helper code
# -----------------------------------
# CONSTANTS
MAX_GUESSES = 6
# GLOBAL VARIABLES
secret_word = '<PASSWORD>'
letters_guessed = []
# From part 3b:
def word_guessed():
'''
Returns True if the player has successfully guessed the word,
and False otherwise.
'''
global secret_word
global letters_guessed
####### YOUR CODE HERE ######
for i in secret_word:
if i not in letters_guessed:
return False
return True
def print_guessed():
'''
Prints out the characters you have guessed in the secret word so far
'''
global secret_word
global letters_guessed
character_list = []
####### YOUR CODE HERE ######
for i in secret_word:
if i in letters_guessed:
character_list.append(i)
else:
character_list.append('-')
return ''.join(character_list)
def play_hangman():
# Actually play the hangman game
global secret_word
global letters_guessed
# Put the mistakes_made variable here, since you'll only use it in this function
mistakes_made = 0
# Update secret_word. Don't uncomment this line until you get to Step 8.
# secret_word = get_word()
####### YOUR CODE HERE ######
guess_times = 0
while guess_times <= MAX_GUESSES:
guess_letter = raw_input('Guess a letter:')
guess_times += 1
guess_letter = guess_letter.lower()
if guess_letter in letters_guessed:
print 'you have already guessed this letter!'
print print_guessed()
else:
letters_guessed.append(guess_letter)
print print_guessed()
if word_guessed():
print 'You win!'
return
print 'You lost'
play_hangman()<file_sep>#print decimal equivalents of 1/2,1/3,1/4
for i in range(1,11):
print 1.0/i
#print out countdown
var = int(raw_input("enter a number"))
while var < 0:
var = int(raw_input("enter a positive number"))
while True:
print var
var -= 1
if var < 0:
var = int(raw_input("enter a number"))
#calculate base and exp
base = int(raw_input("enter a base"))
exp = int(raw_input("enter an exp"))
result = base ** exp
print result
#enter an even number
number = int(raw_input("enter an even number"))
while number%2 != 0:
number = int(raw_input("enter an even number"))
if number%2 == 0:
print "congrats"
break
<file_sep># Problem Set 5: Ghost
# Name:
# Collaborators:
# Time:
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
print " ", len(wordlist), "words loaded."
return wordlist
def get_frequency_dict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
wordlist = load_words()
# TO DO: your code begins here!
word = []
def play_ghost(word_list):
current_player = 1
print 'welcome to Ghost!'
print 'player1 goes first.'
print 'current word fragment: '''
while True:
print 'player %d turn' %(current_player)
print 'player %d says letter:' %(current_player),
user_letter = raw_input()
while not is_valid_letter(user_letter):
print 'This is not a letter, please enter a letter:'
update_word = update_fragment(user_letter)
display_fragment(update_word)
isCompleteWord = is_complete_word(update_word,word_list)
if isCompleteWord:
print 'player %d loses because %s is a word!' %(current_player,update_word)
print 'player %d wins' %((current_player+1)%2)
break
else:
isValid = is_valid_word(update_word, word_list)
if not isValid:
print 'player %d loses because no word begins with %s' %(current_player, update_word)
print 'player %d wins' %((current_player+1)%2)
break
if current_player >= 2:
current_player = (current_player+1)%2
else:
current_player += 1
def update_fragment(letter):
word.append(letter)
return ''.join(word)
def display_fragment(update_word):
print 'current word fragment is:', update_word
def is_valid_letter(letter):
return letter in string.ascii_letters
def is_valid_word(update_word,word_list):
for word in word_list:
if update_word == word.lower()[0:len(update_word)]:
return True
return False
def is_complete_word(fragment,word_list):
return fragment in word_list
if __name__ == '__main__':
word_list = load_words()
play_ghost(word_list)
<file_sep># Name:
# Section:
# nims.py
def play_nims(pile, max_stones):
'''
An interactive two-person game; also known as Stones.
@param pile: the number of stones in the pile to start
@param max_stones: the maximum number of stones you can take on one turn
'''
## Basic structure of program (feel free to alter as you please):
# while [pile is not empty]:
# while [player 1's answer is not valid]:
# [ask player 1]
# [execute player 1's move]
#
# while [player 2's answer is not valid]:
# [ask player 2]
# [execute player 2's move]
#
# print "Game over"
is_input_valid = False
current_player = 0 #keep track of current player
#current_player % 2 == 0 player1
#current_player % 2 == 1 player2
#if there are 4 players, %4
while pile > 0:
is_input_valid = False
while is_input_valid == False:
take_stones = raw_input("enter the number(must 1 to max_stones inclusive) of stones you want to take:")
if not take_stones.isdigit():
continue
if int(take_stones) >= 1 and int(take_stones) <= max_stones and int(take_stones) <= pile:
current_player += 1
is_input_valid = True
pile -= int(take_stones)
#print 'pile is', pile,'current_player is', current_player%2
if pile == 0:
print 'the winner is'
print current_player
if current_player % 2 == 1:
print 'player1'
else:
print 'player2'
play_nims(5,2)
<file_sep># Name:
# Section:
# hw3.py
##### Template for Homework 3, exercises 3.1 - ######
# ********** Exercise 3.1 **********
# Define your function here
##### YOUR CODE HERE #####
def list_intersection(list1,list2):
list_inter = []
for i in list1:
if i in list2:
list_inter.append(i)
return list_inter
# Test Cases for Exercise 3.1
##### YOUR CODE HERE #####
print list_intersection([1,3,5],[5,3,1])
print list_intersection([1,3,6,9],[10,14,3,72,9])
print list_intersection([2,3],[3,3,3,2,10])
print list_intersection([2,4,6],[1,3,5])
print '---------'
# ********** Exercise 3.2 **********
# Define your function here
import math
def ball_collide(ball1, ball2):
##### YOUR CODE HERE #####
distance = math.sqrt(math.pow(ball1[0] - ball2[0],2)+ math.pow(ball1[1] - ball2[1],2))
if distance < ball1[2] + ball2[2]:
return False
else:
return True
# Test Cases for Exercise 3.2
print ball_collide((0, 0, 1), (3, 3, 1)) # Should be False
print ball_collide((5, 5, 2), (2, 8, 3)) # Should be True
print ball_collide((7, 8, 2), (4, 4, 3)) # Should be True
print '--------'
# ********** Exercise 3.3 **********
# Define your dictionary here - populate with classes from last term
my_classes = {}
def add_class(class_num, desc):
##### YOUR CODE HERE #####
my_classes[class_num] = desc
return my_classes
# Here, use add_class to add the classes you're taking next term
add_class('6.189', 'Introduction to Python')
add_class('6.01','Introduction to EECS')
def print_classes(course):
##### YOUR CODE HERE #####
for key in my_classes.keys():
if key[0][0] != course:
print 'no course'
break
else:
print key,'-', my_classes[key]
# Test Cases for Exercise 3.3
##### YOUR CODE HERE #####
print_classes('6')
print_classes('9')
# ********** Exercise 3.4 **********
print '-----3.4------'
NAMES = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank',
'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
# Define your functions here
def combine_lists(l1, l2):
comb_dict = {}
##### YOUR CODE HERE #####
for i in range(0,len(NAMES)):
comb_dict[NAMES[i]] = AGES[i]
return comb_dict
combined_dict = combine_lists(NAMES, AGES) # Finish this line...
def people(age):
# Use combined_dict within this function...
same_age = []
for key in combined_dict.keys():
if age == combined_dict[key]:
same_age.append(key)
return same_age
# Test Cases for Exercise 3.4 (all should be True)
print 'Dan' in people(18) and 'Cathy' in people(18)
print 'Ed' in people(19) and 'Helen' in people(19) and\
'Irene' in people(19) and 'Jack' in people(19) and 'Larry'in people(19)
print 'Alice' in people(20) and 'Frank' in people(20) and 'Gary' in people(20)
print people(21) == ['Bob']
print people(22) == ['Kelly']
print people(23) == []
# ********** Exercise 3.5 **********
print '---3.5'
def zellers(month, day, year):
##### YOUR CODE HERE #####
return "Not Yet Implemented"
# Test Cases for Exercise 3.5
print zellers("March", 10, 1940) == "Sunday" # This should be True
##### YOUR CODE HERE #####<file_sep>with open('input_text.txt','r') as txt:
for line in txt:
print line
for line in open('input_text.txt','r'):
print line[0]
f = open('input_text.txt','r')
for line in f:
print line[0]
f.close()
for i in range(10):
print i,
print >> f, 'hello world'<file_sep>new_tuple = (5,6,7,8)
print "new_tupe is:", new_tuple
print "new_tupe[2] is:", new_tuple[2]
for item in new_tuple:
print item
print "Tuple length is:", len(new_tuple)
for index in range(len(new_tuple)):
print "index is:", index
print "value at that index is:", new_tuple[index]
(a,b,c,d) = new_tuple
print "a is:", a
print "b is:", b
print "c is:", c
print "d is:", d
b = 77
new_tuple =(a,b,c,d)
print "new_tupe is now:", new_tuple<file_sep># # Name:
# # Section:
# # strings_and_lists.py
#
# # ********** Exercise 2.7 **********
#
# def sum_all(number_list):
# # number_list is a list of numbers
# total = 0
# for num in number_list:
# total += num
#
# return total
#
# # Test cases
# print "sum_all of [4, 3, 6] is:", sum_all([4, 3, 6])
# print "sum_all of [1, 2, 3, 4] is:", sum_all([1, 2, 3, 4])
#
#
# def cumulative_sum(number_list):
# # number_list is a list of numbers
#
# ##### YOUR CODE HERE #####
# for i in range(1,len(number_list)):
# number_list[i] += number_list[i-1]
#
# return number_list
#
# # Test Cases
# ##### YOUR CODE HERE #####
# print "cumulative sum of [4,3,6] is:",cumulative_sum([4,3,6])
# print "cumulative sum of [1,2,3,4] is:",cumulative_sum([1,2,3,4])
#
#
# # ********** Exercise 2.8 **********
#
# def report_card():
# ##### YOUR CODE HERE #####
# i = 0
# classes = int(raw_input("How many classes did you take"))
# my_list = []
#
#
# while i < classes:
# elt = {'name':None,'grade':0};
# name = raw_input("what was the name of this class?")
# grade = int(raw_input("what was your grade"))
# elt['name'] = name
# elt['grade'] = grade
# my_list.append(elt)
# i += 1
#
#
# print "report card:"
# total = 0
# for elt in my_list:
# print elt['name'],elt['grade']
# total += elt['grade']
# print "overall gpa", total/len(my_list)
#
#
# # Test Cases
# ## In comments, show the output of one run of your function.
# report_card()
# # ********** Exercise 2.9 **********
#
# # Write any helper functions you need here.
#
# VOWELS = ['a', 'e', 'i', 'o', 'u']
#
# def pig_latin(word):
# # word is a string to convert to pig-latin
# if word[0] in VOWELS:
# word = word + 'hay'
# else:
# word = word[1:]+word[0]+'ay'
# ##### YOUR CODE HERE #####
# return word
#
# # Test Cases
# ##### YOUR CODE HERE #####
# print pig_latin('boot')
# print pig_latin('image')
# ********** Exercise 2.10 **********
# Test Cases
##### YOUR CODE HERE #####
S = [x**3 for x in range(10)]
print S
V = []
print V
def returnAllVowels(str):
vowel_elements = ['a','e','i','o','u']
vowels = [x for x in str if x in vowel_elements]
return vowels
print returnAllVowels("this is cool")
T = [x+y for x in [10,20,30] for y in [1,2,3]]
print T
# ********** Exercise OPT.1 **********
# If you do any work for this problem, submit it here
VOWELS = ['a', 'e', 'i', 'o', 'u']
def pig_latin(word):
# word is a string to convert to pig-latin
if word[0] in VOWELS:
word = word + 'hay'
else:
word = word[1:]+word[0]+'ay'
return word
def translate(sentence):
newSentence = ''
word_list = sentence.split()
for word in word_list:
newSentence += pig_latin(word)
return newSentence
print translate('boot image')
#ootbay
#imagehay
<file_sep>new_string = "hi class"
for letter in new_string:
print letter
s1 = "hi"
s2 = "class"
print s1 + s2
print s1, s2
print s1, 5.23,s2
print "new_string[0] is", new_string[0]
print "new_string[0:3] is", new_string[0:3]
print "len(new_string) is:", len(new_string)
print "new_string.upper()", new_string.upper()
print "new_string.lower()", new_string.lower()
<file_sep>new_list = [3,4,5,6]
print "new list is:", new_list
print "new_list[2] is:", new_list[2]
print "new_list[0:2] is:", new_list[0:2]
for item in new_list:
print item
new_list[2] = 100
print "new_list is:", new_list
new_list.append(87)
print "new_list is:", new_list
new_list.insert(0,200)
print "new_list is:", new_list
<file_sep># Name:
# Section:
# Date:
# hw1.py
##### Template for Homework 1, exercises 1.2-1.5 ######
print "********** Exercise 1.2 **********"
# Do your work for Exercise 1.2 here
print " | | "
print "--------"
print " | | "
print "--------"
print " | | "
#print "Not implemented" # Delete this line when you write your code!
print "********** Exercise 1.3 **********"
# Do your work for Excercise 1.3 here. Hint - how many different
# variables will you need?
var1 = " | | "
var2 = "--------"
for i in range(0,2):
print var1
print var2
print var1
print "********** Exercise 1.4 **********"
print "********* Part II *************"
print 3*5/(2+3)
print ((7+9)**(1/2.0))*2
print (4-7)**3
print ((-19)+100)**(1/4.0)
print 6%4
print "********* Part III *************"
print "********** Exercise 1.5 **********"
#print "Not implemented" # Delete this line when you write your code!
first_name = raw_input("enter your first name:")
last_name = raw_input("enter your last name:")
print("enter your birth date:")
month = raw_input("month?")
day = raw_input("day?")
year = raw_input("year?")
print first_name,last_name,"was born on", month, day, year
print "********** Exercise 1.7 **********"
print "********** Exercise 1.8 **********"
print "********** Exercise op1 **********"
print "********** Exercise op2 **********"<file_sep>hello_world = "hello world"
letter_count = 0
for letter in hello_world:
print "letter number", letter_count, "is",letter
letter_count = letter_count +1
print 'there are',letter_count, "letters in the string", hello_world
for num in range(10):
print num
for num in range(7,15):
print num
count = 1
print "count is inintially", count
while count < 100:
count = count * 9
print "now count is", count
print count<file_sep>class Node:
def __init__(self,cargo=None,next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
node = Node('test')
print node
node1 = Node(1)
print node1
node2 = Node(2)
print node2
node3 = Node(3)
print node3
node1.next = node2
node2.next = node3
node3.next = None
print node1.next
print '------'
def printBackward(list):
if list == None:
return
head = list
tail = list.next
printBackward(tail)
print head,
printBackward(node1)<file_sep>x = None
while not x:
try:
x = int(raw_input())
except:
print 'Invalid number'
<file_sep>#enciper
phrase = raw_input("enter sentence to encrypt:")
shift = raw_input("enter shift value:")
encoded_phrase = ''
#'A' Asc is 65, 'a' Asc is 97
for c in phrase:
asc_code = ord(c)
if asc_code >= 97 and asc_code < 97+26:
encoded_phrase += chr((asc_code+4-97)%26+97)
elif asc_code >= 65 and asc_code < 65+26 :
encoded_phrase += chr((asc_code+4-65)%26+65)
else:
encoded_phrase += c
print encoded_phrase
<file_sep>from graphics import *
import random
## Written by <NAME> & <NAME>, August 2010
## Revised January 2011
############################################################
# GLOBAL VARIABLES
############################################################
BLOCK_SIZE = 40
BLOCK_OUTLINE_WIDTH = 2
BOARD_WIDTH = 12
BOARD_HEIGHT = 12
neighbor_test_blocklist = [(0,0), (1,1)]
toad_blocklist = [(4,4), (3,5), (3,6), (5,7), (6,5), (6,6)]
beacon_blocklist = [(2,3), (2,4), (3,3), (3,4), (4,5), (4,6), (5,5), (5,6)]
glider_blocklist = [(1,2), (2,3), (3,1), (3,2), (3,3)]
pulsar_blocklist = [(2,4), (2,5), (2,6), (4,2), (4,7), (5,2), (5,7),
(6,2), (6,7), (7,4), (7,5), (7,6), ]
# for diehard, make board at least 25x25, might need to change block size
diehard_blocklist = [(5,7), (6,7), (6,8), (10,8), (11,8), (12,8), (11,6)]
############################################################
# TEST CODE (don't worry about understanding this section)
############################################################
def test_neighbors(board):
'''
Code to test the board.get_block_neighbor function
'''
for block in board.block_list.values():
neighbors = board.get_block_neighbors(block)
ncoords = [neighbor.get_coords() for neighbor in neighbors]
if block.get_coords() == (0,0):
zeroneighs = [(0,1), (1,1), (1,0)]
for n in ncoords:
if n not in zeroneighs:
print "Testing block at (0,0)"
print "Got", ncoords
print "Expected", zeroneighs
return False
for neighbor in neighbors:
if neighbor.get_coords() == (1, 1):
if neighbor.is_live() == False:
print "Testing block at (0, 0)..."
print "My neighbor at (1, 1) should be live; it is not."
print "Did you return my actual neighbors, or create new copies of them?"
print "FAIL: get_block_neighbors() should NOT return new Blocks!"
return False
elif block.get_coords() == (1,1):
oneneighs = [(0,0), (0,1), (0,2), (1,0), (1,2), (2,0), (2,1),(2,2)]
for n in ncoords:
if n not in oneneighs:
print "Testing block at (1,1)"
print "Got", ncoords
print "Expected", oneneighs
return False
for n in oneneighs:
if n not in ncoords:
print "Testing block at (1,1)"
print "Got", ncoords
print "Expected", oneneighs
return False
print "Passed neighbor test"
return True
############################################################
# BLOCK CLASS (Read through and understand this part!)
############################################################
class Block(Rectangle):
''' Block class:
Implement a block for a tetris piece
Attributes: x - type: int
y - type: int
specify the position on the board
in terms of the square grid
'''
def __init__(self, pos, color):
'''
pos: a Point object specifing the (x, y) square of the Block (NOT in pixels!)
color: a string specifing the color of the block (eg 'blue' or 'purple')
'''
self.x = pos.x
self.y = pos.y
p1 = Point(pos.x*BLOCK_SIZE,
pos.y*BLOCK_SIZE)
p2 = Point(p1.x + BLOCK_SIZE, p1.y + BLOCK_SIZE)
Rectangle.__init__(self, p1, p2)
self.setWidth(BLOCK_OUTLINE_WIDTH)
self.setFill(color)
self.status = 'dead'
self.new_status = 'None'
def get_coords(self):
return (self.x, self.y)
def set_live(self, canvas):
'''
Sets the block status to 'live' and draws it on the grid.
Be sure to do this on the canvas!
'''
if self.status=='dead':
self.status = 'live'
self.draw(canvas)
def set_dead(self):
'''
Sets the block status to 'dead' and undraws it from the grid.
'''
if self.status=='live':
self.status = 'dead'
self.undraw()
def is_live(self):
'''
Returns True if the block is currently 'live'. Returns False otherwise.
'''
if self.status == 'live':
return True
return False
def reset_status(self, canvas):
'''
Sets the new_status to be the current status
'''
if self.new_status=='dead':
self.set_dead()
elif self.new_status=='live':
self.set_live(canvas)
###########################################################
# BOARD CLASS (Read through and understand this part!)
# Print out and turn in this section.
# Name:
# Recitation:
###########################################################
class Board(object):
''' Board class: it represents the Game of Life board
Attributes: width - type:int - width of the board in squares
height - type:int - height of the board in squares
canvas - type:CanvasFrame - where the blocks will be drawn
block_list - type:Dictionary - stores the blocks for a given position
'''
def __init__(self, win, width, height):
self.width = width
self.height = height
self.win = win
# self.delay is the number of ms between each simulation. Change to be
# shorter or longer if you wish!
self.delay = 1000
# create a canvas to draw the blocks on
self.canvas = CanvasFrame(win, self.width * BLOCK_SIZE,
self.height * BLOCK_SIZE)
self.canvas.setBackground('white')
# initialize grid lines
for x in range(1,self.width):
self.draw_gridline(Point(x, 0), Point(x, self.height))
for y in range(1,self.height):
self.draw_gridline(Point(0, y), Point(self.width, y))
# For each square on the board, we need to initialize
# a block and store that block in a data structure. A
# dictionary (self.block_list) that has key:value pairs of
# (x,y):Block will be useful here.
self.block_list = {}
####### YOUR CODE HERE ######
raise Exception("__init__ not implemented")
def draw_gridline(self, startp, endp):
''' Parameters: startp - a Point of where to start the gridline
endp - a Point of where to end the gridline
Draws two straight 1 pixel lines next to each other, to create
a nice looking grid on the canvas.
'''
line = Line(Point(startp.x*BLOCK_SIZE, startp.y*BLOCK_SIZE), \
Point(endp.x*BLOCK_SIZE, endp.y*BLOCK_SIZE))
line.draw(self.canvas)
line = Line(Point(startp.x*BLOCK_SIZE-1, startp.y*BLOCK_SIZE-1), \
Point(endp.x*BLOCK_SIZE-1, endp.y*BLOCK_SIZE-1))
line.draw(self.canvas)
def random_seed(self, percentage):
''' Parameters: percentage - a number between 0 and 1 representing the
percentage of the board to be filled with
blocks
This method activates the specified percentage of blocks randomly.
'''
for block in self.block_list.values():
if random.random() < percentage:
block.set_live(self.canvas)
def seed(self, block_coords):
'''
Seeds the board with a certain configuration.
Takes in a list of (x, y) tuples representing block coordinates,
and activates the blocks corresponding to those coordinates.
'''
#### YOUR CODE HERE #####
raise Exception("seed not implemented")
def get_block_neighbors(self, block):
'''
Given a Block object, returns a list of neighboring blocks.
Should not return itself in the list.
'''
#### YOUR CODE HERE #####
#### Think about edge conditions!
raise Exception("get_block_neighbors not implemented")
def simulate(self):
'''
Executes one turn of Conways Game of Life using the rules
listed in the handout. Best approached in a two-step strategy:
1. Calculate the new_status of each block by looking at the
status of its neighbors.
2. Set blocks to 'live' if their new_status is 'live' and their
status is 'dead'. Similarly, set blocks to 'dead' if their
new_status is 'dead' and their status is 'live'. Then, remember
to call reset_status(self.canvas) on each block.
'''
#### YOUR CODE HERE #####
raise Exception("simulate not implemented")
def animate(self):
'''
Animates the Game of Life, calling "simulate"
once every second
'''
self.simulate()
self.win.after(self.delay, self.animate)
################################################################
# RUNNING THE SIMULATION
################################################################
if __name__ == '__main__':
# Initalize board
win = Window("Conway's Game of Life")
board = Board(win, BOARD_WIDTH, BOARD_HEIGHT)
## PART 1: Make sure that the board __init__ method works
board.random_seed(.15)
## PART 2: Make sure board.seed works. Comment random_seed above and uncomment
## one of the seed methods below
# board.seed(toad_blocklist)
## PART 3: Test that neighbors work by commenting the above and uncommenting
## the following two lines:
# board.seed(neighbor_test_blocklist)
# test_neighbors(board)
## PART 4: Test that simulate() works by uncommenting the next two lines:
# board.seed(toad_blocklist)
# win.after(2000, board.simulate)
## PART 5: Try animating! Comment out win.after(2000, board.simulate) above, and
## uncomment win.after below.
# win.after(2000, board.animate)
## Yay, you're done! Try seeding with different blocklists (a few are provided at the top of this file!)
win.mainloop()
<file_sep>VOWELS = ['a', 'e', 'i', 'o', 'u']
def pig_latin(word):
# word is a string to convert to pig-latin
if word[0] in VOWELS:
word = word + 'hay'
else:
word = word[1:]+word[0]+'ay'
##### YOUR CODE HERE #####
return word
# Test Cases
##### YOUR CODE HERE #####
print pig_latin('boot')
print pig_latin('image')
<file_sep>def is_a_vowel(c):
if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c =='u':
return True
elif c=='A'or c=='E' or c =='I' or c== 'O' or c == 'U':
return True
else:
return False
print is_a_vowel("u")
print is_a_vowel("E")
def only_vowels(phrase):
vowel_string = ''
for letter in phrase:
if is_a_vowel(letter):
vowel_string += letter
return vowel_string
print "a line of code after the return"
print "the vowels in the phrase 'tim the beaver' are:", only_vowels("tim the beaver")
print only_vowels("hello world")
print only_vowels("klxn")<file_sep>def is_a_party(apples, pizzas):
if apples > 10 and pizzas > 10:
return True
else:
return False
def throw_party():
num_apples = input("How many apples do you have:")
num_pizzas = input("How many pizzas do you have")
if is_a_party(num_apples, num_pizzas):
return "let 's party down"
else:
return "you should go to store first"
##test
print is_a_party(20,20)
print is_a_party(5,15)
print is_a_party(5,2)
print is_a_party(4,8)
print throw_party()<file_sep>first_name = raw_input("enter your first name:")
last_name = raw_input("enter your last name:")
print("enter your birth date:")
month = raw_input("month?")
day = raw_input("day?")
year = raw_input("year?")
print first_name,last_name,"was born on", month, day, year
#compute the day of the week of birthday
#A: the month of year, March-1,,,Dec-10,
# Jan and Feb being counted as 11 and 12
# but should minus 1. If month is Jan or Feb
# then the preceding year is used for computation.
#B: the day of the month(1,2,,,31)
#C: the year of the century(c = 89 for the year 1989)
#D: the century(D = 19 for the year 1989)
#Computation:
# W = (13 * A-1)/5
# X = C/4
# Y = D/4
# Z = W+X+Y+B+C-2*D
# R = the remainder when Z is divided by 7
# R is the day of the week.0 is Sun,1 is Sat.
# if R is negative, add 7 to get positive number.
#http://www.timeanddate.com/calendar/
if month == 'March':
A = 1
elif month == 'April':
A = 2
elif month == 'May':
A = 3
elif month == "June":
A = 4
elif month == "July":
A = 5
elif month == "Augest":
A = 6
elif month == "September":
A = 7
elif month == "October":
A = 8
elif month == "November":
A = 9
elif month == "December":
A = 10
elif month == "January":
A = 10
elif month == "February":
A = 11
else:
print "enter a valid month"
W = (13 * A-1)/5
B = int(day)
C = int(year[2:4])
X = C / 4
D = int(year[0:2])
Y = D / 4
Z = W+X+Y+B+C-2*D
R = Z%7
print R
<file_sep>base = 10
exp = 4
def hello_world():
base = 20
print "inside of helloworld base is",base
return "hello world"
print hello_world()
print "outside of hello world base is", base
def ret_5():
print 5
print ret_5()
def compute_exp(base, exp):
print "inside of function, base is", base
print "inside of function, exp is",exp
return base**exp
print "outside of function, base is", base
print "outside of function, ep is:", exp
print compute_exp(5,0)
print compute_exp(5,3)
print compute_exp(8,2)
|
53e50860646e9c8069f383cf93b09911e5606eb4
|
[
"Python"
] | 27 |
Python
|
kunxue/python_exercises
|
e6f3c41c4e18f330062ddb541e6fbf1badd7cd6c
|
197c0f0619d147f0effac3f785c4bd2e07553c19
|
refs/heads/master
|
<file_sep># Svelte Template
- Jest
- TypeScript
- Scss
- Storybook
- Prettier
## Setup
```bash
yarn install
```
## Run
```bash
yarn run dev
```
## Format
```bash
yarn run format
```
## Storybook
```bash
yarn run Storybook
```
<file_sep>export { Home } from './Home'
export { NotFound } from './NotFound'
|
dc7c136ededed39ec3b966d14bd87c5e13c0b638
|
[
"Markdown",
"TypeScript"
] | 2 |
Markdown
|
MathyouMB/svelte-template
|
e867f09c45f5a6f8f6904438aceea6c50407a0bf
|
b67eb8709136af627bd9fe1cb7dd4ba446ef8cef
|
refs/heads/master
|
<file_sep><?php
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
$pid=$_POST['pid'];
$pname=$_POST['pname'];
$catid=$_POST['catid'];
$proddescr1=$_POST['proddescr'];
$imgpath=$_POST['imgpath'];
$produrl=$_POST['produrl'];
//$imagepath=substr($imgpath, strpos($imgpath,'images'), strpos($imgpath, '@') - strlen($imgpath));
$imagepath="images/"."$imgpath";
$sql="UPDATE PRODUCTS SET pname='$pname',catid='$catid',IMGPATH='$imagepath',pdescr='$proddescr1' URLDETAILS='$produrl' WHERE pid='$pid'";
$retval = mysqli_query($conn, $sql);
if(!$retval) {
echo($imgpath);echo("<\br>");
echo($imagepath);echo("<\br>");
echo($proddescr1);echo("<\br>");
echo(mysqli_error($conn));
die("Failed to insert record");
}
mysqli_close($conn);
?><file_sep><!-- CategoryModel.php -->
<?php
require 'Category.php';
/*
connect to DB
select * from categories
store each category record in one Category class object
store all the objects in array $catList
store the array in session using name "categories
*/
$dbhost = "localhost:3306";
$dbuser = "ecomm1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "ecomm");
if(!$conn ) {
die('Could not connect: ');
} else {
echo 'Connected successfully<br/>';
}
// create one list to store catList
$catList=array();
$idx=0;
// fetch records from categories table
$sql="SELECT * FROM categories";
$retval = mysqli_query($conn, $sql);
if(!$retval) {
die("Failed to fetch record");
} else {
// if records are there
while($row=mysqli_fetch_array($retval, MYSQLI_NUM)) {
// store each record in one Category class object
$cat=new Category($row[0], $row[1]);
// store each object into list
$catList[$idx++]=$cat;
}
// $_SESSION['categories']=serialize($catList);
$_SESSION['categories']=$catList;
$_SESSION['records_count']=$idx;
}
mysqli_free_result($retval);
mysqli_close($conn);
?>
<file_sep><!-- Products.php -->
<?php
$productslst=NULL;
require './Category.php';
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
//$catid=$_POST['catid'];
$count=1;
$nocolumns=8;
$colwidth=floor(12/$nocolumns);
if($colwidth<0)
{
// die("column width is 1");
$colwidth=1;
}
$output=NULL;
$searchterm=$_GET['SearchTerm'];
//die($searchterm);
$searchterm1=$searchterm;
$index=0;
$matchedproducts=array();
//$matchedproducts[0]=1;
$sql2="SELECT * FROM PRODUCTS";
$retval2=mysqli_query($conn, $sql2);
if(!$retval2) {
echo(mysqli_error($conn));
die("Failed to fetch rows");
}
while($row2=mysqli_fetch_array($retval2, MYSQLI_NUM))
{
$filcont=@file_get_contents($row2[6]);
if(!($searchterm==""))
if(stripos($filcont,$searchterm)!=false)
{
// die("file contains:".$filcont." searchterm:".$searchterm);
$matchedproducts[$index++]=$row2[0];
// $sql4="SELECT * FROM PRODUCTS WHERE pid=".$row2[0];
// $retval4=mysqli_query($conn, $sql2);
// $row5=mysqli_fetch_array($retval, MYSQLI_NUM);
}
}
//die("(" . implode(',', $matchedproducts) . ")");
if(!empty($matchedproducts))
$sql="SELECT * FROM products WHERE pdescr LIKE "."'%$searchterm%'" ." OR pname LIKE "."'%$searchterm%'"." OR pid IN (" . implode(',', $matchedproducts) . ")" ;
else
$sql="SELECT * FROM products WHERE pdescr LIKE "."'%$searchterm%'" ." OR pname LIKE "."'%$searchterm%'";
//die($sql);
$retval = mysqli_query($conn, $sql);
if(!$retval) {
echo(mysqli_error($conn));
echo("searchterm=".$searchterm);
echo(" ");
echo($sql);
die("Failed to fetch rows");
}
//die("row count=".mysqli_num_rows($retval2));
//die("no rows found:".mysqli_num_rows($retval));
// if records are there
$output=$output."<div class='container'>";
while($row=mysqli_fetch_array($retval, MYSQLI_NUM)) {
//$productslst.=$row[0]." ".$row[1]." ".$row[2]." ".$row[3]." ".$row[4]."<br/>";
//echo $productslst;
//echo $row[0]." ".$row[1]." ".$row[2]." ".$row[3]." ".$row[4]."<br/>";
if($count == 1)
{
$output=$output."<div class='row'>";
}
//echo "<img src='$row[5]'> <a href='$row[6]'>$row[1]</a></img>" ;
//echo "<div class='container1'><img src='$row[5]'><div class='overlay'> <a href='$row[6]'>$row[1]</a></div></div>" ;
//echo "<div class='container1'><img src='$row[5]'><div class='overlay'> <a href='$row[6]'>$row[1]</a></div></div>" ;
//echo "<img src='$row[5]'><div class='overlay'> <a href='$row[6]'>$row[1]</a></div>" ;
$output=$output."<div width=floor(700/$nocolumns) class='col-sm-"."$colwidth' >";
//$output=$output."<div width=floor(700/$nocolumns) class='col' >";
//$output=$output."<div width=floor(450/$nocolumns) >";
//$output=$output."<a href='$row[6]'><img src='$row[5]' class='image1 img-responsive' width=100 height=100><a href='$row[6]'><p //class='imagetext'> $row[1]</p></a></a>" ;
//die("colwidth:".$colwidth);
$imgwidth=floor(450/$nocolumns);
//die("image width is $imgwidth");
$output=$output."<div class='image1div'><a href='$row[6]'><img src='$row[5]' class='image1 imageclass$colwidth' width=$imgwidth ></br><span class='imagetext'> $row[1]</span></a></div>" ;
//die("style='width:$imgwidth px;height:$imgwidth px;");
$output=$output."</div>";
if($count ==1)
{
}
$count ++;
if($count ==($nocolumns+1))
{
$output=$output."</div>";
$count =1;
}
}
// die("row count is ".$count);
$output=$output."</div>";
//echo $productslst;
mysqli_free_result($retval);
// mysqli_free_result($retval);
mysqli_close($conn);
// $output="<!--".$output;
// $output=$output."-->";
echo $output;
?>
<file_sep><html>
<head>
<title>Add product page</title>
</head>
<body>
<form method="post" action ="addproduct.php">
Choose Prod Id<input type ="text" name="pid"> </input>
Choose Prod name<input type ="text" name="prodname"> </input>
Choose prodimage <input type="file" name="imgpath" > </input>
Product descriptiom<textarea name="proddescr"></textarea>
Page url<input type="text" name ="pageurl" ></input>
<input type="Submit" name="submit" value="submit">
</form>
</body>
</html><file_sep><?php
class Category {
private $catid;
private $catname;
public function __construct($catid, $catname){
$this->catid=$catid;
$this->catname=$catname;
}
public function setCatid($catid) {
$this->catid=$catid;
}
public function setCatname($catname) {
$this->catname=$catname;
}
public function getCatid() {
return $catid;
}
public function getCatname() {
return $catname;
}
}
?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 10, 2019 at 01:07 PM
-- Server version: 10.1.37-MariaDB
-- PHP Version: 7.2.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `actecomm1`
--
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`catid` int(11) NOT NULL,
`catname` varchar(20) DEFAULT NULL,
`hassubcat` enum('true','false') DEFAULT 'false',
`hasparentcat` enum('true','false') DEFAULT 'false'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`catid`, `catname`, `hassubcat`, `hasparentcat`) VALUES
(1, 'Perfumes', 'false', 'false'),
(2, 'Books', 'false', 'false'),
(3, 'Shoes', 'false', 'false'),
(4, 'Mobiles', 'false', 'false'),
(5, 'consumerelectronics', 'true', 'false'),
(6, 'clothing', 'false', 'false'),
(7, 'audio', 'false', 'true'),
(30, 'mp3players', 'false', 'true');
-- --------------------------------------------------------
--
-- Table structure for table `catmap`
--
CREATE TABLE `catmap` (
`parentcatid` int(11) DEFAULT NULL,
`childcatid` int(11) DEFAULT NULL,
`parentcatname` varchar(20) DEFAULT NULL,
`childcatname` varchar(20) DEFAULT NULL,
`rowindex` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `catmap`
--
INSERT INTO `catmap` (`parentcatid`, `childcatid`, `parentcatname`, `childcatname`, `rowindex`) VALUES
(5, 7, 'consumerelectronics', 'audio', 1),
(5, 8, 'consumerelectronics', 'video', 2),
(5, 30, 'consumerelectronics', 'mp3players', 3);
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`pid` int(11) NOT NULL,
`pname` varchar(20) DEFAULT NULL,
`price` double DEFAULT NULL,
`pdescr` varchar(50) DEFAULT NULL,
`catid` int(11) DEFAULT NULL,
`IMGPATH` varchar(100) DEFAULT NULL,
`URLDETAILS` varchar(200) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`pid`, `pname`, `price`, `pdescr`, `catid`, `IMGPATH`, `URLDETAILS`) VALUES
(1, 'Brut', 150, 'Good', 1, 'images/FOGG1.png', 'produrls/fogg1.html'),
(2, 'Java Axe', 150, 'Good', 1, 'images/FOGG1.png', '#'),
(3, 'Davidoff', 150, 'Good', 1, 'images/FOGG1.png', '#'),
(4, 'Figaro', 150, 'Good', 1, 'images/FOGG1.png', '#'),
(5, 'Learning CSS', 200, 'Good', 2, 'images/books1.jpg', '#'),
(6, 'Learning jQuery', 200, 'Good', 2, 'images/books1.jpg', '#'),
(7, 'Learning Bootstrap', 200, 'Good', 2, 'images/books1.jpg', '#'),
(8, 'Learning CSS', 200, 'Good', 2, 'images/books1.jpg', '#'),
(9, 'Fogg1', NULL, 'Fogg1', 1, 'images/FOGG1.png', '#'),
(10, 'Euphoria1', NULL, 'Euphoria1', 1, 'images/Euphoria1.jpg', '#'),
(11, 'Eternity1', NULL, 'Eternity1', 1, 'images/Eternity1.jpg', '#'),
(12, 'Wildstone1', NULL, 'Wildstone1', 1, 'images/wildstone1.png', 'produrls/wildstone1.html'),
(13, 'fogg2', NULL, 'perfume', 1, 'images/FOGG1.png', 'produrls/fogg2.html'),
(14, 'wildstone1', NULL, 'wild stone 2\r\nprice:10$;\r\nxyz', 1, 'images/WILDSTONE2.png', 'produrls/wildstone2.html'),
(16, 'sonyled1', NULL, 'Resolution: HD Ready (1366x768p) | Refresh Rate: 5', 7, 'images/sonyled2.jpg', '#'),
(17, 'samsungled1', NULL, 'Resolution: HD Ready (1366x768p)\r\n Display: Story ', 7, 'images/samsungtel1.jpg', '#'),
(18, 'sonyled2', NULL, 'sony led 2', 7, 'images/sonyled2.jpg', 'produrls/sonyled2.html'),
(19, 'sony led tv 3', NULL, 'sony led tv 3\r\nfeature 1\r\nfeature 2:\r\nfeature 3:', 7, 'images/sonytel1.jpg', 'produrls/sony led tv 3.html'),
(20, 'sony led tv4', NULL, 'description', 7, 'images/sonytel1.jpg', 'produrls/sony led tv4.html'),
(23, 'sony led tv7', NULL, 'description 1', 7, 'images/sonytel1.jpg', 'produrls/sony led tv7.html'),
(27, 'sony led tv10', NULL, 'description 1', 7, 'images/sonytel1.jpg', 'produrls/sony led tv10.html'),
(28, 'sony led tv11', NULL, 'sony led tv 11\r\n\r\nfeature 1 \r\nfeature 2', 7, 'images/sonytel1.jpg', 'produrls/sony led tv11.html'),
(40, 'philipsmp3player1', NULL, 'feature 1 \r\nfeature 2', 30, 'images/philipsmp31.jpg', 'produrls/philipsmp3player1.html'),
(41, 'irulump31', NULL, 'iRULU F20 HiFi Lossless Mp3 Player with Bluetooth:', 30, 'images/irulump31.jpg', 'produrls/irulump31.html'),
(42, 'crispystylemp3_1', NULL, 'Hands-free portability & Clip up design\r\nSupports ', 30, 'images/crispystyl1.jpg', 'produrls/crispstylemp3player1.html'),
(43, 'leoiemp3_1', NULL, 'You can enjoy music by pairing with your Bluetooth', 30, 'images/leoiemp31.jpg', 'produrls/leoiemp3__1.html');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`username` varchar(10) DEFAULT NULL,
`pass` varchar(10) DEFAULT NULL,
`role` varchar(10) DEFAULT 'normal'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`username`, `pass`, `role`) VALUES
('ramesh', 'ramesh', 'admin'),
('surya', 'surya', 'normal');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`catid`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`pid`),
ADD KEY `product_catid_fk` (`catid`);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `products`
--
ALTER TABLE `products`
ADD CONSTRAINT `product_catid_fk` FOREIGN KEY (`catid`) REFERENCES `categories` (`catid`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><!-- CategoriesView.php -->
<?php
require './Category.php';
$catList=unserialize("", (array)$_SESSION['categories']);
// $catList=(array)$_SESSION['categories'];
echo gettype($catList)."<br/>";
echo $catList."<br/>";
$cat=$catList[0];
echo gettype($cat)."<br/>";
echo (array)$cat."<br/>";
$c=(array)$cat;
echo $c[0];
// echo $cat->getCatid()." ".$cat->getCatname();
// echo $cat->getCatname();
echo $_SESSION['records_count'];
?>
<file_sep><img src='../images/lenovo1.png'><div><p>
Processor: AMD E2-9000 processor
Operating System: Pre-loaded Windows 10 Home with lifetime validity
Display: 14-inch HD (1366x786) Laptop | Antiglare display
Memory & Storage: 4GB DDR4 RAM with Integrated Graphics |Storage: 500GB HDD
Design & battery: Laptop weight 2.1kg | Battery Life: Upto 5 hours
Warranty: This genuine Lenovo laptop comes with 1 year domestic warranty from Lenovo covering manufacturing defects and not covering physical damage. For more details, see Warranty section below.
Pre-installed Software: Windows 10 Home | In the Box: Laptop included with battery and charger, user guide
</p></div><form method='GET' action='addtocart.php?pid=44' >Quantity<input type='text' name='quantity' ></input><input type='submit' name='addtocart' value='add to cart'></input></form><file_sep><!-- Categories.php -->
<?php
require './Category.php';
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
$sql="SELECT * FROM categories WHERE hasparentcat='false'";
$retval = mysqli_query($conn, $sql);
if(!$retval) {
die("Failed to fetch record");
} else {
// if records are there
while($row=mysqli_fetch_array($retval, MYSQLI_NUM)) {
// echo "<a href='./Products.php?catid=".$row[0]."'>".$row[1]."</a><br/> ";
echo "<a onclick='showproducts($row[0])' href='#'>".$row[1]."</a><br/> ";
}
}
mysqli_free_result($retval);
mysqli_close($conn);
?>
<file_sep><!-- Products.php -->
<?php
if($_GET['catid']==0)
return;
$productslst=NULL;
require './Category.php';
//die("ENtered products.php");
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "<PASSWORD>");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
$catid=$_GET['catid'];
$count=1;
$nocolumns=$_GET['nocolumns'];
$flcolwidth=12/$nocolumns;
$colwidth=floor(12/$nocolumns);
if($colwidth<=0)
$colwidth=1;
$colid=NULL;
$colclasses=NULL;
// if($flcolwidth>1.2&&$flcolwidth<1.65)
{
// $colclasses="col-sm-1 col-sm-1-5";
}
// else
{
$colclasses="col-sm-".$colwidth;
}
$colact1=NULL;
$widthint=floor(floor($flcolwidth*10)/10);
$widthdec=ceil(($flcolwidth-$widthint)*10);
//die("widthdec is :".(ceil(($flcolwidth-$widthint)*10)));
$colact1=$widthint."".$widthdec;
$output=NULL;
$sql="SELECT * FROM products WHERE catid=".$catid ;
$sql2="SELECT * FROM categories where catid=".$catid." AND hassubcat='false'";
$retval2=mysqli_query($conn, $sql2);
$retval = mysqli_query($conn, $sql);
//die("row count=".mysqli_num_rows($retval2));
if(mysqli_num_rows($retval2)==0) {
$rowcount=0;
mysqli_free_result($retval);
mysqli_free_result($retval2);
$sql3="SELECT CHILDCATNAME, CHILDCATID FROM catmap where PARENTCATID=".$catid;
$retval3 = mysqli_query($conn, $sql3);
//die("row count=".mysqli_num_rows($retval3));
$output=NULL;
$output="<div style='min-width:200px;min-height:200px;'>";
while($row=mysqli_fetch_array($retval3, MYSQLI_NUM)) {
$output.="<a href='#' name=$row[0] onclick='showproducts($row[1])'>$row[0]</a></br>";
$rowcount++;
}
$output.="</div>";
//die("row count =".$rowcount);
//die("Failed to fetch record");
//die($output);
mysqli_free_result($retval3);
} else {
// if records are there
$output=$output."<div class='container'>";
while($row=mysqli_fetch_array($retval, MYSQLI_NUM)) {
//$productslst.=$row[0]." ".$row[1]." ".$row[2]." ".$row[3]." ".$row[4]."<br/>";
//echo $productslst;
//echo $row[0]." ".$row[1]." ".$row[2]." ".$row[3]." ".$row[4]."<br/>";
if($count == 1)
{
$output=$output."<div class='row'>";
}
//echo "<img src='$row[5]'> <a href='$row[6]'>$row[1]</a></img>" ;
//echo "<div class='container1'><img src='$row[5]'><div class='overlay'> <a href='$row[6]'>$row[1]</a></div></div>" ;
//echo "<div class='container1'><img src='$row[5]'><div class='overlay'> <a href='$row[6]'>$row[1]</a></div></div>" ;
//echo "<img src='$row[5]'><div class='overlay'> <a href='$row[6]'>$row[1]</a></div>" ;
//$output=$output."<div class='col-sm-"."$colwidth'>";
//$output=$output."<div class='$colclasses'>";
$output=$output."<div class='".$colclasses." ".$colact1."' style='min-width:200;min-height:200' >";
//below line chnaged to add image overlay effect
//$output=$output."<img src='$row[5]' class='img-responsive' width=100 height=100><a href='$row[6]'>$row[1]</a>" ;
$output=$output."<div class='image1div'><a href='$row[6]'><img src='$row[5]' class='image1 img-responsive' ><span class='imagetext'> $row[1]</span></a></div>" ;
$output=$output."</div>";
if($count ==1)
{
}
$count ++;
if($count ==($nocolumns+1))
{
$output=$output."</div>";
$count =1;
}
}
$output=$output."</div>";
//echo $productslst;
mysqli_free_result($retval);
}
// mysqli_free_result($retval);
mysqli_close($conn);
// $output="<!--".$output;
// $output=$output."-->";
// die("reached end of products.php");
echo $output;
?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 24, 2019 at 01:22 PM
-- Server version: 10.1.37-MariaDB
-- PHP Version: 7.2.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `actecomm1`
--
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`catid` int(11) NOT NULL,
`catname` varchar(20) DEFAULT NULL,
`hassubcat` enum('true','false') DEFAULT 'false',
`hasparentcat` enum('true','false') DEFAULT 'false'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`catid`, `catname`, `hassubcat`, `hasparentcat`) VALUES
(1, 'Perfumes', 'false', 'false'),
(2, 'Books', 'false', 'false'),
(3, 'Shoes', 'false', 'false'),
(4, 'Mobiles', 'false', 'false'),
(5, 'consumerelectronics', 'true', 'false'),
(6, 'clothing', 'false', 'false'),
(7, 'audio', 'false', 'true'),
(8, 'laptops', 'false', 'false'),
(9, 'video', 'false', 'true'),
(30, 'mp3players', 'false', 'true');
-- --------------------------------------------------------
--
-- Table structure for table `catmap`
--
CREATE TABLE `catmap` (
`parentcatid` int(11) DEFAULT NULL,
`childcatid` int(11) DEFAULT NULL,
`parentcatname` varchar(20) DEFAULT NULL,
`childcatname` varchar(20) DEFAULT NULL,
`rowindex` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `catmap`
--
INSERT INTO `catmap` (`parentcatid`, `childcatid`, `parentcatname`, `childcatname`, `rowindex`) VALUES
(5, 7, 'consumerelectronics', 'audio', 1),
(5, 30, 'consumerelectronics', 'mp3players', 3),
(5, 9, 'consumerelectronics', 'video', 4);
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`pid` int(11) NOT NULL,
`pname` varchar(20) DEFAULT NULL,
`price` double DEFAULT NULL,
`pdescr` varchar(200) DEFAULT NULL,
`catid` int(11) DEFAULT NULL,
`IMGPATH` varchar(100) DEFAULT NULL,
`URLDETAILS` varchar(200) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`pid`, `pname`, `price`, `pdescr`, `catid`, `IMGPATH`, `URLDETAILS`) VALUES
(1, 'Brut', 150, 'Good', 1, 'images/FOGG1.png', 'produrls/fogg1.html'),
(2, 'Java Axe', 150, 'Good', 1, 'images/FOGG1.png', '#'),
(3, 'Davidoff', 150, 'Good', 1, 'images/FOGG1.png', '#'),
(4, 'Figaro', 150, 'Good', 1, 'images/FOGG1.png', '#'),
(5, 'Learning CSS', 200, 'Good', 2, 'images/books1.jpg', '#'),
(6, 'Learning jQuery', 200, 'Good', 2, 'images/books1.jpg', '#'),
(7, 'Learning Bootstrap', 200, 'Good', 2, 'images/books1.jpg', '#'),
(8, 'Learning CSS', 200, 'Good', 2, 'images/books1.jpg', '#'),
(9, 'Fogg1', NULL, 'Fogg1', 1, 'images/FOGG1.png', '#'),
(10, 'Euphoria1', NULL, 'Euphoria1', 1, 'images/Euphoria1.jpg', '#'),
(11, 'Eternity1', NULL, 'Eternity1', 1, 'images/Eternity1.jpg', '#'),
(12, 'Wildstone1', NULL, 'Wildstone1', 1, 'images/wildstone1.png', 'produrls/wildstone1.html'),
(13, 'fogg2', NULL, 'perfume', 1, 'images/FOGG1.png', 'produrls/fogg2.html'),
(14, 'wildstone1', NULL, 'wild stone 2\r\nprice:10$;\r\nxyz', 1, 'images/WILDSTONE2.png', 'produrls/wildstone2.html'),
(16, 'sonyled1', NULL, 'Resolution: HD Ready (1366x768p) | Refresh Rate: 5', 7, 'images/sonyled2.jpg', '#'),
(17, 'samsungled1', NULL, 'Resolution: HD Ready (1366x768p)\r\n Display: Story ', 7, 'images/samsungtel1.jpg', '#'),
(18, 'sonyled2', NULL, 'sony led 2', 7, 'images/sonyled2.jpg', 'produrls/sonyled2.html'),
(19, 'sony led tv 3', NULL, 'sony led tv 3\r\nfeature 1\r\nfeature 2:\r\nfeature 3:', 7, 'images/sonytel1.jpg', 'produrls/sony led tv 3.html'),
(20, 'sony led tv4', NULL, 'description', 7, 'images/sonytel1.jpg', 'produrls/sony led tv4.html'),
(23, 'sony led tv7', NULL, 'description 1', 7, 'images/sonytel1.jpg', 'produrls/sony led tv7.html'),
(27, 'sony led tv10', NULL, 'description 1', 7, 'images/sonytel1.jpg', 'produrls/sony led tv10.html'),
(28, 'sony led tv11', NULL, 'sony led tv 11\r\n\r\nfeature 1 \r\nfeature 2', 7, 'images/sonytel1.jpg', 'produrls/sony led tv11.html'),
(40, 'philipsmp3player1', NULL, 'feature 1 \r\nfeature 2', 30, 'images/philipsmp31.jpg', 'produrls/philipsmp3player1.html'),
(41, 'irulump31', NULL, 'iRULU F20 HiFi Lossless Mp3 Player with Bluetooth:', 30, 'images/irulump31.jpg', 'produrls/irulump31.html'),
(42, 'crispystylemp3_1', NULL, 'Hands-free portability & Clip up design\r\nSupports ', 30, 'images/crispystyl1.jpg', 'produrls/crispstylemp3player1.html'),
(43, 'leoiemp3_1', NULL, 'You can enjoy music by pairing with your Bluetooth', 30, 'images/leoiemp31.jpg', 'produrls/leoiemp3__1.html'),
(44, 'lenovo1', NULL, '\r\n Processor: AMD E2-9000 processor\r\n Operat', 8, 'images/lenovo1.png', 'produrls/lenovo1.html'),
(45, 'dell1', NULL, 'The compact and slim body of this Dell New Inspiro', 8, 'images/dell1.png', 'produrls/dell1.html'),
(46, 'hplap1', NULL, '\r\n 2.40GHz Intel Core i3-7100U 8th Gen processo', 8, 'images/hplaptop1.png', 'produrls/hplap1.html'),
(47, 'acer1', NULL, 'Acer Switch One Atom Quad Core - (2 GB/32 GB EMMC ', 8, 'images/acer1.png', 'produrls/acer1.html'),
(48, 'acerswift1', NULL, 'As far as specifications go, the Acer Swift 7 has an 8th Gen Intel Core i7-8500Y Amber Lake processor, up to 512GB of SSD storage, and up to 16GB RAM. The base variant has 256GB SSD storage and 8GB RA', 8, 'images/acerswift1.jpg', 'produrls/acerswift1.html'),
(49, 'aceraspire5', NULL, 'The narrow, 7.82mm1 bezel design offers more real estate for amazing images. With a 15.6” FHD IPS display and Acer Color Intelligence™1 crisp, true-to-life colors come alive. Adjust gamma and saturati', 8, 'images/Aspire_5.png', 'produrls/aceraspire5.html'),
(50, 'acer_spin_1', NULL, 'upercharge your laptop for work and play with an 8th Gen Intel® Core™ i5 processor.1 Intel® processors help apps load faster and allow multiple tasks to run simultaneously without lag. And with a batt', 8, 'images/Aspire_5.png', 'produrls/acer_spin_1.html');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`username` varchar(10) DEFAULT NULL,
`pass` varchar(10) DEFAULT NULL,
`role` varchar(10) DEFAULT 'normal'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`username`, `pass`, `role`) VALUES
('ramesh', '<PASSWORD>', 'admin'),
('surya', 'surya', 'normal');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`catid`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`pid`),
ADD KEY `product_catid_fk` (`catid`);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `products`
--
ALTER TABLE `products`
ADD CONSTRAINT `product_catid_fk` FOREIGN KEY (`catid`) REFERENCES `categories` (`catid`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Navbar Example</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/imgoverlay.css" rel="stylesheet">
<link href="css/flexgrid1.css" rel="stylesheet">
<style>
:root{
--noofcolumns:6;
--imgtextsize:20px;
}
#footer {
float:clear both;
}
.menu, .login, .ads {
//background-color:yellow;
border: solid 1px red;
}
.nav{
background-color:lightgray;
}
.menu
{
background-color:orange;
}
#divcontent
{
background-color:yellow;
}
.ads{
background-color:orange;
}
.image1div {
position:relative;
// padding:5px 0px 5px 0px;
}
.image1div:hover span ,.image1div a span:hover{
position:absolute;
color:darkviolet;
font-weight:bold;
font-size:calc(30/var(--nocolumns))px;
top:75%;
transition:opacity 2s;
transition:font-size 0s;
opacity:1.0;
}
.image1div span
{
//position:relative;
position: absolute;
top:75%;
// font-size:calc(30/var(--nocolumns))px;
opacity:0.9;
}
.image1div{
}
.image1div:hover
{
transition:opacity .8s;
}
/*
.imagetext(
font-size:20;
z-index:2;
}
*/
.imageclass1
{
// width:50px;
}
.col-sm-1-5,.col-sm-3-5, .col-sm-8-5 {
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px;
}
@media (min-width: 768px) {
.col-sm-1-5,.col-sm-3-5, .col-sm-8-5 {
float: left;
}
.col-sm-1-5 {
width:12.5%;
}
body .imageclass8
{
width:50px;
--imgtextsize:8px;
}
.col-sm-3-5 {
width: 29.16666667%;
}
.col-sm-8-5 {
width: 70.83333333%;
}
}
.col-md-1-5,.col-md-3-5, .col-md-8-5 {
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px;
}
@media (min-width: 961px) {
.col-md-1-5,.col-md-3-5, .col-md-8-5 {
float: left;
}
.col-md-1-5{
width:12.5%;
}
.col-md-3-5 {
width: 29.16666667%;
}
.col-md-8-5 {
width: 70.83333333%;
}
}
/*
.col-sm-1-5{
.make-sm-column(2.0);
}*/
</style>
</head>
<body class="mystyle" onload="refreshpage()" onunload="javascript:alert('unloading');" onresize="onresizewnd()">
<!-- jQuery (necessary for Bootstrap’s JavaScript plugins) -->
<script src="js/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<!-- nav bar starts here -->
<nav class="navbar navbar-default">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<!--<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data- -
target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>-->
<a class="navbar-brand" href="#">EComm</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria- -
haspopup="true" aria-expanded="false">Categories <span class="caret"></span></a>
<ul class="dropdown-menu">
<?php
$conn = mysqli_connect("localhost:3306", "admin1", "ramesh", "actecomm1");
$sql="SELECT * FROM categories WHERE hasparentcat='false'";
$retval = mysqli_query($conn, $sql);
if(!$retval) {
die("Failed to fetch record");
} else {
// if records are there
while($row=mysqli_fetch_array($retval, MYSQLI_NUM)) {
//echo "<li><a href='./Products.php?catid=".$row[0]."'>".$row[1]."</a></li>";
echo "<li><a onclick=showproducts($row[0]) href='#'>".$row[1]."</a></li>";
}
}
mysqli_free_result($retval);
mysqli_close($conn);
?>
</ul>
<!-- <ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul> -->
</li>
</ul>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" id="SearchTerm" placeholder="Search">
</div>
<button type="button" onclick="showproducts2()" >Submit</button>
<!--<button type="button" onclick="showproducts2()" class="btn btn-default">Submit</button>-->
</form>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria- -
haspopup="true" aria-expanded="false">User <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="index.html">Login</a></li>
<li><a href="#">New User</a></li>
<li><a href="#">Settings</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Logout</a></li>
</ul>
</li>
</ul>
</div ><!-- /.navbar-collapse -->
</div ><!-- /.container-fluid -->
</nav>
<!-- nav bar ends here -->
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3 menu">
<h4>Categories</h4>
<?php
require "./Categories.php";
?>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 login">
<div class="row" id="divcontent">
<!--<form method="post" action="./Login.php">
<fieldset>
<legend>Login Form</legend>
<table class="table table-hover">
<tr>
<th>Username</th>
<td><input type="text" name="uname"/></td>
</tr>
<tr>
<th>Password</th>
<td><input type="<PASSWORD>" name="pass"/></td>
</tr>
<tr>
<th><input type="submit" name="submit" value="Login"/></th>
<td><input type="reset" name="reset" value="Clear"/></td>
</tr>
</table>
<p align="right"><a href="NewUser.html">New User</a></p>
</fieldset>
</form> -->
</div><!--end of div row-->
</div>
<div class="col-xs-12 col-sm-3 col-md-3 ads">
<h4>ads come here</h4>
</div>
</div>
</div>
<div id="footer">
<table>
<th>About us     </th>
<th>Help </th>
<tr>
<td></td>
<td><a>Your account</a></td>
</tr>
<tr>
<td></td>
<td><a>Your orders</a></td>
</tr>
</table>
</br><p>© Activenet Informatics </p>
</div>
</body>
<script defer>
var firsttime=true;
var nocolumns=8;
var divcontentwidth=100;
var widthlow=false;
var rtime;
var timeout = false;
var delta = 1000;
var debugging=false;
var debuggingnew=false;
var debuggingnew2=false;
var debuggingnew3=false;
var pixpercolumn=75;
if(debuggingnew)alert("initialized globals");
resetnavigatedaway();
sessionStorage.setItem("firsttime",true);
sessionStorage.setItem("nocolumns",12);
sessionStorage.setItem('divcontentwidth',400);
if(getdivcontentwidth()<pixpercolumn)
{
widthlow=true;
sessionStorage.setItem('lowwidth',true);
}
else
{
widthlow=false;
sessionStorage.setItem('lowwidth',false);
}
function initglobals()
{
firsttime=true;
nocolumns=8;
divcontentwidth=100;
widthlow=false;
rtime;
timeout = false;
delta = 1000;
debugging=false;
debuggingnew=true;
}
function resizemaindivs()
{
return;
var elemmenu=document.getElementsByClassName("menu")[0];
var elemads=document.getElementsByClassName("ads")[0];
var firstclass=elemmenu.className.split(" ")[1];
getdivcontentwidth("login");
dbgdivcontentwidth=divcontentwidth;
var newwidth=divcontentwidth+"px";sm
if(divcontentwidth<700 && firstclass=="col-md-3")
{
// elemmenu.style.setProperty("width",newwidth);
// elemads.style.setProperty("width",newwidth);
// elemmenu.className="col-sm-12 col-md-3 menu";
// elemads.className="col-sm-12 col-md-3 ads";
// refreshpage();
}
else
{
// elemmenu.className="col-sm-12 col-md-3 menu";
// elemads.className="col-sm-12 col-md-3 ads ";
//
}
}
function showproducts(catid){
if(debuggingnew2)alert("Entered showproducts!!");
if(debugging)alert("no coulmns in show products:"+nocolumns);
//root.documentElement.style.setProperty('--noofcolumns', nocolumns);
//alert("after");
if(!(catid==0))
{
document.cookie = "catid" + "=" + catid + ";"
}
else
{
catid=0;
// return;
}
// alert("searched="+getCookie("searched"));
if(getCookie("searched")==1&&catid==0)
{
if(debugging)alert("diverting to show products2");
showproducts2();
// document.cookie = "searched" + "=" + "0" + ";"
return;
}
var display = document.getElementById("divcontent");
var xmlhttp = new XMLHttpRequest();
//alert("calling products.php");
getdivcontentwidth("divcontentwidth");
setnocolumns();
xmlhttp.open("GET", "Products.php?catid="+catid+"&nocolumns="+nocolumns);
//alert("Products.php?catid="+catid+"&nocolumns="+nocolumns);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//alert("ajax succeeded");
//alert(this.responseText);
display.innerHTML = this.responseText;
//////////////////////////////////
var rat=getdivcontentwidth("divcontentwidth")/nocolumns;
var fontsz=Math.floor(rat/5);
if(debugging)alert("font size in showproducts is :"+fontsz);
//var fontsz=Math.floor(50/sessionStorage.getItem('nocolumns'));
//fontsz=Math.floor((fontsize/3)*log(fontsz))
var strfsz=fontsz+"px";
////////////////////////////////////
//var fontsz=Math.floor(100/nocolumns);
//var strfsz=fontsz+"px";
//alert(strfsz);
var res=document.getElementsByClassName("imagetext");
for(var i=0;i<res.length;i++)
{
res[i].style.setProperty('font-size',strfsz);
}
var cols=document.getElementsByClassName("col-sm-1-5");
for(var i=0;i<cols.length;i++)
{
// cols[i].style.setProperty(width,"12.5%");
}
getdivwidth("divcontentwidth");
//setnocolumns();
setcolwidths();
} else {
display.innerHTML = "Loading...";
};
}
setCookie("searched",0,1);
var fontsz=Math.floor(30/nocolumns);
var strfsz=fontsz+" px";
/* if (this.readyState === 4 && this.status === 200)
{
alert(strfz);
getElementsByClass("imagetext").style.fontSize=strfsz;
}*/
}
function showproducts2(){
if(debuggingnew2)alert("Entered showproducts2");
//document.cookie = " searched" + "=" + "1" + ";"
if(debugging)alert("no coulmns in show products 2:"+nocolumns);
setCookie("searched",1,1);
setCookie("catid",0,1);
var display = document.getElementById("divcontent");
var xmlhttp = new XMLHttpRequest();
var searchterm= document.getElementById("SearchTerm").value;
// alert("search termis:"+searchterm);
//getdivcontentwidth();
//setnocolumns();
if(debugging)alert("divcontentwidth:"+divcontentwidth);
if(nocolumns<3)
{
//setdivcontentwidth(400);
setnocolumns();
}
else
{
// getdivcontentwidth();
if(debugging)alert("showproducts2 got width :"+divcontentwidth);
setnocolumns();
}
if(debugging)alert("no coulmns in show products 2 after call to setcolumns:"+nocolumns);
if(debuggingnew)alert("no columns!!!!!! :"+nocolumns);
xmlhttp.open("GET", "Productslist.php?SearchTerm="+searchterm+"&nocolumns="+nocolumns);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
if(debugging)alert("ajax succeeded");
if(debugging)alert(this.responseText);
display.innerHTML = this.responseText;
resizemaindivs();
//////////////////////
var prevdivcontentwidth=divcontentwidth;
if(prevdivcontentwidth!=getdivcontentwidth("login"))
{
refreshpage();
return;
}
var rat=getdivcontentwidth("divcontentwidth")/nocolumns;
var fontsz=Math.floor(rat/5);
//if(debugging)alert("divwidth //is"+sessionStorage.getItem('divcontentwidth')+"nocolumns"+sessionStorage.getItem('nocolumns')+"font size in showproducts2 is //:"+fontsz);
if(debuggingnew)alert("divwidth is"+divcontentwidth+"nocolumns"+nocolumns+"font size in showproducts2 is :"+fontsz);
//var fontsz=Math.floor(50/sessionStorage.getItem('nocolumns'));
//fontsz=Math.floor((fontsz/3)*Math.log(fontsz));
if(debugging)alert("LOG font size in showproducts2 is :"+fontsz);
var strfsz=fontsz+"px";
/////////////////////
// var fontsz=Math.floor(100/nocolumns);
// var strfsz=fontsz+"px";
//dbg vars over
//alert(strfsz);
var res=document.getElementsByClassName("imagetext");
for(var i=0;i<res.length;i++)
{
res[i].style.setProperty('font-size',strfsz);
}
/*
var cols=document.getElementsByClassName("col-sm-1-5");
for(var i=0;i<cols.length;i++)
{
cols[i].style.setProperty(width,"12.5%");
}
*/
//getdivcontentwidth();
//setnocolumns();
setcolwidths();
} else {
display.innerHTML = "Loading...";
};
}
/*
if (this.readyState === 4 && this.status === 200)
{
alert("s2 fontssize:"+strfsz);
getElementsByClass("imagetext").style.fontSize=strfsz;
}
*/
}
/*
function genprodpg(pid){
//alert("Entered showproducts");
var display = document.getElementById("divcontent");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "genprod.php?pid="+pid);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//alert("ajax succeeded");
//alert(this.responseText);
display.innerHTML = this.responseText;
} else {
display.innerHTML = "Loading...";
};
}
}
*/
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function deleteCookie(name) { setCookie(name, '', -1); }
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
/*
$(window).resize(function() {
alert("onresize");
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
});
*/
function onresizewnd()
{
delta=200;
if(debugging)alert("resize called with timeout:"+delta);
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
//refreshpage();
}
function resizeend() {
if (new Date() - rtime < delta) {
setTimeout(resizeend, delta);
} else {
if(debugging)alert("resize end called!!!");
timeout = false;
getdivcontentwidth("login");
if(debuggingnew)alert2("1 resize end divcontentwidth:"+divcontentwidth);
//setdivcontentwidth(divcontentwidth);
setnocolumns();
if(debuggingnew)alert("2 resize end divcontentwidth:"+divcontentwidth);
refreshpage();
// refreshpage();
}
}
function getdivwidth(par)
{
if(debuggingnew2)alert("Entering getdivwidth");
//getdivcontentwidth();
//return;
var ele;
if(par=="divcontent")
ele = document.getElementById("divcontent"); // Do not use #
else
ele = document.getElementsByClassName("login")[0];
var eleStyle = window.getComputedStyle(ele);
/* Below is the width of ele */
var eleWidth = eleStyle.width;
var numberwidth=Number(eleWidth.replace('px',''));
return(divcontentwidth=Math.floor(numberwidth));
//alert("1:"+getdivcontentwidth());
}
function getdivcontentwidth(par)
{
// if(debuggingnew2)alert("Entering getdivcotentwidth");
//var pixwidth=$("#divcontent").css("width");
/*
var pixwidth=document.querySelector("#divcontent").width;
divcontentwidth=Number(pixwidth.replace('px',''));
return divcontentwidth;
*/
//var bb = document.querySelector("#divcontent")
var bb;
if(par=="divcontent")
bb = document.querySelector("#divcontent")
.getBoundingClientRect();
else
bb = document.querySelector(".login")
.getBoundingClientRect();
var width = bb.right - bb.left;
if(debuggingnew2)alert("returning divcontent width:"+width);
return(divcontentwidth=width);
}
function setnocolumns2()
{
if(debuggingnew2)alert("Entering setnocolumns2");
getdivcontentwidth("login");
nocolumns=Math.ceil(divcontentwidth/pixpercolumn);
}
function setdivcontentwidth(divwidth,par)
{
if(debuggingnew2)alert("Entering setdivcontentwidth");
var newwidth=divwidth+"px";
if(par=="login")
document.getElementsByClassName('login')[0].style.setProperty('width',newwidth);
if(par=="divcontentwidth")
document.getElementById("divcontent").style.setProperty('width',newwidth);
if(par=="both")
{
document.getElementsByClassName('login')[0].style.setProperty('width',newwidth);
document.getElementById("divcontent").style.setProperty('width',newwidth);
}
}
function setnocolumns()
{
if(debuggingnew2)alert("setting no columns");
//var ele = document.getElementById("divcontent"), // Do not use #
var ele = document.getElementsByClassName("login"), // Do not use #
eleStyle = window.getComputedStyle(ele[0]);
var eleWidth = eleStyle.width;
var numberwidth=Number(eleWidth.replace('px',''));
var numWidth=Math.floor(numberwidth);
numWidth=getdivcontentwidth("login");
// numWidth=divcontentwidth;
if(debugging)alert("div width is :"+numWidth);
if(numWidth<pixpercolumn || numWidth>1200)
{
// document.querySelector(".login").style.setProperty('min-width','300px');
// document.querySelector(".login").style.width=document.querySelector("body").style.width-30;
document.querySelector("#divcontent").style.setProperty('min-width','300px');
//document.querySelector("#divcontent").style.setProperty('width',200);
//document.getElementsByClassName('login')[0].style.setProperty('width','400px');
//document.getElementsById('#divcontent').style.setProperty('width','400px');
//setdivcontentwidth("login",400);
sessionStorage.setItem('divcontentwidth',400);
sessionStorage.setItem('nocolumns',6);
//alert(document.querySelector(".style.getProperty('width'));
//nocolumns=Math.floor(max(numWidth,71)/70);
//var tmpwidth=document.querySelector("#divcontent").style.width;
widthlow=false;
nocolumns=6;
/*
var noiter=0;
while((divcontentwidth=getdivcontentwidth("login"))<70&&noiter<100)
{
sleep(10);
alert(noiter++);
}
*/
nocolumns=Math.ceil(divcontentwidth/pixpercolumn);
//divcontentwidth=400;
/*
var tmpwidth=document.getElementById('divcontent').style.width;
// alert("tmp width is:"+tmpwidth);
tmpwidth=Number(tmpwidth.replace("px",""));
// alert("tmp width number is:"+tmpwidth);
nocolumns=Math.floor(Number(tmpwidth)/70)+2;
// alert("nocolumns in refresh:"+nocolumns);
sessionStorage.setItem('nocolumns',nocolumns);
alert("width is :"+tmpwidth+"returningwith nocolumns:"+nocolumns);
*/
return;
}
//nocolumns=Math.floor(numWidth/70);
nocolumns=Math.ceil(numWidth/pixpercolumn);
// alert("nocolumns:"+nocolumns);
if(nocolumns<1)
nocolumns=1;
if(nocolumns>12)
nocolumns=12;
if(debugging)alert("no columns is"+nocolumns);
// sessionStorage.setItem("nocolumns",nocolumns);
// alert("setting no columns:"+nocolumns);
}
function resetdivwidth(par)
{
if(debuggingnew2)alert("resetting div width");
if(par=="login")
document.getElementsByClassName("login")[0].style.setProperty('width','400px');
if(par=="divcontentwidth")
document.getElementById("divcontent").style.setProperty('width','400px');
if(par=="both"){
document.getElementById("divcontent").style.setProperty('width','400px');
document.getElementsByClassName("login")[0].style.setProperty('width','400px');
}
}
function navigatedaway()
{
return sessionStorage.getItem('navigatedaway');
}
function setnavigatedaway()
{
sessionStorage.setItem('navigatedaway',true);
sessionStorage.setItem('divcontentwidth',divcontentwidth);
sessionStorage.setItem('nocolumns',nocolumns);
}
function resetnavigatedaway()
{
sessionStorage.setItem('navigatedaway',false);
}
function refreshpage()
{
if(debuggingnew2)alert("in refreshpage ");
firsttime=sessionStorage.getItem("firsttime");
if(navigatedaway())
{
if(debuggingnew)alert("navigated");
//divcontentwidth=sessionStorage.getItem('divcontentwidth');
//setdivcontentwidth(divcontentwidth,"divcontentwidth");
//resetnavigatedaway();
}
//if(!firsttime)
{
getdivcontentwidth("login");
setnocolumns();
}
if(widthlow)
{
if(debuggingnew)alert("resetting width!");
//resetdivwidth("both");
//setnocolumns();
widthlow=false;
}
// nocolumns=sessionStorage.getItem("nocolumns");
// alert("in refreshpage no columns:"+nocolumns);
// setnocolumns();
if(debugging)alert("after call:"+nocolumns);
/*
var ele = document.getElementById("divcontent"), // Do not use #
eleStyle = window.getComputedStyle(ele);
var eleWidth = eleStyle.width;
var numberwidth=Number(eleWidth.replace('px',''));
var numWidth=Math.floor(numberwidth);
alert(numWidth);
if(firsttime)
{
// alert("adding event listener");
// window.addEventListener('load',setcolwidths,false);
firsttime=false;
}
nocolumns=Math.floor(numWidth/150);
if(nocolumns<1)
nocolumns=1;
if(nocolumns>12)
nocolumns=12;
*/
var cols=document.getElementsByClassName("col-sm-1-5");
for(var i=0;i<cols.length;i++)
{
cols[i].style.setProperty(width,"12.5%");
}
//if(firsttime==false)
{
// setcolwidths();
}
// else
// firsttime=false;
// 2if (!(document.cookie.indexOf("searched=") >= 0&&document.cookie.indexOf("catid=")>=0))
// return;
//alert("both cookies not set");
//alert("searched="+getCookie("searched"));
//alert("catid="+getCookie("catid"));
//alert("Entered showproducts");
if(getCookie("searched")==1)
{
if(debugging)alert("seach cookie present calling show products 2");
showproducts2()
// document.cookie = "searched" + "=" + "0" + ";"
return;
}
var catid=getCookie("catid");
var searchterm=getCookie("searched");
if(catid==0&&searchterm==0)
{
if(debuggingnew2)alert("no search term or cat id returnng from refresh page");
return;
}
var display = document.getElementById("divcontent");
var xmlhttp = new XMLHttpRequest();
if(debugging)alert("not searched");
setnocolumns();
if(debuggingnew2)alert("calling products.php catid:"+catid+"nocolumns:"+nocolumns+"divcontentwidth:"+divcontentwidth);
xmlhttp.open("GET", "Products.php?catid="+catid+"&nocolumns="+nocolumns);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//alert("ajax succeeded");
//alert(this.responseText);
if(debuggingnew3) alert("getting category wise");
display.innerHTML = this.responseText;
resizemaindivs();
var prevdivcontentwidth=divcontentwidth;
if(prevdivcontentwidth!=getdivcontentwidth("login"))
{
refreshpage();
return;
}
//var fontsz=Math.floor(100/nocolumns);/
var rat=getdivcontentwidth("divcontentwidth")/nocolumns;
var fontsz=Math.floor(rat/5);
if(debuggingnew)alert("font size is :"+fontsz);
//var fontsz=Math.floor(50/sessionStorage.getItem('nocolumns'));
var strfsz=fontsz+"px";
//dbg vars over
// alert(strfsz);
var res=document.getElementsByClassName("imagetext");
for(var i=0;i<res.length;i++)
{
res[i].style.setProperty('font-size',strfsz);
}
//getdivwidth();
//setnocolumns();
/* resizing main*/
/*end resiziing main divs*/
setcolwidths();
firsttime=false;
} else {
display.innerHTML = "Loading...";
};
}
//setnocolumns();
firsttime=false;
// sessionStorage.setItem('nocolumns',nocolumns);
}
function removecookies()
{
alert("removing cookeis");
deleteCookie("catid");
deleteCookie("searched");
}
function settextfont()
{
var elems=document.getElementsByClassName("imagetext");
for(var i=0;i<elems.length;i++)
elems[i].style.setProperty('font-size',Math.floor(150/nocolumns));
}
function setcolwidths()
{
var listelems;
var classnames;
var widthelem=0;
var percentval=0;
if(debuggingnew2)alert("setting col widths");
for(var j=1;j<13;j++)
{
listelems=document.getElementsByClassName("col-sm-"+j);
//alert("col-sm-"+j);
for(var i=0;i<listelems.length;i++)
{
classnames=listelems[i].classList;
prclassname=classnames.item(1);
percentval=Number(prclassname[0]+"."+prclassname[1])*7.9;
widthelem=percentval+"%";
// alert(widthelem);
listelems[i].style.setProperty("width",widthelem);
}
}
}
</script>
</html><file_sep><?php
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
$pid=$_POST['pid'];
$pname=$_POST['pname'];
$catid=$_POST['catid'];
$proddescr1=$_POST['proddescr'];
$imgpath=$_POST['imgpath'];
$produrl=$_POST['produrl'];
$emptyurl=false;
$fullurl=NULL;
if($produrl==NULL)
{
$emptyurl=true;
}
//$imagepath=substr($imgpath, strpos($imgpath,'images'), strpos($imgpath, '@') - strlen($imgpath));
$imagepath="images/"."$imgpath";
if($emptyurl)
{
$fname="produrls/$pname";
$ext="html";
$fullurl=$fname.".".$ext;
}
else
$fullurl=$produrl;
$sql="INSERT INTO PRODUCTS(pid,pname,catid,IMGPATH,pdescr,URLDETAILS) VALUES ('$pid','$pname','$catid','$imagepath','$proddescr1','$fullurl')";
$retval = mysqli_query($conn, $sql);
$modimagepath="../".$imagepath;
// if($emptyurl)
{
$content="<img src='$modimagepath'><div><p>$proddescr1</p></div>";
$actionpart="addtocart.php?pid=".$_POST['pid'];
$content.="<form method='GET' action='$actionpart' >Quantity<input type='text' name='quantity' ></input><input type='submit' name='addtocart' value='add to cart'></input></form>";
$fpurl=fopen($fullurl,'w');
fwrite($fpurl,$content);
fclose($fpurl);
}
if(!$retval) {
echo($imgpath);echo("<\br>");
echo($imagepath);echo("<\br>");
echo($proddescr1);echo("<\br>");
echo(mysqli_error($conn));
die("Failed to insert record");
}
mysqli_close($conn);
?><file_sep><!-- CategoryController.php -->
<?php
/*
check is catList exist in session scope with name 'categories'
if exist
send CategoriesView to browser
else
connect to CategoryModel
*/
/*
if(isset($_SESSION['categories'])) {
// send CategoriesView.php to browser
// nothin but redirect
header("Location:./CategoriesView.php");
} else {
// include
*/
include 'CategoryModel.php';
header("Location:./CategoriesView.php");
/*
}
*/
?>
<file_sep><!-- Login.php -->
<?php
// echo phpinfo();
session_start();
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
echo 'Connected successfully<br/>';
}
// read username and password from html form
$uname=$_POST['uname'];
$pass=$_POST['pass'];
$sql="SELECT ROLE FROM users WHERE username='".$uname."' AND pass='".$pass."'";
$retval = mysqli_query($conn, $sql);
if(!$retval) {
die("Failed to fetch record");
} else {
echo "Login Successful";
// store the user in session object
$_SESSION['user'] = $uname;
$row=mysqli_fetch_array($retval,MYSQLI_NUM);
// connect to CategoryController
// header("Location:./CategoryController.php");
if($row[0]=="normal")
header("Location:./index.php");
else
header("Location:./admin.html");
}
mysqli_free_result($retval);
mysqli_close($conn);
?>
<file_sep><!-- Products.php -->
<?php
$productslst=NULL;
require './Category.php';
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
//$catid=$_POST['catid'];
$count=1;
$nocolumns=$_GET['nocolumns'];
$flcolwidth=12/$nocolumns;
$colwidth=floor($flcolwidth);
if($colwidth<0)
{
// die("column width is 1");
$colwidth=1;
}
$colname=NULL;
$colid=NULL;
$colact=NULL;
$colact1=NULL;
$widthint=floor(floor($flcolwidth*10)/10);
$widthdec=ceil(($flcolwidth-$widthint)*10);
//die("widthdec is :".(ceil(($flcolwidth-$widthint)*10)));
$colact1=$widthint."".$widthdec;
/* if($flcolwidth>1.2&&$flcolwidth<1.65)
{
$colname="col-sm-1";
$colid="icol-sm-1-5";
$colact="col-sm-1-5";
}
else
{
*/
$colname="col-sm-$colwidth";
/* }*/
//die("at 1:".$colact1);
//die($colsuffix);
$output=NULL;
$searchterm=$_GET['SearchTerm'];
//die($searchterm);
$searchterm1=$searchterm;
$index=0;
$matchedproducts=array();
//$matchedproducts[0]=1;
$sql2="SELECT * FROM PRODUCTS";
$retval2=mysqli_query($conn, $sql2);
if(!$retval2) {
echo(mysqli_error($conn));
die("Failed to fetch rows");
}
while($row2=mysqli_fetch_array($retval2, MYSQLI_NUM))
{
$filcont=@file_get_contents($row2[6]);
if(!($searchterm==""))
if(stripos($filcont,$searchterm)!=false)
{
// die("file contains:".$filcont." searchterm:".$searchterm);
$matchedproducts[$index++]=$row2[0];
// $sql4="SELECT * FROM PRODUCTS WHERE pid=".$row2[0];
// $retval4=mysqli_query($conn, $sql2);
// $row5=mysqli_fetch_array($retval, MYSQLI_NUM);
}
}
//die("(" . implode(',', $matchedproducts) . ")");
if(!empty($matchedproducts))
$sql="SELECT * FROM products WHERE pdescr LIKE "."'%$searchterm%'" ." OR pname LIKE "."'%$searchterm%'"." OR pid IN (" . implode(',', $matchedproducts) . ")" ;
else
$sql="SELECT * FROM products WHERE pdescr LIKE "."'%$searchterm%'" ." OR pname LIKE "."'%$searchterm%'";
//die($sql);
$retval = mysqli_query($conn, $sql);
if(!$retval) {
echo(mysqli_error($conn));
echo("searchterm=".$searchterm);
echo(" ");
echo($sql);
die("Failed to fetch rows");
}
// if records are there
$output=$output."<div class='container'>";
$divind=0;
while($row=mysqli_fetch_array($retval, MYSQLI_NUM)) {
//$productslst.=$row[0]." ".$row[1]." ".$row[2]." ".$row[3]." ".$row[4]."<br/>";
//echo $productslst;
//echo $row[0]." ".$row[1]." ".$row[2]." ".$row[3]." ".$row[4]."<br/>";
if($count == 1)
{
$output=$output."<div class='row'>";
}
$test=(string)"".$colname."";
//die($test);
//$output=$output."<div class='thumbnail'>";
$output=$output."<div class='".$colname." ".$colact1."' >";
//die("at 2:".$colact1);
$imgwidth=floor(450/$nocolumns);
//die("image width is $imgwidth");
/*$output=$output."<div class='image1div'><a href='$row[6]'><img src='$row[5]' class='imageclass$nocolumns image1 img-responsive' ></br><span class='imagetext'> $row[1]</span></a></div>" ;*/
$output=$output."<div class='image1div'><a href='$row[6]'><img src='$row[5]' class='imageclass$nocolumns image1 img-responsive' ></br><div style='float:none'><span class='imagetext' > $row[1]</span></div></a></div>" ;
//die("style='width:$imgwidth px;height:$imgwidth px;");
$output=$output."</div>";//col end here
//$output=$output."</div>";//thubnail ends here
if($count ==1)
{
}
$count ++;
if($count ==($nocolumns+1))
{
$output=$output."</div>";
$count =1;
}
}
// die("row count is ".$count);
//on line 81 div is closed here
$output=$output."</div>";
//echo $productslst;
mysqli_free_result($retval);
// mysqli_free_result($retval);
mysqli_close($conn);
// $output="<!--".$output;
// $output=$output."-->";
echo $output;
?>
<file_sep><?php
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
$catid=$_POST['newcatid'];
$catname=$_POST['newcatname'];
//if(!empty($_POST['subcatid']))
// $HasSubCat='true';
//else
// $HasSubCat='false';
if(!empty($_POST['parcatid']))
$HasParCat='true';
else
$HasParCat='false';
//$childcatname=$_POST['childcatname'];
$parcatname=$_POST['parcatname'];
//$childcatid=$_POST['childcatid'];
$parcatid=$_POST['parcatid'];
$HasSubCat="false";
$sql="INSERT INTO CATEGORIES(catid,catname,hassubcat,hasparentcat) VALUES ($catid,'$catname','$HasSubCat','$HasParCat')";
$retval = mysqli_query($conn, $sql);
if(!$retval) {
echo(mysqli_error($conn));
die("Failed to insert record");
}
if(!empty($parcatid))
{
$sql="SELECT MAX(rowindex) AS 'maxrowindex' FROM catmap";
$queryres=mysqli_query($conn, $sql);
while($row=mysqli_fetch_array($queryres,MYSQLI_ASSOC))
$rowindexmax=$row["maxrowindex"];
//$rowval=mysqli_fetch_array($queryres, MYSQLI_NUM);
//$rowval1=$rowval;
$rowindexmax++;
//die("maxrow is:".$rowindexmax);
$sql="INSERT INTO CATMAP values ($parcatid,$catid,'$parcatname','$catname',".$rowindexmax.")";
//die($sql);
$retval = mysqli_query($conn, $sql);
if(!$retval) {
echo(mysqli_error($conn));
die("Failed to insert record");
}
$sql="Update categories Set hasparentcat='true' where catid=".$catid;
$retval = mysqli_query($conn, $sql);
if(!$retval) {
echo(mysqli_error($conn));
die("Failed to update record");
}
}
mysqli_close($conn);
?><file_sep><?php
echo "<html><head></head><body>"
$productslst=NULL;
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
$pid=$_GET['pid'];
$sql="SELECT * FROM products WHERE pid=".$pid;
$retval = mysqli_query($conn, $sql);
if(!$retval) {
die("Failed to fetch record");
} else {
// if records are there
while($row=mysqli_fetch_array($retval, MYSQLI_NUM)) {
$urldetails=$row[6];
if($urldetails=="#")
{
echo "<img src='$row[5]'><div><p>'$row[3]'</p></div>";
}
}
}
echo"</body></html>"
?><file_sep><?php
//die($_POST['imgpath']);
$dbhost = "localhost:3306";
$dbuser = "admin1";
$dbpass = "<PASSWORD>";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "actecomm1");
if(!$conn ) {
die('Could not connect: ');
} else {
// echo 'Connected successfully<br/>';
}
$sql="SELECT urldetails from products where pid=".$_POST['pid'];
$retval=mysqli_query($conn, $sql);
if(!$retval) {
echo(mysqli_error($conn));
die("Failed to fetch rows");
}
$row=mysqli_fetch_array($retval);
$pageurl=NULL;
if(empty($_POST['pageurl']))
$pageurl=$row[0];
else
$pageurl=$_POST['pageurl'];
$fprodpage=fopen($pageurl,'w');
$imgpath=$_POST['imgpath'];
$content="<html><head><style>imgdiv {float:left}</style><script>
</script></head><body>";
$content="<div id='imgdiv'>";
$content.="<img src=";
$content.="\"../images/$imgpath\"";
$prodname=$_POST['prodname'];
$content.=">$prodname</img>";
$content=$content."</div>";
$proddescr=$_POST['proddescr'];
$content=$content."<div id='proddescr'>$proddescr</div>";
$content.="</body></html>";
//die($_POST['pid']);
$actionpart="addtocart.php?pid=".$_POST['pid'];
//$actionpart="addtocart.php?pid=23";
$content.="<form method='GET' action='$actionpart' >Quantity<input type='text' name='quantity'></input><input type='submit' name='addtocart' value='add to cart'></input></form>";
fwrite($fprodpage,$content);
fclose($fprodpage);
if(!empty($_POST['pageurl']))
{
$sql="UPDATE PRODUCTS SET URLDETAILS= "."\"$pageurl\""." WHERE pid=".$_POST['pid'];
//die( $sql);
$retval2=mysqli_query($conn, $sql);
if(!$retval2) {
echo(mysqli_error($conn));
die("Failed to update record");
}
}
mysqli_free_result($retval);
mysqli_close($conn);
?>
|
00906255787fe1d37e963d9de341a80154bd8abf
|
[
"SQL",
"HTML",
"PHP"
] | 19 |
PHP
|
rameshdk/actecommproj1
|
b566792f714d81ade7f2fa33f47e12dce2b0026b
|
e5e00c7ca4bfce6b78ed8ea857aee2de8bb43453
|
refs/heads/master
|
<file_sep>const fs = require('fs');
const SystemFonts = require('../dist/main').default;
const fontkit = require('fontkit');
const systemFonts = new SystemFonts({ debug: true, fontkit });
// const request = [
// {family: 'Avenir Next', style: 'Bold'},
// {family: 'Avenir Next', style: 'Demi Bold Italic'},
// {family: 'Avenir Next', style: 'Demi Bold'},
// {family: 'HaveHeartTwo', style: 'Regular'},
// {family: 'Avenir Next', style: 'Heavy'},
// {family: 'Avenir Next', style: 'Medium'}
// ];
// // systemFonts.findFonts(request).then( result => {
// // console.log(result);
// // }).catch(e => console.error(e));
// console.log(systemFonts.findFontsSync(request));
// systemFonts.getFontsExtended().then(res => {
// res.forEach(item => {
// if(item.family.toLowerCase().indexOf('avenir') !== -1) {
// console.log(item);
// }
// });
// });
const dir = 'test/test-folder';
fs.readdir(dir, (err, files) => {
const arr = files.map(file => dir + '/' + file);
console.log(arr);
systemFonts.installFonts(arr).then(res => console.log(res)).catch(e => console.error('ERR', e));
});
|
f5f9a6ef579f638b8567e0018b88a55266cc6266
|
[
"JavaScript"
] | 1 |
JavaScript
|
rebellium/dnm-font-manager
|
d22494ea4eda62f35845d361315b0ed4b529b29c
|
d66cc7c8aaea6d23f65c3228dc49b7a16e88a72e
|
refs/heads/master
|
<file_sep>#ifndef CONSTSH
#define CONSTSH
//https://www.geeksforgeeks.org/constants-in-c/
const short BITS = 16;
//phyical memory
//const int TOTAL_MEMORY = 1 << BITS;
const int TOTAL_MEMORY = 65536;
const short PAGE_SIZE = 256;
//2^16-8 16bit system with 256 bytes of page size
const short PAGE_COUNT = 256;
const short FRAME_SIZE = 256;
//page no - 8 bits (0-255) offset - 8 bits (0-255) , hex - 32 bits
// 1111 1111 0000 0000 - 65280
const short MASK = 0xFF00;
// 1111 1111 - 255
const short OFFSET = 0xFF;
//no of bits shift
const short SHIFT = 8;
// 16bit / page size = 2^16-8 = 2^8 * 2bytes(amount of bytes available to hold addresses)
//256 * 2 = 512b ;
const short PAGE_TABLE_ENTRY_SIZE = 512;
const short HARD_DRIVE_MEMORY = 512;
//(2049-20479)
const short LOWEST_RAND = 2048;
const short HIGHEST_RAND = 20480;
// characters(33-126)
const short LOWEST_ASCII = 32;
const short HIGHEST_ASCII = 127;
// *pointers cant be constants
char* PAGE_TABLE_LOCATION = "./data/page_table.txt";
char* PHYSICAL_MEMORY_LOCATION = "./data/physical_memory.txt";
char* HARD_DRIVE_MEMORY_LOCATION = "./data/hard_drive_memory.txt";
#endif
<file_sep>#ifndef MYFUNCTIONSH
#define MYFUNCTIONSH
void my_swap_function(char*,char*);
void hey_printf_print_this(char*);
void free_that_memory(char*);
char* get_physical_memory(int);
char* get_page_table_memory(short);
short get_page_number(short, short, short);
short get_me_that_ascii(short,short);
void put_physical_memory(char* , char*, int);
void put_page_table(char*);
void put_hard_drive_memory_table(char*, char* , short,short,short);
short get_rand(short,short);
#endif
<file_sep># MemorySimulationandPaging
Application which simulates the structures and processes used by both an
Operating System and a Central Processing Unit to implement memory virtualization for a 16 bit virtual address space which
employs a page size of 256 bytes. The simulated system makes use of a single-level linear page table which is stored in
the system’s simulated physical memory
To compile the project type in terminal
: make
To clean
: make clean
To start
: make start
<file_sep>CFLAGS = -c -Wall
CC = gcc
DISTDIR= dist
DATADIR= data
LIBDIR = lib
OBJECTS= $(DISTDIR)/simulate.o\
$(DISTDIR)/myfunctions.o
link: $(OBJECTS)
$(CC) $? -o $(DISTDIR)/simulate
$(DISTDIR)/simulate.o: simulate.c
$(CC) $(CFLAGS) $? -o $(DISTDIR)/simulate.o
$(DISTDIR)/myfunctions.o: $(LIBDIR)/myfunctions.c
$(CC) $(CFLAGS) $? -o $(DISTDIR)/myfunctions.o
clean:
rm -rf ./$(DISTDIR) && mkdir ./$(DISTDIR) && rm -rf ./$(DATADIR) && mkdir ./$(DATADIR)
start:
./$(DISTDIR)/simulate
<file_sep>#include "lib/myfunctions.h"
#include "lib/consts.h"
#include <stdio.h>
int main(){
//https://www.quora.com/What-is-the-difference-between-char*-and-char
//https://www.geeksforgeeks.org/whats-difference-between-char-s-and-char-s-in-c/
char *physical_memory = get_physical_memory(TOTAL_MEMORY);
hey_printf_print_this("---allocating total memory---");
// hard_drive_memory = same as pte size ie (only 2 pages)
char *hard_drive_memory = get_page_table_memory(HARD_DRIVE_MEMORY);
hey_printf_print_this("---allocating hard drive memory---");
char *page_table = get_page_table_memory(PAGE_TABLE_ENTRY_SIZE);
// could make above func with 2 arguments to do this
//printf("---allocating page table entry size---%5hu\n", PAGE_TABLE_ENTRY_SIZE);
//get_rand(LOWEST_RAND,HIGHEST_RAND);
hey_printf_print_this("---randomness is in my drivers---");
put_physical_memory(PHYSICAL_MEMORY_LOCATION , physical_memory , TOTAL_MEMORY);
hey_printf_print_this("---creating your physical_memory.txt---");
put_page_table(PAGE_TABLE_LOCATION);
hey_printf_print_this("---creating your page_table.txt---");
put_hard_drive_memory_table(HARD_DRIVE_MEMORY_LOCATION, hard_drive_memory , HARD_DRIVE_MEMORY,LOWEST_ASCII,HIGHEST_ASCII);
free_that_memory(physical_memory);
hey_printf_print_this("---physical_memory freed---");
free_that_memory(hard_drive_memory);
hey_printf_print_this("---hard_drive_memory freed---");
free_that_memory(page_table);
hey_printf_print_this("---page_table memory freed");
return 0;
}
<file_sep>#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include "myfunctions.h"
void my_swap_function(char* physical_memory, char* hard_drive_memory){
short temp = *physical_memory;
*physical_memory = *hard_drive_memory;
*hard_drive_memory = temp;
}
void hey_printf_print_this(char* printable){
printf("%s\n",printable );
}
void free_that_memory(char* memory){
free(memory);
}
char* get_physical_memory(int total_memory){
char *physical_memory = malloc(total_memory);
return physical_memory;
}
char* get_page_table_memory (short page_table_size){
char *page_table = malloc(page_table_size);
return page_table;
}
short get_page_number(short value , short mask , short shift) {
//value & mask -> offset
return ((value & mask)>>shift);
}
short get_me_that_ascii(short low , short high){
return get_rand(low,high);
}
void put_physical_memory(char* location, char* physical_memory , int totalSize)
{
FILE *ppmfile;
ppmfile = fopen(location, "w");
fprintf(ppmfile, "Address \t|\t Frame \t|\t Content\n----------\t|\t------------\t|\t----------\n");
for(int x = 0; x < totalSize; ++x) //pass in Address Size
{
fprintf(ppmfile, "0x%x \t\t\t|\t %d\t\t\t\t\t|\t%c\n", x , x/256, get_me_that_ascii(32,127));
physical_memory++;
// printf("Function Value: %c\n", *physicalMemory);
}
fclose(ppmfile);
}
void put_page_table(char* location)
{
FILE *pptfile;
pptfile = fopen(location, "w");
fprintf(pptfile, "Page \t|\tPage Table Entry\n---------\t|\t-------------\n");
fclose(pptfile);
}
void put_hard_drive_memory_table(char* location, char* hard_drive_memory , short totalSize,short lowascii,short highascii){
FILE *phdmtfile;
phdmtfile = fopen(location, "w");
fprintf(phdmtfile, "Page \t|\t Content \n");
for(short x = 0; x < totalSize; ++x) //pass in Address Size
{
fprintf(phdmtfile, "0x%x \t\t\t|\t %c\n", x , get_me_that_ascii(lowascii,highascii));
hard_drive_memory++;
}
fclose(phdmtfile);
}
//https://en.wikipedia.org/wiki//dev/random
//https://stackoverflow.com/questions/2572366/how-to-use-dev-random-or-urandom-in-c
// Using PRNG which is provided by UNIX
short get_rand(short low , short high){
//2049
low = low + 1 ;
// 20480 - 2049 = 18431
high = high - low ;
unsigned char buffer[4];
int fd = open("/dev/urandom", O_RDONLY);
read(fd, buffer, 4);
//buffer now contains the random data
close(fd);
// 4 * 4char is 32 bits , which is int
// type conversion - preserves accurate values passed , also helpful while dealing with void pointers
// deferencing , Accessing value of buffer
// https://www.youtube.com/watch?v=H4MQXBF6FN4&index=3&list=PLD28639E2FFC4B86A
unsigned int newbuffer = *(int *)&buffer;
//printf("%X\n",newbuffer);
srand(newbuffer);
// 0 + 2049 = 2049
// 18430 + 2049 = 20479
//printf("%d\n", rand() % high + low); //using new highs and lows to get values in between(boundary exclusive)
return rand() % high + low;
}
|
3c24b47010c0843f0f183a0178fc6d34ebd7e5ee
|
[
"Markdown",
"C",
"Makefile"
] | 6 |
C
|
AkshatJen/MemorySimulationandPaging
|
49c15cc7360ea6ede274dc0068f7abf49b1b7133
|
70d75694270888fd499b9dec1ff11ca4bc35c485
|
refs/heads/master
|
<file_sep>public class PeaceStop {
public static void main(String[] args) {
System.out.println("Peace.Stop");
}
}
|
7de881308fbb330ebb2a74eced31805acda9b741
|
[
"Java"
] | 1 |
Java
|
AdnanRumi/MavenProject
|
0d5928fc2f2cc581f0e690e0f26a017b6f5ed173
|
f6e4f920302b25987d79e3d70b22a01830f92a20
|
refs/heads/master
|
<repo_name>glorygithub/shiyanlou<file_sep>/louqa/qa/views.py
#! /usr/bin/env python
# encoding: utf-8
from flask import Blueprint, render_template
qa = Blueprint('qa',__name__,url_prefix='')
@qa.route('/<title>')
@qa.route('/',defaults={'title':None})
def index(title):
return render_template("qa/index.html",title=title,tem_str="world")
|
23736cfcaefcc0a5cf6882bb235e681730ba781d
|
[
"Python"
] | 1 |
Python
|
glorygithub/shiyanlou
|
1890aa51ce90e68044d5426b3b026c7cf2ad7203
|
26d0c52cb266c725eacc589d2b798641cd6a198c
|
refs/heads/master
|
<repo_name>springheeljack/Old-Project<file_sep>/TowerDefence/TowerDefence/Spawner.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TowerDefence
{
public class Spawner : Building
{
public static float spawnTime = 0.5f;
public bool ReadyToSpawn
{
get { return timer == 0.0f; }
}
float timer;
public Spawner(Tile t) : base(t)
{
Texture = Game.texSpawner;
ResetTimer();
}
public override void Update()
{
if (timer > 0.0f)
timer -= Game.frameTime;
if (timer < 0.0f)
timer = 0.0f;
}
public void ResetTimer()
{
timer = spawnTime;
}
}
}
<file_sep>/TowerDefence/TowerDefence/Creep.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TowerDefence
{
public class Creep
{
public static float Speed = 100.0f;
Texture2D texture;
Vector2 position;
Path path;
int tracePosition = 0;
public Creep(Vector2 position)
{
this.position = position;
texture = Game.texCreep;
path = new Path(new Node((int)position.X / 32, (int)position.Y / 32));
}
public void Update()
{
Node currentTrace = path.trace.ElementAt(tracePosition);
if (position.X < currentTrace.x * 32+16)
position.X += Game.frameTime * Speed;
if (position.X > currentTrace.x * 32 + 16)
position.X -= Game.frameTime * Speed;
if (position.Y < currentTrace.y * 32 + 16)
position.Y += Game.frameTime * Speed;
if (position.Y > currentTrace.y * 32 + 16)
position.Y -= Game.frameTime * Speed;
if (currentTrace.x * 32 + 16 > TLCorner.X && currentTrace.x * 32 + 16 < BRCorner.X && currentTrace.y * 32 + 16 > TLCorner.Y && currentTrace.y * 32 + 16 < BRCorner.Y)
{
tracePosition++;
if (tracePosition >= path.trace.Count)
tracePosition = 0;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, null, new Rectangle(position.ToPoint(), texture.Bounds.Size), null, new Vector2(texture.Bounds.Width/2), 0.0f, Vector2.One, Color.White, 0.0f);
}
public Vector2 TLCorner
{
get
{
return position - texture.Bounds.Size.ToVector2() / 2;
}
}
public Vector2 BRCorner
{
get
{
return position + texture.Bounds.Size.ToVector2() / 2;
}
}
}
}
<file_sep>/TowerDefence/TowerDefence/CreepManager.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TowerDefence
{
public class CreepManager
{
int maxCreeps = 10;
List<Creep> creeps = new List<Creep>();
public void SpawnCreep(Point position)
{
Creep newCreep = new Creep(position.ToVector2());
creeps.Add(newCreep);
}
public void Update()
{
foreach (Spawner s in Game.allSpawners)
{
if (s.ReadyToSpawn && creeps.Count < maxCreeps)
{
SpawnCreep(s.position);
s.ResetTimer();
}
}
foreach (Creep c in creeps)
c.Update();
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (Creep c in creeps)
c.Draw(spriteBatch);
}
}
}<file_sep>/TowerDefence/TowerDefence/Building.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TowerDefence
{
public abstract class Building
{
int health;
int maxHealth;
public Point position;
public virtual void Draw(SpriteBatch spriteBatch)
{
//spriteBatch.Draw(Texture, new Rectangle(position, Texture.Bounds.Size), Color.White);
spriteBatch.Draw(Texture, null, new Rectangle(position, Texture.Bounds.Size), null, new Vector2(Game.iTILE_SIZE_HALF), 0.0f, Vector2.One, Color.White, 0.0f);
}
public abstract void Update();
public Texture2D Texture;
public Tile Tile;
public Building(Tile t)
{
Tile = t;
}
}
}<file_sep>/TowerDefence/TowerDefence/Castle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
namespace TowerDefence
{
public class Castle : Building
{
public Castle(Tile t) : base(t)
{
Texture = Game.texCastle;
}
public override void Update()
{
throw new NotImplementedException();
}
}
}
<file_sep>/TowerDefence/TowerDefence/Tile.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TowerDefence
{
public enum Terrain
{
Grass,
Rock
}
public class Tile
{
int cost = 1;
public int Cost
{
get { return cost; }
set { cost = value; }
}
int x;
int y;
public int X { get { return x; } }
public int Y { get { return y; } }
Terrain terrain;
Building building;
public Building Building
{
get { return building; }
set { building = value; }
}
Texture2D texture;
public Tile(Texture2D texture,int X,int Y,Terrain terrain)
{
this.texture = texture;
x = X;
y = Y;
building = null;
this.terrain = terrain;
}
public void Draw(SpriteBatch spriteBatch, Point position)
{
spriteBatch.Draw(texture, new Rectangle(position, Game.pTILE_SIZE), Color.White);
if (building != null)
building.Draw(spriteBatch);
}
public bool IsPassable
{
get
{
return !(building is Tower) && terrain == Terrain.Grass;
}
}
}
}<file_sep>/TowerDefence/TowerDefence/Game.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
namespace TowerDefence
{
public class Game : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
//Constants
public const int iTILE_SIZE = 32;
public const int iTILE_SIZE_HALF = iTILE_SIZE / 2;
public static readonly Point pTILE_SIZE = new Point(iTILE_SIZE);
public const int iMAP_WIDTH = 40;
public const int iMAP_HEIGHT = 20;
public static float frameTime;
public static Tile[,] tiles = new Tile[iMAP_WIDTH, iMAP_HEIGHT];
List<Building> allBuildings = new List<Building>();
List<Tower> allTowers = new List<Tower>();
public static List<Spawner> allSpawners = new List<Spawner>();
public static Castle castle;
static CreepManager creepManager = new CreepManager();
public static Texture2D texTileGrass;
public static Texture2D texTileRock;
public static Texture2D texCastle;
public static Texture2D texTower, texTowerBarrel, texSpawner, texCreep;
public Game()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
graphics.PreferredBackBufferHeight = 720;
graphics.PreferredBackBufferWidth = 1280;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
texTileGrass = Content.Load<Texture2D>("Tile/Grass");
texTileRock = Content.Load<Texture2D>("Tile/Rock");
texCastle = Content.Load<Texture2D>("Building/Castle");
texTower = Content.Load<Texture2D>("Building/Tower");
texTowerBarrel = Content.Load<Texture2D>("Building/TowerBarrel");
texSpawner = Content.Load<Texture2D>("Building/Spawner");
texCreep = Content.Load<Texture2D>("Creep/Creep");
LoadMap("test.tdmap");
CreateBuilding(new Tower(tiles[3, 3]));
CreateBuilding(new Tower(tiles[2, 3]));
CreateBuilding(new Tower(tiles[1, 3]));
for (int i = 3; i < 17; i++)
CreateBuilding(new Tower(tiles[i, 6]));
CreateBuilding(new Castle(tiles[5, 5]));
CreateBuilding(new Spawner(tiles[15, 15]));
//CreateBuilding(new Spawner(tiles[15, 14]));
//CreateBuilding(new Spawner(tiles[15, 13]));
//CreateBuilding(new Spawner(tiles[6, 5]));
//CreateBuilding(new Spawner(tiles[4, 3]));
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
frameTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
foreach (Spawner s in allSpawners)
s.Update();
creepManager.Update();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
for (int x = 0; x < iMAP_WIDTH; x++)
for (int y = 0; y < iMAP_HEIGHT; y++)
tiles[x, y].Draw(spriteBatch, new Point(x * iTILE_SIZE, y * iTILE_SIZE));
creepManager.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
void LoadMap(string path)
{
string fileText = System.IO.File.ReadAllText("Map/" + path);
string cleanedFileText = "";
foreach (char c in fileText)
if (!char.IsControl(c))
cleanedFileText += c;
fileText = cleanedFileText;
int count = 0;
Texture2D texture;
Terrain terrain;
foreach (char c in fileText)
{
if (c == '0')
{
texture = texTileGrass;
terrain = Terrain.Grass;
}
else
{
texture = texTileRock;
terrain = Terrain.Rock;
}
tiles[count % iMAP_WIDTH, count / iMAP_WIDTH] = new Tile(texture, count % iMAP_WIDTH, count / iMAP_WIDTH, terrain);
count++;
}
}
void CreateBuilding(Building building)
{
building.position = new Point(building.Tile.X * iTILE_SIZE + iTILE_SIZE_HALF, building.Tile.Y * iTILE_SIZE + iTILE_SIZE_HALF);
tiles[building.Tile.X, building.Tile.Y].Building = building;
allBuildings.Add(building);
if (building is Tower)
allTowers.Add(building as Tower);
else if (building is Spawner)
allSpawners.Add(building as Spawner);
else if (building is Castle)
{
if (castle != null)
throw new Exception("Only one castle can exist at once.");
castle = building as Castle;
}
}
}
}<file_sep>/README.md
# Year-3-Project<file_sep>/TowerDefence/TowerDefence/Tower.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TowerDefence
{
public class Tower : Building
{
public float rotation = 0.0f;
public Texture2D barrelTexture;
public Tower(Tile t) : base(t)
{
Texture = Game.texTower;
barrelTexture = Game.texTowerBarrel;
}
public override void Update()
{
throw new NotImplementedException();
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
spriteBatch.Draw(barrelTexture, null, new Rectangle(position, barrelTexture.Bounds.Size), null, new Vector2(Game.iTILE_SIZE_HALF), rotation, Vector2.One, Color.White, 0.0f);
}
}
}
|
1fb0ac6ee5f02fe634769a1e4422c8a6ed55125b
|
[
"Markdown",
"C#"
] | 9 |
C#
|
springheeljack/Old-Project
|
7e1baa035efe18878aae31b4cf5e4c363129d162
|
de698e6d2702d65455cdecd59af7871f3321f852
|
refs/heads/main
|
<file_sep>/* eslint-disable no-return-assign */
import express from 'express';
import 'express-async-errors';
import { createTodo, getAllTodos, updateTodo } from '../../controllers/todo';
import middlewares from '../../middlewares';
const { validate, createTodoSchema, updateTodoSchema } = middlewares;
const todoRoutes = express();
todoRoutes.get('/all', getAllTodos);
todoRoutes.post('/', validate(createTodoSchema), createTodo);
todoRoutes.patch('/update/:id', validate(updateTodoSchema), updateTodo);
export default todoRoutes;
<file_sep>/**
* @Module UserController
* @description Controlls all the user based activity
*/
/**
* @static
* @description Returns message based on the status
* @param {Object} res - Response object
* @param {Number} status - Appropraite error status
* @param {String} error - The appropriate error message
* @returns {Object} res object to report approprate error
* @memberof Utilites
*/
export function errorStat(res, status, error) {
return res.status(status).json({ status, error });
}
/**
* @static
* @description Returns message based on the status
* @param {Object} res - Response object
* @param {integer} status - status code to be sent
* @param {String} key - the output data key
* @param {Object} value - the output data values
* @returns {Object} res object to report the appropraite message
* @memberof Utilities
*/
export function successStat(res, status, key, value) {
return res.status(status).json({ status, [key]: value });
}
/**
* @static
* @description Returns message based on the status
* @param {Object} res - Response object
* @param {Object} req - Request object
* @param {Object} object - object to be validated
* @param {Object} schema - The schema object
* @param {Functon} next - The next function
* @returns {Object} res object to report the appropraite message
* @memberof Utilities
*/
export function validateJoi(object, schema, req, res, next, name) {
const { error, value } = schema.validate(object, { abortEarly: false });
if (error) {
return errorStat(
res,
400,
error.details.map((detail) => {
const message = detail.message.replace(/"/gi, '');
return message;
})
);
}
req.body.validated = value;
return next();
}
<file_sep>/* eslint-disable newline-per-chained-call */
import Joi from '@hapi/joi';
export const createTodoSchema = Joi.object().keys({
title: Joi.string().required(),
description: Joi.string(),
completed: Joi.boolean(),
});
export const updateTodoSchema = Joi.object({
id: Joi.string().uuid(),
completed: Joi.boolean(),
});
<file_sep>'use strict';
module.exports = (sequelize, DataTypes) => {
const Todos = sequelize.define(
'Todos',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: DataTypes.STRING,
description: DataTypes.TEXT,
completed: DataTypes.BOOLEAN,
},
{}
);
Todos.associate = function (models) {
// associations can be defined here
};
return Todos;
};
<file_sep>import models from '../database/models';
import helpers from '../helpers';
// const userRepository = new dbRepository(models.User);
const { successStat, errorStat } = helpers;
/**
* / @static
* @description Allows a user to create a todo
* @param {Object} req - Request object
* @param {Object} res - Response object
* @returns {Object} object containing user created todo
* @memberof TodoController
*/
export const createTodo = async (req, res) => {
const todo = await models.Todos.create({
...req.body.validated,
});
return successStat(res, 201, 'data', todo);
};
/**
* / @static
* @description Allows a user to getAll Todos
* @param {Object} req - Request object
* @param {Object} res - Response object
* @returns {Object} object containing user created todo
* @memberof TodoController
*/
export const getAllTodos = async (req, res) => {
const todos = await models.Todos.findAll();
return successStat(res, 201, 'data', todos);
};
/**
* / @static
* @description Allows a user to update Todos
* @param {Object} req - Request object
* @param {Object} res - Response object
* @returns {Object} object containing user created todo
* @memberof TodoController
*/
export const updateTodo = async (req, res) => {
const { id } = req.body.validated;
const todo = await models.Todos.findOne({
where: { id },
});
todo.update(req.body.validated);
return successStat(res, 201, 'data', todo);
};
<file_sep>import { errorStat, successStat, validateJoi } from './Utilities';
export default {
errorStat,
successStat,
validateJoi,
};
<file_sep>import express from 'express';
import 'express-async-errors';
import cookieParser from 'cookie-parser';
import logger from 'morgan';
import chalk from 'chalk';
import cors from 'cors';
import { config } from 'dotenv';
import path from 'path';
import Routes from './routes/v1';
import db from './database/models';
config();
const app = express();
app.use(cors());
app.use(cookieParser());
app.use(logger('dev'));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '../site/build')));
app.get('/api/v1', (req, res) =>
res.status(200).json({
message: 'Welcome to the Todos App',
})
);
// Routes(app);
app.use('/api/v1', Routes);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../site/build', 'index.html'));
});
// to catch a 404 and send to error handler
app.use((req, res) =>
res.status(404).json({
status: 404,
error: `Route ${req.url} Not found`,
})
);
const { sequelize } = db;
sequelize
.authenticate()
.then(() => {
console.log('Sequelize connection was successful');
})
.catch((err) => {
console.log(chalk.yellow(err.message));
});
// app error handler, to handle sync and asyc errors
app.use((err, req, res, next) => {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
if (res.headersSent) return next(err);
console.log(err);
return res.status(err.status || 500).json({
status: res.statusCode,
error: err.message,
});
});
export default app;
<file_sep>import React, { useContext, useState, useEffect } from 'react';
import TodoDetails from './TodoDetails';
import { TodoContext } from '../contexts/TodoContext';
import { axiosInstance } from '../helpers';
import loader from '../assets/loader.gif';
const TodoList = () => {
const { todos, dispatch } = useContext(TodoContext);
const [loading, setloading] = useState(!todos);
useEffect(() => {
const getAllTodos = async () => {
const todos = await axiosInstance.get('/todos/all');
dispatch({ type: 'GET_ALL_TODOS', todos: todos.data.data });
setloading(false);
};
if (loading) {
getAllTodos();
}
}, [todos, dispatch, loading]);
if (!todos) {
return (
<div className="todo-list">
<div className="loading">
<img src={loader} alt="loading" />
</div>
</div>
);
}
return (
<div className="todo-list">
{todos.length ? (
<ul>
{todos.map((todo) => {
return <TodoDetails todo={todo} key={todo.id} />;
})}
</ul>
) : (
<div className="todo-list empty">
No todos yet, use the form to create your first todo
</div>
)}
</div>
);
};
export default TodoList;
<file_sep>import React, { useContext } from 'react';
import { TodoContext } from '../contexts/TodoContext';
const Navbar = () => {
const { todos } = useContext(TodoContext);
const itemLength = todos?.reduce((acc, cur) => {
if (!cur.completed) {
return acc + 1;
}
return acc;
}, 0);
return (
<div className="navbar">
<h1>My Todo List</h1>
<p>
Currently you have {itemLength ? itemLength : 'no'} todo
{itemLength < 1 ? 's' : ''} to get through...
</p>
</div>
);
};
export default Navbar;
<file_sep>import axios from 'axios';
const patterns = {
title: /^[^\n]{2,30}$/,
dscription: /^[^\n]{2,255}$/,
};
export const validate = (field, Regex) => {
if (patterns[Regex].test(field)) return true;
return false;
};
export const validateInput = (event) =>
validate(event.target.value, event.target.attributes.name.value);
const baseurl =
process.env.NODE_ENV === 'development' ? 'http://localhost:4000' : '';
export const axiosInstance = axios.create({
baseURL: `${baseurl}/api/v1`,
headers: {
'Access-Control-Allow-Headers':
'Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type',
'Access-Control-Allow-Origin': '*',
},
});
<file_sep>export const todoReducer = (state, action) => {
switch (action.type) {
case 'GET_ALL_TODOS':
return action.todos;
case 'ADD_TODO':
return [...state, action.todo];
case 'MARK_TODO':
return state.map((todo) => {
if (todo.id === action.todo.id) {
return { ...todo, completed: action.todo.completed };
}
return todo;
});
default:
return state;
}
};
<file_sep># useage
- uncomment the .env.sample
- Provide a postgres url as shown
- run npm install && cd site && npm install
- run mpn run build
- run npm start
# Things I could do better
- Implement better validation on frontend (Although I validated in the backend)
- Make the page responsive
- Wrote more test
- Taken more time in the assessment
- I am still trying to integrate typescript, I didnt because I felt it will slow me down, given my proficiency, I've started learning though. Hopefully that won't be a problem.
## Some design decisons
- I decided to use react context api, its a bit faster
- I decided to have both the form and the List on the same page, I think it looks better
<file_sep># Finoa - Frontend Engineer - Offline Coding Exercise
Using TypeScript and a frontend development framework of your choice,
for example Angular, Vue, or React, please build a simple todo
application that can be accessed and used in the browser. We do not
expect a super fancy, feature-loaded application, but would like to
get to know your way of structuring a project and implementing the
necessary code. Every detail not specified in the requirements below
is up to you. Please **do not** spend more than **two hours** on this
task and feel free to also hand in your work in progress if you did
not finish the complete task on time.
## Specific requirements:
The todo application shall consist out of a single view and be
implemented as a single page application, background requests are
preferred over page reloads. Within the view, there should be a list
of all currently existing todo tasks and an easy interface to add a
new todo task, i.e., two input fields to add a name as well as
description for a new task and a button to save the new task. Besides
adding a new task, one should be able to tick existing tasks, such
that the application marks these tasks as done. Please make your todo
application persistent across page reloads by adding a basic API
endpoint which can store a new task and return all
available tasks. Finally, please add at least one unit test and one
integration test which can be run automatically, indicating how you
would test your work.
## Additional requirements:
If you have the time and the ideas, feel free to add comments to
your code explaining your design decisions with respect to the
application's structure, concept and design. For example, why
something is built as a reusable component, how one could extend the
application with further features, what are advantages and
disadvantages of your decisions, etc.. If you want, you can add stubs
for features one could add but you did not implement, e.g. a menu bar
containing a profile image or something like this.
## What will be evaluated:
1. clean and understandable code,
2. overall structure and concept of the application,
3. maintainability and test-ability of the code,
4. extend-ability of the application with further features and
5. overall familiarity with the coding language and ecosystem.
## How to submit:
Please send a link to a git repository containing your code or a
zip-archive containing your repository, including the `.git`
directory.
<file_sep>import express from 'express';
import 'express-async-errors';
import todos from './todos';
const router = express.Router();
router.use('/todos', todos);
export default router;
<file_sep>import chalk from 'chalk';
import http from 'http';
import { config } from 'dotenv';
import app from './server';
config();
const { PORT } = process.env;
const port = PORT || 4000;
const server = http.createServer(app);
server.listen(port, () => {
console.log(`Server is running on port ${chalk.yellow(port)}`);
});
export default { app };
<file_sep>import validate from './validators';
import { createTodoSchema, updateTodoSchema } from './validators/schemas/todos';
export default {
validate,
createTodoSchema,
updateTodoSchema,
};
<file_sep>import React, { useContext, useState } from 'react';
import { useToasts } from 'react-toast-notifications';
import { TodoContext } from '../contexts/TodoContext';
import { axiosInstance } from '../helpers';
import loader from '../assets/loader.gif';
const NewBookForm = () => {
const { dispatch } = useContext(TodoContext);
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [loading, setLoading] = useState();
const { addToast } = useToasts();
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
try {
const todo = await axiosInstance.post(`/todos`, { title, description });
dispatch({ type: 'ADD_TODO', todo: todo.data.data });
setTitle('');
setDescription('');
addToast('😉 Successfully Added', {
appearance: 'success',
autoDismiss: true,
});
} catch (err) {
addToast(err.message, {
appearance: 'error',
autoDismiss: true,
});
}
setLoading(false);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Todo"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
<input
type="text"
placeholder="Descrition"
value={description}
onChange={(e) => setDescription(e.target.value)}
required
/>
<button type="submit" className="btn">
<span>Add Todo</span>
{loading && (
<span className="btn-loader">
<img src={loader} alt="loading" />
</span>
)}
</button>
</form>
);
};
export default NewBookForm;
|
644b0bc9c0b4ac23a89e767209e97f0c026aff1a
|
[
"JavaScript",
"Markdown"
] | 17 |
JavaScript
|
cvjude/Todo_App
|
47915c3c4a954a093108135e8680fab05341ba96
|
38d2ab6b8e13e86e4b1b7ac022b7abdb031fc631
|
refs/heads/master
|
<file_sep>#!/bin/bash
## Simple install script
symlinks=()
install_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
ignore_files=('install.sh' 'README.md')
for commit_file in *
do
# Don't do ignore_files
if [[ " ${ignore_files[@]} " =~ " ${commit_file} " ]]
then
continue
fi
dotfile="${HOME}/.${commit_file}"
if [[ ! -L ${dotfile} ]]
then
# Backup if real file
if [ -e ${dotfile} ]
then
mv "${dotfile}" "${dotfile}.backup"
echo "Backed up ${dotfile} to ${dotfile}.backup"
fi
# Symlink if it doesn't exist
ln -s "${install_dir}/${commit_file}" "${dotfile}"
echo "Created symlink ${dotfile} -> ${install_dir}/${commit_file}"
fi
done
exit 0
|
bba1719be41b93bed15eb83e9cbf7d73269063c4
|
[
"Shell"
] | 1 |
Shell
|
christopher-alabada/dotfiles
|
7cc670f6d2dc55daac28e919efed2fb95b7b2778
|
51e09ee8733e899a81d5c4283ed677626fede351
|
refs/heads/master
|
<file_sep>struct node { int i; struct node *next; };
void print_list(struct node * a);
struct node * insert_front(struct node * a, int n);
struct node * remove_node(struct node * front, int data);
struct node * free_list(struct node * a);
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "header.h"
int main() {
struct node * A = NULL;
// printing empty list (print_list)
printf("Printing empty list...\n");
printf("Result: ");
print_list(A);
printf("\nAdding items to list...\n");
// adding nodes to front of list (insert_front)
A = insert_front(A, 9);
A = insert_front(A, 99);
A = insert_front(A, 999);
A = insert_front(A, 8);
A = insert_front(A, 88);
A = insert_front(A, 888);
A = insert_front(A, 808);
// printing list after adding nodes
printf("Result: ");
print_list(A);
// testing out removing first node
printf("\nRemoving node containing 808 from the list...\n");
A = remove_node(A, 808);
printf("Result: ");
print_list(A);
// testing out removing middle node
printf("\nRemoving node containing 99 from the list...\n");
A = remove_node(A, 99);
printf("Result: ");
print_list(A);
// testing out removing last node
printf("\nRemoving node containing 9 from the list...\n");
A = remove_node(A, 9);
printf("Result: ");
print_list(A);
// testing out remvoing node whose target does not exist
printf("\nRemoving node containing 2000 from the list...\n");
A = remove_node(A, 2000);
printf("Result: ");
print_list(A);
printf("\nFreeing list...\n");
A = free_list(A);
printf("Result: ");
print_list(A);
return 0;
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "header.h"
/* --- INSTRUCTIONS ---
void print_list(struct node *);
Should take a pointer to a node struct and print out all of the data in the list
struct node * insert_front(struct node *, int);
Should take a pointer to the existing list and the data to be added, create a new node and put it at the beginning of the list.
The second argument should match whatever data you contain in your nodes.
Returns a pointer to the beginning of the list.
struct node * free_list(struct node *);
Should take a pointer to a list as a parameter and then go through the entire list freeing each node and return a pointer to the beginning of the list (which should be NULL by then).
struct node * remove_node(struct node *front, int data);
Remove the node containing data from the list pointed to by front.
If data is not in the list, nothing is changed.
Returns a pointer to the beginning of the list.
Your list functions should be in a .c/.h library, with a separate .c file used for testing.
--- INSTRUCTIONS --- */
void print_list(struct node * a) {
// starting list on open bracket
printf("[ ");
while (a != NULL) {
// prints integer stored in node
printf("%d ", a->i);
// sets to next node
a = a->next;
}
// ends list on closed bracket
printf("]\n");
}
struct node * insert_front(struct node * a, int n) {
// allocate space for new node
struct node * new = malloc(sizeof(struct node));
// store provided integer in node
new->i = n;
// appends new node to front of linked list
new->next = a;
// return pointer of front
return new;
}
struct node * remove_node(struct node * front, int data) {
// checking to see if front has target data
if (front->i == data) {
struct node * front2 = front->next;
free(front);
front = NULL;
return front2; }
// cycling through linked list, looking for node w/ matching data
struct node * a = front;
// checking to make sure both current and next are NOT null
while (a != NULL && a->next != NULL) {
// checking to see if next data is equal to target
if (a->next->i == data) {
// creating node pointing to the node after the soon-to-be deleted node
struct node * newNext = a->next->next;
// creating node pointing to node being deleted
struct node * oldNext = a->next;
a->next = newNext;
// freeing allocated space for node being deleted
free(oldNext);
oldNext = NULL;
return front;
}
// iterating to next node
a = a->next;
}
// this return only occurs when a) the list is empty, or b) when the entire list has been searched
return front;
}
struct node * free_list(struct node * a) {
// iterating through list
while (a != NULL) {
// printing while freeing as shown in example
printf("Freeing %d\n", a->i);
struct node * old = a;
// moving to next
a = a->next;
// freeing allocated space for node being deleted
free(old);
old = NULL;
}
return a;
}
|
19e0ad9866918106f974791ac3597f969e4d3b79
|
[
"C"
] | 3 |
C
|
ahmedksultan/list
|
610e245e1cff4e85a1f01be1bddcbfee4e88448f
|
b72cf59531dafba783789e1be263e8492c2ef6cd
|
refs/heads/master
|
<repo_name>sksundaram-learning/kafka-sparkstreaming-cassandra-swarm<file_sep>/cluster-management/start-cluster-local.sh
#Create master node (named master)
export MASTER_MACHINE_NAME=master
docker-machine create --driver virtualbox $MASTER_MACHINE_NAME
# Make the node the Swarm master, and gives it master label
export MASTER_IP=$(docker-machine ip $MASTER_MACHINE_NAME)
docker-machine ssh $MASTER_MACHINE_NAME docker swarm init --advertise-addr $MASTER_IP
docker-machine ssh $MASTER_MACHINE_NAME docker node update --label-add role=master master
# get token that we will use to add workers to the Swarm
export TOKEN=$(docker-machine ssh $MASTER_MACHINE_NAME docker swarm join-token worker -q)
#Create worker nodes (named them worker-x) and gives them worker label
export NUM_WORKERS=2
export WORKER_MACHINE_NAME=worker-
for INDEX in $(seq $NUM_WORKERS)
do
(
docker-machine create --driver virtualbox $WORKER_MACHINE_NAME$INDEX
docker-machine ssh $WORKER_MACHINE_NAME$INDEX docker swarm join --token $TOKEN $MASTER_IP:2377
docker-machine ssh $MASTER_MACHINE_NAME docker node update --label-add role=worker $WORKER_MACHINE_NAME$INDEX
) &
done
wait
#Create overlay network
docker-machine ssh $MASTER_MACHINE_NAME docker network create --attachable --driver overlay cluster-network
<file_sep>/README.md
## Scalable Kafka - Spark streaming - Cassandra pipeline in Docker Swarm
This repository provides a basis to
* Create clusters using docker-machine and Docker Swarm. We provide scripts to create clusters either locally using virtual machines, or on AWS (Amazon Web Services)
* Start Kafka, Spark cluster standalone, and Cassandra as Docker Swarm services
* Run an example demo using a Jupyter notebook connected to the cluster, where a Spark streaming application collects messages from Kafka and writes them to Cassandra

### Preliminary requirements
* Docker version 1.13.1 and docker-machine version 0.9.0
* Additionally:
* Virtual Box, in order to create virtual machines (VMs), and/or
* An account on AWS, in order to create AWS instances.
The scripts were tested using Mac OS 10.10.5 and Ubuntu 14.04, on a host (for VMs) with 16GB RAM and 2 CPUs.
### Create cluster
Use the scripts in [cluster-management](cluster-management):
* `start-cluster-local.sh` : Creates a cluster of virtual machines.
* `start-cluster-aws.sh` : Creates a cluster of AWS machines.
The scripts create a 3 node cluster (one master and two workers) per default. See the [cluster management README](cluster-management/README.md) for more details.
### Start services
Use the 'start all' script in the service-management folder to start all services
```
eval $(docker-machine env master)
start-all-services.sh
```
### Interact wih the cluster from a notebook
Connect to notebook demo container
```
docker run -it --network=cluster-network \
-p 8888:8888 -p 4040:4040 -p 23:22 \
yannael/notebook-demo bash
```
Create Cassandra database for demo script
```
cqlsh cassandra-seed -f init_cassandra.cql
```
Start notebook
```
notebook
```
Connect to masterIP:8888 in your browser (where masterIP is the IP of the master node of the cluster) to access the notebooks.
### Acknowledgments:
For providing base material to this repository
* [https://medium.com/@aoc/running-spark-on-docker-swarm-777b87b5aa3#.4ahmoqvsf](https://medium.com/@aoc/running-spark-on-docker-swarm-777b87b5aa3#.4ahmoqvsf)
* [https://github.com/big-data-europe](https://medium.com/@aoc/running-spark-on-docker-swarm-777b87b5aa3#.4ahmoqvsf)
For funding
* [BruFence: 'Scalable machine learning for automating defense system'](http://www.securit-brussels.be/project/brufence), a project funded by the Institute for the Encouragement of Scientific Research and Innovation of Brussels (INNOVIRIS, Brussels Region, Belgium)
<file_sep>/containers/base-os/Dockerfile
FROM centos:centos7
RUN yum -y update;
RUN yum -y clean all;
# Install basic tools
RUN yum install -y wget dialog curl sudo lsof vim axel telnet nano openssh-server openssh-clients bzip2 passwd tar bc git unzip net-tools
#Install Java
RUN yum install -y java-1.8.0-openjdk java-1.8.0-openjdk-devel
ENV JAVA_HOME /etc/alternatives/java_sdk
RUN echo root | passwd root --stdin
ENV HOME /root
WORKDIR $HOME
<file_sep>/cluster-management/stop-cluster.sh
docker-machine ls | grep "^master" | cut -d\ -f1 | xargs docker-machine stop
docker-machine ls | grep "^worker" | cut -d\ -f1 | xargs docker-machine stop
<file_sep>/service-management/stop-all-services.sh
docker service ls | grep "spark" | cut -d\ -f1 | xargs docker service rm
docker service rm kafka
docker service ls | grep "cassandra" | cut -d\ -f1 | xargs docker service rm
<file_sep>/containers/README.md
## Containers
* [base-os](base-os/README.md): base containers for the containers below. CentOS 7 + Java 1.8 + a few linux commonly used Linux packages
* [spark](spark/README.md): contains Spark 2.1.0 for Hadoop 2.6
* [kafka](kafka/README.md): Contains Kafka 0.10.1.1 for Scala 2.11
* [notebook-demo](notebook-demo/README.md): Contains Kafka Python and Jupyter, with demo notebooks.
All containers are available from Dockerhub
[https://hub.docker.com/u/yannael](https://hub.docker.com/u/yannael/)
<file_sep>/cluster-management/delete-cluster.sh
docker-machine ls | grep "^master" | cut -d\ -f1 | xargs docker-machine rm --force
docker-machine ls | grep "^worker" | cut -d\ -f1 | xargs docker-machine rm --force
<file_sep>/cluster-management/start-cluster-aws.sh
#Start master
export REGION=eu-west-1
export ZONE=c
export MASTER_TYPE=m3.medium
export AMI=ami-3ffca759 #Ubuntu 14.04 official
export DRIVER_OPTIONS="\
--driver amazonec2 \
--amazonec2-ami $AMI \
--amazonec2-security-group=default \
--amazonec2-zone $ZONE \
--amazonec2-region $REGION"
export MASTER_OPTIONS="$DRIVER_OPTIONS \
--amazonec2-instance-type=$MASTER_TYPE"
export MACHINE_NAME=master
docker-machine create $MASTER_OPTIONS $MACHINE_NAME
eval $(docker-machine env master)
# get private ip of the master machine, you need a jq utility json parser
export MASTER_IP=$(aws ec2 describe-instances --output json | jq -r ".Reservations[].Instances[] | select(.KeyName==\"$MACHINE_NAME\" and .State.Name==\"running\") | .PrivateIpAddress")
# init the Swarm master
docker-machine ssh $MACHINE_NAME sudo gpasswd -a ubuntu docker
docker-machine ssh $MACHINE_NAME sudo service docker restart
docker-machine ssh $MACHINE_NAME docker swarm init --advertise-addr $MASTER_IP
docker-machine ssh $MACHINE_NAME docker node update --label-add role=master $MACHINE_NAME
# get token that we will use to add workers to the Swarm
export TOKEN=$(docker-machine ssh $MACHINE_NAME sudo docker swarm join-token worker -q)
#Start workers
export WORKER_TYPE=m3.medium
export SPOT_PRICE=0.067
export NUM_WORKERS=2
export WORKER_OPTIONS="$DRIVER_OPTIONS \
--amazonec2-request-spot-instance \
--amazonec2-spot-price=$SPOT_PRICE \
--amazonec2-instance-type=$WORKER_TYPE"
export MACHINE_NAME=worker-
for INDEX in $(seq $NUM_WORKERS)
do
(
docker-machine create $WORKER_OPTIONS $MACHINE_NAME$INDEX
docker-machine ssh $MACHINE_NAME$INDEX sudo gpasswd -a ubuntu docker
docker-machine ssh $MACHINE_NAME$INDEX sudo service docker restart
docker-machine ssh $MACHINE_NAME$INDEX docker swarm join --token $TOKEN $MASTER_IP:2377
docker-machine ssh master docker node update --label-add role=worker $MACHINE_NAME$INDEX
) &
done
wait
#Create overlay network
docker-machine ssh master docker network create --attachable --driver overlay cluster-network
<file_sep>/containers/spark/Dockerfile
FROM yannael/base-os
#Install Anaconda Python distribution
#RUN wget https://repo.continuum.io/archive/Anaconda3-4.2.0-Linux-x86_64.sh
#RUN bash Anaconda3-4.2.0-Linux-x86_64.sh -b
#ENV PATH $HOME/anaconda3/bin:$PATH
# Fix the value of PYTHONHASHSEED
# Note: this is needed when you use Python 3.3 or greater
#ENV PYTHONHASHSEED 1
RUN wget http://d3kbcqa49mib13.cloudfront.net/spark-2.1.0-bin-hadoop2.6.tgz \
&& tar -xvzf spark-2.1.0-bin-hadoop2.6.tgz \
&& mv spark-2.1.0-bin-hadoop2.6 spark \
&& rm spark-2.1.0-bin-hadoop2.6.tgz
ENV SPARK_HOME $HOME/spark
ENV PYTHONPATH $SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-0.10.4-src.zip:$PYTHON_PATH
ENV PATH $SPARK_HOME/bin:$SPARK_HOME/sbin:$PATH
#ENV PYSPARK_PYTHON=$HOME/anaconda3/bin/python
<file_sep>/cluster-management/README.md
## Cluster management
Two scripts are provided, to create a cluster of 3 nodes either locally, with virtual machines, or on AWS. The scripts require either VirtualBox to be installed (VMs), or to have an account on Amazon (AWS).
See
* [https://www.virtualbox.org/wiki/Downloads](https://www.virtualbox.org/wiki/Downloads) for VirtualBox installation
* [https://aws.amazon.com/getting-started/](https://aws.amazon.com/getting-started/) to get started with AWS.
The scripts mostly follow instructions given on the [https://docs.docker.com/engine/swarm/swarm-tutorial/](Docker Swarm tutorial), to create a manager node and two worker nodes, and from [this blog post](https://medium.com/@aoc/running-spark-on-docker-swarm-777b87b5aa3#.4ahmoqvsf) for creating an AWS docker cluster
The master node is first created, and its swarm token tag retrieved. Worker nodes are then created and connected to the master node through the token tag.
### Creation of a cluster of local virtual machines
Use
```
start-cluster-local.sh
```
to start the cluster. It takes about 5 minutes.
### Creation of a cluster of AWS instances
Note: Your account on Amazon must be created, your credentials stored in ~/.aws/credentials. See for example [there](https://gist.github.com/ghoranyi/f2970d6ab2408a8a37dbe8d42af4f0a5) for details.
Use
```
start-cluster-aws.sh
```
to start the cluster. It takes about 15 minutes.
<file_sep>/containers/kafka/README.md
## Kafka
Container with Kafka_2.11-0.10.1.1
Built with
```
docker build -t yannael/kafka .
```
Available on Dockerhub at https://hub.docker.com/r/yannael/kafka/
```
docker pull yannael/kafka
```
Size: 973MB.
<file_sep>/service-management/start-kafka-service.sh
#Service kafka: one instance, used for Kafka server
docker service create \
--name kafka \
--constraint node.hostname==master \
--replicas 1 \
--network cluster-network \
yannael/kafka \
/usr/bin/startup_script.sh
<file_sep>/containers/notebook-demo/Dockerfile
FROM yannael/spark
RUN yum install -y gcc python-devel
#Instal pip
RUN curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
RUN python get-pip.py
#Install Kafka client for Python
RUN pip install kafka-python
#Install Cassandra
ADD datastax.repo /etc/yum.repos.d/datastax.repo
RUN yum install -y datastax-ddc
#Install Jupyter
RUN pip install jupyter
#Add notebooks and script to create demo Cassandra table
ADD notebooks /root/notebooks
ADD init_cassandra.cql /root/init_cassandra.cql
#Makes alias to start notebook more easily
RUN echo "alias notebook=\"jupyter notebook --ip=* --NotebookApp.open_browser=False --NotebookApp.token=''\"" >> /root/.bashrc
<file_sep>/service-management/README.md
## Service management
This directory contains scripts to start Kakfa, Spark and Cassandra services.
* `start-kafka-service.sh` : Starts a service running a Zookeeper server and a Kafka server, with one replica constrained tu run on the master node.
* `start-spark-services.sh` : Starts (i) a service running the master role for Spark standalone cluster, with one replica constrained tu run on the master node and (ii) a service running the worker roles for Spark standalone cluster, with two replicas constrained tu run on the worker nodes.
* `start-cassandra-services.sh` : Starts three services running the Cassandra, with one replica each, and constrained to run on each node (master, worker-1 and worker-2). The service running on the master node is configured to be the seed node for the Cassandra ring.
All services may be started or stopped using the `start-all-services.sh` and `stop-all-services.sh`, respectively.
See [How services work](https://docs.docker.com/engine/swarm/how-swarm-mode-works/services/) and [Docker service create](https://docs.docker.com/engine/reference/commandline/service_create/) on Docker website for further information on options available (such as limiting CPU and memory usage, sharing volumes, etc, ...).
<file_sep>/service-management/start-spark-services.sh
#Service Master: One instance, used for Spark standalone cluster master
eval $(docker-machine env master)
docker service create \
--name spark-master \
--replicas 1 \
--constraint node.hostname==master \
--network cluster-network \
-p 8080:8080 \
yannael/spark \
/root/spark/bin/spark-class org.apache.spark.deploy.master.Master --host 0.0.0.0
while [[ -z $(docker service ls |grep spark-master| grep 1/1) ]]; do
Echo Waiting for spark master service to start...
sleep 5
done;
#Service worker: $NUM_WORKERS instances, used for Spark standalone cluster workers
export NUM_WORKERS=2
docker service create \
--name spark-worker \
--constraint node.hostname!=master \
--replicas $NUM_WORKERS \
--network cluster-network \
yannael/spark \
/root/spark/bin/spark-class org.apache.spark.deploy.worker.Worker spark://spark-master:7077
<file_sep>/service-management/start-all-services.sh
./start-spark-services.sh
./start-kafka-service.sh
./start-cassandra-services.sh
<file_sep>/containers/kafka/Dockerfile
FROM yannael/base-os
#Install Kafka
RUN wget http://apache.belnet.be/kafka/0.10.1.1/kafka_2.11-0.10.1.1.tgz
RUN tar xvzf kafka_2.11-0.10.1.1.tgz
RUN mv kafka_2.11-0.10.1.1 kafka
ENV PATH $HOME/kafka/bin:$PATH
#Startup (start SSH, Kafka)
ADD startup_script.sh /usr/bin/startup_script.sh
RUN chmod +x /usr/bin/startup_script.sh
<file_sep>/containers/spark/README.md
## Spark
Container with Spark 2.1.0 for Hadoop 2.6 and Anaconda 3-4.2.0 (Python 3.5)
Built with
```
docker build -t yannael/spark .
```
Available on Dockerhub at https://hub.docker.com/r/yannael/spark/
```
docker pull yannael/spark
```
Size: 3.368GB.
<file_sep>/containers/kafka/startup_script.sh
#!/bin/bash
$HOME/kafka/bin/zookeeper-server-start.sh $HOME/kafka/config/zookeeper.properties > $HOME/zookeeper.log 2>&1 &
$HOME/kafka/bin/kafka-server-start.sh $HOME/kafka/config/server.properties > $HOME/kafka.log 2>&1
<file_sep>/service-management/start-cassandra-services.sh
docker service create \
--name cassandra-seed \
--constraint node.hostname==master \
--network cluster-network \
cassandra:3.9
#Need to sleep a bit so IP can be retrieved below
while [[ -z $(docker service ls |grep cassandra-seed| grep 1/1) ]]; do
Echo Waiting for Cassandra seed service to start...
sleep 5
done;
export CASSANDRA_SEED=`docker-machine ssh master \
"docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' \
$(docker ps |grep cassandra|cut -d ' ' -f 1)"`
docker service create \
--name cassandra-node1 \
--constraint node.hostname==worker-1 \
--network cluster-network \
--env CASSANDRA_SEEDS=$CASSANDRA_SEED \
cassandra:3.9
docker service create \
--name cassandra-node2 \
--constraint node.hostname==worker-2 \
--network cluster-network \
--env CASSANDRA_SEEDS=$CASSANDRA_SEED \
cassandra:3.9
<file_sep>/containers/base-os/README.md
## base-os
The container is a basis for all other containers. It is a centos7 container to which were added
* Java 1.8
* Some basic packages which I find useful (nano, nettools, ssh, ...)
* a password for root user
Built with
```
docker build -t yannael/base-os .
```
Available on Dockerhub at https://hub.docker.com/r/yannael/base-os/
```
docker pull yannael/base-os
```
Size: 863MB.
|
cfd3e0bc26d923dee0dbc167b88f56aae510ca6b
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 21 |
Shell
|
sksundaram-learning/kafka-sparkstreaming-cassandra-swarm
|
259dfc4641b20481c059bb76954a2c04603af194
|
d90854d85009a3fe785ef78eb07508fc9f5459e4
|
refs/heads/master
|
<repo_name>mizutake/pacridon<file_sep>/sql/user_followings.sql
DROP TABLE IF EXISTS `user_followings`;
CREATE TABLE `user_followings`(
`id` INT(11) AUTO_INCREMENT NOT NULL PRIMARY KEY,
`user_id`INT(11) NOT NULL,
UNIQUE `userID`(`user_id`),
`target_id`INT(11) NOT NULL,
UNIQUE `targetID`(`target_id`)
);<file_sep>/src/models/user_followings.js
class user_followings extends Record {
static tableName() {
return "user_followings";
}
static columns() {
return ["user_id", "target_id"]
}
static create(UserFollowing){
return new this({user_id: res.locals.currentUser, target_id:req.params.id}).save();
}
}
module.exports = user_followings;<file_sep>/memo.md
# やろうとしていること
- 日時表示
- 編集可能にする
- 編集時の日時追加 (tootした時のを上書き保存せずに表示する)
- Alldelete可能にする
- 画像投稿
# 理由
- 日時表示
- 編集可能にする
- 編集時の日時追加
ここまではなんとか自分でもできそうだなと
思ったから
- Alldelete可能にする
は、色々とtootをしていたらものすごい量になって一個ずつでは無く一気に消せたら楽だろうと思ったから
- 画像投稿 は、あまりできるきがしないので余裕があったらやりたい
# 今後やってみたいこと
- 他のsnsのtimelineを持ってくるをできるきがあまりしないけどやってみたい
<file_sep>/src/routes/api/followings.js
const UserFollowing = require('../../models/user_following');
module.exports = function (app) {
app.post('/api/followings/:target_id', function(req, res) {
if (!res.locals.currentUser) {
res.status(401).json({ "error": "Unauthorized" });
return;
}
let following = new UserFollowings({user_id: res.locals.currentUser, target_id:req.params.id})
// following.save()
// .then((following) => {
// res.json({ following: following.data });
// }).catch((err) => {
// res.status(500).json({ error: err.toString() })
// });
following.create(res.locals.currentUser, req.params.id).then((following) => {
res.json({ following: following.data });
}).catch((err) => {
res.status(500).json({ error: err.toString() })
});
});
};
|
22b8fdcb473487197f1cbb92700eee96e46eda69
|
[
"JavaScript",
"SQL",
"Markdown"
] | 4 |
SQL
|
mizutake/pacridon
|
708e339090f3cef07075b3980a465d24eae6cbac
|
ff4ce89e439d5ef573eee131928b3813278ead85
|
refs/heads/master
|
<file_sep>package com.jlxc.app.base.manager;
import android.database.Cursor;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.utils.LogUtils;
/**
* 用户Manager
*/
public class UserManager {
private UserModel user;
private static UserManager userManager;
public synchronized static UserManager getInstance() {
if (userManager == null) {
userManager = new UserManager();
userManager.user = new UserModel();
}
return userManager;
}
private UserManager() {
}
public UserModel getUser() {
if (null == user.getUsername() && null == user.getLogin_token()) {
find();
}
return user;
}
public void setUser(UserModel user) {
this.user = user;
}
//本地持久化
public void saveAndUpdate() {
clear();
String sql = "insert into jlxc_user (id,username,name,helloha_id,sex,phone_num,school,school_code,head_image,head_sub_image,age,birthday,city,sign,background_image,login_token,im_token,iosdevice_token) " +
"values ('"+user.getUid()+"', '"+user.getUsername()+"', '"+user.getName()+"', '"+user.getHelloha_id()+"'," +
" '"+user.getSex()+"', '"+user.getPhone_num()+"', '"+user.getSchool()+"', '"+user.getSchool_code()+"'" +
", '"+user.getHead_image()+"', '"+user.getHead_sub_image()+"', '"+user.getAge()+"', '"+user.getBirthday()+"'" +
", '"+user.getCity()+"', '"+user.getSign()+"', '"+user.getBackground_image()+"', '"+user.getLogin_token()+"', '"+user.getIm_token()+"', '')";
DBManager.getInstance().excute(sql);
}
//获取本地数据
public void find() {
String sql = "select * from jlxc_user Limit 1";
Cursor cursor = DBManager.getInstance().query(sql);
if (cursor.moveToNext()) {
UserModel userModel = new UserModel();
userModel.setUid(cursor.getInt(0));
userModel.setUsername(cursor.getString(1));
userModel.setName(cursor.getString(2));
userModel.setHelloha_id(cursor.getString(3));
userModel.setSex(cursor.getInt(4));
userModel.setPhone_num(cursor.getString(5));
userModel.setSchool(cursor.getString(6));
userModel.setSchool_code(cursor.getString(7));
userModel.setHead_image(cursor.getString(8));
userModel.setHead_sub_image(cursor.getString(9));
userModel.setAge(cursor.getInt(10));
userModel.setBirthday(cursor.getString(11));
userModel.setCity(cursor.getString(12));
userModel.setSign(cursor.getString(13));
userModel.setBackground_image(cursor.getString(14));
userModel.setLogin_token(cursor.getString(15));
userModel.setIm_token(cursor.getString(16));
setUser(userModel);
}
}
//清除本地数据
public void clear() {
String sql = "delete from jlxc_user";
DBManager.getInstance().excute(sql);
}
// public void setCurrLoginUser(Context context, User currLoginUser) {
// DbUtils db = DBManager.getInstance().getDB(context);
// User dbUser;
// try {
// if (null != currLoginUser) {
// dbUser = db.findFirst(User.class);
// if (null == dbUser) {
// db.save(currLoginUser);
// } else {
// db.update(currLoginUser);
// }
// }
// } catch (DbException e) {
// e.printStackTrace();
// }
// this.currLoginUser = currLoginUser;
// }
}
<file_sep>package com.jlxc.app.group.model;
import java.util.LinkedList;
import java.util.List;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.news.model.NewsModel;
import com.jlxc.app.personal.model.MyNewsListItemModel;
import com.jlxc.app.personal.model.MyNewsListItemModel.MyNewsBodyItem;
import com.jlxc.app.personal.model.MyNewsListItemModel.MyNewsOperateItem;
import com.jlxc.app.personal.model.MyNewsListItemModel.MyNewsTitleItem;
public class NewsToItemsModel {
// 将数据转换为动态item形式的数据
public static List<MyNewsListItemModel> newsToItem(
List<NewsModel> orgDataList) {
LinkedList<MyNewsListItemModel> itemList = new LinkedList<MyNewsListItemModel>();
for (NewsModel newsMd : orgDataList) {
itemList.add(createNewsTitle(newsMd, MyNewsListItemModel.NEWS_TITLE));
itemList.add(createBody(newsMd, MyNewsListItemModel.NEWS_BODY));
itemList.add(createOperate(newsMd, MyNewsListItemModel.NEWS_OPERATE));
}
return itemList;
}
// 提取新闻中的头部信息
private static MyNewsListItemModel createNewsTitle(NewsModel news, int Type) {
MyNewsTitleItem item = new MyNewsTitleItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setUserName(news.getUserName());
item.setSendTime(news.getSendTime());
item.setUserTag(news.getUserSchool());
item.setUserID(news.getUid());
item.setUserHeadImage(news.getUserHeadImage());
item.setUserSubHeadImage(news.getUserHeadSubImage());
} catch (Exception e) {
LogUtils.e("createNewsTitle error.");
}
return item;
}
// 提取新闻中的主体信息
private static MyNewsListItemModel createBody(NewsModel news, int Type) {
MyNewsBodyItem item = new MyNewsBodyItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setNewsContent(news.getNewsContent());
item.setImageNewsList(news.getImageNewsList());
item.setLocation(news.getLocation());
} catch (Exception e) {
LogUtils.e("createBody error.");
}
return (MyNewsListItemModel) item;
}
// 提取新闻中的操作信息
private static MyNewsListItemModel createOperate(NewsModel news, int Type) {
MyNewsOperateItem item = new MyNewsOperateItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setIsLike(news.getIsLike());
item.setReplyCount(news.getCommentQuantity());
item.setLikeCount(news.getLikeQuantity());
} catch (Exception e) {
LogUtils.e("createOperate error.");
}
return (MyNewsListItemModel) item;
}
}
<file_sep>package com.jlxc.app.personal.ui.activity;
import android.content.pm.PackageManager.NameNotFoundException;
import android.widget.TextView;
import com.jlxc.app.R;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.lidroid.xutils.view.annotation.ViewInject;
public class AboutUsActivity extends BaseActivityWithTopBar {
//版本tv
@ViewInject(R.id.version_text_view)
private TextView versionTextView;
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_about;
}
@Override
protected void setUpView() {
setBarText("关于");
try {
String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
versionTextView.setText(versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
<file_sep>package com.jlxc.app.group.model;
import java.io.Serializable;
//话题模型
public class GroupTopicModel implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
//话题ID
private int topic_id;
//话题名
private String topic_name;
//话题描述
private String topic_detail;
//话题封面原图
private String topic_cover_image;
//话题封面缩略图
private String topic_cover_sub_image;
//成员数量
private int member_count;
//新闻数量
private int news_count;
//未读数量
private int unread_news_count;
//最后一次刷新时间
private String last_refresh_date;
//是否有内容
private boolean has_news;
public int getTopic_id() {
return topic_id;
}
public void setTopic_id(int topic_id) {
this.topic_id = topic_id;
}
public String getTopic_name() {
return topic_name;
}
public void setTopic_name(String topic_name) {
this.topic_name = topic_name;
}
public String getTopic_cover_sub_image() {
return topic_cover_sub_image;
}
public void setTopic_cover_sub_image(String topic_cover_sub_image) {
this.topic_cover_sub_image = topic_cover_sub_image;
}
public int getMember_count() {
return member_count;
}
public void setMember_count(int member_count) {
this.member_count = member_count;
}
public int getUnread_news_count() {
return unread_news_count;
}
public void setUnread_news_count(int unread_news_count) {
this.unread_news_count = unread_news_count;
}
public String getLast_refresh_date() {
return last_refresh_date;
}
public void setLast_refresh_date(String last_refresh_date) {
this.last_refresh_date = last_refresh_date;
}
public int getNews_count() {
return news_count;
}
public void setNews_count(int news_count) {
this.news_count = news_count;
}
public String getTopic_detail() {
return topic_detail;
}
public void setTopic_detail(String topic_detail) {
this.topic_detail = topic_detail;
}
public String getTopic_cover_image() {
return topic_cover_image;
}
public void setTopic_cover_image(String topic_cover_image) {
this.topic_cover_image = topic_cover_image;
}
public boolean isHas_news() {
return has_news;
}
public void setHas_news(boolean has_news) {
this.has_news = has_news;
}
}
<file_sep>package com.jlxc.app.news.ui.view;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.jlxc.app.R;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.ui.view.RoundImageView;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.news.model.LikeModel;
import com.lidroid.xutils.BitmapUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
public class LikeImageListView extends LinearLayout {
// 超小分辨率手机
private final static int TINY_PIX = 320;
// 小分辨率手机
private final static int SMALL_PIX = 480;
// 大
private final static int LAGER_PIX = 1280;
// 上行文信息
private Context mContext;
// 屏幕的尺寸
private static int screenWidth = 0;
// 根布局
private RelativeLayout rootView;
// 赞的图片
private List<RoundImageView> likeImageViews = new ArrayList<RoundImageView>();
// 其余点赞 的人
private TextView allLikeView;
// 最多点赞数默认为8
private int maxLikeCount = 8;
// 所有点赞数
private int allLikeCount = 0;
// 点赞数据集
private List<LikeModel> likeList;
// 动态的id
private String newsId;
// 点击事件回调接口
private EventCallBack callInterface;
// 加载图片
private ImageLoader imgLoader;
// 图片配置
private DisplayImageOptions options;
public LikeImageListView(Context context) {
super(context);
}
public LikeImageListView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
getWidget();
controlSizeInit();
}
// 初始化
private void init() {
imgLoader = ImageLoader.getInstance();
// 显示图片的配置
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading_default)
.showImageOnFail(R.drawable.default_avatar).cacheInMemory(true)
.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
}
/**
* 获取控件
* */
private void getWidget() {
View view = View.inflate(mContext, R.layout.custom_like_list_layout,
this);
rootView = (RelativeLayout) view
.findViewById(R.id.layout_like_list_root_view);
allLikeView = (TextView) view
.findViewById(R.id.tv_custom_like_all_person);
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_A));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_B));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_C));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_D));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_E));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_F));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_G));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_H));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_I));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_J));
likeImageViews.add((RoundImageView) view
.findViewById(R.id.iv_like_head_img_K));
setWidgetListener();
}
/**
* 事件监听
* */
private void setWidgetListener() {
for (int index = 0; index < likeImageViews.size(); index++) {
likeImageViews.get(index).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
for (int index = 0; index < likeImageViews.size(); index++) {
if (view.getId() == likeImageViews.get(index).getId()) {
callInterface.onItemClick(JLXCUtils
.stringToInt(likeList.get(index)
.getUserID()));
break;
}
}
}
});
}
allLikeView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
callInterface.onAllPersonBtnClick(newsId);
}
});
}
/**
* 设置操作回调
*
* @param callInterface
*/
public void setEventListener(EventCallBack callInterface) {
this.callInterface = callInterface;
}
/**
* 计算尺寸
* */
private void controlSizeInit() {
// 获取屏幕尺寸
DisplayMetrics displayMet = getResources().getDisplayMetrics();
screenWidth = displayMet.widthPixels;
// 计算显示的头像个数
if (screenWidth <= TINY_PIX) {
maxLikeCount = 6;
} else if (screenWidth > TINY_PIX && screenWidth <= SMALL_PIX) {
maxLikeCount = 7;
} else if (screenWidth > SMALL_PIX && screenWidth <= LAGER_PIX) {
maxLikeCount = 8;
} else {
maxLikeCount = 9;
}
}
/**
* 初始化
* */
public void dataInit(int allCount, String nId) {
allLikeCount = allCount;
newsId = nId;
}
/**
* 数据绑定
* */
public void listDataBindSet(List<LikeModel> imageList) {
likeList = imageList;
listRefresh();
}
/**
* 数据绑定
* */
private void listRefresh() {
if (likeList.size() == 0) {
rootView.setVisibility(View.GONE);
} else {
rootView.setVisibility(View.VISIBLE);
}
if (likeList.size() < maxLikeCount) {
allLikeView.setVisibility(View.INVISIBLE);
} else {
allLikeView.setVisibility(View.VISIBLE);
allLikeView.setText(String.valueOf(allLikeCount));
}
for (int index = 0; index < likeImageViews.size(); index++) {
RoundImageView tpImageView = likeImageViews.get(index);
if (index < likeList.size() && index < maxLikeCount) {
if (tpImageView.getVisibility() == View.GONE) {
tpImageView.setVisibility(View.VISIBLE);
}
// 显示头像
if (null != likeList.get(index).getHeadSubImage()
&& likeList.get(index).getHeadSubImage().length() > 0) {
imgLoader.displayImage(likeList.get(index)
.getHeadSubImage(), likeImageViews.get(index),
options);
} else {
likeImageViews.get(index).setImageResource(
R.drawable.default_avatar);
}
} else {
tpImageView.setVisibility(View.GONE);
}
}
}
/**
* 插入到首部
* */
public void insertToFirst(LikeModel newData) {
if (!likeList.contains(newData)) {
likeList.add(0, newData);
allLikeCount++;
listRefresh();
} else {
LogUtils.e("我的点赞数据已经存在");
}
}
//
public void removeHeadImg() {
for (int index = 0; index < likeList.size(); index++) {
if (JLXCUtils.stringToInt(likeList.get(index).getUserID()) == UserManager
.getInstance().getUser().getUid()) {
likeList.remove(index);
allLikeCount--;
break;
} else if (index >= likeList.size()) {
LogUtils.e("点赞发生了错误,未找到数据.");
}
}
listRefresh();
}
/**
* 点击事件回调接口
* */
public interface EventCallBack {
public void onItemClick(int userId);
public void onAllPersonBtnClick(String newsId);
}
}
<file_sep>package com.jlxc.app.discovery.utils;
import java.util.LinkedList;
import java.util.List;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.discovery.model.PersonModel;
import com.jlxc.app.discovery.model.RecommendItemData;
import com.jlxc.app.discovery.model.RecommendItemData.RecommendInfoItem;
import com.jlxc.app.discovery.model.RecommendItemData.RecommendPhotoItem;
import com.jlxc.app.discovery.model.RecommendItemData.RecommendTitleItem;
public class DataToRecommendItem {
// 将数据转换为item形式的数据
public static List<RecommendItemData> dataToItems(
List<PersonModel> personList) {
LinkedList<RecommendItemData> itemList = new LinkedList<RecommendItemData>();
for (int i=0; i < personList.size(); i++) {
PersonModel personMd = personList.get(i);
itemList.add(createRecommendInfo(personMd, i));
//最少要显示三张照片
if (personMd.getImageList().size() >= 3) {
itemList.add(createPhotoItem(personMd));
}
}
return itemList;
}
/**
* 创建头部
* */
public static RecommendItemData createRecommendTitle() {
RecommendTitleItem item = new RecommendTitleItem();
item.setItemType(RecommendItemData.RECOMMEND_TITLE);
return item;
}
// 提取基本信息
private static RecommendItemData createRecommendInfo(PersonModel person, int location) {
RecommendInfoItem item = new RecommendInfoItem();
try {
item.setItemType(RecommendItemData.RECOMMEND_INFO);
item.setUserID(person.getUerId());
item.setUserName(person.getUserName());
item.setUserSchool(person.getUserSchool());
item.setHeadImage(person.getHeadImage());
item.setHeadSubImage(person.getHeadSubImage());
item.setAdd(person.getIsFriend());
item.setRelationTag(person.getType());
item.setOriginIndex(location);
} catch (Exception e) {
LogUtils.e("create person info error.");
}
return item;
}
// 提取照片信息
private static RecommendItemData createPhotoItem(PersonModel personMd) {
RecommendPhotoItem item = new RecommendPhotoItem();
try {
item.setItemType(RecommendItemData.RECOMMEND_PHOTOS);
item.setUserId(personMd.getUerId());
item.setPhotoSubUrl(personMd.getImageList());
} catch (Exception e) {
LogUtils.e("createNewsTitle error.");
}
return item;
}
}
<file_sep>package com.jlxc.app.group.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import com.jlxc.app.R;
/**
* 下拉操作菜单
* */
public class OperatePopupWindow extends PopupWindow {
// 布局
private View conentView;
// onclick
private OperateListener listener;
@SuppressLint("NewApi")
public OperatePopupWindow(final Context context) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 获取布局
conentView = inflater
.inflate(R.layout.popup_window_group_operate, null);
// 创建部分的设置
LinearLayout createNewLayout = (LinearLayout) conentView
.findViewById(R.id.layout_create_new_group);
createNewLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
listener.createClick();
OperatePopupWindow.this.dismiss();
}
});
// 更多频道部分的设置
LinearLayout moreGroupLayout = (LinearLayout) conentView
.findViewById(R.id.layout_group_list);
moreGroupLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
listener.lookMoreGroup();
OperatePopupWindow.this.dismiss();
}
});
// 设置PopupWindow的View
this.setContentView(conentView);
// 设置窗体的尺寸
this.setWidth(LayoutParams.WRAP_CONTENT);
this.setHeight(LayoutParams.WRAP_CONTENT);
// 设置窗体可点击
this.setFocusable(true);
this.setOutsideTouchable(true);
// 刷新状态
this.update();
// 背景变暗
this.setBackgroundDrawable(new ColorDrawable(0x00000000));
// 设置窗体动画效果
this.setAnimationStyle(R.style.anim_group_operate);
}
/**
* 显示窗体
*/
public void showPopupWindow(View parent) {
if (!this.isShowing()) {
this.showAsDropDown(parent, 0, 0);
} else {
this.dismiss();
}
}
// 监听器
public interface OperateListener {
// 创建
public void createClick();
// 更多
public void lookMoreGroup();
// 类别
}
public OperateListener getListener() {
return listener;
}
public void setListener(OperateListener listener) {
this.listener = listener;
}
}
<file_sep>package com.jlxc.app.login.ui.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.ActivityManager;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.ui.activity.BaseActivity;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
@SuppressLint("ResourceAsColor")
public class LoginActivity extends BaseActivity {
//用户名输入框
@ViewInject(R.id.usernameEt)
private EditText usernameEt;
//登录注册按钮
@ViewInject(R.id.loginRegisterBtn)
private Button loginRegisterBtn;
//布局文件
@ViewInject(R.id.login_activity)
private RelativeLayout loginLayout;
@OnClick(value={R.id.loginRegisterBtn,R.id.login_activity})
public void loginOrRegisterClick(View v) {
switch (v.getId()) {
//登录或者注册判断
case R.id.loginRegisterBtn:
loginOrRegister();
break;
case R.id.login_activity:
try {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
LogUtils.e("登录或注册页面出错。");
}
break;
default:
break;
}
}
/**
* 登录或者注册跳转
*/
public void loginOrRegister() {
final String username = usernameEt.getText().toString().trim();
if (!username.matches(JLXCConst.PHONENUMBER_PATTERN)) {
Toast.makeText(LoginActivity.this, "真笨,手机号码都写错了 (︶︿︶)",
Toast.LENGTH_SHORT).show();
return;
}
//网络请求
showLoading("正在验证,请稍后", true);
RequestParams params = new RequestParams();
params.addBodyParameter("username", username);
HttpManager.post(JLXCConst.IS_USER, params, new JsonRequestCallBack<String>(new LoadDataHandler<String>(){
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
// TODO Auto-generated method stub
super.onSuccess(jsonResponse, flag);
int status = jsonResponse.getInteger(JLXCConst.HTTP_STATUS);
switch (status) {
case JLXCConst.STATUS_SUCCESS:
hideLoading();
JSONObject result = jsonResponse.getJSONObject(JLXCConst.HTTP_RESULT);
//登录
int loginDirection = 1;
//注册
int registerDirection = 2;
int direction = result.getIntValue("direction");
if (direction == loginDirection) {
//跳转
Intent intent = new Intent(LoginActivity.this, SecondLoginActivity.class);
intent.putExtra("username", username);
startActivityWithRight(intent);
}
if (direction == registerDirection) {
//发送验证码
sendVerify(username);
}
break;
case JLXCConst.STATUS_FAIL:
hideLoading();
Toast.makeText(LoginActivity.this, jsonResponse.getString(JLXCConst.HTTP_MESSAGE),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(HttpException arg0, String arg1, String flag) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1, flag);
hideLoading();
Toast.makeText(LoginActivity.this, "网络异常",
Toast.LENGTH_SHORT).show();
}
}, null));
}
//发送验证码
public void sendVerify(final String username) {
//发送验证码
// try {
// SMSSDK.getVerificationCode("86",usernameEt.getText().toString().trim());
// } catch (Exception e) {
// }
Intent intent = new Intent(LoginActivity.this, VerifyActivity.class);
intent.putExtra("username", usernameEt.getText().toString().trim());
startActivityWithRight(intent);
// //网络请求
// RequestParams params = new RequestParams();
// params.addBodyParameter("phone_num", username);
// HttpManager.post(JLXCConst.GET_MOBILE_VERIFY, params, new JsonRequestCallBack<String>(new LoadDataHandler<String>(){
//
// @Override
// public void onSuccess(JSONObject jsonResponse, String flag) {
// // TODO Auto-generated method stub
// super.onSuccess(jsonResponse, flag);
// int status = jsonResponse.getInteger(JLXCConst.HTTP_STATUS);
// switch (status) {
// case JLXCConst.STATUS_SUCCESS:
// hideLoading();
// //跳转
// Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
// intent.putExtra("username", username);
// startActivityWithRight(intent);
//
// break;
// case JLXCConst.STATUS_FAIL:
// hideLoading();
// Toast.makeText(LoginActivity.this, jsonResponse.getString(JLXCConst.HTTP_MESSAGE),
// Toast.LENGTH_SHORT).show();
// }
// }
// @Override
// public void onFailure(HttpException arg0, String arg1, String flag) {
// // TODO Auto-generated method stub
// super.onFailure(arg0, arg1, flag);
// hideLoading();
// Toast.makeText(LoginActivity.this, "网络异常",
// Toast.LENGTH_SHORT).show();
// }
//
// }, null));
}
/**
* 重写返回操作
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
ActivityManager.getInstence().exitApplication();
return true;
} else
return super.onKeyDown(keyCode, event);
}
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_login;
}
@Override
protected void loadLayout(View v) {
// TODO Auto-generated method stub
}
@Override
protected void setUpView() {
////////////////////////测试数据//////////////////////////
// usernameEt.setText("13736661234");
// UserModel userModel = UserManager.getInstance().getUser();
// if (null != userModel.getUsername() && null != userModel.getLogin_token()) {
// //跳转主页 自动登录
// Intent intent = new Intent(this, MainTabActivity.class);
// startActivity(intent);
// }
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
// try {
// EventHandler eh=new EventHandler(){
// @Override
// public void afterEvent(int event, int result, Object data) {
// Message msg = new Message();
// msg.arg1 = event;
// msg.arg2 = result;
// msg.obj = data;
// handler.sendMessage(msg);
// }
// };
// SMSSDK.registerEventHandler(eh);
// } catch (Exception e) {
// System.out.println("没初始化SMSSDK 因为这个短信sdk对DEBUG有影响 所以不是RELEASE不初始化");
// }
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
// try {
// SMSSDK.unregisterAllEventHandler();
// } catch (Exception e) {
// System.out.println("没初始化SMSSDK 因为这个短信sdk对DEBUG有影响 所以不是RELEASE不初始化");
// }
}
// @SuppressLint("HandlerLeak")
// Handler handler=new Handler(){
//
// @Override
// public void handleMessage(Message msg) {
// hideLoading();
// // TODO Auto-generated method stub
// super.handleMessage(msg);
// int event = msg.arg1;
// int result = msg.arg2;
// Object data = msg.obj;
// Log.e("event", "event="+event);
// if (result == SMSSDK.RESULT_COMPLETE) {
// //短信注册成功后,返回MainActivity,然后提示新好友
// if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
//// Toast.makeText(getApplicationContext(), "提交验证码成功", Toast.LENGTH_SHORT).show();
// } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
// Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
// intent.putExtra("username", usernameEt.getText().toString().trim());
// startActivityWithRight(intent);
//
// }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){//返回支持发送验证码的国家列表
//// Toast.makeText(getApplicationContext(), "获取国家列表成功", Toast.LENGTH_SHORT).show();
//
// }
// } else {
// ((Throwable) data).printStackTrace();
// ToastUtil.show(LoginActivity.this, "网络有点小问题");
// }
//
// }
//
// };
}
<file_sep>package com.jlxc.app.login.ui.activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.CountDownTimer;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.ui.activity.MainTabActivity;
import com.jlxc.app.base.ui.view.CustomAlertDialog;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.Md5Utils;
import com.jlxc.app.base.utils.ToastUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
public class RegisterActivity extends BaseActivityWithTopBar {
private final static String INTENT_KEY = "username";
// 是否是忘记密码
private Boolean isFindPwd;
// 用户 的电话号码
private String userPhoneNumber;
// 密码
private String password = "";
// 返回按钮
@ViewInject(R.id.base_tv_back)
private TextView backTextView;
// 页面标头
@ViewInject(R.id.base_tv_title)
private TextView titletTextView;
// 完成按钮
@ViewInject(R.id.next_button)
private Button nextButton;
// 密码框
@ViewInject(R.id.passwd_edittext)
private EditText passwdeEditText;
// 点击事件绑定
@OnClick({ R.id.base_tv_back, R.id.next_button,
R.id.register_activity })
public void viewCickListener(View view) {
switch (view.getId()) {
case R.id.base_tv_back:
backClick();
break;
case R.id.next_button:
// 点击下一步
nextClick();
break;
// case R.id.revalidated_textview:
// getVerificationCode();
// break;
case R.id.register_activity:
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
break;
default:
break;
}
}
// 初始化数据
private void init() {
Intent intent = getIntent();
userPhoneNumber = intent.getStringExtra(INTENT_KEY);
isFindPwd = intent.getBooleanExtra("isFindPwd", false);
}
// 点击返回
private void backClick() {
final CustomAlertDialog confirmDialog = new CustomAlertDialog(
this, "确定不注册了么T_T", "是的", "不了");
confirmDialog.show();
confirmDialog.setClicklistener(new CustomAlertDialog.ClickListenerInterface() {
@Override
public void doConfirm() {
confirmDialog.dismiss();
finishWithRight();
}
@Override
public void doCancel() {
confirmDialog.dismiss();
}
});
}
// 点击下一步按钮
private void nextClick() {
password = passwdeEditText.getText().toString();
// 判断输入值是否正确
if (password.length() < 6) {
ToastUtil.show(RegisterActivity.this, "密码最少得6位啦");
} else {
// 忘记密码
if (isFindPwd) {
findPwd();
} else {
// 注册
startRegister();
}
}
}
// 找回密码
private void findPwd() {
showLoading("数据上传中^_^", false);
//先验证验证码
// SMSSDK.submitVerificationCode("86", userPhoneNumber, verifycodeEditText.getText().toString().trim());
finishPwd();
// RequestParams params = new RequestParams();
// params.addBodyParameter("username", userPhoneNumber);
// params.addBodyParameter("password", <PASSWORD>));
// params.addBodyParameter("verify_code",
// String.valueOf(verifyCodeEditTextValue));
//
// HttpManager.post(JLXCConst.FIND_PWD, params,
// new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
//
// @Override
// public void onSuccess(JSONObject jsonResponse, String flag) {
// super.onSuccess(jsonResponse, flag);
// int status = jsonResponse
// .getInteger(JLXCConst.HTTP_STATUS);
// if (status == JLXCConst.STATUS_SUCCESS) {
// hideLoading();
// JSONObject result = jsonResponse
// .getJSONObject(JLXCConst.HTTP_RESULT);
// UserModel userMd = new UserModel();
// userMd.setContentWithJson(result);
// UserManager.getInstance().setUser(userMd);
// ToastUtil.show(RegisterActivity.this, "修改成功");
// // 数据持久化
// UserManager.getInstance().saveAndUpdate();
// // 跳转主页
// Intent intent = new Intent(RegisterActivity.this,
// MainTabActivity.class);
// startActivity(intent);
//
// }
//
// if (status == JLXCConst.STATUS_FAIL) {
// hideLoading();
// ToastUtil.show(RegisterActivity.this, jsonResponse
// .getString(JLXCConst.HTTP_MESSAGE));
// }
// }
//
// @Override
// public void onFailure(HttpException arg0, String arg1,
// String flag) {
// super.onFailure(arg0, arg1, flag);
// hideLoading();
// showConfirmAlert("提示", "注册失败,请检查网络连接!");
// }
// }, null));
}
// 找回密码
private void finishPwd() {
// showLoading("数据上传中^_^", false);
RequestParams params = new RequestParams();
params.addBodyParameter("username", userPhoneNumber);
params.addBodyParameter("password", <PASSWORD>));
HttpManager.post(JLXCConst.FIND_PWD, params,
new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
hideLoading();
JSONObject result = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
UserModel userMd = new UserModel();
userMd.setContentWithJson(result);
UserManager.getInstance().setUser(userMd);
ToastUtil.show(RegisterActivity.this, "修改成功");
// 数据持久化
UserManager.getInstance().saveAndUpdate();
// 跳转主页
Intent intent = new Intent(RegisterActivity.this,
MainTabActivity.class);
startActivity(intent);
}
if (status == JLXCConst.STATUS_FAIL) {
hideLoading();
ToastUtil.show(RegisterActivity.this, jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
hideLoading();
showConfirmAlert("提示", "注册失败,请检查网络连接!");
}
}, null));
}
// 开始注册
private void startRegister() {
RegisterActivity.this.showLoading("正在注册", false);
//先验证验证码 测试注释掉
// SMSSDK.submitVerificationCode("86", userPhoneNumber, verifycodeEditText.getText().toString().trim());
finishRegister();
// RegisterActivity.this.showLoading("正在注册", false);
// RequestParams params = new RequestParams();
// params.addBodyParameter("username", userPhoneNumber);
// params.addBodyParameter("password", <PASSWORD>));
// params.addBodyParameter("verify_code", verifyCodeEditTextValue);
//
// HttpManager.post(JLXCConst.REGISTER_USER, params,
// new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
//
// @Override
// public void onSuccess(JSONObject jsonResponse, String flag) {
// super.onSuccess(jsonResponse, flag);
// int status = jsonResponse
// .getInteger(JLXCConst.HTTP_STATUS);
// if (status == JLXCConst.STATUS_SUCCESS) {
// hideLoading();
// JSONObject result = jsonResponse
// .getJSONObject(JLXCConst.HTTP_RESULT);
// // 设置用户实例
// UserModel userMd = new UserModel();
// userMd.setContentWithJson(result);
// UserManager.getInstance().setUser(userMd);
// // 数据持久化
// UserManager.getInstance().saveAndUpdate();
// ToastUtil.show(RegisterActivity.this, "注册成功");
// // 跳转至选择学校页面
// Intent intent = new Intent(RegisterActivity.this,
// SelectSchoolActivity.class);
// startActivity(intent);
// }
//
// if (status == JLXCConst.STATUS_FAIL) {
// hideLoading();
// ToastUtil.show(RegisterActivity.this, jsonResponse
// .getString(JLXCConst.HTTP_MESSAGE));
// }
// }
//
// @Override
// public void onFailure(HttpException arg0, String arg1,
// String flag) {
// super.onFailure(arg0, arg1, flag);
// hideLoading();
// ToastUtil.show(RegisterActivity.this, "注册失败,你网络太垃圾了!");
// }
//
// }, null));
}
//验证成功 完成注册
private void finishRegister() {
RequestParams params = new RequestParams();
params.addBodyParameter("username", userPhoneNumber);
params.addBodyParameter("password", <PASSWORD>));
// params.addBodyParameter("verify_code", verifyCodeEditTextValue);
HttpManager.post(JLXCConst.REGISTER_USER, params,
new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
hideLoading();
JSONObject result = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
// 设置用户实例
UserModel userMd = new UserModel();
userMd.setContentWithJson(result);
UserManager.getInstance().setUser(userMd);
// 数据持久化
UserManager.getInstance().saveAndUpdate();
ToastUtil.show(RegisterActivity.this, "注册成功");
// 跳转至选择学校页面
Intent intent = new Intent(RegisterActivity.this,
SelectSchoolActivity.class);
startActivity(intent);
}
if (status == JLXCConst.STATUS_FAIL) {
hideLoading();
ToastUtil.show(RegisterActivity.this, jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
hideLoading();
ToastUtil.show(RegisterActivity.this, "注册失败,你网络太垃圾了!");
}
}, null));
}
@Override
public int setLayoutId() {
return R.layout.activity_register_layout;
}
@Override
protected void setUpView() {
init();
if (isFindPwd) {
titletTextView.setText("修改密码");
}else {
titletTextView.setText("注册");
}
RelativeLayout rlBar = (RelativeLayout) findViewById(R.id.layout_base_title);
rlBar.setBackgroundResource(R.color.main_clear);
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
// try {
// //验证码接收器
// EventHandler eh=new EventHandler(){
// @Override
// public void afterEvent(int event, int result, Object data) {
// Message msg = new Message();
// msg.arg1 = event;
// msg.arg2 = result;
// msg.obj = data;
// handler.sendMessage(msg);
// }
// };
// SMSSDK.registerEventHandler(eh);
// } catch (Exception e) {
// System.out.println("没初始化SMSSDK 因为这个短信sdk对DEBUG有影响 所以不是RELEASE不初始化");
// }
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
// try{
// SMSSDK.unregisterAllEventHandler();
// } catch (Exception e) {
// System.out.println("没初始化SMSSDK 因为这个短信sdk对DEBUG有影响 所以不是RELEASE不初始化");
// }
}
@Override
protected void loadLayout(View v) {
}
// 获取验证码
// private void getVerificationCode() {
//
// try {
// //发送验证码
// SMSSDK.getVerificationCode("86",userPhoneNumber);
// } catch (Exception e) {
// // TODO: handle exception
// }
// // 设置字体颜色
// revalidatedTextView.setTextColor(Color.GRAY);
// // 网络请求
// RequestParams params = new RequestParams();
// params.addBodyParameter("phone_num", userPhoneNumber);
//
// HttpManager.post(JLXCConst.GET_MOBILE_VERIFY, params,
// new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
//
// @Override
// public void onSuccess(JSONObject jsonResponse, String flag) {
// super.onSuccess(jsonResponse, flag);
// int status = jsonResponse
// .getInteger(JLXCConst.HTTP_STATUS);
// if (status == JLXCConst.STATUS_SUCCESS) {
// ToastUtil.show(RegisterActivity.this, "验证码已发送");
// verifyCountdownTimer.start();
// }
//
// if (status == JLXCConst.STATUS_FAIL) {
// hideLoading();
// showConfirmAlert("提示", jsonResponse
// .getString(JLXCConst.HTTP_MESSAGE));
// }
// }
//
// @Override
// public void onFailure(HttpException arg0, String arg1,
// String flag) {
// super.onFailure(arg0, arg1, flag);
// hideLoading();
// showConfirmAlert("提示", "获取失败,请检查网络连接!");
// }
// }, null));
// }
/**
* 重写返回操作
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
backClick();
return true;
} else
return super.onKeyDown(keyCode, event);
}
// @SuppressLint("HandlerLeak")
// Handler handler=new Handler(){
//
// @Override
// public void handleMessage(Message msg) {
// hideLoading();
// // TODO Auto-generated method stub
// super.handleMessage(msg);
// int event = msg.arg1;
// int result = msg.arg2;
// Object data = msg.obj;
// Log.e("event", "event="+event);
// if (result == SMSSDK.RESULT_COMPLETE) {
// //短信注册成功后,返回MainActivity,然后提示新好友
// if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
// //完成注册或者找回密码
// if (isFindPwd) {
// finishPwd();
// } else {
// // 注册
// finishRegister();
// }
// } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
// ToastUtil.show(RegisterActivity.this, "验证码已发送至您的手机");
//
// }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){//返回支持发送验证码的国家列表
//// Toast.makeText(getApplicationContext(), "获取国家列表成功", Toast.LENGTH_SHORT).show();
//
// }
// } else {
// ((Throwable) data).printStackTrace();
// ToastUtil.show(RegisterActivity.this, "验证码错误");
// System.out.println(((Throwable) data).toString());
//// int resId = getStringRes(RegisterActivity.this, "smssdk_network_error");
//// Toast.makeText(MainActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
//// if (resId > 0) {
//// Toast.makeText(MainActivity.this, resId, Toast.LENGTH_SHORT).show();
//// }
// }
//
// }
//
// };
}
<file_sep>package com.jlxc.app.login.ui.activity;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.services.core.s;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.news.model.SchoolModel;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
public class SelectSchoolActivity extends BaseActivityWithTopBar {
// 下拉模式
public static final int PULL_DOWM_MODE = 0;
// 上拉模式
public static final int PULL_UP_MODE = 1;
// 学校数据列表
private List<SchoolModel> mDatas = new ArrayList<SchoolModel>();
// 学校listview的适配器
private HelloHaAdapter<SchoolModel> schoolAdapter;
// 父layout
@ViewInject(R.id.root_layout)
private LinearLayout rootLayout;
// 搜索框
@ViewInject(R.id.search_edittext)
private EditText searchEditText;
// 学校列表标头
@ViewInject(R.id.school_list_title_textview)
private TextView listTitleTextView;
// 学校列表listview
@ViewInject(R.id.school_listview)
private PullToRefreshListView schoolListView;
// 提示信息
@ViewInject(R.id.tv_school_prompt)
private TextView promptTextView;
// 用户当前所在的区域编码
private String districtCode = "110101";
// 需要搜索的学校名字
private String schoolName = "";
// 查询学校时的page值
private int pageIndex = 1;
// 定位对象
private Location districtLocation;
// 是否下拉刷新
private boolean isPullDowm = false;
// 是否是最后一页
private boolean isLastPage = false;
// 是否正在请求数据
private boolean isRequestingData = false;
// 注册的时候使用或者修改信息的时候使用
private boolean notRegister;
@OnClick({ R.id.root_layout })
public void viewCickListener(View view) {
switch (view.getId()) {
case R.id.root_layout:
// 隐藏输入键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
break;
default:
break;
}
}
@Override
public int setLayoutId() {
return R.layout.activity_select_school_layout;
}
@Override
protected void setUpView() {
setBarText("选择学校");
// 设置是否是注册进入的
Intent intent = getIntent();
setNotRegister(intent.getBooleanExtra("notRegister", false));
// 初始化listView
initListViewSet();
// 设置搜索框内容改变的监听事件
searchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence str, int start, int before,
int count) {
isPullDowm = true;
schoolName = str.toString();
if (!schoolName.equals("")) {
listTitleTextView.setText("搜索到的学校");
} else {
listTitleTextView.setText("猜你在这些学校");
}
pageIndex = 1;
getSchoolList(String.valueOf(pageIndex), districtCode,
schoolName);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
// 开始定位,每0.2s通知一次,距离变化10通知一次,超时时间为5秒
districtLocation = new Location(SelectSchoolActivity.this);
districtLocation.locateInit(200, 10, 5000);
showLoading("定位中..", true);
TextView backBtn = (TextView) findViewById(R.id.base_tv_back);
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
back();
}
});
}
/***
*
* listview的设置
*/
private void initListViewSet() {
// 设置为底部刷新模式
schoolListView.setMode(Mode.BOTH);
schoolAdapter = new HelloHaAdapter<SchoolModel>(
SelectSchoolActivity.this, R.layout.school_listitem_layout,
mDatas) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper,
SchoolModel item) {
// 学校绑定
helper.setText(R.id.school_name_textView, item.getSchoolName());
// 位置绑定
if (item.getSchoolType().equals(
SchoolModel.JUNIOR_MIDDLE_SCHOOL)) {
helper.setText(R.id.school_location_textView,
item.getCityName() + item.getDistrictName()
+ " ▪ 初中");
} else if (item.getSchoolType().equals(
SchoolModel.SENIOR_MIDDLE_SCHOOL)) {
helper.setText(R.id.school_location_textView,
item.getCityName() + item.getDistrictName()
+ " ▪ 高中");
} else {
// 其他
}
}
};
// 适配器绑定
schoolListView.setAdapter(schoolAdapter);
schoolListView.setPullToRefreshOverScrollEnabled(false);
// 设置刷新事件监听
schoolListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
// 下拉刷新
isPullDowm = true;
pageIndex = 1;
getSchoolList(String.valueOf(pageIndex), districtCode,
schoolName);
}
@Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
if (!isLastPage && !isRequestingData) {
// 上拉刷新
isRequestingData = true;
isPullDowm = false;
getSchoolList(String.valueOf(pageIndex), districtCode,
schoolName);
isRequestingData = false;
}
}
});
/**
* 设置底部自动刷新
* */
schoolListView
.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
@Override
public void onLastItemVisible() {
if (!isLastPage) {
// 底部自动加载
schoolListView.setMode(Mode.PULL_FROM_END);
schoolListView.setRefreshing(true);
}
}
});
/**
* 设置点击item到事件
* */
schoolListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// 隐藏输入键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
// 更新数据
updateUserSchool(schoolAdapter.getItem(position - 1)
.getSchoolName(), schoolAdapter.getItem(position - 1)
.getSchoolCode());
}
});
}
/**
* 数据转化
* */
private void jsonToSchoolData(List<JSONObject> dataList) {
List<SchoolModel> newDatas = new ArrayList<SchoolModel>();
for (JSONObject schoolobj : dataList) {
SchoolModel tempModel = new SchoolModel();
tempModel.setContentWithJson(schoolobj);
newDatas.add(tempModel);
}
if (isPullDowm) {
schoolAdapter.replaceAll(newDatas);
} else {
schoolAdapter.addAll(newDatas);
}
if (null != dataList) {
dataList.clear();
}
if (schoolAdapter.getCount() == 0) {
promptTextView.setVisibility(View.VISIBLE);
promptTextView.setText("然而并没有任何学校 ヽ(.◕ฺˇд ˇ◕ฺ;)ノ");
} else {
promptTextView.setVisibility(View.GONE);
}
}
/**
* 获取学校列表
* */
private void getSchoolList(String page, String districtCode,
String schoolName) {
if (districtCode.length() == 0) {
districtCode = "110101";
}
// 参数设置
RequestParams params = new RequestParams();
params.addBodyParameter("page", page);
params.addBodyParameter("district_code", districtCode);
params.addBodyParameter("school_name", schoolName);
HttpManager.post(JLXCConst.GET_SCHOOL_LIST, params,
new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
@SuppressWarnings("unchecked")
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
// 获取学校列表
schoolListView.onRefreshComplete();
List<JSONObject> objList = (List<JSONObject>) jResult
.get("list");
jsonToSchoolData(objList);
if (jResult.getString("is_last").equals("1")) {
isLastPage = true;
schoolListView.setMode(Mode.PULL_FROM_START);
} else {
isLastPage = false;
pageIndex++;
schoolListView.setMode(Mode.BOTH);
}
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(SelectSchoolActivity.this,
jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
if (!isLastPage) {
schoolListView.setMode(Mode.BOTH);
}
schoolListView.onRefreshComplete();
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
ToastUtil.show(SelectSchoolActivity.this,
"卧槽,竟然查询失败,检查下网络");
if (!isLastPage) {
schoolListView.setMode(Mode.BOTH);
}
schoolListView.onRefreshComplete();
}
}, null));
}
/**
* 上传学校数据
* */
private void updateUserSchool(final String schoolName,
final String schoolCode) {
final UserModel userModel = UserManager.getInstance().getUser();
// 参数设置
RequestParams params = new RequestParams();
params.addBodyParameter("uid", userModel.getUid() + "");
params.addBodyParameter("school", schoolName);
params.addBodyParameter("school_code", schoolCode);
HttpManager.post(JLXCConst.CHANGE_SCHOOL, params,
new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
// 设置数据
userModel.setSchool(schoolName);
userModel.setSchool_code(schoolCode);
// 数据持久化
UserManager.getInstance().saveAndUpdate();
if (isNotRegister()) {
finishWithRight();
} else {
// 注册进来的 跳转到下一页面
Intent intent = new Intent(
SelectSchoolActivity.this,
RegisterInformationActivity.class);
startActivityWithRight(intent);
}
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(SelectSchoolActivity.this,
jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
LogUtils.e("学校上传失败");
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
ToastUtil.show(SelectSchoolActivity.this,
"卧槽,操作失败,检查下网络");
}
}, null));
}
/**
* 定位获取区域代码
* */
private class Location implements AMapLocationListener {
private Context mContext;
private LocationManagerProxy aMapLocManager = null;
public Location(Context context) {
mContext = context;
}
/**
* 初始化定位,通知时间(毫秒),通知距离(米),超时值(毫秒)
*/
public void locateInit(long minTime, float minDistance, int timeOutValue) {
aMapLocManager = LocationManagerProxy.getInstance(mContext);
aMapLocManager.requestLocationData(
LocationProviderProxy.AMapNetwork, minTime, minDistance,
this);
LogUtils.i("Locate init successed.");
}
/**
* 停止定位并销毁对象
*/
private void stopLocation() {
if (aMapLocManager != null) {
aMapLocManager.removeUpdates(this);
aMapLocManager.destroy();
}
aMapLocManager = null;
LogUtils.i("Locate stop successed.");
}
@Override
public void onLocationChanged(android.location.Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(AMapLocation location) {
// 隐藏HUD
hideLoading();
if (location != null) {
districtCode = location.getAdCode();
LogUtils.i("get district Code successed.");
// 查询区域代码成功后开始查找学校数据
isPullDowm = false;
getSchoolList(String.valueOf(pageIndex), districtCode,
schoolName);
stopLocation();
}
}
}
@Override
protected void onStop() {
// 停止定位
districtLocation.stopLocation();
super.onStop();
}
/**
* 返回操作
* */
private void back() {
// 停止定位
districtLocation.stopLocation();
// 返回首页
if (notRegister) {
finishWithRight();
} else {
Intent intent = new Intent(SelectSchoolActivity.this,
LoginActivity.class);
startActivityWithRight(intent);
}
}
/**
* 重写返回操作
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
back();
return true;
} else
return super.onKeyDown(keyCode, event);
}
public boolean isNotRegister() {
return notRegister;
}
public void setNotRegister(boolean notRegister) {
this.notRegister = notRegister;
}
}<file_sep>package com.jlxc.app.news.model;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import com.jlxc.app.base.utils.LogUtils;
/**
* 将每条动态拆分成不同的部分
* */
public class ItemModel {
// 动态item的种类数
public static final int NEWS_ITEM_TYPE_COUNT = 5;
// 校园item的种类数
public static final int CAMPUS_ITEM_TYPE_COUNT = 5;
// 动态详情item的种类数
public static final int NEWS_DETAIL_ITEM_TYPE_COUNT = 5;
// 圈子item的种类数
public static final int GROUP_NEWS_ITEM_TYPE_COUNT = 3;
// 表示动态各item类型
public static final int NEWS_TITLE = 0;
public static final int NEWS_BODY = 1;
public static final int NEWS_LIKELIST = 2;
public static final int NEWS_COMMENT = 3;
public static final int NEWS_OPERATE = 4;
// 表示校园各item类型
public static final int CAMPUS_TITLE = 0;
public static final int CAMPUS_BODY = 1;
public static final int CAMPUS_OPERATE = 2;
public static final int CAMPUS_LIKELIST = 3;
public static final int CAMPUS_HEAD = 4;
// 表示动态详情各item类型
public static final int NEWS_DETAIL_TITLE = 0;
public static final int NEWS_DETAIL_BODY = 1;
public static final int NEWS_DETAIL_LIKELIST = 2;
public static final int NEWS_DETAIL_COMMENT = 3;
public static final int NEWS_DETAIL_SUB_COMMENT = 4;
// 动态的id
private String newsID = "";
// 当前的item类型
private int itemType;
public int getItemType() {
return itemType;
}
/**
* 设置item的类型
* */
public void setItemType(int type) {
switch (type) {
case 0:
case 1:
case 2:
case 3:
case 4:
itemType = type;
break;
default:
LogUtils.e("items type error");
break;
}
}
public String getNewsID() {
return newsID;
}
public void setNewsID(String newsID) {
this.newsID = newsID;
}
/**
* 动态的头部
* */
public static class TitleItem extends ItemModel {
// 动态发布者的头像缩略图
private String headSubImage;
// 动态发布者的头像
private String headImage;
// 动态发布者的名字
private String userName;
// 学校
private String userSchool;
// 学校id
private String schoolCode;
// 显示用户的id
private String userID;
// 显示是否已赞
private boolean isLike;
// 所有点赞的人
private int likeCount;
// 发布的时间
private String sendTime;
// 标签来源
private String tagContent = "";
public String getHeadSubImage() {
return headSubImage;
}
public void setHeadSubImage(String headSubImage) {
this.headSubImage = headSubImage;
}
public String getHeadImage() {
return headImage;
}
public void setHeadImage(String userHeadImage) {
this.headImage = userHeadImage;
}
public String getUserName() {
return userName;
}
public void setUserName(String userNameStr) {
this.userName = userNameStr;
}
public String getUserSchool() {
return userSchool;
}
public void setUserSchool(String userSchool) {
this.userSchool = userSchool;
}
public boolean getIsLike() {
return isLike;
}
public void setIsLike(String isLike) {
if (isLike.equals("0")) {
this.isLike = false;
} else {
this.isLike = true;
}
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(String likeCount) {
try {
this.likeCount = Integer.parseInt(likeCount);
} catch (Exception e) {
LogUtils.e("点赞数据格式错误.");
}
}
public String getSendTime() {
return sendTime;
}
public void setSendTime(String sendTime) {
this.sendTime = sendTime;
}
public String getTagContent() {
return tagContent;
}
public void setTagContent(String tagContent) {
this.tagContent = tagContent;
}
public String getSchoolCode() {
return schoolCode;
}
public void setSchoolCode(String schoolCode) {
this.schoolCode = schoolCode;
}
}
/**
* 动态的主体
* */
public static class BodyItem extends ItemModel {
// 动态的文字内容
private String newsContent;
// 动态的图片列表
private List<ImageModel> newsImageList = new ArrayList<ImageModel>();
// 发布的位置
private String location;
// 发布的时间
private String sendTime;
// 发布到的圈子(为0时不存在)
private int topicID;
// 发布到的圈子名
private String topicName;
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
public List<ImageModel> getNewsImageListList() {
return newsImageList;
}
public void setImageNewsList(List<ImageModel> imageList) {
this.newsImageList = imageList;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getSendTime() {
return sendTime;
}
public void setSendTime(String sendTime) {
this.sendTime = sendTime;
}
public int getTopicID() {
return topicID;
}
public void setTopicID(int topicID) {
this.topicID = topicID;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
}
/**
* 动态的操作部分
* */
public static class OperateItem extends ItemModel {
// 是否已赞
private boolean isLike = false;
// 点赞数
private int likeCount;
// 发布的时间
private String sendTime;
// 发布到的圈子(为0时不存在)
private int topicID;
// 发布到的圈子名
private String topicName;
public boolean getIsLike() {
return isLike;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(String likeCount) {
try {
this.likeCount = Integer.parseInt(likeCount);
} catch (Exception e) {
LogUtils.e("点赞数据格式错误.");
}
}
public void setIsLike(String isLike) {
if (isLike.equals("1")) {
this.isLike = true;
} else {
this.isLike = false;
}
}
public String getSendTime() {
return sendTime;
}
public void setSendTime(String sendTime) {
this.sendTime = sendTime;
}
public int getTopicID() {
return topicID;
}
public void setTopicID(int topicID) {
this.topicID = topicID;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
}
/**
* 已赞的人的头像部分
* */
public static class LikeListItem extends ItemModel {
// 点赞数
private int likeCount;
// 点赞的人头像
private List<LikeModel> likeList = new ArrayList<LikeModel>();
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(String likeCount) {
try {
this.likeCount = Integer.parseInt(likeCount);
} catch (Exception e) {
LogUtils.e("点赞数据格式错误.");
}
}
public List<LikeModel> getLikeHeadListimage() {
return likeList;
}
public void setLikeHeadListimage(List<LikeModel> list) {
this.likeList = list;
}
}
/**
* 评论列表部分
* */
public static class CommentListItem extends ItemModel {
// 评论数
private int replyCount;
// 评论列表
private List<CommentModel> commentList = new ArrayList<CommentModel>();
public int getReplyCount() {
return replyCount;
}
public void setReplyCount(String replyCount) {
try {
this.replyCount = Integer.parseInt(replyCount);
} catch (Exception e) {
LogUtils.e("评论数据格式错误.");
}
}
public List<CommentModel> getCommentList() {
return commentList;
}
public void setCommentList(List<CommentModel> cmtList) {
this.commentList = cmtList;
}
}
/**
* 评论列表部分
* */
public static class CommentItem extends ItemModel {
// 评论列表
private CommentModel commentData = new CommentModel();
public CommentModel getCommentModel() {
return commentData;
}
public void setComment(CommentModel cmt) {
this.commentData = cmt;
}
}
/**
* 校园的头部
* */
public static class CampusHeadItem extends ItemModel {
private String schoolName;
// 学校的人列表
private List<CampusPersonModel> personList = new ArrayList<CampusPersonModel>();
public List<CampusPersonModel> getPersonList() {
return personList;
}
public void setPersonList(List<CampusPersonModel> List) {
this.personList = List;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
}
/**
* 子评论item数据
* */
public static class SubCommentItem extends ItemModel {
// 子评论对象
private SubCommentModel subCommentModel;
public SubCommentModel getSubCommentModel() {
return subCommentModel;
}
public void setSubCommentModel(SubCommentModel subCommentModel) {
this.subCommentModel = subCommentModel;
}
}
}
<file_sep>package com.jlxc.app.news.ui.activity;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.adapter.MultiItemTypeSupport;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.ui.view.CustomAlertDialog;
import com.jlxc.app.base.ui.view.CustomListViewDialog;
import com.jlxc.app.base.ui.view.CustomListViewDialog.ClickCallBack;
import com.jlxc.app.base.ui.view.KeyboardLayout;
import com.jlxc.app.base.ui.view.KeyboardLayout.onKeyboardsChangeListener;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.TimeHandle;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.group.ui.activity.GroupNewsActivity;
import com.jlxc.app.news.model.CommentModel;
import com.jlxc.app.news.model.ImageModel;
import com.jlxc.app.news.model.ItemModel;
import com.jlxc.app.news.model.ItemModel.BodyItem;
import com.jlxc.app.news.model.ItemModel.CommentItem;
import com.jlxc.app.news.model.ItemModel.LikeListItem;
import com.jlxc.app.news.model.ItemModel.SubCommentItem;
import com.jlxc.app.news.model.ItemModel.TitleItem;
import com.jlxc.app.news.model.LikeModel;
import com.jlxc.app.news.model.NewsConstants;
import com.jlxc.app.news.model.NewsModel;
import com.jlxc.app.news.model.SubCommentModel;
import com.jlxc.app.news.ui.view.LikeButton;
import com.jlxc.app.news.ui.view.LikeImageListView;
import com.jlxc.app.news.ui.view.LikeImageListView.EventCallBack;
import com.jlxc.app.news.ui.view.MultiImageMetroView;
import com.jlxc.app.news.ui.view.MultiImageMetroView.JumpCallBack;
import com.jlxc.app.news.ui.view.TextViewHandel;
import com.jlxc.app.news.utils.DataToItem;
import com.jlxc.app.news.utils.NewsOperate;
import com.jlxc.app.news.utils.NewsOperate.LikeCallBack;
import com.jlxc.app.news.utils.NewsOperate.OperateCallBack;
import com.jlxc.app.personal.ui.activity.OtherPersonalActivity;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
public class NewsDetailActivity extends BaseActivityWithTopBar {
// 记录对动态的操作
private String actionType = NewsConstants.OPERATE_NO_ACTION;
// 评论的类型
private int commentType = NewsConstants.Input_Type_Comment;
// 主listview
@ViewInject(R.id.news_detail_listView)
private PullToRefreshListView newsDetailListView;
// 评论输入框
@ViewInject(R.id.edt_comment_input)
private EditText commentEditText;
// 评论发送按钮
@ViewInject(R.id.btn_comment_send)
private Button btnSendComment;
// 数据源
private List<ItemModel> dataList;
// 主适配器
private HelloHaAdapter<ItemModel> detailAdapter;
// 当前的动态对象
private NewsModel currentNews;
// 加载图片
private ImageLoader imgLoader;
// 图片配置
private DisplayImageOptions options;
// 使支持多种item
private MultiItemTypeSupport<ItemModel> multiItemTypeSupport = null;
// 点击view监听对象
private ItemViewClick itemViewClickListener;
// 对动态的操作
private NewsOperate<ItemModel> newsOPerate;
// 评论的内容
private String commentContent = "";
// 当前的操作的item
private CommentModel currentCommentModel;
// 当前的操作的子评论对象
private SubCommentModel currentSubCmtModel;
// 当前操作的位置
private int currentOperateIndex = 0;
// 是否是第一次请求数据
private boolean firstRequstData = true;
// 点赞按钮
private LikeButton likeBtn;
// 已赞头像部件
private LikeImageListView likeControl;
/**
* 事件监听函数
* */
@OnClick(value = { R.id.base_ll_right_btns, R.id.btn_comment_send })
private void clickEvent(View view) {
switch (view.getId()) {
// 删除动态
case R.id.base_ll_right_btns:
deleteCurrentNews();
break;
// 发布评论
case R.id.btn_comment_send:
publishComment();
break;
default:
break;
}
}
@Override
public int setLayoutId() {
return R.layout.activity_news_detail;
}
@Override
protected void setUpView() {
init();
multiItemTypeSet();
listViewSet();
newsOperateSet();
// 监听输入框文本的变化
commentEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence str, int start, int before,
int count) {
commentContent = str.toString().trim();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
// 监听软键盘是否打开
((KeyboardLayout) findViewById(R.id.news_detail_root_view))
.setOnkeyboarddStateListener(new onKeyboardsChangeListener() {
@Override
public void onKeyBoardStateChange(int state) {
if (KeyboardLayout.KEYBOARD_STATE_HIDE == state) {
// 内容为空并且,软键盘隐藏时
if (commentContent.length() <= 0) {
commentType = NewsConstants.Input_Type_Comment;
commentEditText.setHint("是时候来条神评论了...");
}
}
}
});
Intent intent = this.getIntent();
if (null != intent) {
if (intent.hasExtra(NewsConstants.INTENT_KEY_NEWS_OBJ)) {
currentNews = (NewsModel) intent
.getSerializableExtra(NewsConstants.INTENT_KEY_NEWS_OBJ);
// 获取传递过来的的数据
detailAdapter.replaceAll(DataToItem
.newsDetailToItems(currentNews));
} else if (intent.hasExtra(NewsConstants.INTENT_KEY_NEWS_ID)) {
currentNews = new NewsModel();
currentNews.setNewsID(intent
.getStringExtra(NewsConstants.INTENT_KEY_NEWS_ID));
} else {
LogUtils.e("未传递任何动态信息到详情页面.");
}
} else {
LogUtils.e("跳转到详情页面时,意图null.");
}
// 更新数据
getNewsDetailData(
String.valueOf(UserManager.getInstance().getUser().getUid()),
currentNews.getNewsID());
}
/**
* 数据的初始化
* */
private void init() {
setBarText("详情");
dataList = new ArrayList<ItemModel>();
itemViewClickListener = new ItemViewClick();
// 图片加载初始化
imgLoader = ImageLoader.getInstance();
// 显示图片的配置
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.default_avatar)
.showImageOnFail(R.drawable.default_avatar).cacheInMemory(true)
.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
}
/**
* 初始状态处理
* */
private void stateHandel() {
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
switch (bundle.getInt(NewsConstants.INTENT_KEY_COMMENT_STATE)) {
case NewsConstants.KEY_BOARD_CLOSE:
btnSendComment.setFocusable(true);
break;
case NewsConstants.KEY_BOARD_COMMENT:
commentEditText.setFocusable(true);
commentEditText.setFocusableInTouchMode(true);
commentEditText.requestFocus();
commentType = NewsConstants.Input_Type_Comment;
setKeyboardStatu(true);
break;
case NewsConstants.KEY_BOARD_REPLY:
// 直接回复评论
String cmtId = bundle
.getString(NewsConstants.INTENT_KEY_COMMENT_ID);
for (int index = 0; index < dataList.size(); ++index) {
ItemModel tempItemModel = dataList.get(index);
int itemType = tempItemModel.getItemType();
if (ItemModel.NEWS_DETAIL_COMMENT == itemType) {
// 回复评论
currentCommentModel = ((CommentItem) tempItemModel)
.getCommentModel();
if (currentCommentModel.getCommentID().equals(cmtId)) {
commentEditText.setHint("回复:"
+ currentCommentModel.getPublishName());
commentType = NewsConstants.Input_Type_SubComment;
break;
}
} else if (ItemModel.NEWS_DETAIL_SUB_COMMENT == itemType) {
// 回复子评论
currentSubCmtModel = ((SubCommentItem) tempItemModel)
.getSubCommentModel();
if (currentSubCmtModel.getSubID().equals(cmtId)) {
commentEditText.setHint("回复:"
+ currentSubCmtModel.getPublishName());
commentType = NewsConstants.Input_Type_SubReply;
break;
}
}
currentOperateIndex = index + 1;
}
commentEditText.setFocusable(true);
commentEditText.setFocusableInTouchMode(true);
commentEditText.requestFocus();
setKeyboardStatu(true);
break;
default:
break;
}
}
/**
* 设置键盘状态
* */
private void setKeyboardStatu(boolean state) {
if (state) {
InputMethodManager imm = (InputMethodManager) commentEditText
.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
} else {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(NewsDetailActivity.this
.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* 动态操作设置
* */
private void newsOperateSet() {
newsOPerate = new NewsOperate<ItemModel>(NewsDetailActivity.this);
newsOPerate.setOperateListener(new OperateCallBack() {
@Override
public void onStart(int operateType) {
switch (operateType) {
case NewsOperate.OP_Type_Delete_News:
// 删除动态
break;
case NewsOperate.OP_Type_Add_Comment:
showLoading("努力发布中...", true);
case NewsOperate.OP_Type_Delete_Comment:
break;
case NewsOperate.OP_Type_Add_Sub_Comment: {
showLoading("努力发布中...", true);
}
break;
case NewsOperate.OP_Type_Delete_Sub_Comment:
break;
default:
break;
}
}
@Override
public void onFinish(int operateType, boolean isSucceed,
Object resultValue) {
actionType = NewsConstants.OPERATE_UPDATE;
switch (operateType) {
case NewsOperate.OP_Type_Delete_News:
if (isSucceed) {
ToastUtil.show(NewsDetailActivity.this, "删除成功");
// 返回上一页
actionType = NewsConstants.OPERATE_DELETET;
finishWithRight();
}
break;
case NewsOperate.OP_Type_Add_Comment:
if (isSucceed) {
// 发布成功则更新评论
CommentModel resultmModel = (CommentModel) resultValue;
detailAdapter.add(DataToItem.createComment(
resultmModel, ItemModel.NEWS_DETAIL_COMMENT));
// 滚动到底部
newsDetailListView.getRefreshableView().setSelection(
detailAdapter.getCount() - 1);
hideLoading();
} else {
hideLoading();
}
break;
case NewsOperate.OP_Type_Delete_Comment:
if (isSucceed) {
detailAdapter.remove(currentOperateIndex);
String topID = currentCommentModel.getCommentID();
// 删除所属的子评论
while (currentOperateIndex < detailAdapter.getCount()) {
if (ItemModel.NEWS_DETAIL_SUB_COMMENT == detailAdapter
.getItem(currentOperateIndex).getItemType()) {
if (((SubCommentItem) detailAdapter
.getItem(currentOperateIndex))
.getSubCommentModel().getTopCommentId()
.equals(topID)) {
detailAdapter.remove(currentOperateIndex);
} else {
break;
}
} else {
break;
}
}
ToastUtil.show(NewsDetailActivity.this, "删除成功");
} else {
ToastUtil.show(NewsDetailActivity.this, "竟然删除失败,检查网络");
}
break;
case NewsOperate.OP_Type_Add_Sub_Comment:
if (isSucceed) {
// 发布成功则更新评论
SubCommentModel resultmModel = (SubCommentModel) resultValue;
// 找到需要插入的位置
int index = currentOperateIndex + 1;
while (index < detailAdapter.getCount()) {
int itemType = detailAdapter.getItem(index)
.getItemType();
if (ItemModel.NEWS_DETAIL_COMMENT == itemType) {
break;
}
index++;
}
// 插入子评论
detailAdapter.insert(index, DataToItem
.createSubComment(resultmModel,
currentNews.getNewsID(),
ItemModel.NEWS_DETAIL_SUB_COMMENT));
// 滚动到添加的评论处
newsDetailListView.getRefreshableView().setSelection(
index);
hideLoading();
} else {
hideLoading();
}
break;
case NewsOperate.OP_Type_Delete_Sub_Comment:
if (isSucceed) {
detailAdapter.remove(currentOperateIndex);
ToastUtil.show(NewsDetailActivity.this, "删除成功");
} else {
ToastUtil.show(NewsDetailActivity.this, "竟然删除失败");
}
break;
default:
break;
}
}
});
}
/**
* listView 支持多种item的设置
* */
private void multiItemTypeSet() {
multiItemTypeSupport = new MultiItemTypeSupport<ItemModel>() {
@Override
public int getLayoutId(int position, ItemModel itemData) {
int layoutId = 0;
switch (itemData.getItemType()) {
case ItemModel.NEWS_DETAIL_TITLE:
layoutId = R.layout.news_detail_title_layout;
break;
case ItemModel.NEWS_DETAIL_BODY:
layoutId = R.layout.news_detail_body_layout;
break;
case ItemModel.NEWS_DETAIL_LIKELIST:
layoutId = R.layout.news_detail_likelist_layout;
break;
case ItemModel.NEWS_DETAIL_COMMENT:
layoutId = R.layout.news_detail_comment_layout;
break;
case ItemModel.NEWS_DETAIL_SUB_COMMENT:
layoutId = R.layout.news_detail_subcomment_layout;
break;
default:
break;
}
return layoutId;
}
@Override
public int getViewTypeCount() {
return ItemModel.NEWS_DETAIL_ITEM_TYPE_COUNT;
}
@Override
public int getItemViewType(int postion, ItemModel itemData) {
int itemtype = 0;
switch (itemData.getItemType()) {
case ItemModel.NEWS_DETAIL_TITLE:
itemtype = ItemModel.NEWS_DETAIL_TITLE;
break;
case ItemModel.NEWS_DETAIL_BODY:
itemtype = ItemModel.NEWS_DETAIL_BODY;
break;
case ItemModel.NEWS_DETAIL_LIKELIST:
itemtype = ItemModel.NEWS_DETAIL_LIKELIST;
break;
case ItemModel.NEWS_DETAIL_COMMENT:
itemtype = ItemModel.NEWS_DETAIL_COMMENT;
break;
case ItemModel.NEWS_DETAIL_SUB_COMMENT:
itemtype = ItemModel.NEWS_DETAIL_SUB_COMMENT;
break;
default:
break;
}
return itemtype;
}
};
}
/**
* listview设置
* */
private void listViewSet() {
// 设置刷新模式
newsDetailListView.setMode(Mode.PULL_FROM_START);
/**
* 刷新监听
* */
newsDetailListView
.setOnRefreshListener(new OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
firstRequstData = false;
getNewsDetailData(
String.valueOf(UserManager.getInstance()
.getUser().getUid()),
currentNews.getNewsID());
}
@Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
// 上拉
/*
* getNewsDetailData(String.valueOf(userModel.getUid()),
* currentNews.getNewsID());
*/
}
});
/**
* adapter的设置
* */
detailAdapter = new HelloHaAdapter<ItemModel>(NewsDetailActivity.this,
dataList, multiItemTypeSupport) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper,
ItemModel item) {
switch (helper.layoutId) {
case R.layout.news_detail_title_layout:
setTitleItemView(helper, item);
break;
case R.layout.news_detail_body_layout:
setBodyItemView(helper, item);
break;
case R.layout.news_detail_likelist_layout:
setLikeListItemView(helper, item);
break;
case R.layout.news_detail_comment_layout:
setComentItemView(helper, item);
break;
case R.layout.news_detail_subcomment_layout:
setSubComentItemView(helper, item);
break;
default:
break;
}
}
};
// 设置不可点击
detailAdapter.setItemsClickEnable(false);
newsDetailListView.setAdapter(detailAdapter);
}
/**
* titleItem的数据绑定与设置
* */
private void setTitleItemView(HelloHaBaseAdapterHelper helper,
ItemModel item) {
TitleItem titleData = (TitleItem) item;
// 显示头像
imgLoader.displayImage(titleData.getHeadSubImage(),
(ImageView) helper.getView(R.id.img_news_detail_user_head),
options);
// 设置用户名,发布的时间,标签
helper.setText(R.id.txt_news_detail_user_name, titleData.getUserName());
helper.setText(R.id.txt_news_detail_user_tag, titleData.getUserSchool());
// 点赞按钮
likeBtn = helper.getView(R.id.btn_news_detail_like);
if (titleData.getIsLike()) {
likeBtn.setStatue(true);
} else {
likeBtn.setStatue(false);
}
// 设置事件监听
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
helper.setOnClickListener(R.id.img_news_detail_user_head, listener);
helper.setOnClickListener(R.id.txt_news_detail_user_name, listener);
helper.setOnClickListener(R.id.btn_news_detail_like, listener);
helper.setOnClickListener(R.id.txt_news_detail_user_tag, listener);
}
/**
* 设置新闻主体item
* */
private void setBodyItemView(HelloHaBaseAdapterHelper helper, ItemModel item) {
final BodyItem bodyData = (BodyItem) item;
List<ImageModel> pictureList = bodyData.getNewsImageListList();
// MultiImageView bodyImages =
// helper.getView(R.id.miv_news_detail_images);
MultiImageMetroView bodyImages = helper
.getView(R.id.miv_news_detail_images);
bodyImages.imageDataSet(pictureList);
bodyImages.setJumpListener(new JumpCallBack() {
@Override
public void onImageClick(Intent intentToimageoBig) {
startActivity(intentToimageoBig);
}
});
// 设置 文字内容
if (bodyData.getNewsContent().equals("")) {
helper.setVisible(R.id.txt_news_detail_content, false);
} else {
helper.setVisible(R.id.txt_news_detail_content, true);
TextView contentView = helper.getView(R.id.txt_news_detail_content);
// customTvHandel.setTextContent(contentView);
contentView.setText(bodyData.getNewsContent());
// 长按复制
contentView.setOnLongClickListener(TextViewHandel
.getLongClickListener(NewsDetailActivity.this,
bodyData.getNewsContent()));
}
// 设置地理位置
if (bodyData.getLocation().equals("")) {
helper.setVisible(R.id.txt_news_detail_location, false);
} else {
helper.setVisible(R.id.txt_news_detail_location, true);
helper.setText(R.id.txt_news_detail_location,
bodyData.getLocation());
}
// 发布时间
helper.setText(R.id.txt_news_detail_publish_time,
TimeHandle.getShowTimeFormat(bodyData.getSendTime()));
// 是发到圈子里的东西
if (bodyData.getTopicID() > 0) {
helper.setVisible(R.id.txt_news_detial_topic_name, true);
// 显示修改
helper.setText(R.id.txt_news_detail_publish_time,
TimeHandle.getShowTimeFormat(bodyData.getSendTime()));
helper.setText(R.id.txt_news_detial_topic_name,
bodyData.getTopicName());
} else {
helper.setVisible(R.id.txt_news_detial_topic_name, false);
}
// 设置事件监听
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
helper.setOnClickListener(R.id.txt_news_detial_topic_name, listener);
}
/**
* 设置点赞部分item
* */
private void setLikeListItemView(HelloHaBaseAdapterHelper helper,
ItemModel item) {
likeControl = helper.getView(R.id.control_like_listview);
likeControl.dataInit(
JLXCUtils.stringToInt(currentNews.getLikeQuantity()),
currentNews.getNewsID());
likeControl.listDataBindSet(currentNews.getLikeHeadListimage());
likeControl.setEventListener(new EventCallBack() {
@Override
public void onItemClick(int userId) {
JumpToHomepage(userId);
}
@Override
public void onAllPersonBtnClick(String newsId) {
// 跳转到点赞的人
Intent intentToALLPerson = new Intent(NewsDetailActivity.this,
AllLikePersonActivity.class);
intentToALLPerson.putExtra(
AllLikePersonActivity.INTENT_KEY_NEWS_ID, newsId);
startActivityWithRight(intentToALLPerson);
}
});
}
/**
* 设置评论item
* */
private void setComentItemView(HelloHaBaseAdapterHelper helper,
ItemModel item) {
CommentModel comment = ((CommentItem) item).getCommentModel();
// 显示评论头像
imgLoader.displayImage(comment.getHeadSubImage(),
(ImageView) helper.getView(R.id.iv_comment_head), options);
// 设置评论的时间、学校与内容
helper.setText(R.id.txt_news_detail_comment_time,
TimeHandle.getShowTimeFormat(comment.getAddDate()));
helper.setText(R.id.txt_news_detail_comment_name,
comment.getPublishName());
// 内容控件
TextView contentView = helper
.getView(R.id.txt_news_detail_comment_content);
contentView.setText(comment.getCommentContent());
// 设置长按复制
helper.setOnLongClickListener(
R.id.layout_news_detail_comment_root_view, TextViewHandel
.getLongClickListener(NewsDetailActivity.this,
comment.getCommentContent()));
// 设置评论item的点击事件
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
helper.setOnClickListener(R.id.iv_comment_head, listener);
helper.setOnClickListener(R.id.layout_news_detail_comment_root_view,
listener);
helper.setOnClickListener(R.id.txt_news_detail_comment_name, listener);
}
/**
* 设置子评论item
* */
private void setSubComentItemView(HelloHaBaseAdapterHelper helper,
ItemModel item) {
SubCommentModel subCmtModel = ((SubCommentItem) item)
.getSubCommentModel();
helper.setText(R.id.txt_sub_comment_by_name,
subCmtModel.getPublishName());
helper.setText(R.id.txt_by_sub_comment_name, subCmtModel.getReplyName());
// 内容控件
TextView contentView = helper.getView(R.id.txt_sub_comment_content);
contentView.setText(subCmtModel.getCommentContent());
// 设置长按复制
helper.setOnLongClickListener(R.id.subcomment_root_view, TextViewHandel
.getLongClickListener(NewsDetailActivity.this,
subCmtModel.getCommentContent()));
// 设置评论item的点击事件
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
helper.setOnClickListener(R.id.subcomment_root_view, listener);
helper.setOnClickListener(R.id.txt_sub_comment_by_name, listener);
helper.setOnClickListener(R.id.txt_by_sub_comment_name, listener);
}
/**
* 数据处理
*/
private void JsonToNewsModel(JSONObject data) {
currentNews.setContentWithJson(data);
// 如果是自己发布的动态
if (true/*currentNews.getUid().equals(
String.valueOf(UserManager.getInstance().getUser().getUid()))*/) {
addRightImgBtn(R.layout.right_image_button,
R.id.layout_top_btn_root_view, R.id.img_btn_right_top);
}
dataList = DataToItem.newsDetailToItems(currentNews);
detailAdapter.replaceAll(dataList);
}
/**
* 获取动态详情数据
* */
private void getNewsDetailData(String uid, String newsId) {
String path = JLXCConst.NEWS_DETAIL + "?" + "news_id=" + newsId
+ "&user_id=" + uid;
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
JsonToNewsModel(jResult);
if (firstRequstData) {
stateHandel();
} else {
newsDetailListView.onRefreshComplete();
}
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(NewsDetailActivity.this,
jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
if (!firstRequstData) {
newsDetailListView.onRefreshComplete();
}
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
if (!firstRequstData) {
newsDetailListView.onRefreshComplete();
}
ToastUtil.show(NewsDetailActivity.this, "网络有毒=_=");
}
}, null));
}
/**
* 删除动态
* */
private void deleteCurrentNews() {
final CustomAlertDialog confirmDialog = new CustomAlertDialog(
NewsDetailActivity.this, "真的狠心删除吗?", "狠心", "舍不得");
confirmDialog.show();
confirmDialog
.setClicklistener(new CustomAlertDialog.ClickListenerInterface() {
@Override
public void doConfirm() {
newsOPerate.deleteNews(currentNews.getNewsID());
confirmDialog.dismiss();
}
@Override
public void doCancel() {
confirmDialog.dismiss();
}
});
}
// 点击回复发送按钮
private void publishComment() {
if (commentContent.length() > 0) {
String tempContent = commentContent;
// 清空输入内容
commentEditText.setText("");
commentEditText.setHint("来条神评论...");
// 隐藏输入键盘
setKeyboardStatu(false);
switch (commentType) {
case NewsConstants.Input_Type_Comment:
// 发布评论
CommentModel temMode = new CommentModel();
temMode.setCommentContent(tempContent);
temMode.setAddDate(TimeHandle.getCurrentDataStr());
newsOPerate.publishComment(UserManager.getInstance().getUser(),
currentNews.getNewsID(), tempContent);
break;
case NewsConstants.Input_Type_SubComment:
// 发布二级评论
SubCommentModel tempMd = new SubCommentModel();
tempMd.setCommentContent(tempContent);
tempMd.setReplyUid(currentCommentModel.getUserId());
tempMd.setReplyName(currentCommentModel.getPublishName());
tempMd.setReplyCommentId(currentCommentModel.getCommentID());
tempMd.setTopCommentId(currentCommentModel.getCommentID());
newsOPerate.publishSubComment(UserManager.getInstance()
.getUser(), currentNews.getNewsID(), tempMd);
break;
case NewsConstants.Input_Type_SubReply:
// 发布子回复
SubCommentModel tpMold = new SubCommentModel();
tpMold.setCommentContent(tempContent);
tpMold.setReplyUid(currentSubCmtModel.getPublishId());
tpMold.setReplyName(currentSubCmtModel.getPublishName());
tpMold.setReplyCommentId(currentSubCmtModel.getSubID());
tpMold.setTopCommentId(currentSubCmtModel.getTopCommentId());
newsOPerate.publishSubComment(UserManager.getInstance()
.getUser(), currentNews.getNewsID(), tpMold);
break;
default:
break;
}
}
}
/**
* view点击事件
* */
public class ItemViewClick implements ListItemClickHelp {
@Override
public void onClick(View view, int postion, int viewID) {
switch (viewID) {
case R.id.img_news_detail_user_head:
case R.id.txt_news_detail_user_name:
TitleItem titleData = (TitleItem) detailAdapter
.getItem(postion);
JumpToHomepage(JLXCUtils.stringToInt(titleData.getUserID()));
break;
case R.id.txt_news_detail_user_tag:
TitleItem schoolData = (TitleItem) detailAdapter
.getItem(postion);
// 跳转至校园主页
Intent intentCampusInfo = new Intent(NewsDetailActivity.this,
CampusHomeActivity.class);
intentCampusInfo.putExtra(
CampusHomeActivity.INTENT_SCHOOL_CODE_KEY,
schoolData.getSchoolCode());
startActivityWithRight(intentCampusInfo);
break;
case R.id.btn_news_detail_like:
actionType = NewsConstants.OPERATE_UPDATE;
likeOperate();
break;
case R.id.txt_news_detial_topic_name:
// 圈子
BodyItem bodyData = (BodyItem) detailAdapter.getItem(postion);
// 确认有圈子
if (bodyData.getTopicID() > 0) {
// 跳转至圈子内容部分
Intent intentToGroupNews = new Intent();
intentToGroupNews.setClass(NewsDetailActivity.this,
GroupNewsActivity.class);
// 传递名称
intentToGroupNews.putExtra(
GroupNewsActivity.INTENT_KEY_TOPIC_NAME,
bodyData.getTopicName());
// 传递ID
intentToGroupNews.putExtra(
GroupNewsActivity.INTENT_KEY_TOPIC_ID,
bodyData.getTopicID());
startActivityWithRight(intentToGroupNews);
}
break;
case R.id.layout_news_detail_comment_root_view:
case R.id.iv_comment_head:
case R.id.txt_news_detail_comment_name:
currentCommentModel = ((CommentItem) detailAdapter
.getItem(postion)).getCommentModel();
if (viewID == R.id.layout_news_detail_comment_root_view) {
currentOperateIndex = postion;
if (currentCommentModel.getUserId().equals(
String.valueOf(UserManager.getInstance().getUser()
.getUid()))) {
// 如果是自己发布的评论,则删除评论
List<String> menuList = new ArrayList<String>();
menuList.add("删除评论");
final CustomListViewDialog downDialog = new CustomListViewDialog(
NewsDetailActivity.this, menuList);
downDialog.setClickCallBack(new ClickCallBack() {
@Override
public void Onclick(View view, int which) {
newsOPerate.deleteComment(
currentCommentModel.getCommentID(),
currentNews.getNewsID());
downDialog.cancel();
}
});
downDialog.show();
} else {
// 发布回复别人的评论
commentEditText.requestFocus();
commentEditText.setHint("回复:"
+ currentCommentModel.getPublishName());
commentType = NewsConstants.Input_Type_SubComment;
// 显示键盘
setKeyboardStatu(true);
}
} else {
JumpToHomepage(JLXCUtils.stringToInt(currentCommentModel
.getUserId()));
}
break;
// 点击了子评论
case R.id.subcomment_root_view:
case R.id.txt_sub_comment_by_name:
case R.id.txt_by_sub_comment_name:
currentSubCmtModel = ((SubCommentItem) detailAdapter
.getItem(postion)).getSubCommentModel();
if (viewID == R.id.subcomment_root_view) {
currentOperateIndex = postion;
if (currentSubCmtModel.getPublishId().equals(
String.valueOf(UserManager.getInstance().getUser()
.getUid()))) {
// 如果是自己发布的评论,则删除评论
List<String> menuList = new ArrayList<String>();
menuList.add("删除回复");
final CustomListViewDialog downDialog = new CustomListViewDialog(
NewsDetailActivity.this, menuList);
downDialog.setClickCallBack(new ClickCallBack() {
@Override
public void Onclick(View view, int which) {
newsOPerate.deleteSubComment(
currentSubCmtModel.getSubID(),
currentNews.getNewsID());
downDialog.cancel();
}
});
downDialog.show();
} else {
// 找到topComment
int index = postion;
while (index >= 0) {
if (ItemModel.NEWS_DETAIL_COMMENT == detailAdapter
.getItem(index).getItemType()) {
break;
}
--index;
}
currentCommentModel = ((CommentItem) detailAdapter
.getItem(index)).getCommentModel();
commentEditText.requestFocus();
commentEditText.setHint("回复:"
+ currentSubCmtModel.getPublishName());
commentType = NewsConstants.Input_Type_SubReply;
setKeyboardStatu(true);
}
} else if (viewID == R.id.txt_sub_comment_by_name) {
JumpToHomepage(JLXCUtils.stringToInt(currentSubCmtModel
.getPublishId()));
} else {
JumpToHomepage(JLXCUtils.stringToInt(currentSubCmtModel
.getReplyUid()));
}
break;
default:
break;
}
}
}
/**
* 点赞操作
* */
private void likeOperate() {
final TitleItem operateData = (TitleItem) detailAdapter.getItem(0);
newsOPerate.setLikeListener(new LikeCallBack() {
@Override
public void onOperateStart(boolean isLike) {
if (isLike) {
// 点赞操作
if (null != likeControl) {
newsOPerate.addHeadToLikeList(likeControl);
} else {
newsOPerate.addDataToLikeList(detailAdapter, 2);
}
operateData.setLikeCount(String.valueOf(operateData
.getLikeCount() + 1));
likeBtn.setStatue(true);
operateData.setIsLike("1");
} else {
// 取消点赞
if (null != likeControl) {
newsOPerate.removeHeadFromLikeList(likeControl);
} else {
newsOPerate.removeDataFromLikeList(detailAdapter, 2);
}
operateData.setLikeCount(String.valueOf(operateData
.getLikeCount() - 1));
likeBtn.setStatue(false);
operateData.setIsLike("0");
}
}
@Override
public void onOperateFail(boolean isLike) {
// 撤销上次
newsOPerate.operateRevoked();
if (isLike) {
operateData.setLikeCount(String.valueOf(operateData
.getLikeCount() - 1));
likeBtn.setStatue(false);
operateData.setIsLike("0");
} else {
operateData.setLikeCount(String.valueOf(operateData
.getLikeCount() + 1));
likeBtn.setStatue(true);
operateData.setIsLike("1");
}
}
});
if (operateData.getIsLike()) {
newsOPerate.uploadLikeOperate(operateData.getNewsID(), false);
} else {
newsOPerate.uploadLikeOperate(operateData.getNewsID(), true);
}
}
/**
* listview点击事件接口,用于区分不同view的点击事件
*
* @author Alan
*
*/
private interface ListItemClickHelp {
void onClick(View view, int postion, int viewID);
}
/**
* 跳转至用户的主页
*/
private void JumpToHomepage(int userID) {
Intent intentUsrMain = new Intent(NewsDetailActivity.this,
OtherPersonalActivity.class);
intentUsrMain.putExtra(OtherPersonalActivity.INTENT_KEY, userID);
startActivityWithRight(intentUsrMain);
}
// 重写
@Override
public void finishWithRight() {
updateResultData();
super.finishWithRight();
}
// 监听返回事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
this.finishWithRight();
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}
/**
* 保存对动态的数据,并广播给上一个activity
* */
private void updateResultData() {
Intent mIntent = new Intent(JLXCConst.BROADCAST_NEWS_LIST_REFRESH);
if (actionType.equals(NewsConstants.OPERATE_UPDATE)) {
// 点赞数据
LikeListItem likeData = (LikeListItem) detailAdapter.getItem(2);
List<LikeModel> newlkList = likeData.getLikeHeadListimage();
// 评论数据
TitleItem titleData = (TitleItem) detailAdapter.getItem(0);
String isLike = "0";
if (titleData.getIsLike()) {
isLike = "1";
}
// 最新的评论数据
List<CommentModel> newCmtList = new ArrayList<CommentModel>();
for (int index = 0; index < detailAdapter.getCount(); index++) {
if (ItemModel.NEWS_DETAIL_COMMENT == detailAdapter.getItem(
index).getItemType()) {
newCmtList.add(((CommentItem) detailAdapter.getItem(index))
.getCommentModel());
}
}
currentNews.setIsLike(isLike);
currentNews.setLikeQuantity(titleData.getLikeCount() + "");
currentNews.setCommentQuantity(String.valueOf(detailAdapter
.getCount() - 3));
currentNews.setLikeHeadListimage(newlkList);
currentNews.setCommentList(newCmtList);
mIntent.putExtra(NewsConstants.OPERATE_UPDATE, currentNews);
} else if (actionType.equals(NewsConstants.OPERATE_DELETET)) {
// 删除操作
mIntent.putExtra(NewsConstants.OPERATE_DELETET,
currentNews.getNewsID());
} else if (actionType.equals(NewsConstants.OPERATE_NO_ACTION)) {
// 没有操作
mIntent.putExtra(NewsConstants.OPERATE_NO_ACTION, "");
}
// 发送广播
LocalBroadcastManager.getInstance(NewsDetailActivity.this)
.sendBroadcast(mIntent);
}
}
<file_sep>package com.jlxc.app.message.ui.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.BitmapManager;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.NewsPushModel;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.ui.view.CustomAlertDialog;
import com.jlxc.app.base.ui.view.CustomListViewDialog;
import com.jlxc.app.base.ui.view.CustomListViewDialog.ClickCallBack;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.TimeHandle;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.message.model.IMModel;
import com.jlxc.app.personal.ui.activity.OtherPersonalActivity;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
//新好友
public class NewFriendsActivity extends BaseActivityWithTopBar {
@ViewInject(R.id.new_friend_list_view)
ListView newFriendListView;
//adapter
HelloHaAdapter<IMModel> newFriendAdapter;
// BitmapUtils bitmapUtils;
//新图片缓存工具 头像
DisplayImageOptions headImageOptions;
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_new_friend_list;
}
@Override
protected void setUpView() {
headImageOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.default_avatar)
.showImageOnFail(R.drawable.default_avatar)
.cacheInMemory(true)
.cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
setBarText("新的朋友");
// bitmapUtils = BitmapManager.getInstance().getHeadPicBitmapUtils(this, R.drawable.default_avatar, true, true);
initListView();
refreshListView();
//发送通知
sendNotify();
}
//////////////////////////////private method////////////////////////////////
private void initListView() {
//初始化adapter
newFriendAdapter = new HelloHaAdapter<IMModel>(this, R.layout.new_friend_adapter) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper, final IMModel item) {
//头像
ImageView imageView = helper.getView(R.id.head_image_view);
if (null != item.getAvatarPath() && item.getAvatarPath().length() > 0) {
ImageLoader.getInstance().displayImage(JLXCConst.ATTACHMENT_ADDR + item.getAvatarPath(), imageView, headImageOptions);
}else {
imageView.setImageResource(R.drawable.default_avatar);
}
//姓名
helper.setText(R.id.name_text_view, item.getTitle());
// ImageView unreadImageView = helper.getView(R.id.unread_image_view);
//是否是新的
// if (item.getIsRead() == 0) {
// unreadImageView.setVisibility(View.VISIBLE);
// }else {
// unreadImageView.setVisibility(View.GONE);
// }
if (null != item.getAddDate() && item.getAddDate().length()>4) {
//时间
helper.setText(R.id.time_text_view, TimeHandle.getShowTimeFormat(item.getAddDate()));
}else {
helper.setText(R.id.time_text_view, "");
}
}
};
newFriendListView.setAdapter(newFriendAdapter);
//点击进入详情
newFriendListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
IMModel imModel = newFriendAdapter.getItem(position);
Intent intent = new Intent(NewFriendsActivity.this, OtherPersonalActivity.class);
intent.putExtra(OtherPersonalActivity.INTENT_KEY, JLXCUtils.stringToInt(imModel.getTargetId().replace(JLXCConst.JLXC, "")));
startActivityWithRight(intent);
}
});
//长按删除
newFriendListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
List<String> menuList = new ArrayList<String>();
menuList.add("删除内容");
final CustomListViewDialog confirmDialog = new CustomListViewDialog(
NewFriendsActivity.this, menuList);
confirmDialog.setClickCallBack(new ClickCallBack() {
@Override
public void Onclick(View view, int which) {
IMModel imModel = newFriendAdapter.getItem(position);
imModel.setIsNew(0);
imModel.update();
refreshListView();
confirmDialog.dismiss();
}
});
if (null != confirmDialog && !confirmDialog.isShowing()) {
confirmDialog.show();
}
return true;
}
});
}
private void refreshListView() {
List<IMModel> newFriendList = IMModel.findAllNewFriends();
newFriendAdapter.replaceAll(newFriendList);
//设置已读
IMModel.hasRead();
//通知
Intent notifyIntent = new Intent(JLXCConst.BROADCAST_TAB_BADGE);
sendBroadcast(notifyIntent);
}
// //添加好友
// private void addFriend(final IMModel imModel) {
//
// // 参数设置
// RequestParams params = new RequestParams();
// params.addBodyParameter("user_id", UserManager.getInstance().getUser().getUid()+"");
// params.addBodyParameter("friend_id", imModel.getTargetId().replace(JLXCConst.JLXC, "")+"");
//
// showLoading("添加中^_^", false);
// HttpManager.post(JLXCConst.Add_FRIEND, params,
// new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
//
// @Override
// public void onSuccess(JSONObject jsonResponse, String flag) {
// super.onSuccess(jsonResponse, flag);
//
// hideLoading();
// int status = jsonResponse.getInteger(JLXCConst.HTTP_STATUS);
// ToastUtil.show(NewFriendsActivity.this,jsonResponse.getString(JLXCConst.HTTP_MESSAGE));
//
// if (status == JLXCConst.STATUS_SUCCESS) {
// //本地数据持久化
// IMModel newModel = IMModel.findByGroupId(imModel.getTargetId());
// //如果存在更新
// if (null != newModel) {
// newModel.setTitle(imModel.getTitle());
// newModel.setAvatarPath(imModel.getAvatarPath());
// newModel.setIsNew(1);
// newModel.setIsRead(1);
// newModel.setCurrentState(IMModel.GroupHasAdd);
// newModel.update();
// }else {
// newModel = new IMModel();
// newModel.setType(IMModel.ConversationType_PRIVATE);
// newModel.setTargetId(imModel.getTargetId());
// newModel.setTitle(imModel.getTitle());
// newModel.setAvatarPath(imModel.getAvatarPath());
// newModel.setIsNew(1);
// newModel.setIsRead(1);
// newModel.setCurrentState(IMModel.GroupHasAdd);
// newModel.setOwner(UserManager.getInstance().getUser().getUid());
// newModel.save();
// }
//
// refreshListView();
// }
// }
//
// @Override
// public void onFailure(HttpException arg0, String arg1,
// String flag) {
// super.onFailure(arg0, arg1, flag);
// hideLoading();
// ToastUtil.show(NewFriendsActivity.this,
// "网络异常");
// }
// }, null));
// }
//发送通知
private void sendNotify() {
//通知刷新
Intent tabIntent = new Intent(JLXCConst.BROADCAST_TAB_BADGE);
sendBroadcast(tabIntent);
//通知页面刷新
Intent messageIntent = new Intent(JLXCConst.BROADCAST_NEW_MESSAGE_PUSH);
sendBroadcast(messageIntent);
//顶部刷新
Intent messageTopIntent = new Intent(JLXCConst.BROADCAST_MESSAGE_REFRESH);
sendBroadcast(messageTopIntent);
}
}
<file_sep>package com.jlxc.app.message.helper;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.utils.TimeHandle;
import com.jlxc.app.message.model.IMModel;
//发现部分的 添加好友帮助类
public class MessageAddFriendHelper {
//添加好友
public static void addFriend(IMModel imModel) {
//本地数据持久化
IMModel newModel = IMModel.findByGroupId(imModel.getTargetId());
//如果存在更新
if (null != newModel) {
newModel.setTitle(imModel.getTitle());
newModel.setAvatarPath(imModel.getAvatarPath());
// newModel.setIsNew(0);
// newModel.setIsRead(1);
newModel.setCurrentState(IMModel.GroupHasAdd);
// newModel.setAddDate(TimeHandle.getCurrentDataStr());
newModel.update();
}else {
newModel = new IMModel();
newModel.setType(IMModel.ConversationType_PRIVATE);
newModel.setTargetId(imModel.getTargetId());
newModel.setTitle(imModel.getTitle());
newModel.setAvatarPath(imModel.getAvatarPath());
// newModel.setAddDate(TimeHandle.getCurrentDataStr());
newModel.setIsNew(0);
newModel.setIsRead(1);
newModel.setCurrentState(IMModel.GroupHasAdd);
newModel.setOwner(UserManager.getInstance().getUser().getUid());
newModel.save();
}
}
}
<file_sep>package com.jlxc.app.news.model;
import java.io.Serializable;
import com.alibaba.fastjson.JSONObject;
public class SubCommentModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3721167041844355170L;
// 子评论的id
private String subID;
// 评论者的名字
private String publishName;
// 顶部的评论id
private String topCommentId;
// 被回复者的id
private String replyUid;
// 被回复飞评论id
private String replyCommentId;
// 被回复者的名字
private String replyName;
// 添加的日期
private String addData;
// 发布者的名字
private String publisId;
// 发布的内容
private String commentContent;
// 内容注入
public void setContentWithJson(JSONObject object) {
if (object.containsKey("id")) {
setSubID(object.getString("id"));
}
if (object.containsKey("name")) {
setPublishName(object.getString("name"));
}
if (object.containsKey("top_comment_id")) {
setTopCommentId(object.getString("top_comment_id"));
}
if (object.containsKey("reply_uid")) {
setReplyUid(object.getString("reply_uid"));
}
if (object.containsKey("reply_comment_id")) {
setReplyCommentId(object.getString("reply_comment_id"));
}
if (object.containsKey("reply_name")) {
setReplyName(object.getString("reply_name"));
}
if (object.containsKey("add_date")) {
setAddData(object.getString("add_date"));
}
if (object.containsKey("user_id")) {
setPublishId(object.getString("user_id"));
}
if (object.containsKey("comment_content")) {
setCommentContent(object.getString("comment_content"));
}
}
public String getSubID() {
return subID;
}
public void setSubID(String subID) {
this.subID = subID;
}
public String getPublishName() {
return publishName;
}
public void setPublishName(String publishName) {
this.publishName = publishName;
}
public String getTopCommentId() {
return topCommentId;
}
public void setTopCommentId(String topCommentId) {
this.topCommentId = topCommentId;
}
public String getReplyUid() {
return replyUid;
}
public void setReplyUid(String replyUid) {
this.replyUid = replyUid;
}
public String getReplyCommentId() {
return replyCommentId;
}
public void setReplyCommentId(String replyCommentId) {
this.replyCommentId = replyCommentId;
}
public String getReplyName() {
return replyName;
}
public void setReplyName(String replyName) {
this.replyName = replyName;
}
public String getAddData() {
return addData;
}
public void setAddData(String addData) {
this.addData = addData;
}
public String getPublishId() {
return publisId;
}
public void setPublishId(String userId) {
publisId = userId;
}
public String getCommentContent() {
return commentContent;
}
public void setCommentContent(String commentContent) {
this.commentContent = commentContent;
}
}
<file_sep>package com.jlxc.app.personal.model;
//最近来访模型
/**
* @author lixiaohang
*
*/
public class OtherPeopleFriendModel {
private int uid;//uid
private String name;//姓名
private String head_sub_image;//头像
private String school;//学校
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHead_sub_image() {
return head_sub_image;
}
public void setHead_sub_image(String head_sub_image) {
this.head_sub_image = head_sub_image;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
<file_sep>package com.jlxc.app.group.ui.activity;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.personal.ui.activity.OtherPersonalActivity;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
public class GroupInfoActivity extends BaseActivityWithTopBar {
public static String INTENT_KEY = "topicId";
// 图片
@ViewInject(R.id.group_image_view)
private ImageView topicImageView;
// 圈子名
@ViewInject(R.id.group_name_text_view)
private TextView topicNameTextView;
// 圈子内容数量
@ViewInject(R.id.group_news_count_text_view)
private TextView topicCountTextView;
// 活跃程度
@ViewInject(R.id.active_text_view)
private TextView activeTextView;
// 活跃图
@ViewInject(R.id.active_image_view)
private ImageView activeImageView;
// 创建者姓名
@ViewInject(R.id.create_name_text_view)
private TextView createNameTextView;
// 类别名
@ViewInject(R.id.category_name)
private TextView categoryNametTextView;
// 创建者头像
@ViewInject(R.id.create_head_image_view)
private ImageView createImageView;
// 成员数量
@ViewInject(R.id.member_count_text_view)
private TextView memberCountTextView;
// 话题详情
@ViewInject(R.id.group_description_text_view)
private TextView topicDescTextView;
// 操作按钮 关注或者取消关注
@ViewInject(R.id.btn_group_operate)
private Button groupOperateButton;
// 成员A
@ViewInject(R.id.img_number_A)
private ImageView memberAImageView;
// 成员B
@ViewInject(R.id.img_number_B)
private ImageView memberBImageView;
// 成员C
@ViewInject(R.id.img_number_C)
private ImageView memberCImageView;
// 成员D
@ViewInject(R.id.img_number_D)
private ImageView memberDImageView;
// 加载图片
@SuppressWarnings("unused")
private ImageLoader imgLoader;
// 图片配置
private DisplayImageOptions options;
// 话题id
private int topicId;
// 是否已经关注了
private boolean isJoin;
// 创建人ID
private int creatorId;
//类别ID
private int categoryId;
//类别名字
private String categoryName;
// 成员数组
private List<TopicMember> topicMembers;
@OnClick({ R.id.layout_group_info_create_creator,
R.id.layout_group_info_member, R.id.btn_group_operate, R.id.category_layout})
private void clickEvent(View view) {
switch (view.getId()) {
// 点击创建人item
case R.id.layout_group_info_create_creator:
if (creatorId != 0) {
Intent creatorIntent = new Intent(this, OtherPersonalActivity.class);
creatorIntent.putExtra(OtherPersonalActivity.INTENT_KEY, creatorId);
startActivityWithRight(creatorIntent);
}
break;
// 查看所有所有成员
case R.id.layout_group_info_member:
if (topicId != 0) {
Intent allIntent = new Intent(this, GroupAllPersonActivity.class);
allIntent.putExtra(GroupAllPersonActivity.INTENT_KEY, topicId);
startActivityWithRight(allIntent);
}
break;
// 操作按钮事件
case R.id.btn_group_operate:
if (topicId != 0) {
joinOrExit();
}
break;
// 类别布局
case R.id.category_layout:
if (categoryId != 0) {
// 跳转至更多圈子列表
Intent intentToGroupList = new Intent();
intentToGroupList.setClass(this,MoreGroupListActivity.class);
intentToGroupList.putExtra(
MoreGroupListActivity.INTENT_CATEGORY_ID_KEY,
categoryId);
intentToGroupList.putExtra(
MoreGroupListActivity.INTENT_CATEGORY_NAME_KEY,
categoryName);
startActivityWithRight(intentToGroupList);
}
break;
default:
break;
}
}
@Override
public int setLayoutId() {
return R.layout.activity_group_info;
}
@Override
protected void setUpView() {
// 获取intent
Intent intent = getIntent();
topicId = intent.getIntExtra(INTENT_KEY, 0);
initImageLoader();
initWidget();
// 数据获取
getGroupInfoData();
}
/**
* 初始化图片加载工具
* */
private void initImageLoader() {
// 获取显示图片的实例
imgLoader = ImageLoader.getInstance();
// 显示图片的配置
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading_default)
.showImageOnFail(R.drawable.image_load_fail).cacheInMemory(true)
.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
}
/**
* 控件初始化
* */
private void initWidget() {
setBarText("频道信息");
// 添加圈子设置按钮
ImageView groupSetting = addRightImgBtn(R.layout.right_image_button,
R.id.layout_top_btn_root_view, R.id.img_btn_right_top);
groupSetting.setImageResource(R.drawable.setting_btn);
groupSetting.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intentGroupSet = new Intent(GroupInfoActivity.this,
GroupManageActivity.class);
startActivityWithRight(intentGroupSet);
}
});
// 隐藏设置按钮
groupSetting.setVisibility(View.GONE);
}
/**
* 获取群组数据
* */
private void getGroupInfoData() {
// 获取群组详情
String path = JLXCConst.GET_TOPIC_DETAIL + "?topic_id=" + topicId
+ "&user_id=" + UserManager.getInstance().getUser().getUid();
LogUtils.i(path, 1);
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
hideLoading();
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
handleResult(jResult);
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(GroupInfoActivity.this, jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
hideLoading();
super.onFailure(arg0, arg1, flag);
ToastUtil.show(GroupInfoActivity.this, "oh no 获取失败...");
}
}, null));
}
// 处理结果
private void handleResult(JSONObject result) {
JSONObject content = result.getJSONObject("content");
// 名字
topicNameTextView.setText(content.getString("topic_name"));
// 内容
int newsCount = result.getIntValue("news_count");
topicCountTextView.setText(newsCount + "条内容");
if (newsCount > 100) {
activeTextView.setText("热门");
activeImageView.setImageResource(R.drawable.group_statues_hot);
} else if (newsCount > 50) {
activeTextView.setText("中等");
activeImageView.setImageResource(R.drawable.group_statues_moderate);
} else {
activeTextView.setText("冷清");
activeImageView.setImageResource(R.drawable.group_statues_cold);
}
// 图片
ImageLoader.getInstance().displayImage(
JLXCConst.ATTACHMENT_ADDR
+ content.getString("topic_cover_image"),
topicImageView, options);
// 创建者
createNameTextView.setText(content.getString("name"));
//类别ID
categoryId = content.getIntValue("category_id");
categoryName = content.getString("category_name");
// 类别名
categoryNametTextView.setText(categoryName);
creatorId = content.getIntValue("user_id");
// 创建者头像
ImageLoader.getInstance()
.displayImage(
JLXCConst.ATTACHMENT_ADDR
+ content.getString("head_sub_image"),
createImageView, options);
// 成员数量
memberCountTextView.setText(result.getString("member_count"));
// 圈子介绍
topicDescTextView.setText(content.getString("topic_detail"));
// 加入状态
int joinState = result.getInteger("join_state");
groupOperateButton.setVisibility(View.VISIBLE);
if (joinState == 1) {
isJoin = true;
groupOperateButton.setText("取消关注");
groupOperateButton.setBackgroundResource(R.drawable.logout_btn);
} else {
isJoin = false;
groupOperateButton.setText("关注");
groupOperateButton
.setBackgroundResource(R.drawable.alert_dialog_confirm_btn_normal);
}
//如果是创建者隐藏
if (creatorId == UserManager.getInstance().getUser().getUid()) {
groupOperateButton.setVisibility(View.GONE);
}
topicMembers = new ArrayList<GroupInfoActivity.TopicMember>();
List<ImageView> memberImageViews = new ArrayList<ImageView>();
memberImageViews.add(memberAImageView);
memberImageViews.add(memberBImageView);
memberImageViews.add(memberCImageView);
memberImageViews.add(memberDImageView);
// 成员们 最多4个
JSONArray members = result.getJSONArray("members");
for (int i = 0; i < members.size(); i++) {
JSONObject object = members.getJSONObject(i);
ImageView memberImageView = memberImageViews.get(i);
// 显示出来
memberImageView.setVisibility(View.VISIBLE);
TopicMember member = new TopicMember();
member.setUser_id(object.getIntValue("user_id"));
member.setName(object.getString("name"));
member.setHead_sub_image(object.getString("head_sub_image"));
topicMembers.add(member);
ImageLoader.getInstance().displayImage(
JLXCConst.ATTACHMENT_ADDR + member.getHead_sub_image(),
memberImageView, options);
}
}
// 加入或者退出
private void joinOrExit() {
// 参数设置
RequestParams params = new RequestParams();
params.addBodyParameter("user_id", UserManager.getInstance().getUser()
.getUid()
+ "");
params.addBodyParameter("topic_id", topicId + "");
// 路径
String path = JLXCConst.JOIN_TOPIC;
if (isJoin) {
path = JLXCConst.QUIT_TOPIC;
showLoading("取消关注中..", false);
} else {
showLoading("关注中..", false);
}
HttpManager.post(path, params, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
hideLoading();
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
ToastUtil.show(GroupInfoActivity.this, jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
// 更新UI及其界面状态
if (isJoin) {
isJoin = false;
groupOperateButton.setText("关注");
groupOperateButton
.setBackgroundResource(R.drawable.alert_dialog_confirm_btn_normal);
} else {
isJoin = true;
groupOperateButton.setText("取消关注");
groupOperateButton
.setBackgroundResource(R.drawable.logout_btn);
}
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(GroupInfoActivity.this, jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
hideLoading();
super.onFailure(arg0, arg1, flag);
ToastUtil.show(GroupInfoActivity.this, "网络异常");
}
}, null));
}
@SuppressWarnings("unused")
private class TopicMember {
private int user_id;
private String name;
private String head_sub_image;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHead_sub_image() {
return head_sub_image;
}
public void setHead_sub_image(String head_sub_image) {
this.head_sub_image = head_sub_image;
}
}
}
<file_sep>package com.jlxc.app.group.model;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.news.model.ImageModel;
import com.jlxc.app.news.model.LikeModel;
/**
* 将每条动态拆分成不同的部分
* */
public class SchoolItemModel {
// 校园item的种类数
public static final int SCHOOL_NEWS_ITEM_TYPE_COUNT = 4;
// 表示校园各item类型
public static final int SCHOOL_NEWS_TITLE = 0;
public static final int SCHOOL_NEWS_BODY = 1;
public static final int SCHOOL_NEWS_OPERATE = 2;
public static final int SCHOOL_NEWS_LIKELIST = 3;
// 动态的id
private String newsID = "";
// 当前的item类型
private int itemType;
public int getItemType() {
return itemType;
}
/**
* 设置item的类型
* */
public void setItemType(int type) {
switch (type) {
case 0:
case 1:
case 2:
case 3:
itemType = type;
break;
default:
LogUtils.e("items type error");
break;
}
}
public String getNewsID() {
return newsID;
}
public void setNewsID(String newsID) {
this.newsID = newsID;
}
/**
* 动态的头部
* */
public static class SchoolNewsTitleItem extends SchoolItemModel {
// 动态发布者的头像缩略图
private String headSubImage;
// 动态发布者的头像
private String headImage;
// 动态发布者的名字
private String userName;
// 显示用户的id
private String userID;
// 发布的时间
private String sendTime;
public String getHeadSubImage() {
return headSubImage;
}
public void setHeadSubImage(String headSubImage) {
this.headSubImage = headSubImage;
}
public String getHeadImage() {
return headImage;
}
public void setHeadImage(String userHeadImage) {
this.headImage = userHeadImage;
}
public String getUserName() {
return userName;
}
public void setUserName(String userNameStr) {
this.userName = userNameStr;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getSendTime() {
return sendTime;
}
public void setSendTime(String sendTime) {
this.sendTime = sendTime;
}
}
/**
* 动态的主体
* */
public static class SchoolNewsBodyItem extends SchoolItemModel {
// 动态的文字内容
private String newsContent;
// 动态的图片列表
private List<ImageModel> newsImageList = new ArrayList<ImageModel>();
// 发布的位置
private String location;
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
public List<ImageModel> getNewsImageListList() {
return newsImageList;
}
public void setImageNewsList(List<ImageModel> imageList) {
this.newsImageList = imageList;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
/**
* 动态的操作部分
* */
public static class SchoolNewsOperateItem extends SchoolItemModel {
// 是否已赞
private boolean isLike = false;
// 点赞数
private int likeCount;
// 评论数
private int commentCount;
public boolean getIsLike() {
return isLike;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(String likeCount) {
try {
this.likeCount = Integer.parseInt(likeCount);
} catch (Exception e) {
LogUtils.e("点赞数据格式错误.");
}
}
public void setIsLike(String isLike) {
if (isLike.equals("1")) {
this.isLike = true;
} else {
this.isLike = false;
}
}
public int getCommentCount() {
return commentCount;
}
public void setCommentCount(int commentCount) {
this.commentCount = commentCount;
}
}
/**
* 已赞的人的头像部分
* */
public static class SchoolNewsLikeListItem extends SchoolItemModel {
// 点赞数
private int likeCount;
// 点赞的人头像
private List<LikeModel> likeList = new ArrayList<LikeModel>();
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(String likeCount) {
try {
this.likeCount = Integer.parseInt(likeCount);
} catch (Exception e) {
LogUtils.e("点赞数据格式错误.");
}
}
public List<LikeModel> getLikeHeadListimage() {
return likeList;
}
public void setLikeHeadListimage(List<LikeModel> list) {
this.likeList = list;
}
}
}
<file_sep>package com.jlxc.app.login.ui.activity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import com.jlxc.app.R;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.ui.view.CustomAlertDialog;
import com.jlxc.app.base.utils.ToastUtil;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
public class VerifyActivity extends BaseActivityWithTopBar {
private final static String INTENT_KEY = "username";
// 是否是忘记密码
private Boolean isFindPwd;
// 当前倒计时的值
private int countdownValue = 0;
// 倒计时对象
private CountDownTimer verifyCountdownTimer = null;
// 用户 的电话号码
private String userPhoneNumber;
// 用户输入的验证码
private String verifyCodeEditTextValue;
// 返回按钮
@ViewInject(R.id.base_tv_back)
private TextView backTextView;
// 页面标头
@ViewInject(R.id.base_tv_title)
private TextView titletTextView;
// 提示电话的textview
@ViewInject(R.id.phone_prompt_textview)
private TextView phonePromptTextView;
// 验证码输入框
@ViewInject(R.id.verificationcode_edittext)
private EditText verifycodeEditText;
// 下一步按钮
@ViewInject(R.id.next_button)
private Button nextButton;
// 重新验证
@ViewInject(R.id.revalidated_textview)
private TextView revalidatedTextView;
// 点击事件绑定
@OnClick({ R.id.base_tv_back, R.id.next_button, R.id.revalidated_textview,
R.id.register_activity })
public void viewCickListener(View view) {
switch (view.getId()) {
case R.id.base_tv_back:
backClick();
break;
case R.id.next_button:
// 点击下一步
nextClick();
break;
case R.id.revalidated_textview:
getVerificationCode();
break;
case R.id.register_activity:
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
break;
default:
break;
}
}
// 初始化数据
private void init() {
Intent intent = getIntent();
userPhoneNumber = intent.getStringExtra(INTENT_KEY);
isFindPwd = intent.getBooleanExtra("isFindPwd", false);
}
// 点击返回
private void backClick() {
if (countdownValue > 0) {
final CustomAlertDialog confirmDialog = new CustomAlertDialog(
this, "已经发送验证码了,再等会儿", "好的", "不了");
confirmDialog.show();
confirmDialog.setClicklistener(new CustomAlertDialog.ClickListenerInterface() {
@Override
public void doConfirm() {
confirmDialog.dismiss();
}
@Override
public void doCancel() {
verifyCountdownTimer.cancel();
finishWithRight();
confirmDialog.dismiss();
}
});
} else {
finishWithRight();
}
}
// 点击下一步按钮
private void nextClick() {
verifyCodeEditTextValue = verifycodeEditText.getText().toString();
// 判断输入值是否正确
if (verifyCodeEditTextValue.length() == 0) {
ToastUtil.show(VerifyActivity.this, "验证码未输入");
} else {
// 忘记密码
if (isFindPwd) {
findPwd();
} else {
// 注册
startRegister();
}
}
}
// 找回密码
private void findPwd() {
showLoading("数据上传中^_^", false);
try {
//先验证验证码
SMSSDK.submitVerificationCode("86", userPhoneNumber, verifycodeEditText.getText().toString().trim());
} catch (Exception e) {
hideLoading();
showLoading("。。。您先等会,好像有点问题", false);
}
// nextActivity();
}
// // 找回密码
// private void finishPwd() {
// Intent intent = new Intent(this, RegisterActivity.class);
// intent.putExtra("isFindPwd", isFindPwd);
// intent.putExtra("username", userPhoneNumber);
// startActivityWithRight(intent);
// }
// 开始注册
private void startRegister() {
VerifyActivity.this.showLoading("验证中︿( ̄︶ ̄)︿", false);
try {
//先验证验证码 测试注释掉
SMSSDK.submitVerificationCode("86", userPhoneNumber, verifycodeEditText.getText().toString().trim());
} catch (Exception e) {
hideLoading();
showLoading("。。。您先等会,好像有点问题", false);
}
// nextActivity();
}
//验证成功 下一页
private void nextActivity() {
hideLoading();
Intent intent = new Intent(this, RegisterActivity.class);
intent.putExtra("username", userPhoneNumber);
intent.putExtra("isFindPwd", isFindPwd);
startActivityWithRight(intent);
}
// //验证成功 完成注册
// private void finishRegister() {
// Intent intent = new Intent(this, RegisterActivity.class);
// intent.putExtra("username", userPhoneNumber);
// startActivityWithRight(intent);
// }
@Override
public int setLayoutId() {
return R.layout.activity_verify_layout;
}
@Override
protected void setUpView() {
// 填写从短信SDK应用后台注册得到的APPKEY
String APPKEY = "<KEY>";//463db7238681 27fe7909f8e8
// 填写从短信SDK应用后台注册得到的APPSECRET
String APPSECRET = "f3d6e97c5b3a1872336ff370a08d1aeb";
//初始化验证码
SMSSDK.initSDK(this,APPKEY,APPSECRET);
init();
//初始化获取一次验证码
SMSSDK.getVerificationCode("86",userPhoneNumber);
RelativeLayout rlBar = (RelativeLayout) findViewById(R.id.layout_base_title);
rlBar.setBackgroundResource(R.color.main_clear);
titletTextView.setText("验证码");
phonePromptTextView.setText("验证码已发送至:" + userPhoneNumber);
revalidatedTextView.setEnabled(false);
verifyCountdownTimer = new CountDownTimer(60000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
countdownValue = (int) millisUntilFinished / 1000;
revalidatedTextView.setText(countdownValue + "s 后重发");
}
@Override
public void onFinish() {
countdownValue = 0;
revalidatedTextView.setEnabled(true);
revalidatedTextView.setText("获取验证码");
}
};
// 开始倒计时
verifyCountdownTimer.start();
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
try {
//验证码接收器
EventHandler eh=new EventHandler(){
@Override
public void afterEvent(int event, int result, Object data) {
Message msg = new Message();
msg.arg1 = event;
msg.arg2 = result;
msg.obj = data;
handler.sendMessage(msg);
}
};
SMSSDK.registerEventHandler(eh);
} catch (Exception e) {
System.out.println("没初始化SMSSDK 因为这个短信sdk对DEBUG有影响 所以不是RELEASE不初始化");
}
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
SMSSDK.unregisterAllEventHandler();
} catch (Exception e) {
System.out.println("没初始化SMSSDK 因为这个短信sdk对DEBUG有影响 所以不是RELEASE不初始化");
}
}
@Override
protected void loadLayout(View v) {
}
// 获取验证码
private void getVerificationCode() {
try {
//发送验证码
SMSSDK.getVerificationCode("86",userPhoneNumber);
verifyCountdownTimer.start();
showLoading("验证码获取中..", true);
} catch (Exception e) {
// TODO: handle exception
}
// // 设置字体颜色
// revalidatedTextView.setTextColor(Color.GRAY);
// // 网络请求
// RequestParams params = new RequestParams();
// params.addBodyParameter("phone_num", userPhoneNumber);
//
// HttpManager.post(JLXCConst.GET_MOBILE_VERIFY, params,
// new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
//
// @Override
// public void onSuccess(JSONObject jsonResponse, String flag) {
// super.onSuccess(jsonResponse, flag);
// int status = jsonResponse
// .getInteger(JLXCConst.HTTP_STATUS);
// if (status == JLXCConst.STATUS_SUCCESS) {
// ToastUtil.show(VerifyActivity.this, "验证码已发送");
// verifyCountdownTimer.start();
// }
//
// if (status == JLXCConst.STATUS_FAIL) {
// hideLoading();
// showConfirmAlert("提示", jsonResponse
// .getString(JLXCConst.HTTP_MESSAGE));
// }
// }
//
// @Override
// public void onFailure(HttpException arg0, String arg1,
// String flag) {
// super.onFailure(arg0, arg1, flag);
// hideLoading();
// showConfirmAlert("提示", "获取失败,请检查网络连接!");
// }
// }, null));
}
/**
* 重写返回操作
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
backClick();
return true;
} else
return super.onKeyDown(keyCode, event);
}
@SuppressLint("HandlerLeak")
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
hideLoading();
// TODO Auto-generated method stub
super.handleMessage(msg);
int event = msg.arg1;
int result = msg.arg2;
Object data = msg.obj;
Log.e("event", "event="+event);
if (result == SMSSDK.RESULT_COMPLETE) {
//短信注册成功后,返回MainActivity,然后提示新好友
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
//完成注册或者找回密码
nextActivity();
} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
ToastUtil.show(VerifyActivity.this, "验证码已发送至您的手机");
}else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){//返回支持发送验证码的国家列表
}
} else {
((Throwable) data).printStackTrace();
ToastUtil.show(VerifyActivity.this, "竟然连验证码都写错了Σ( ° △ °|||)︴ ");
}
}
};
}
<file_sep>package com.jlxc.app.discovery.ui.fragment;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.adapter.MultiItemTypeSupport;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.ui.fragment.BaseFragment;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.discovery.model.PersonModel;
import com.jlxc.app.discovery.model.RecommendItemData;
import com.jlxc.app.discovery.model.RecommendItemData.RecommendInfoItem;
import com.jlxc.app.discovery.model.RecommendItemData.RecommendPhotoItem;
import com.jlxc.app.discovery.model.RecommendItemData.RecommendTitleItem;
import com.jlxc.app.discovery.ui.avtivity.ContactsUserActivity;
import com.jlxc.app.discovery.ui.avtivity.SameSchoolActivity;
import com.jlxc.app.discovery.ui.avtivity.SearchUserActivity;
import com.jlxc.app.discovery.utils.DataToRecommendItem;
import com.jlxc.app.message.helper.MessageAddFriendHelper;
import com.jlxc.app.message.model.IMModel;
import com.jlxc.app.personal.ui.activity.MyNewsListActivity;
import com.jlxc.app.personal.ui.activity.OtherPersonalActivity;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
@SuppressLint("ResourceAsColor") public class DiscoveryFragment extends BaseFragment {
// private final static int SCANNIN_GREQUEST_CODE = 1;
private static final String LOOK_ALL_PHOTOS = "btn_all_photos";
// 用户实例
private UserModel userModel;
// 上下文信息
private Context mContext;
// 加载图片
private ImageLoader imgLoader;
// 图片配置
private DisplayImageOptions options;
// // 屏幕的尺寸
// private int screenWidth = 0;
// // 标头
// @ViewInject(R.id.tv_discovey_title)
// private TextView titleTextView;
// // 扫一扫按钮
// @ViewInject(R.id.qrcode_scan_btn)
// private ImageButton qrcodeScanBtn;
// 搜索框按钮
@ViewInject(R.id.tv_discovey_search)
private TextView searchTextView;
// 推荐的人列表
@ViewInject(R.id.listview_discovey)
private PullToRefreshListView rcmdPersonListView;
// 提示信息
@ViewInject(R.id.tv_recommend_prompt)
private TextView recommendPrompt;
// 原始数据
private List<PersonModel> personList = new ArrayList<PersonModel>();
// item数据
private List<RecommendItemData> itemDataList = new ArrayList<RecommendItemData>();
// 适配器
private HelloHaAdapter<RecommendItemData> personItemAdapter = null;
// 使支持多种item
private MultiItemTypeSupport<RecommendItemData> multiItemTypeRecommend = null;
// 是否是最后一页数据
private boolean lastPage = false;
// 当前的数据页
private int currentPage = 1;
// 是否下拉
private boolean isPullDowm = false;
// 点击view监听对象
private ItemViewClick itemViewClickListener;
// // 点击图片监听
// private ImageGridViewItemClick imageItemClickListener;
// 是否正在请求上拉数据
private boolean isRequestingUpData = false;
/**
* 点击事件监听
* */
@OnClick(value = { R.id.tv_discovey_search })
private void clickEvent(View view) {
switch (view.getId()) {
// // 扫一扫页面
// case R.id.qrcode_scan_btn:
// Intent qrIntent = new Intent();
// qrIntent.setClass(getActivity(), MipcaCaptureActivity.class);
// qrIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// getActivity().startActivityForResult(qrIntent,
// SCANNIN_GREQUEST_CODE);
//
// break;
// 搜索页面
case R.id.tv_discovey_search:
Intent searchIntent = new Intent(getActivity(),
SearchUserActivity.class);
startActivityWithRight(searchIntent);
break;
}
}
@Override
public int setLayoutId() {
return R.layout.fragment_add_friend_layout;
}
@Override
public void loadLayout(View rootView) {
}
@Override
public void setUpViews(View rootView) {
init();
multiItemTypeSet();
newsListViewSet();
// 添加title部分
RecommendTitleItem titleItem = new RecommendTitleItem();
personItemAdapter.add(titleItem);
// 首次更新数据
isPullDowm = true;
getRecommentData(String.valueOf(userModel.getUid()),
String.valueOf(currentPage));
}
private void init() {
mContext = this.getActivity().getApplicationContext();
userModel = UserManager.getInstance().getUser();
itemViewClickListener = new ItemViewClick();
// imageItemClickListener = new ImageGridViewItemClick();
// 获取显示图片的实例
imgLoader = ImageLoader.getInstance();
// 显示图片的配置
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.default_avatar)
.showImageOnFail(R.drawable.default_avatar).cacheInMemory(true)
.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
// 获取屏幕尺寸
// DisplayMetrics displayMet = getResources().getDisplayMetrics();
// screenWidth = displayMet.widthPixels;
// 提示信息初始化
recommendPrompt.setText("一大波童鞋即将来袭 (•ิ _ •ิ )");
}
/**
* listView 支持多种item的设置
* */
private void multiItemTypeSet() {
multiItemTypeRecommend = new MultiItemTypeSupport<RecommendItemData>() {
@Override
public int getLayoutId(int position, RecommendItemData itemData) {
int layoutId = 0;
switch (itemData.getItemType()) {
case RecommendItemData.RECOMMEND_TITLE:
layoutId = R.layout.discovery_new_friend_listview_head;
break;
case RecommendItemData.RECOMMEND_INFO:
layoutId = R.layout.discovery_new_friend_item_person_info;
break;
case RecommendItemData.RECOMMEND_PHOTOS:
layoutId = R.layout.discovery_new_friend_item_photolist;
break;
default:
break;
}
return layoutId;
}
@Override
public int getViewTypeCount() {
return RecommendItemData.RECOMMEND_ITEM_TYPE_COUNT;
}
@Override
public int getItemViewType(int postion, RecommendItemData itemData) {
int itemtype = 0;
switch (itemData.getItemType()) {
case RecommendItemData.RECOMMEND_TITLE:
itemtype = RecommendItemData.RECOMMEND_TITLE;
break;
case RecommendItemData.RECOMMEND_INFO:
itemtype = RecommendItemData.RECOMMEND_INFO;
break;
case RecommendItemData.RECOMMEND_PHOTOS:
itemtype = RecommendItemData.RECOMMEND_PHOTOS;
break;
default:
break;
}
return itemtype;
}
};
}
/**
* listView 的设置
* */
private void newsListViewSet() {
// 设置刷新模式
rcmdPersonListView.setMode(Mode.BOTH);
// 刷新监听
rcmdPersonListView
.setOnRefreshListener(new OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
userModel = UserManager.getInstance().getUser();
currentPage = 1;
isPullDowm = true;
getRecommentData(String.valueOf(userModel.getUid()),
String.valueOf(currentPage));
}
@Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
if (!lastPage && !isRequestingUpData) {
isRequestingUpData = true;
isPullDowm = false;
getRecommentData(
String.valueOf(userModel.getUid()),
String.valueOf(currentPage));
isRequestingUpData = false;
}
}
});
/**
* 设置底部自动刷新
* */
rcmdPersonListView
.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
@Override
public void onLastItemVisible() {
if (!lastPage) {
rcmdPersonListView.setMode(Mode.PULL_FROM_END);
rcmdPersonListView.setRefreshing(true);
}
}
});
/**
* adapter的设置
* */
personItemAdapter = new HelloHaAdapter<RecommendItemData>(mContext,
itemDataList, multiItemTypeRecommend) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper,
RecommendItemData item) {
switch (helper.layoutId) {
case R.layout.discovery_new_friend_listview_head:
setTitleItemView(helper, item);
break;
case R.layout.discovery_new_friend_item_person_info:
setInfoItemView(helper, item);
break;
case R.layout.discovery_new_friend_item_photolist:
setPhotoItemView(helper, item);
break;
default:
break;
}
}
};
// 设置不可点击
personItemAdapter.setItemsClickEnable(false);
rcmdPersonListView.setAdapter(personItemAdapter);
}
/**
* 设置title
* */
private void setTitleItemView(HelloHaBaseAdapterHelper helper,
RecommendItemData item) {
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
helper.setOnClickListener(R.id.tv_add_contact_tips, listener);
helper.setOnClickListener(R.id.tv_add_campus_tips, listener);
}
/**
* 设置基本信息
* */
private void setInfoItemView(HelloHaBaseAdapterHelper helper,
RecommendItemData item) {
RecommendInfoItem titleData = (RecommendInfoItem) item;
// 显示头像
if (null != titleData.getHeadSubImage()
&& titleData.getHeadSubImage().length() > 0) {
imgLoader
.displayImage(titleData.getHeadSubImage(),
(ImageView) helper.getView(R.id.iv_recommend_head),
options);
} else {
((ImageView) helper.getView(R.id.iv_recommend_head))
.setImageResource(R.drawable.default_avatar);
}
// 设置用户信息
helper.setText(R.id.tv_recommend_name, titleData.getUserName());
if (!titleData.getRelationTag().equals("")) {
helper.setText(R.id.tv_recommend_tag,
" ◆ " + titleData.getRelationTag());
} else {
helper.setText(R.id.tv_recommend_tag, "");
}
helper.setText(R.id.tv_recommend_school, titleData.getUserSchool());
Button addButton = helper.getView(R.id.btn_recomment_add);
if (titleData.isAdd()) {
addButton.setEnabled(false);
addButton.setText("已关注");
addButton.setBackgroundResource(R.color.main_gary);
addButton.setTextColor(getResources().getColorStateList(R.color.main_white));
} else {
addButton.setText("关注");
addButton.setBackgroundResource(R.color.main_yellow);
addButton.setTextColor(getResources().getColorStateList(R.color.main_brown));
addButton.setEnabled(true);
}
final int postion = helper.getPosition();
if (1 == postion) {
helper.setVisible(R.id.view_recommend_driver, false);
} else {
helper.setVisible(R.id.view_recommend_driver, true);
}
// 监听事件
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
helper.setOnClickListener(R.id.layout_recommend_info_rootview, listener);
helper.setOnClickListener(R.id.btn_recomment_add, listener);
}
/**
* 绑定相册
* */
private void setPhotoItemView(HelloHaBaseAdapterHelper helper,
RecommendItemData item) {
RecommendPhotoItem photoListData = (RecommendPhotoItem) item;
imgLoader.displayImage(photoListData.getPhotoSubUrl().get(0),
(ImageView) helper.getView(R.id.iv_recommend_photo_A), options);
imgLoader.displayImage(photoListData.getPhotoSubUrl().get(1),
(ImageView) helper.getView(R.id.iv_recommend_photo_B), options);
imgLoader.displayImage(photoListData.getPhotoSubUrl().get(2),
(ImageView) helper.getView(R.id.iv_recommend_photo_C), options);
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
helper.setOnClickListener(R.id.layout_photos_root_view, listener);
}
// /**
// * 设置可以左右滑动的相册
// * */
// private void setPhotoItemView2(HelloHaBaseAdapterHelper helper,
// RecommendItemData item) {
// RecommendPhotoItem photoListData = (RecommendPhotoItem) item;
// // 封装数据
// List<Map<String, String>> photoInfoList = new ArrayList<Map<String, String>>();
// for (int index = 0; index < photoListData.getPhotoSubUrl().size(); index++) {
// Map<String, String> tpMap = new HashMap<String, String>();
// tpMap.put("USER_ID", photoListData.getUserId());
// tpMap.put("PHOTO_SUB_URL", photoListData.getPhotoSubUrl()
// .get(index));
// if (null != photoListData.getPhotoUrl()
// && index < photoListData.getPhotoUrl().size()) {
// tpMap.put("PHOTO_URL", photoListData.getPhotoUrl().get(index));
// }
// photoInfoList.add(tpMap);
// }
//
// // 照片的尺寸,正方形显示
// final int photoSize = screenWidth / 3;
// final int horizontalSpace = 5;
// HelloHaAdapter<Map<String, String>> newsGVAdapter = new HelloHaAdapter<Map<String, String>>(
// mContext, R.layout.discovery_new_friend_photos_gridview_item,
// photoInfoList) {
// @Override
// protected void convert(HelloHaBaseAdapterHelper helper,
// Map<String, String> data) {
// String subAdd = data.get("PHOTO_SUB_URL");
// if (subAdd.equals(LOOK_ALL_PHOTOS)) {
// /********* 添加查看所有照片按钮 *******/
// ImageView imgView = helper
// .getView(R.id.iv_recommend_photos_item);
// LayoutParams laParams = (LayoutParams) imgView
// .getLayoutParams();
// laParams.width = photoSize / 2;
// laParams.height = photoSize;
// imgView.setLayoutParams(laParams);
// imgView.setScaleType(ImageView.ScaleType.FIT_XY);
// helper.setImageResource(R.id.iv_recommend_photos_item,
// R.drawable.default_avatar);
// } else {
// // 设置相册的尺寸的图片大小
// ImageView imgView = helper
// .getView(R.id.iv_recommend_photos_item);
// LayoutParams laParams = (LayoutParams) imgView
// .getLayoutParams();
// laParams.width = laParams.height = photoSize
// - horizontalSpace;
// imgView.setLayoutParams(laParams);
// imgLoader.displayImage(subAdd, (ImageView) helper
// .getView(R.id.iv_recommend_photos_item), options);
// }
// }
// };
// NoScrollGridView photoGridView = null;
// // NoScrollGridView photoGridView = (NoScrollGridView) helper
// // .getView(R.id.gv_recommend_photos);
// // 设置gridview的尺寸
// int photoCount = photoInfoList.size();
// int gridviewWidth = (int) ((photoCount - 1)
// * (photoSize + horizontalSpace) + photoSize / 2);
// LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
// gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
// photoGridView.setColumnWidth(photoSize);
// photoGridView.setHorizontalSpacing(horizontalSpace);
// photoGridView.setNumColumns(photoCount);
// photoGridView.setLayoutParams(params);
//
// photoGridView.setAdapter(newsGVAdapter);
//
// /**
// * 点击图片事件
// * */
// photoGridView.setOnItemClickListener(imageItemClickListener);
// }
/**
* 获取推荐的人的数据
* */
private void getRecommentData(String userId, String page) {
String path = JLXCConst.RECOMMEND_FRIENDS_LIST + "?" + "user_id="
+ userId + "&page=" + page + "&size=";
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@SuppressWarnings("unchecked")
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
// 获取数据列表
List<JSONObject> JPersonList = (List<JSONObject>) jResult
.get("list");
JsonToItemData(JPersonList);
rcmdPersonListView.onRefreshComplete();
if (jResult.getString("is_last").equals("0")) {
lastPage = false;
currentPage++;
rcmdPersonListView.setMode(Mode.BOTH);
} else {
lastPage = true;
rcmdPersonListView
.setMode(Mode.PULL_FROM_START);
}
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(mContext, jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
rcmdPersonListView.onRefreshComplete();
if (!lastPage) {
rcmdPersonListView.setMode(Mode.BOTH);
}
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
ToastUtil.show(mContext, "网络抽筋了,请检查 =_=");
rcmdPersonListView.onRefreshComplete();
if (!lastPage) {
rcmdPersonListView.setMode(Mode.BOTH);
}
}
}, null));
}
/**
* 数据解析
* */
private void JsonToItemData(List<JSONObject> dataList) {
if (isPullDowm) {
// 下拉
personList.clear();
for (JSONObject newsObj : dataList) {
PersonModel tempPerson = new PersonModel();
tempPerson.setContentWithJson(newsObj);
if (tempPerson.getImageList().size() >= 3) {
tempPerson.getImageList().add(LOOK_ALL_PHOTOS);
}
personList.add(tempPerson);
}
} else {
// 上拉
HashSet<PersonModel> DuplicateSet = new HashSet<PersonModel>(
personList);
for (JSONObject newsObj : dataList) {
PersonModel tempPerson = new PersonModel();
tempPerson.setContentWithJson(newsObj);
if (tempPerson.getImageList().size() >= 3) {
tempPerson.getImageList().add(LOOK_ALL_PHOTOS);
}
if (DuplicateSet.add(tempPerson)) {
personList.add(tempPerson);
}
}
}
itemDataList = DataToRecommendItem.dataToItems(personList);
RecommendTitleItem titleItem = new RecommendTitleItem();
itemDataList.add(0, titleItem);
personItemAdapter.replaceAll(itemDataList);
if (null != dataList) {
dataList.clear();
}
if (personItemAdapter.getCount() <= 1) {
recommendPrompt.setVisibility(View.VISIBLE);
recommendPrompt.setText("好像出了点什么问题 (;′⌒`)");
} else {
recommendPrompt.setVisibility(View.GONE);
}
}
/**
* 去除重复的值
* */
/**
* item上的view点击事件
* */
public class ItemViewClick implements ListItemClickHelp {
@Override
public void onClick(View view, int position, int viewID) {
switch (viewID) {
case R.id.tv_add_contact_tips:
// 跳转到添加通讯录好友页面
Intent intentToContacts = new Intent(mContext,
ContactsUserActivity.class);
startActivityWithRight(intentToContacts);
break;
// 添加同校好友
case R.id.tv_add_campus_tips:
Intent sameSchoolIntent = new Intent(getActivity(),
SameSchoolActivity.class);
startActivityWithRight(sameSchoolIntent);
break;
// 点击推荐的人
case R.id.layout_recommend_info_rootview:
RecommendInfoItem currentInfoItem = (RecommendInfoItem) personItemAdapter
.getItem(position);
JumpToHomepage(JLXCUtils.stringToInt(currentInfoItem
.getUserID()));
break;
// 点击添加按钮
case R.id.btn_recomment_add:
RecommendInfoItem addInfoItem = (RecommendInfoItem) personItemAdapter
.getItem(position);
IMModel imModel = new IMModel();
String headImage = addInfoItem.getHeadImage();
if (headImage != null) {
headImage = headImage
.replace(JLXCConst.ATTACHMENT_ADDR, "");
} else {
headImage = "";
}
imModel.setAvatarPath(headImage);
imModel.setTargetId(JLXCConst.JLXC + addInfoItem.getUserID());
imModel.setTitle(addInfoItem.getUserName());
addFriend(imModel, position);
break;
case R.id.layout_photos_root_view:
RecommendPhotoItem photoItem = (RecommendPhotoItem) personItemAdapter
.getItem(position);
Intent intent = new Intent(mContext, MyNewsListActivity.class);
intent.putExtra(MyNewsListActivity.INTNET_KEY_UID,
photoItem.getUserId());
startActivityWithRight(intent);
// 跳转到相册
break;
default:
break;
}
}
}
/**
* listview点击事件接口,用于区分不同view的点击事件
*
* @author Alan
*/
private interface ListItemClickHelp {
void onClick(View view, int postion, int viewID);
}
/**
* 图片gridview监听
*/
public class ImageGridViewItemClick implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
@SuppressWarnings("unchecked")
HelloHaAdapter<Map<String, String>> photosAdapter = (HelloHaAdapter<Map<String, String>>) parent
.getAdapter();
Map<String, String> currentMap = photosAdapter.getItem(position);
// String currentImgPath = currentMap.get("PHOTO_SUB_URL");
// if (!currentImgPath.equals(LOOK_ALL_PHOTOS)) {
// // 跳转到图片详情页面
// List<String> imageList = new ArrayList<String>();
// for (int index = 0; index < photosAdapter.getCount() - 1;
// index++) {
// imageList.add(photosAdapter.getItem(index).get(
// "PHOTO_SUB_URL"));
// }
// jumpToBigImage(BigImgLookActivity.INTENT_KEY_IMG_LIST,
// imageList, position);
// } else {
// 跳转到动态列表
Intent intent = new Intent(mContext, MyNewsListActivity.class);
intent.putExtra(MyNewsListActivity.INTNET_KEY_UID,
currentMap.get("USER_ID"));
startActivity(intent);
// }
}
}
/**
* 跳转至用户的主页
*/
private void JumpToHomepage(int userID) {
Intent intentUsrMain = new Intent(mContext, OtherPersonalActivity.class);
intentUsrMain.putExtra(OtherPersonalActivity.INTENT_KEY, userID);
startActivityWithRight(intentUsrMain);
}
// /**
// * 跳转查看大图
// */
// private void jumpToBigImage(String intentKey, Object path, int index) {
// if (intentKey.equals(BigImgLookActivity.INTENT_KEY)) {
// // 单张图片跳转
// String pathUrl = (String) path;
// Intent intentPicDetail = new Intent(mContext,
// BigImgLookActivity.class);
// intentPicDetail.putExtra(BigImgLookActivity.INTENT_KEY, pathUrl);
// startActivity(intentPicDetail);
// } else if (intentKey
// .equals(BigImgLookActivity.INTENT_KEY_IMG_MODEl_LIST)) {
// // 传递model列表
// @SuppressWarnings("unchecked")
// List<ImageModel> mdPath = (List<ImageModel>) path;
// Intent intent = new Intent(mContext, BigImgLookActivity.class);
// intent.putExtra(BigImgLookActivity.INTENT_KEY_IMG_MODEl_LIST,
// (Serializable) mdPath);
// intent.putExtra(BigImgLookActivity.INTENT_KEY_INDEX, index);
// startActivity(intent);
// } else if (intentKey.equals(BigImgLookActivity.INTENT_KEY_IMG_LIST)) {
// // 传递String列表
// @SuppressWarnings("unchecked")
// List<String> mdPath = (List<String>) path;
// Intent intent = new Intent(mContext, BigImgLookActivity.class);
// intent.putExtra(BigImgLookActivity.INTENT_KEY_IMG_LIST,
// (Serializable) mdPath);
// intent.putExtra(BigImgLookActivity.INTENT_KEY_INDEX, index);
// startActivity(intent);
// } else {
// LogUtils.e("未传递图片地址");
// }
// }
// 添加好友
private void addFriend(final IMModel imModel, final int index) {
// 参数设置
RequestParams params = new RequestParams();
params.addBodyParameter("user_id", UserManager.getInstance().getUser()
.getUid()
+ "");
params.addBodyParameter("friend_id",
imModel.getTargetId().replace(JLXCConst.JLXC, "") + "");
showLoading(getActivity(), "添加中^_^", false);
HttpManager.post(JLXCConst.Add_FRIEND, params,
new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
hideLoading();
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
ToastUtil.show(getActivity(),
jsonResponse.getString(JLXCConst.HTTP_MESSAGE));
if (status == JLXCConst.STATUS_SUCCESS) {
// 添加好友
MessageAddFriendHelper.addFriend(imModel);
// 更新
RecommendInfoItem recommendItemData = (RecommendInfoItem) itemDataList
.get(index);
recommendItemData.setAdd("1");
personItemAdapter.replaceAll(itemDataList);
//已经加为好友
PersonModel personModel = personList.get(recommendItemData.getOriginIndex());
personModel.setIsFriend("1");
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
hideLoading();
ToastUtil.show(getActivity(), "网络异常");
}
}, null));
}
}
<file_sep>package com.jlxc.app.news.ui.activity;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.utils.ConfigUtils;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.news.model.CampusPersonModel;
import com.jlxc.app.news.ui.activity.CampusAllPersonActivity;
import com.jlxc.app.news.ui.activity.CampusNewsActivity;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
public class CampusHomeActivity extends BaseActivityWithTopBar {
//学校ID
public static final String INTENT_SCHOOL_CODE_KEY = "schoolCode";
// 学校的人
private List<CampusPersonModel> personList;
// 加载图片
private ImageLoader imgLoader;
// 图片配置
private DisplayImageOptions options;
// 学校位置
@ViewInject(R.id.txt_campus_home_school_local)
private TextView schoolLocationTextView;
// 学校名字
@ViewInject(R.id.txt_campus_home_school_name)
private TextView schoolNameTextView;
// 学校学生数量
@ViewInject(R.id.txt_campus_home_mumber_count)
private TextView studentCountTextView;
// 未读的消息数量
@ViewInject(R.id.tv_campus_home_news_count)
private TextView unreadNewsTextView;
// 校园的人布局
@ViewInject(R.id.layout_campus_home_member_rootview)
private LinearLayout campusMumberLayout;
// 校园的动态
@ViewInject(R.id.layout_campus_home_news_rootview)
private LinearLayout campusNewsLayout;
// 展示在外边的第一个人
@ViewInject(R.id.img_campus_home_mumber_A)
private ImageView OutsidePersonA;
// 展示在外面的第二个人
@ViewInject(R.id.img_campus_home_mumber_B)
private ImageView OutsidePersonB;
// 展示在外面的第三个人
@ViewInject(R.id.img_campus_home_mumber_C)
private ImageView OutsidePersonC;
// 学校代码
private String schoolCode;
@Override
public int setLayoutId() {
return R.layout.activity_campus_home_layout;
}
@Override
protected void setUpView() {
init();
setWidgetListener();
// 进入本页面时请求数据
getCampusHomeData();
}
/**
* 数据的初始化
* */
private void init() {
setBarText("校园主页");
// 图片加载初始化
imgLoader = ImageLoader.getInstance();
// 显示图片的配置
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.default_avatar)
.showImageOnFail(R.drawable.default_avatar).cacheInMemory(true)
.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
// 获取是否是本校学生浏览
Intent intent = this.getIntent();
if (intent.hasExtra(INTENT_SCHOOL_CODE_KEY)) {
schoolCode = intent.getStringExtra(INTENT_SCHOOL_CODE_KEY);
} else {
LogUtils.e("未传递查看类型");
}
//处理学校
if (null == schoolCode || schoolCode.length() < 1) {
schoolCode = UserManager.getInstance().getUser().getSchool_code();
}
personList = new ArrayList<CampusPersonModel>();
}
/**
* 数据绑定
* */
private void schoolHomeData(JSONObject homeJsonObject) {
// 学校默认自己学校
schoolNameTextView.setText(UserManager.getInstance().getUser().getSchool());
// 学校位置
if (homeJsonObject.containsKey("school")) {
//位置
JSONObject schoolObject = homeJsonObject.getJSONObject("school");
String locationString = schoolObject.getString("city_name") + " ▪ "+ schoolObject.getString("district_name");
schoolLocationTextView.setText(locationString);
//名字
if (schoolObject.containsKey("name")) {
schoolNameTextView.setText(schoolObject.getString("name"));
}
}
if (homeJsonObject.containsKey("student_count")) {
// 学校人数
studentCountTextView.setText(JLXCUtils.stringToInt(homeJsonObject
.getString("student_count")) + "人");
}
if (homeJsonObject.containsKey("unread_news_count")) {
// 新闻未读tv
int unreadCount = JLXCUtils.stringToInt(homeJsonObject
.getString("unread_news_count"));
if (unreadCount > 0) {
if (unreadCount > 99) {
unreadCount = 99;
}
unreadNewsTextView.setVisibility(View.VISIBLE);
unreadNewsTextView.setText(unreadCount + "");
} else {
unreadNewsTextView.setVisibility(View.GONE);
}
// 非本校学生查看则把动态模块隐藏
if (null != schoolCode && !schoolCode.equals(UserManager.getInstance().getUser().getSchool_code())) {
unreadNewsTextView.setVisibility(View.GONE);
}
}
// 解析学校的人
if (homeJsonObject.containsKey("info")) {
@SuppressWarnings("unchecked")
List<JSONObject> JPersonList = (List<JSONObject>) homeJsonObject
.get("info");
// 清空
personList.clear();
// 解析校园的人
for (JSONObject personObj : JPersonList) {
CampusPersonModel tempPerson = new CampusPersonModel();
tempPerson.setContentWithJson(personObj);
personList.add(tempPerson);
}
}
// 将头像绑定到imageview上
if (personList.size() >= 3) {
OutsidePersonA.setVisibility(View.VISIBLE);
OutsidePersonB.setVisibility(View.VISIBLE);
OutsidePersonC.setVisibility(View.VISIBLE);
imgLoader.displayImage(personList.get(0).getHeadSubImage(),
OutsidePersonA, options);
imgLoader.displayImage(personList.get(1).getHeadSubImage(),
OutsidePersonB, options);
imgLoader.displayImage(personList.get(2).getHeadSubImage(),
OutsidePersonC, options);
} else if (personList.size() >= 2) {
OutsidePersonA.setVisibility(View.VISIBLE);
OutsidePersonB.setVisibility(View.VISIBLE);
OutsidePersonC.setVisibility(View.GONE);
imgLoader.displayImage(personList.get(0).getHeadSubImage(),
OutsidePersonA, options);
imgLoader.displayImage(personList.get(1).getHeadSubImage(),
OutsidePersonB, options);
} else if (personList.size() >= 1) {
OutsidePersonA.setVisibility(View.VISIBLE);
OutsidePersonB.setVisibility(View.GONE);
OutsidePersonC.setVisibility(View.GONE);
imgLoader.displayImage(personList.get(0).getHeadSubImage(),
OutsidePersonA, options);
} else {
OutsidePersonA.setVisibility(View.GONE);
OutsidePersonB.setVisibility(View.GONE);
OutsidePersonC.setVisibility(View.GONE);
}
}
/**
* 设置事件监听
* */
private void setWidgetListener() {
campusMumberLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// 跳转到所有校友列表页面
Intent personIntent = new Intent(CampusHomeActivity.this,
CampusAllPersonActivity.class);
personIntent.putExtra(CampusAllPersonActivity.INTENT_SCHOOL_CODE_KEY, schoolCode);
startActivityWithRight(personIntent);
}
});
campusNewsLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
unreadNewsTextView.setVisibility(View.GONE);
// 跳转至校园动态页面
Intent intentToGroupNews = new Intent();
intentToGroupNews.setClass(CampusHomeActivity.this,CampusNewsActivity.class);
intentToGroupNews.putExtra(CampusNewsActivity.INTENT_SCHOOL_CODE_KEY, schoolCode);
startActivityWithRight(intentToGroupNews);
}
});
}
/**
* 获取学校动态的数据
* */
private void getCampusHomeData() {
// 上一次查询时间处理
String lastRefeshTime = ConfigUtils
.getStringConfig(ConfigUtils.LAST_REFRESH__SCHOOL_HOME_NEWS_DATE);
if (null == lastRefeshTime || lastRefeshTime.length() < 1) {
lastRefeshTime = "";
ConfigUtils.saveConfig(
ConfigUtils.LAST_REFRESH__SCHOOL_HOME_NEWS_DATE,
System.currentTimeMillis() / 1000 + "");
}
// 1441074913
String path = JLXCConst.SCHOOL_HOME_DATA + "?" + "user_id="
+ UserManager.getInstance().getUser().getUid()
+ "&school_code="
+ schoolCode
+ "&last_time=" + lastRefeshTime;
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
// 处理数据
schoolHomeData(jResult);
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(CampusHomeActivity.this,
jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
ToastUtil.show(CampusHomeActivity.this,
"网络抽筋了,请检查(→_→)");
}
}, null));
}
}
<file_sep>package com.jlxc.app.login.ui.fragment;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.jlxc.app.R;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.ui.activity.MainTabActivity;
import com.jlxc.app.base.ui.fragment.BaseFragment;
import com.jlxc.app.login.ui.activity.LaunchActivity;
import com.jlxc.app.login.ui.activity.LoginActivity;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
public class LaunchCircleFragment3 extends BaseFragment{
@ViewInject(R.id.launch_image_view)
private ImageView launchImageView;
@ViewInject(R.id.enter_button)
private ImageButton enterButton;
@OnClick({R.id.enter_button})
private void methodClick(View view){
switch (view.getId()) {
case R.id.enter_button:
UserModel userModel = UserManager.getInstance().getUser();
if (null != userModel.getUsername() && null != userModel.getLogin_token()) {
startActivity(new Intent(getActivity(), MainTabActivity.class));
} else {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
getActivity().finish();
break;
default:
break;
}
}
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.fragment_launch_circle;
}
@Override
public void loadLayout(View rootView) {
}
@Override
public void setUpViews(View rootView) {
enterButton.setVisibility(View.VISIBLE);
launchImageView.setImageResource(R.drawable.guide_page3);
}
}
<file_sep>package com.jlxc.app.base.ui.activity;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient.ConnectCallback;
import io.rong.imlib.RongIMClient.ErrorCode;
import io.rong.imlib.model.Conversation;
import io.yunba.android.manager.YunBaManager;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import com.jlxc.app.R;
import com.jlxc.app.base.helper.RongCloudEvent;
import com.jlxc.app.base.manager.NewVersionCheckManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.NewsPushModel;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.group.ui.fragment.GroupMainFragment;
import com.jlxc.app.message.model.IMModel;
import com.jlxc.app.message.ui.fragment.MessageMainFragment;
import com.jlxc.app.news.model.NewsConstants;
import com.jlxc.app.news.receiver.NewMessageReceiver;
import com.jlxc.app.news.ui.fragment.MainNewsListFragment;
import com.jlxc.app.personal.ui.activity.OtherPersonalActivity;
import com.jlxc.app.personal.ui.fragment.PersonalFragment;
import com.lidroid.xutils.view.annotation.ViewInject;
public class MainTabActivity extends BaseActivity {
private final static int SCANNIN_GREQUEST_CODE = 1;
// FragmentTabHost对象
@ViewInject(android.R.id.tabhost)
public FragmentTabHost mTabHost;
private LayoutInflater layoutInflater;
// private Class<?> fragmentArray[] = { MainPageFragment.class,
// MessageMainFragment.class,DiscoveryFragment.class,
// PersonalFragment.class };
private Class<?> fragmentArray[] = { MainNewsListFragment.class,
GroupMainFragment.class, MessageMainFragment.class,
PersonalFragment.class };
private int mImageViewArray[] = { R.drawable.tab_home_btn,
R.drawable.tab_find_btn,R.drawable.tab_message_btn,
R.drawable.tab_me_btn };
private String mTextviewArray[] = { "主页", "发现", "消息", "我" };
// //已经连接
// private boolean isConnect = false;
// im未读数量
public void initTab() {
layoutInflater = LayoutInflater.from(this);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.getTabWidget().setDividerDrawable(null);
int count = fragmentArray.length;
for (int i = 0; i < count; i++) {
TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
.setIndicator(getTabItemView(i));
mTabHost.addTab(tabSpec, fragmentArray[i], null);
// mTabHost.getTabWidget().getChildAt(i)
// .setBackgroundResource(R.drawable.selector_tab_background);
final int index = i;
if (index == 0) {
// 选择首页刷新和其他的不太一样
mTabHost.getTabWidget().getChildAt(i)
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (mTabHost.getCurrentTab() == 0) {
Intent mIntent = new Intent(
JLXCConst.BROADCAST_NEWS_LIST_REFRESH);
mIntent.putExtra(
NewsConstants.NEWS_LISTVIEW_REFRESH,
"");
// 发送广播
LocalBroadcastManager.getInstance(
MainTabActivity.this)
.sendBroadcast(mIntent);
// 徽标更新
Intent tabIntent = new Intent(
JLXCConst.BROADCAST_TAB_BADGE);
sendBroadcast(tabIntent);
}
mTabHost.setCurrentTab(index);
}
});
} else {
// 选择首页刷新和其他的不太一样
mTabHost.getTabWidget().getChildAt(index)
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mTabHost.setCurrentTab(index);
// 徽标更新
Intent tabIntent = new Intent(
JLXCConst.BROADCAST_TAB_BADGE);
sendBroadcast(tabIntent);
}
});
}
}
// 注册通知
registerNotify();
refreshTab();
}
// 初始化融云
private void initRong() {
String token = "";
UserModel userModel = UserManager.getInstance().getUser();
if (null != userModel.getIm_token()
&& userModel.getIm_token().length() > 0) {
token = userModel.getIm_token();
}
LogUtils.i("" + token, 1);
// 先设置一次 避免重启的时候因为已连接而导致没设置
RongCloudEvent.getInstance().setOtherListener();
RongIM.connect(token, new ConnectCallback() {
@Override
public void onError(ErrorCode arg0) {
LogUtils.i("error", 1);
}
@Override
public void onSuccess(String arg0) {
// Toast.makeText(MainTabActivity.this, "connect onSuccess",
// Toast.LENGTH_SHORT).show();
LogUtils.i("rong init ok", 1);
RongCloudEvent.getInstance().setOtherListener();
// 设置im未读监听
final Conversation.ConversationType[] conversationTypes = {
Conversation.ConversationType.PRIVATE,
Conversation.ConversationType.DISCUSSION,
Conversation.ConversationType.GROUP,
Conversation.ConversationType.SYSTEM,
Conversation.ConversationType.APP_PUBLIC_SERVICE,
Conversation.ConversationType.PUBLIC_SERVICE };
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
RongIM.getInstance()
.setOnReceiveUnreadCountChangedListener(
mCountListener, conversationTypes);
}
}, 1000);
}
@Override
public void onTokenIncorrect() {
LogUtils.i("token incorrect", 1);
}
});
}
// 初始化云巴
private void initYunBa() {
// registerMessageRecevier();
final UserModel userModel = UserManager.getInstance().getUser();
if (userModel.getUid() != 0) {
YunBaManager.subscribe(this, new String[] { JLXCConst.JLXC
+ userModel.getUid() }, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken arg0) {
LogUtils.i("yunba init ok", 1);
// LogUtils.i("yunba success"+JLXCConst.JLXC+userModel.getUid(),
// 1);
// Looper.prepare();
// Toast.makeText(MainTabActivity.this, "yunba success",
// Toast.LENGTH_SHORT).show();
// Looper.loop();
}
@Override
public void onFailure(IMqttToken arg0, Throwable arg1) {
Looper.prepare();
// Toast.makeText(MainTabActivity.this, "yunba fail",
// Toast.LENGTH_SHORT).show();
Looper.loop();
}
});
}
}
// 获取最新版本号
private void getLastVersion() {
new NewVersionCheckManager(this, this).checkNewVersion(false, null);
}
@SuppressLint("InflateParams")
private View getTabItemView(int index) {
View view = layoutInflater.inflate(R.layout.tab_item_view, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
imageView.setImageResource(mImageViewArray[index]);
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(mTextviewArray[index]);
return view;
}
@Override
public int setLayoutId() {
return R.layout.activity_main;
}
@Override
protected void loadLayout(View v) {
}
@Override
protected void setUpView() {
// 初始化tab
initTab();
// 初始化融云
initRong();
// 初始化云巴
initYunBa();
// 获取最新版本
getLastVersion();
}
@Override
protected void onRestart() {
super.onRestart();
}
/**
* 重写返回操作
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
// ActivityManager.getInstence().exitApplication();
// if (null != newMessageReceiver) {
// unregisterReceiver(newMessageReceiver);
// newMessageReceiver = null;
// }
// if (RongIM.getInstance() != null)
// RongIM.getInstance().disconnect();
// SMSSDK.unregisterAllEventHandler();
moveTaskToBack(true);
// final AlertDialog.Builder alterDialog = new
// AlertDialog.Builder(this);
// alterDialog.setMessage("确定退出该账号吗?");
// alterDialog.setCancelable(true);
//
// alterDialog.setPositiveButton("确定", new
// DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// if (RongIM.getInstance() != null)
// RongIM.getInstance().disconnect();
// if (null != newMessageReceiver) {
// unregisterReceiver(newMessageReceiver);
// newMessageReceiver = null;
// }
// ActivityManager.getInstence().exitApplication();
// // killThisPackageIfRunning(MainTabActivity.this,
// "com.jlxc.app");
// // Process.killProcess(Process.myPid());
//
// // finish();
//
// }
// });
// alterDialog.setNegativeButton("取消", new
// DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.cancel();
// }
// });
// alterDialog.show();
return true;
} else
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
if (null != newMessageReceiver) {
unregisterReceiver(newMessageReceiver);
newMessageReceiver = null;
}
if (RongIM.getInstance() != null)
RongIM.getInstance().disconnect();
// if (RongIM.getInstance() != null)
// RongIM.getInstance().logout();
// Process.killProcess(Process.myPid());
super.onDestroy();
}
// 友盟集成
public void onResume() {
super.onResume();
// MobclickAgent.onResume(this);
}
public void onPause() {
super.onPause();
// MobclickAgent.onPause(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SCANNIN_GREQUEST_CODE:
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String resultString = bundle.getString("result");
// mTextView.setText(resultString);
// mImageView.setImageBitmap((Bitmap)
// data.getParcelableExtra("bitmap"));
// 如果是可以用的
if (resultString.contains(JLXCConst.JLXC)) {
String baseUid = resultString.substring(4);
int uid = JLXCUtils.stringToInt(new String(Base64.decode(
baseUid, Base64.DEFAULT)));
if (uid == UserManager.getInstance().getUser().getUid()) {
ToastUtil.show(this, "不要没事扫自己玩(ㅎ‸ㅎ)");
} else {
Intent intent = new Intent(this,
OtherPersonalActivity.class);
intent.putExtra(OtherPersonalActivity.INTENT_KEY, uid);
startActivity(intent);
}
}
ToastUtil.show(this, "'" + resultString + "'" + "是什么");
}
break;
}
}
// //////////////////////////////private
// method////////////////////////////////
private NewMessageReceiver newMessageReceiver;
// 注册通知
private void registerNotify() {
// 刷新tab
newMessageReceiver = new NewMessageReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 刷新tab
refreshTab();
}
};
IntentFilter intentFilter = new IntentFilter(
JLXCConst.BROADCAST_TAB_BADGE);
registerReceiver(newMessageReceiver, intentFilter);
}
// 刷新tab 未读标志
private void refreshTab() {
View messageView = mTabHost.getTabWidget().getChildAt(2);
TextView unreadTextView = (TextView) messageView
.findViewById(R.id.unread_text_view);
// 聊天页面
// 新好友请求未读
int newFriendsCount = 0;
// 徽标 最多显示99
// 未读推送
int newsUnreadCount = 0;
try {
newFriendsCount = IMModel.unReadNewFriendsCount();
newsUnreadCount = NewsPushModel.findUnreadCount().size();
} catch (Exception e) {
// TODO: handle exception
}
final Conversation.ConversationType[] conversationTypes = {
Conversation.ConversationType.PRIVATE,
Conversation.ConversationType.DISCUSSION,
Conversation.ConversationType.GROUP,
Conversation.ConversationType.SYSTEM,
Conversation.ConversationType.APP_PUBLIC_SERVICE,
Conversation.ConversationType.PUBLIC_SERVICE };
int unreadCount = 0;
if (null != RongIM.getInstance()) {
if (null != RongIM.getInstance().getRongIMClient()) {
try {
unreadCount = RongIM.getInstance().getRongIMClient()
.getUnreadCount(conversationTypes);
} catch (Exception e) {
LogUtils.i("unread 异常", 1);
}
}
}
int total = newsUnreadCount + newFriendsCount + unreadCount;
if (total > 99) {
total = 99;
}
// 暂时不显示未读消息
// unreadTextView.setText(total+"");
if (total == 0) {
unreadTextView.setVisibility(View.GONE);
} else {
unreadTextView.setVisibility(View.VISIBLE);
}
}
// @Override
// protected void onSaveInstanceState(Bundle outState) {
// // TODO Auto-generated method stub
// outState.putBoolean("isConnect", isConnect);
// LogUtils.i("on save" + " "+ isConnect, 1);
//
// super.onSaveInstanceState(outState);
// }
// @Override
// public void onConfigurationChanged(android.content.res.Configuration
// newConfig) {
// super.onConfigurationChanged(newConfig);
//
// };
//
// @Override
// protected void onRestoreInstanceState(Bundle savedInstanceState) {
//
// isConnect = savedInstanceState.getBoolean("isConnect");
// LogUtils.i("on restroe" + " "+ isConnect, 1);
// isConnect = true;
//
// super.onRestoreInstanceState(savedInstanceState);
// }
// im未读监听器
public RongIM.OnReceiveUnreadCountChangedListener mCountListener = new RongIM.OnReceiveUnreadCountChangedListener() {
@Override
public void onMessageIncreased(int count) {
refreshTab();
}
};
// 杀死进程
public static void killThisPackageIfRunning(final Context context,
String packageName) {
android.app.ActivityManager activityManager = (android.app.ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses(packageName);
}
}
<file_sep>package com.jlxc.app.personal.ui.activity;
import java.util.List;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.BitmapManager;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.message.model.IMModel;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;
////////////////////////该类废弃 改用MyFriendListActivity////////////////////////////////////////////
public class FriendListActivity extends BaseActivityWithTopBar {
@ViewInject(R.id.list_view)
private ListView friendListView;
private HelloHaAdapter<IMModel> friendsAdapter;
// private BitmapUtils bitmapUtils;
private List<IMModel> friendList;
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_friend_list;
}
@Override
protected void setUpView() {
// TODO Auto-generated method stub
// setBitmapUtils(BitmapManager.getInstance().getHeadPicBitmapUtils(this, R.drawable.default_avatar, true, true));
initListView();
//同步好友
syncFriends();
}
///////////////////////////override////////////////////////////
@Override
public void onResume() {
super.onResume();
friendList = IMModel.findHasAddAll();
friendsAdapter.replaceAll(friendList);
}
///////////////////////////private method////////////////////////////
private void initListView() {
//设置内容
friendsAdapter = new HelloHaAdapter<IMModel>(
FriendListActivity.this, R.layout.friend_listitem_adapter) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper,
final IMModel item) {
helper.setText(R.id.name_text_view, item.getTitle());
ImageView headImageView = helper.getView(R.id.head_image_view);
// bitmapUtils.display(headImageView, JLXCConst.ATTACHMENT_ADDR+item.getAvatarPath());
}
};
friendListView.setAdapter(friendsAdapter);
friendListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
IMModel imModel = friendList.get(position);
String uid = imModel.getTargetId().replace(JLXCConst.JLXC, "");
//跳转到其他人页面
Intent intent = new Intent(FriendListActivity.this, OtherPersonalActivity.class);
intent.putExtra(OtherPersonalActivity.INTENT_KEY, JLXCUtils.stringToInt(uid));
startActivityWithRight(intent);
}
});
}
//同步好友
public void syncFriends() {
//判断是否需要同步
String path = JLXCConst.NEED_SYNC_FRIENDS + "?" + "user_id=" + UserManager.getInstance().getUser().getUid()
+ "&friends_count="+IMModel.findHasAddAll().size();
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
//是否需要更新
int needUpdate = jResult.getIntValue("needUpdate");
if (needUpdate>0) {
//需要更新好友列表
getFriends();
}
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
}
}, null));
}
public void getFriends() {
//同步
String path = JLXCConst.GET_FRIENDS_LIST + "?" + "user_id=" + UserManager.getInstance().getUser().getUid();
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse.getJSONObject(JLXCConst.HTTP_RESULT);
JSONArray jsonArray = jResult.getJSONArray(JLXCConst.HTTP_LIST);
//建立模型数组
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String jlxcUid = JLXCConst.JLXC+jsonObject.getIntValue("uid");
IMModel model = IMModel.findByGroupId(jlxcUid);
if (null != model) {
model.setTitle(jsonObject.getString("name"));
model.setAvatarPath(jsonObject.getString("head_image"));
model.setRemark(jsonObject.getString("friend_remark"));
model.setCurrentState(IMModel.GroupHasAdd);
model.update();
}else {
model = new IMModel();
model.setType(IMModel.ConversationType_PRIVATE);
model.setTargetId(jlxcUid);
model.setTitle(jsonObject.getString("name"));
model.setAvatarPath(jsonObject.getString("head_image"));
model.setRemark(jsonObject.getString("friend_remark"));
model.setOwner(UserManager.getInstance().getUser().getUid());
model.setIsNew(0);
model.setIsRead(1);
model.setCurrentState(IMModel.GroupHasAdd);
model.save();
}
}
//刷新
friendList = IMModel.findHasAddAll();
friendsAdapter.replaceAll(friendList);
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
}
}, null));
}
}
<file_sep>package com.jlxc.app.group.model;
import com.alibaba.fastjson.JSONObject;
public class GroupPersonModel {
// 头像缩略图
private String headSubImage;
// 名字
private String userName;
// 性别
private String sex;
// 用户id
private String userId;
public void setContentWithJson(JSONObject object) {
if (object.containsKey("user_id")) {
setUserId(object.getString("user_id"));
}
if (object.containsKey("sex")) {
setSex(object.getString("sex"));
}
if (object.containsKey("head_sub_image")) {
setHeadSubImage(object.getString("head_sub_image"));
}
if (object.containsKey("name")) {
setUserName(object.getString("name"));
}
}
public String getHeadSubImage() {
return headSubImage;
}
public void setHeadSubImage(String headSubImage) {
this.headSubImage = headSubImage;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
<file_sep>package com.jlxc.app.discovery.ui.avtivity;
import com.jlxc.app.R;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
public class DiscoveryHomeActivity extends BaseActivityWithTopBar {
//intent key
// public static String SCHOOL_CODE = "schoolCode";
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_discovery_main;
}
@Override
protected void setUpView() {
setBarText("找同学");
}
}
<file_sep>package com.jlxc.app.personal.ui.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.BitmapManager;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.ui.view.CustomAlertDialog;
import com.jlxc.app.base.utils.FileUtil;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.ToastUtil;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
//我的名片页面
public class MyCardActivity extends BaseActivityWithTopBar {
//头像
@ViewInject(R.id.head_image_view)
private ImageView headImageView;
//姓名
@ViewInject(R.id.name_text_view)
private TextView nameTextView;
//hellohaId
@ViewInject(R.id.helloha_text_view)
private TextView hellohaTextView;
//hellohaEt
@ViewInject(R.id.helloha_edit_text)
private EditText hellohaEditText;
//hellohaBtn
@ViewInject(R.id.helloha_button)
private Button saveButton;
//设置按钮
@ViewInject(R.id.set_button)
private Button setButton;
//二维码
@ViewInject(R.id.qrcode_image_view)
private ImageView qrcodeImageView;
//hellohaLayout
@ViewInject(R.id.helloha_layout)
private LinearLayout hellohalLayout;
private DisplayImageOptions headImageOptions;
// //bitmapUtils
// BitmapUtils bitmapUtil;
//用户模型
private UserModel userModel;
@OnClick({R.id.set_button, R.id.helloha_button})
private void clickEvent(View view) {
switch (view.getId()) {
case R.id.set_button:
//设置按钮
setButton.setVisibility(View.GONE);
hellohalLayout.setVisibility(View.VISIBLE);
break;
case R.id.helloha_button:
//保存按钮
saveHelloHaId();
break;
case R.id.my_card_layout:
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
break;
default:
break;
}
}
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_my_card;
}
@Override
protected void setUpView() {
setBarText("我的名片");
userModel = UserManager.getInstance().getUser();
if (null != userModel.getHelloha_id() && userModel.getHelloha_id().length() > 0) {
hellohaTextView.setVisibility(View.VISIBLE);
hellohaTextView.setText("HelloHa号"+userModel.getHelloha_id());
}else {
setButton.setVisibility(View.VISIBLE);
}
headImageOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.default_avatar)
.showImageOnFail(R.drawable.default_avatar)
.cacheInMemory(false)
.cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
nameTextView.setText(userModel.getName());
// bitmapUtil.display(headImageView, JLXCConst.ATTACHMENT_ADDR+userModel.getHead_image());
ImageLoader.getInstance().displayImage(JLXCConst.ATTACHMENT_ADDR+userModel.getHead_image(), headImageView, headImageOptions);
getQRCode();
}
//////////////////////////private method////////////////////////
private void getQRCode() {
String path = JLXCConst.GET_USER_QRCODE+"?"+"uid="+userModel.getUid();
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
String qrpath = jsonResponse.getString(JLXCConst.HTTP_RESULT);
ImageLoader.getInstance().displayImage(JLXCConst.ROOT_PATH+qrpath, qrcodeImageView, headImageOptions);
// bitmapUtil.display(qrcodeImageView, JLXCConst.ROOT_PATH+qrpath);
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(MyCardActivity.this, jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
}
}, null));
}
//保存HelloHaId
private void saveHelloHaId() {
//必须按格式
if (hellohaEditText.getText().toString().matches(JLXCConst.USER_ACCOUNT_PATTERN) == false) {
ToastUtil.show(this, "账号只能由6-20位字母数字下划线组成╮(╯_╰)╭");
return;
}
final CustomAlertDialog confirmDialog = new CustomAlertDialog(
this, "账号设置后不能更改,你愿意和它相伴一生吗", "确定", "取消");
confirmDialog.show();
confirmDialog.setClicklistener(new CustomAlertDialog.ClickListenerInterface() {
@Override
public void doConfirm() {
setHelloHaId();
confirmDialog.dismiss();
}
@Override
public void doCancel() {
confirmDialog.dismiss();
}
});
// //提示
// new AlertDialog.Builder(this).setPositiveButton("确定", new OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// setHelloHaId();
// }
// }).setNegativeButton("取消", null).setTitle("注意").setMessage("账号设置后不能更改,你愿意和它相伴一生吗").show();
}
//设置HelloHaId
private void setHelloHaId(){
hellohaEditText.setEnabled(false);
//网络请求
RequestParams params = new RequestParams();
params.addBodyParameter("uid", userModel.getUid()+"");
params.addBodyParameter("helloha_id", hellohaEditText.getText().toString().trim());
showLoading("账号设置中", false);
//上传
HttpManager.post(JLXCConst.SET_HELLOHAID, params, new JsonRequestCallBack<String>(new LoadDataHandler<String>(){
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
//设置成功
userModel.setHelloha_id(hellohaEditText.getText().toString().trim());
//本地缓存
UserManager.getInstance().saveAndUpdate();
//布局改变
hellohalLayout.setVisibility(View.GONE);
hellohaTextView.setVisibility(View.VISIBLE);
hellohaTextView.setText("HelloHa号:"+userModel.getHelloha_id());
}else {
if (jsonResponse.getJSONObject(JLXCConst.HTTP_RESULT).getIntValue("flag") == 1) {
//有号
String helloHaId = jsonResponse.getJSONObject(JLXCConst.HTTP_RESULT).getString("helloha_id");
if (null != helloHaId && helloHaId.length()>0) {
userModel.setHelloha_id(helloHaId);
//本地缓存
UserManager.getInstance().saveAndUpdate();
//布局改变
hellohalLayout.setVisibility(View.GONE);
hellohaTextView.setVisibility(View.VISIBLE);
hellohaTextView.setText("HelloHa账号:"+userModel.getHelloha_id());
}
}
}
hideLoading();
ToastUtil.show(MyCardActivity.this, jsonResponse.getString(JLXCConst.HTTP_MESSAGE));
hellohaEditText.setEnabled(true);
}
@Override
public void onFailure(HttpException arg0, String arg1, String flag) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1, flag);
hideLoading();
ToastUtil.show(MyCardActivity.this, "网络异常");
hellohaEditText.setEnabled(true);
}
}, null));
}
}
<file_sep>package com.jlxc.app.personal.model;
/**
* 好友模型
* @author lixiaohang
*
*/
public class FriendModel {
//用户id
private int uid;
//用户姓名
private String name;
//头像缩略图
private String head_sub_image;
//头像大图
private String head_image;
//学校
private String school;
//是否被关注或已经关注
private boolean isOrHasAttent;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHead_sub_image() {
return head_sub_image;
}
public void setHead_sub_image(String head_sub_image) {
this.head_sub_image = head_sub_image;
}
public String getHead_image() {
return head_image;
}
public void setHead_image(String head_image) {
this.head_image = head_image;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public boolean isOrHasAttent() {
return isOrHasAttent;
}
public void setOrHasAttent(boolean isOrHasAttent) {
this.isOrHasAttent = isOrHasAttent;
}
}
<file_sep>package com.jlxc.app.base.utils;
public interface JLXCConst {
// 正式环境 192.168.3.11 192.168.1.107 www.90newtec.com
// 测试环境
public static final String DOMIN = "http://www.90newtec.com/jlxc_php/index.php/Home/MobileApi";
public static final String ATTACHMENT_ADDR = "http://www.90newtec.com/jlxc_php/Uploads/";
public static final String ROOT_PATH = "http://www.90newtec.com/jlxc_php/";
public static final int STATUS_SUCCESS = 1;// 接口返回成功
public static final int STATUS_FAIL = 0;// 接口返回失败
public static final String HTTP_MESSAGE = "message"; // 返回值信息
public static final String HTTP_RESULT = "result";// 返回值结果
public static final String HTTP_STATUS = "status";// 返回值状态
public static final String HTTP_LIST = "list";// 返回值列表
public static final int PAGE_SIZE = 10;
// IM和推送 公用前缀
public static final String JLXC = "jlxc";// 返回值列表
// broadCast
// 状态回复消息或点赞或者新好友
public static final String BROADCAST_NEW_MESSAGE_PUSH = "com.jlxc.broadcastreceiver.newsPush";
// tab栏徽标更新通知
public static final String BROADCAST_TAB_BADGE = "com.jlxc.broadcastreceiver.tabBadge";
// 消息顶部更新
public static final String BROADCAST_MESSAGE_REFRESH = "com.jlxc.broadcastreceiver.messageRefresh";
// 动态详细更新后上一页面也进行更新
public static final String BROADCAST_NEWS_LIST_REFRESH = "com.jlxc.broadcastreceiver.newsDetailRefresh";
// 新圈子发布
public static final String BROADCAST_NEW_TOPIC_REFRESH = "com.jlxc.broadcastreceiver.newTopicPublish";
// 匹配网页
public static final String URL_PATTERN = "[http|https]+[://]+[0-9A-Za-z:/[-]_#[?][=][.][&]]*";
// 匹配手机号
public static final String PHONENUMBER_PATTERN = "1[3|4|5|7|8|][0-9]{9}";
// 用户名匹配
public static final String USER_ACCOUNT_PATTERN = "^[a-zA-Z0-9]{6,20}+$";
// 匹配身份证号:15位 18位
public static final String ID_CARD = "^\\d{15}|^\\d{17}([0-9]|X|x)$";
// 姓名正则
public static final String NAME_PATTERN = "([\u4e00-\u9fa5]{2,5})(·[\u4e00-\u9fa5]{2,5})*";
// //////////////////////////////////////////////登录注册部分////////////////////////////////////////////////
// 是否有该用户
public static final String IS_USER = DOMIN + "/isUser";
// 获取验证码
public static final String GET_MOBILE_VERIFY = DOMIN + "/getMobileVerify";
// 用户注册
public static final String REGISTER_USER = DOMIN + "/registerUser";
// 找回密码
public static final String FIND_PWD = DOMIN + "/findPwd";
// 用户登录
public static final String LOGIN_USER = DOMIN + "/loginUser";
// 注册时填写个人信息
public static final String SAVE_PERSONAL_INFO = DOMIN + "/savePersonalInfo";
// //////////////////////////////////////////////首页'说说'部分////////////////////////////////////////////////
// 发布状态
public static final String PUBLISH_NEWS = DOMIN + "/publishNews";
// 状态新闻列表
public static final String NEWS_LIST = DOMIN + "/newsList";
// 校园广场新闻列表
public static final String SCHOOL_NEWS_LIST = DOMIN + "/schoolNewsList";
// 校园广场新闻主页
public static final String SCHOOL_HOME_DATA = DOMIN + "/schoolHomeData";
// 状态点赞列表
public static final String GET_NEWS_LIKE_LIST = DOMIN + "/getNewsLikeList";
// 发送评论
public static final String SEND_COMMENT = DOMIN + "/sendComment";
// 删除评论
public static final String DELETE_COMMENT = DOMIN + "/deleteComment";
// 删除二级评论
public static final String DELETE_SECOND_COMMENT = DOMIN
+ "/deleteSecondComment";
// 发送二级评论
public static final String SEND_SECOND_COMMENT = DOMIN
+ "/sendSecondComment";
// 点赞或者取消赞
public static final String LIKE_OR_CANCEL = DOMIN + "/likeOrCancel";
// 新闻详情
public static final String NEWS_DETAIL = DOMIN + "/newsDetail";
// 浏览过该新闻的用户列表
public static final String GET_NEWS_VISIT_LIST = DOMIN
+ "/getNewsVisitList";
// //////////////////////////////////////////////个人信息////////////////////////////////////////////////
// 修改个人信息
public static final String CHANGE_PERSONAL_INFORMATION = DOMIN
+ "/changePersonalInformation";
// 获取学校列表
public static final String GET_SCHOOL_LIST = DOMIN + "/getSchoolList";
// 获取学校学生列表
public static final String GET_SCHOOL_STUDENT_LIST = DOMIN
+ "/getSchoolStudentList";
// 修改学校
public static final String CHANGE_SCHOOL = DOMIN + "/changeSchool";
// 设置HelloHaID
public static final String SET_HELLOHAID = DOMIN + "/setHelloHaId";
// 获取用户二维码
public static final String GET_USER_QRCODE = DOMIN + "/getUserQRCode";
// 修改个人信息中的图片 如背景图 头像
public static final String CHANGE_INFORMATION_IMAGE = DOMIN
+ "/changeInformationImage";
// 个人信息中 获取最新动态的三张图片 旧版
public static final String GET_NEWS_IMAGES = DOMIN + "/getNewsImages";
// 个人信息中 获取最新动态的十张图片
public static final String GET_NEWS_COVER_LIST = DOMIN + "/getNewsCoverList";
// 个人信息中 获取来访三张头像 弃用
public static final String GET_VISIT_IMAGES = DOMIN + "/getVisitImages";
// 个人信息中 获取粉丝数量
public static final String GET_FANS_COUNT = DOMIN + "/getFansCount";
// 个人信息中 获取好友三张头像
public static final String GET_FRIENDS_IMAGE = DOMIN + "/getFriendsImage";
// 个人信息中 用户发布过的状态列表
public static final String USER_NEWS_LIST = DOMIN + "/userNewsList";
// 个人信息 删除状态
public static final String DELETE_NEWS = DOMIN + "/deleteNews";
// 个人信息 查看别人的信息 旧版
public static final String PERSONAL_INFORMATION = DOMIN
+ "/personalInformation";
// 个人信息 查看别人的信息
public static final String PERSONAL_INFO = DOMIN
+ "/personalInfo";
// 最近来访列表
public static final String GET_VISIT_LIST = DOMIN + "/getVisitList";
// 删除来访
public static final String DELETE_VISIT = DOMIN + "/deleteVisit";
// 别人的好友列表
public static final String GET_OTHER_FRIENDS_LIST = DOMIN
+ "/getOtherFriendsList";
// 共同的好友列表
public static final String GET_COMMON_FRIENDS_LIST = DOMIN
+ "/getCommonFriendsList";
// 举报用户
public static final String REPORT_OFFENCE = DOMIN + "/reportOffence";
// 版本更新
// http://localhost/jlxc_php/index.php/Home/MobileApi/getLastestVersion?sys=2
public static final String GET_LASTEST_VERSION = DOMIN
+ "/getLastestVersion";
// ////////////////////////////////////////IM模块//////////////////////////////////////////
// 添加好友
// http://localhost/jlxc_php/index.php/Home/MobileApi/addFriend
public static final String Add_FRIEND = DOMIN + "/addFriend";
// 删除好友
// http://localhost/jlxc_php/index.php/Home/MobileApi/deleteFriend
public static final String DELETE_FRIEND = DOMIN + "/deleteFriend";
// 添加好友备注
// http://localhost/jlxc_php/index.php/Home/MobileApi/addRemark
public static final String ADD_REMARK = DOMIN + "/addRemark";
// 获取图片和名字
// http://localhost/jlxc_php/index.php/Home/MobileApi/getImageAndName
public static final String GET_IMAGE_AND_NAME = DOMIN + "/getImageAndName";
// 是否同步好友
// http://localhost/jlxc_php/index.php/Home/MobileApi/NeedSyncFriends
public static final String NEED_SYNC_FRIENDS = DOMIN + "/needSyncFriends";
// 获取好友列表
// http://localhost/jlxc_php/index.php/Home/MobileApi/getFriendsList
public static final String GET_FRIENDS_LIST = DOMIN + "/getFriendsList";
// 获取关注列表
// http://localhost/jlxc_php/index.php/Home/MobileApi/getAttentList
public static final String GET_ATTENT_LIST = DOMIN + "/getAttentList";
// 获取粉丝列表
// http://localhost/jlxc_php/index.php/Home/MobileApi/getFansList
public static final String GET_FANS_LIST = DOMIN + "/getFansList";
// 获取其他人的关注列表
// http://localhost/jlxc_php/index.php/Home/MobileApi/getAttentList
public static final String GET_OTHER_ATTENT_LIST = DOMIN + "/getOtherAttentList";
// 获取其他人的粉丝列表
// http://localhost/jlxc_php/index.php/Home/MobileApi/getFansList
public static final String GET_OTHER_FANS_LIST = DOMIN + "/getOtherFansList";
// 获取全部好友列表
// http://localhost/jlxc_php/index.php/Home/MobileApi/getAllFriendsList
public static final String GET_ALL_FRIENDS_LIST = DOMIN
+ "/getAllFriendsList";
////////////////////////////////////////发现模块 圈子//////////////////////////////////////////
// http://localhost/jlxc_php/index.php/Home/MobileApi/getTopicCategory
// 获取圈子类型
public static final String GET_TOPIC_CATEGORY = DOMIN + "/getTopicCategory";
// http://localhost/jlxc_php/index.php/Home/MobileApi/postNewTopic
// 创建一个圈子
public static final String POST_NEW_TOPIC = DOMIN + "/postNewTopic";
// http://localhost/jlxc_php/index.php/Home/MobileApi/getTopicDetail
// 获取圈子详情
public static final String GET_TOPIC_DETAIL = DOMIN + "/getTopicDetail";
// 加入一个圈子详情
public static final String JOIN_TOPIC = DOMIN + "/joinTopic";
// 退出一个圈子详情
public static final String QUIT_TOPIC = DOMIN + "/quitTopic";
// 获取我的圈子列表
//http://localhost/jlxc_php/index.php/Home/MobileApi/getMyTopicList
public static final String GET_MY_TOPIC_LIST = DOMIN + "/getMyTopicList";
// 获取我的圈子列表
public static final String GET_TOPIC_NEWS_LIST = DOMIN + "/getTopicNewsList";
// 获取圈子成员列表
public static final String GET_TOPIC_MEMBER_LIST = DOMIN + "/getTopicMemberList";
// 获取话题主页列表
public static final String GET_TOPIC_HOME_LIST = DOMIN + "/getTopicHomeList";
// 获取分类话题列表
public static final String GET_CATEGORY_TOPIC_LIST = DOMIN + "/getCategoryTopicList";
////////////////////////////////////////发现模块//////////////////////////////////////////
// http://localhost/jlxc_php/index.php/Home/MobileApi/getContactUser
// 获取联系人用户
public static final String GET_CONTACT_USER = DOMIN + "/getContactUser";
// http://localhost/jlxc_php/index.php/Home/MobileApi/getSameSchoolList
// 获取同校的人列表
public static final String GET_SAME_SCHOOL_LIST = DOMIN
+ "/getSameSchoolList";
// http://localhost/jlxc_php/index.php/Home/MobileApi/findUserList
// 搜索用户列表
public static final String FIND_USER_LIST = DOMIN + "/findUserList";
// http://localhost/jlxc_php/index.php/Home/MobileApi/helloHaIdExists
// 判断该哈哈号是否存在
public static final String HELLOHA_ID_EXISTS = DOMIN + "/helloHaIdExists";
// http://localhost/jlxc_php/index.php/Home/MobileApi/recommendFriendsList
// 推荐的人列表
public static final String RECOMMEND_FRIENDS_LIST = DOMIN
+ "/recommendFriendsList";
}
<file_sep>package com.jlxc.app.personal.model;
/**
* 共同好友model
* @author lixiaohang
*/
public class CommonFriendsModel {
private int friend_id;//用户id
private String head_sub_image;//用户头像缩略图
public int getFriend_id() {
return friend_id;
}
public void setFriend_id(int friend_id) {
this.friend_id = friend_id;
}
public String getHead_sub_image() {
return head_sub_image;
}
public void setHead_sub_image(String head_sub_image) {
this.head_sub_image = head_sub_image;
}
}
<file_sep>package com.jlxc.app.group.ui.activity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.group.model.GroupTopicModel;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
/**
* 圈子列表
* */
public class MyGroupListActivity extends BaseActivityWithTopBar {
// 圈子的相关信息
// private final static String GROUP_TYPE = "group_type";
// private final static String GROUP_NAME = "group_name";
// private final static String GROUP_MEMBER = "group_member";
// private final static String GROUP_COVER_IMG = "group_cover_image";
// private final static String GROUP_UNREAD_COUNT = "group_unread_msg";
// 圈子类别
// private final static String GROUP_TYPE_SCHOOL = "school";
// private final static String GROUP_TYPE_ATTENTION = "attention";
// private final static String GROUP_TYPE_CREATE = "create";
// 动态listview
@ViewInject(R.id.listview_my_group)
private PullToRefreshListView groupListView;
// 提示信息
@ViewInject(R.id.txt_my_group_prompt)
private TextView myGroupPrompt;
// 动态列表适配器
private HelloHaAdapter<GroupTopicModel> groupAdapter = null;
// 用户关注的圈子信息数据
private List<GroupTopicModel> groupList = new ArrayList<GroupTopicModel>();
// 点击view监听对象
private ItemViewClick itemViewClickListener;
// 加载图片
private ImageLoader imgLoader;
// 图片配置
private DisplayImageOptions options;
@Override
public int setLayoutId() {
return R.layout.activity_my_group_list;
}
@Override
protected void setUpView() {
// 设置标头
setBarText("我的频道");
// 初始化
initialize();
newsListViewSet();
// 获取我的圈子列表
getMyTopicList();
}
/**
* 数据的初始化
* */
private void initialize() {
itemViewClickListener = new ItemViewClick();
// 获取显示图片的实例
imgLoader = ImageLoader.getInstance();
// 显示图片的配置
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading_default)
.showImageOnFail(R.drawable.image_load_fail)
.cacheInMemory(true).cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
/**
* listView 的设置
* */
private void newsListViewSet() {
// 设置刷新模式
groupListView.setMode(Mode.DISABLED);
/**
* 刷新监听
* */
groupListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
}
@Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
}
});
/**
* adapter的设置
* */
groupAdapter = new HelloHaAdapter<GroupTopicModel>(
MyGroupListActivity.this, R.layout.listitem_my_group_layout,
groupList) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper,
GroupTopicModel item) {
// 关注的圈子
imgLoader.displayImage(
JLXCConst.ATTACHMENT_ADDR
+ item.getTopic_cover_sub_image(),
(ImageView) helper.getView(R.id.img_my_group_icon),
options);
helper.setText(R.id.txt_my_group_name, item.getTopic_name());
helper.setText(R.id.txt_group_member_count,
item.getMember_count() + "人关注");
int unread = item.getUnread_news_count();
if (unread > 0) {
helper.setVisible(R.id.txt_my_group_unread_news_count, true);
helper.setText(R.id.txt_my_group_unread_news_count, unread
+ "");
} else {
helper.setVisible(R.id.txt_my_group_unread_news_count,
false);
}
// 设置事件监听
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion,
view.getId());
}
};
helper.setOnClickListener(R.id.layout_group_Listitem_rootview,
listener);
}
};
// 设置不可点击
groupAdapter.setItemsClickEnable(false);
groupListView.setAdapter(groupAdapter);
}
/**
* item上的view点击事件
* */
public class ItemViewClick implements ListItemClickHelp {
@Override
public void onClick(View view, int postion, int viewID) {
switch (viewID) {
case R.id.layout_group_Listitem_rootview:
// 跳转至圈子内容部分
Intent intentToGroupNews = new Intent();
intentToGroupNews.setClass(MyGroupListActivity.this,
GroupNewsActivity.class);
// 传递名称
intentToGroupNews.putExtra(
GroupNewsActivity.INTENT_KEY_TOPIC_NAME, groupAdapter
.getItem(postion).getTopic_name());
// 传递ID
intentToGroupNews.putExtra(
GroupNewsActivity.INTENT_KEY_TOPIC_ID, groupAdapter
.getItem(postion).getTopic_id());
// 设置为0
GroupTopicModel model = groupList.get(postion);
model.setUnread_news_count(0);
groupAdapter.replaceAll(groupList);
startActivityWithRight(intentToGroupNews);
break;
default:
break;
}
}
}
/**
* listview点击事件接口,用于区分不同view的点击事件
*
* @author Alan
*/
private interface ListItemClickHelp {
void onClick(View view, int postion, int viewID);
}
// 获取我的话题
private void getMyTopicList() {
// 获取群组详情
String path = JLXCConst.GET_MY_TOPIC_LIST + "?user_id="
+ UserManager.getInstance().getUser().getUid();
LogUtils.i(path, 1);
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
hideLoading();
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
jsonToGroupData(jResult
.getJSONArray(JLXCConst.HTTP_LIST));
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(MyGroupListActivity.this,
jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
hideLoading();
super.onFailure(arg0, arg1, flag);
ToastUtil.show(MyGroupListActivity.this, "获取失败。。");
}
}, null));
}
/**
* 数据处理
*/
private void jsonToGroupData(JSONArray dataList) {
groupList.clear();
for (int i = 0; i < dataList.size(); i++) {
JSONObject object = dataList.getJSONObject(i);
GroupTopicModel groupTopicModel = new GroupTopicModel();
groupTopicModel.setTopic_id(object.getIntValue("topic_id"));
groupTopicModel.setTopic_name(object.getString("topic_name"));
groupTopicModel.setMember_count(object.getIntValue("member_count"));
groupTopicModel.setTopic_cover_sub_image(object
.getString("topic_cover_sub_image"));
groupTopicModel.setUnread_news_count(object
.getIntValue("unread_news_count"));
groupList.add(groupTopicModel);
}
groupAdapter.replaceAll(groupList);
//显示提示信息
if (groupAdapter.getCount() <= 0) {
myGroupPrompt.setVisibility(View.VISIBLE);
} else {
myGroupPrompt.setVisibility(View.GONE);
}
}
}
<file_sep>package com.jlxc.app.discovery.model;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.base.utils.JLXCConst;
public class PersonModel {
// 用户的id
private String userId;
// 用户名
private String userName;
// 用户所在的学校
private String userSchool;
// 学校代码
private String schoolCode;
// 用户的头像
private String headImage;
// 头像的缩略图
private String headSubImage;
// 照片列表
private List<String> imageList;
// 关系来源
private String type;
// 是否为朋友
private String isFriend = "0";
// 电话号码
private String phoneNumber;
// 性别
private String sex;
@SuppressWarnings("unchecked")
public void setContentWithJson(JSONObject object) {
if (object.containsKey("uid")) {
setUerId(object.getString("uid"));
}
if (object.containsKey("name")) {
setUserName(object.getString("name"));
}
if (object.containsKey("school")) {
setUserSchool(object.getString("school"));
}
if (object.containsKey("school_code")) {
setSchoolCoed(object.getString("school_code"));
}
if (object.containsKey("head_image")) {
setHeadImage(JLXCConst.ATTACHMENT_ADDR
+ object.getString("head_image"));
}
if (object.containsKey("head_sub_image")) {
setHeadSubImage(JLXCConst.ATTACHMENT_ADDR
+ object.getString("head_sub_image"));
}
// 图片的转换
if (object.containsKey("images")) {
List<JSONObject> JImageObj = (List<JSONObject>) object
.get("images");
List<String> imgList = new ArrayList<String>();
for (JSONObject imgObject : JImageObj) {
imgList.add(JLXCConst.ATTACHMENT_ADDR
+ imgObject.getString("sub_url"));
}
setImageList(imgList);
}
// 类型转换
if (object.containsKey("type")) {
JSONObject JTypeObj = (JSONObject) object.get("type");
setType(JTypeObj.getString("content"));
}
if (object.containsKey("is_friend")) {
setIsFriend(object.getString("is_friend"));
}
if (object.containsKey("phone")) {
setPhoneNumber(object.getString("phone"));
}
}
// 重写hashCode方法
@Override
public int hashCode() {
return this.userId.hashCode();
}
// 重写equals方法
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (null != obj && obj instanceof PersonModel) {
PersonModel p = (PersonModel) obj;
if (userId.equals(p.userId) && userName.equals(p.userName)
&& userSchool.equals(p.userSchool)) {
return true;
}
}
return false;
}
public String getUerId() {
return userId;
}
public void setUerId(String userId) {
this.userId = userId;
}
public String getUserSchool() {
return userSchool;
}
public void setUserSchool(String userSchool) {
this.userSchool = userSchool;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSchoolCoed() {
return schoolCode;
}
public void setSchoolCoed(String schoolCode) {
this.schoolCode = schoolCode;
}
public String getHeadImage() {
return headImage;
}
public void setHeadImage(String headImage) {
this.headImage = headImage;
}
public String getHeadSubImage() {
return headSubImage;
}
public void setHeadSubImage(String headSubImage) {
this.headSubImage = headSubImage;
}
public List<String> getImageList() {
return imageList;
}
public void setImageList(List<String> imageList) {
this.imageList = imageList;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getIsFriend() {
return isFriend;
}
public void setIsFriend(String isFriend) {
this.isFriend = isFriend;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
<file_sep>package com.jlxc.app.news.ui.activity;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.BitmapManager;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.news.model.LikeModel;
import com.jlxc.app.personal.ui.activity.OtherPersonalActivity;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.bitmap.callback.DefaultBitmapLoadCallBack;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
public class AllLikePersonActivity extends BaseActivityWithTopBar {
public final static String INTENT_KEY_NEWS_ID = "news_id";
// 点赞的人的listview
@ViewInject(R.id.listview_all_like_person)
private PullToRefreshListView allPersonListView;
// 数据源
private List<LikeModel> dataList = new ArrayList<LikeModel>();
// 适配器
private HelloHaAdapter<LikeModel> allPersonAdapter;
// 当前的刷新模式
private boolean isPullDown = false;
// 当前的数据页
private int currentPage = 1;
// 动态的ID
private String newsId;
// 是否是最后一页数据
private String lastPage = "0";
// 是否正在请求数据
private boolean isRequestingData = false;
// 加载图片
private ImageLoader imgLoader;
// 图片配置
private DisplayImageOptions options;
@Override
public int setLayoutId() {
return R.layout.activity_all_like_person_layout;
}
@Override
protected void setUpView() {
setBarText("点了赞的小伙伴 (o・_・)");
init();
listviewSet();
// 首次进入获取数据
isPullDown = true;
getCampusAllPerson(newsId, "1");
}
/**
* 初始化
* */
private void init() {
// 获取学校代码
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
newsId = bundle.getString(INTENT_KEY_NEWS_ID);
//
// 获取实例
imgLoader = ImageLoader.getInstance();
// 显示图片的配置
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading_default)
.showImageOnFail(R.drawable.default_avatar).cacheInMemory(true)
.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
}
/**
* 数据绑定初始化
* */
private void listviewSet() {
// 设置刷新模式
allPersonListView.setMode(Mode.BOTH);
allPersonAdapter = new HelloHaAdapter<LikeModel>(
AllLikePersonActivity.this,
R.layout.all_like_person_item_layout, dataList) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper,
LikeModel item) {
// 绑定头像图片
// 绑定头像图片
if (null != item.getHeadSubImage()
&& item.getHeadSubImage().length() > 0) {
imgLoader
.displayImage(
item.getHeadSubImage(),
(ImageView) helper
.getView(R.id.iv_all_like_person_item_head),
options);
} else {
((ImageView) helper
.getView(R.id.iv_all_like_person_item_head))
.setImageResource(R.drawable.default_avatar);
}
// 绑定昵称
helper.setText(R.id.tv_all_like_person_item_name,
item.getName());
}
};
/**
* 刷新监听
* */
allPersonListView
.setOnRefreshListener(new OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
if (!isRequestingData) {
isRequestingData = true;
currentPage = 1;
isPullDown = true;
getCampusAllPerson(newsId,
String.valueOf(currentPage));
}
}
@Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
if (!lastPage.equals("1") && !isRequestingData) {
isRequestingData = true;
isPullDown = false;
getCampusAllPerson(newsId,
String.valueOf(currentPage));
}
}
});
/**
* 设置底部自动刷新
* */
allPersonListView
.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
@Override
public void onLastItemVisible() {
if (!lastPage.equals("1")) {
allPersonListView.setMode(Mode.PULL_FROM_END);
allPersonListView.setRefreshing(true);
}
}
});
allPersonListView.setAdapter(allPersonAdapter);
// 单击
allPersonListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intentUsrMain = new Intent(AllLikePersonActivity.this,
OtherPersonalActivity.class);
intentUsrMain.putExtra(
OtherPersonalActivity.INTENT_KEY,
JLXCUtils.stringToInt(allPersonAdapter.getItem(
position - 1).getUserID()));
startActivityWithRight(intentUsrMain);
}
});
}
private void JsonToPersonData(List<JSONObject> jPersonList) {
List<LikeModel> List = new ArrayList<LikeModel>();
// 解析校园的人
for (JSONObject likeObj : jPersonList) {
LikeModel tempPerson = new LikeModel();
tempPerson.setContentWithJson(likeObj);
List.add(tempPerson);
}
if (isPullDown) {
allPersonAdapter.replaceAll(List);
} else {
allPersonAdapter.addAll(List);
}
if (null != jPersonList) {
jPersonList.clear();
}
}
/**
* 获取学校所有学生信息
* */
private void getCampusAllPerson(String newsID, String page) {
String path = JLXCConst.GET_NEWS_LIKE_LIST + "?" + "&news_id=" + newsID
+ "&page=" + page + "&size=";
LogUtils.i("path=" + path);
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@SuppressWarnings("unchecked")
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
// 获取数据列表
List<JSONObject> JPersonList = (List<JSONObject>) jResult
.get("list");
JsonToPersonData(JPersonList);
allPersonListView.onRefreshComplete();
lastPage = jResult.getString("is_last");
if (lastPage.equals("0")) {
currentPage++;
allPersonListView.setMode(Mode.BOTH);
} else {
allPersonListView.setMode(Mode.PULL_FROM_START);
}
isRequestingData = false;
}
if (status == JLXCConst.STATUS_FAIL) {
allPersonListView.onRefreshComplete();
if (lastPage.equals("0")) {
allPersonListView.setMode(Mode.BOTH);
}
ToastUtil.show(AllLikePersonActivity.this,
jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
}
isRequestingData = false;
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
super.onFailure(arg0, arg1, flag);
allPersonListView.onRefreshComplete();
if (lastPage.equals("0")) {
allPersonListView.setMode(Mode.BOTH);
}
ToastUtil.show(AllLikePersonActivity.this,
"网络故障,请检查=_=");
isRequestingData = false;
}
}, null));
}
}
<file_sep>package com.jlxc.app.news.ui.view;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jlxc.app.R;
import com.jlxc.app.base.ui.activity.BigImgLookActivity;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.news.model.ImageModel;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
public class MultiImageMetroView extends RelativeLayout {
// 根布局
private LinearLayout rootView;
// 底部布局
private LinearLayout bottomLayout;
// 左边布局
private LinearLayout leftLayout;
// 右边布局
private LinearLayout rightLayout;
// 中间布局
private LinearLayout middleLayout;
// 多图
private List<ImageView> imageViewsList = new ArrayList<ImageView>();
//
private Context mContext;
// 图片源
private List<ImageModel> dataList = new ArrayList<ImageModel>();
// 点击事件回调接口
private JumpCallBack jumpInterface;
// 加载图片
private ImageLoader imgLoader;
// 图片配置
private DisplayImageOptions options;
public MultiImageMetroView(Context context) {
super(context);
}
public MultiImageMetroView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
getWidget();
}
/**
* 初始化
* */
private void init() {
imgLoader = ImageLoader.getInstance();
// 显示图片的配置
options = new DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.showImageOnLoading(R.drawable.loading_default)
.showImageOnFail(R.drawable.image_load_fail)
.cacheInMemory(false).cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
/**
* 快速滑动时是否加载图片
* */
public void loadImageOnFastSlide(PullToRefreshListView listView,
boolean isLoad) {
listView.setOnScrollListener(new PauseOnScrollListener(imgLoader, true,
isLoad));
}
/**
* 获取控件
* */
private void getWidget() {
View view = View.inflate(mContext,
R.layout.custom_multi_metro_imageview, this);
// 获取布局
rootView = (LinearLayout) view
.findViewById(R.id.layout_multi_image_root_view);
bottomLayout = (LinearLayout) view
.findViewById(R.id.layout_multi_pic_bottom);
leftLayout = (LinearLayout) view
.findViewById(R.id.layout_multi_pic_left);
middleLayout = (LinearLayout) view
.findViewById(R.id.layout_multi_pic_middle);
rightLayout = (LinearLayout) view
.findViewById(R.id.layout_multi_pic_right);
// 获取控件
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_A));
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_B));
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_C));
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_D));
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_E));
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_F));
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_G));
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_H));
imageViewsList.add((ImageView) view
.findViewById(R.id.iv_custom_picture_I));
}
/**
* 事件监听
* */
private void setClickListener(final List<ImageView> tempimageViewsList) {
// 图片点击事件
for (int index = 0; index < tempimageViewsList.size(); index++) {
tempimageViewsList.get(index).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View view) {
for (int postion = 0; postion < tempimageViewsList
.size(); postion++) {
if (view.getId() == tempimageViewsList.get(
postion).getId()) {
jumpToBigImage(
BigImgLookActivity.INTENT_KEY_IMG_MODEl_LIST,
dataList, postion);
break;
}
}
}
});
}
}
/**
* 绑定数据
*/
public void imageDataSet(final List<ImageModel> pictureList) {
dataList = pictureList;
// 用于存放将要显示的imageview
List<ImageView> tempimageViewsList = new ArrayList<ImageView>();
// 先隐藏
for (int index = 0; index < imageViewsList.size(); index++) {
imageViewsList.get(index).setVisibility(View.GONE);
}
leftLayout.setVisibility(View.GONE);
rightLayout.setVisibility(View.GONE);
bottomLayout.setVisibility(View.GONE);
middleLayout.setVisibility(View.GONE);
rootView.setVisibility(View.GONE);
switch (pictureList.size()) {
// 只有一张图片
case 1:
leftLayout.setVisibility(View.VISIBLE);
tempimageViewsList.add(imageViewsList.get(0));
break;
// 2张图片
case 2:
leftLayout.setVisibility(View.VISIBLE);
middleLayout.setVisibility(View.VISIBLE);
tempimageViewsList.add(imageViewsList.get(0));
tempimageViewsList.add(imageViewsList.get(1));
break;
// 3张图片
case 3:
rightLayout.setVisibility(View.VISIBLE);
middleLayout.setVisibility(View.VISIBLE);
tempimageViewsList.add(imageViewsList.get(1));
tempimageViewsList.add(imageViewsList.get(2));
tempimageViewsList.add(imageViewsList.get(5));
break;
// 4张图片
case 4:
leftLayout.setVisibility(View.VISIBLE);
middleLayout.setVisibility(View.VISIBLE);
tempimageViewsList.add(imageViewsList.get(0));
tempimageViewsList.add(imageViewsList.get(1));
tempimageViewsList.add(imageViewsList.get(3));
tempimageViewsList.add(imageViewsList.get(4));
break;
// 5张图片
case 5:
leftLayout.setVisibility(View.VISIBLE);
rightLayout.setVisibility(View.VISIBLE);
middleLayout.setVisibility(View.VISIBLE);
tempimageViewsList.add(imageViewsList.get(0));
tempimageViewsList.add(imageViewsList.get(1));
tempimageViewsList.add(imageViewsList.get(2));
tempimageViewsList.add(imageViewsList.get(4));
tempimageViewsList.add(imageViewsList.get(5));
break;
// 6张图片
case 6:
leftLayout.setVisibility(View.VISIBLE);
rightLayout.setVisibility(View.VISIBLE);
middleLayout.setVisibility(View.VISIBLE);
tempimageViewsList.add(imageViewsList.get(0));
tempimageViewsList.add(imageViewsList.get(1));
tempimageViewsList.add(imageViewsList.get(2));
tempimageViewsList.add(imageViewsList.get(3));
tempimageViewsList.add(imageViewsList.get(4));
tempimageViewsList.add(imageViewsList.get(5));
break;
// 7张图片
case 7:
leftLayout.setVisibility(View.VISIBLE);
rightLayout.setVisibility(View.VISIBLE);
bottomLayout.setVisibility(View.VISIBLE);
middleLayout.setVisibility(View.VISIBLE);
tempimageViewsList.add(imageViewsList.get(0));
tempimageViewsList.add(imageViewsList.get(1));
tempimageViewsList.add(imageViewsList.get(2));
tempimageViewsList.add(imageViewsList.get(4));
tempimageViewsList.add(imageViewsList.get(5));
tempimageViewsList.add(imageViewsList.get(6));
tempimageViewsList.add(imageViewsList.get(8));
break;
// 8张图片
case 8:
leftLayout.setVisibility(View.VISIBLE);
rightLayout.setVisibility(View.VISIBLE);
bottomLayout.setVisibility(View.VISIBLE);
middleLayout.setVisibility(View.VISIBLE);
tempimageViewsList.add(imageViewsList.get(0));
tempimageViewsList.add(imageViewsList.get(1));
tempimageViewsList.add(imageViewsList.get(2));
tempimageViewsList.add(imageViewsList.get(3));
tempimageViewsList.add(imageViewsList.get(4));
tempimageViewsList.add(imageViewsList.get(5));
tempimageViewsList.add(imageViewsList.get(7));
tempimageViewsList.add(imageViewsList.get(8));
break;
// 9张图片
case 9:
leftLayout.setVisibility(View.VISIBLE);
rightLayout.setVisibility(View.VISIBLE);
bottomLayout.setVisibility(View.VISIBLE);
middleLayout.setVisibility(View.VISIBLE);
tempimageViewsList = imageViewsList;
break;
default:
break;
}
// 绑定图片
for (int index = 0; index < tempimageViewsList.size(); index++) {
tempimageViewsList.get(index).setColorFilter(Color.parseColor("#05000000"));
if (rootView.getVisibility() == View.GONE) {
rootView.setVisibility(View.VISIBLE);
}
tempimageViewsList.get(index).setVisibility(View.VISIBLE);
if (tempimageViewsList.size() == 1) {
// 只有一张图片时显示大图
imgLoader.displayImage(pictureList.get(index).getURL(),
tempimageViewsList.get(index), options);
} else if (tempimageViewsList.size() == 2) {
// 有两张图片时,第一张显示大图
if (index == 0) {
imgLoader.displayImage(pictureList.get(index).getURL(),
tempimageViewsList.get(index), options);
} else {
imgLoader.displayImage(pictureList.get(index).getSubURL(),
tempimageViewsList.get(index), options);
}
} else {
// 显示缩略图
imgLoader.displayImage(pictureList.get(index).getSubURL(),
tempimageViewsList.get(index), options);
}
}
setClickListener(tempimageViewsList);
}
/**
* 设置跳转回调
*
* @param callInterface
*/
public void setJumpListener(JumpCallBack callInterface) {
this.jumpInterface = callInterface;
}
/**
* 跳转查看大图
*/
private void jumpToBigImage(String intentKey, Object path, int index) {
if (intentKey.equals(BigImgLookActivity.INTENT_KEY)) {
// 单张图片跳转
String pathUrl = (String) path;
Intent intentPicDetail = new Intent(mContext,
BigImgLookActivity.class);
intentPicDetail.putExtra(BigImgLookActivity.INTENT_KEY, pathUrl);
jumpInterface.onImageClick(intentPicDetail);
} else if (intentKey
.equals(BigImgLookActivity.INTENT_KEY_IMG_MODEl_LIST)) {
// 传递model列表
@SuppressWarnings("unchecked")
List<ImageModel> mdPath = (List<ImageModel>) path;
Intent intent = new Intent(mContext, BigImgLookActivity.class);
intent.putExtra(BigImgLookActivity.INTENT_KEY_IMG_MODEl_LIST,
(Serializable) mdPath);
intent.putExtra(BigImgLookActivity.INTENT_KEY_INDEX, index);
jumpInterface.onImageClick(intent);
} else if (intentKey.equals(BigImgLookActivity.INTENT_KEY_IMG_LIST)) {
// 传递String列表
@SuppressWarnings("unchecked")
List<String> mdPath = (List<String>) path;
Intent intent = new Intent(mContext, BigImgLookActivity.class);
intent.putExtra(BigImgLookActivity.INTENT_KEY_IMG_LIST,
(Serializable) mdPath);
intent.putExtra(BigImgLookActivity.INTENT_KEY_INDEX, index);
jumpInterface.onImageClick(intent);
} else {
LogUtils.e("未传递图片地址");
}
}
/**
* 点击事件回调接口
* */
public interface JumpCallBack {
public void onImageClick(Intent intentToimageoBig);
}
}
<file_sep>package com.jlxc.app.personal.ui.activity;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.BitmapManager;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.personal.model.CommonFriendsModel;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
public class CommonFriendsActivity extends BaseActivityWithTopBar {
public final static String INTENT_KEY = "uid";
//gridView用adapter
HelloHaAdapter<CommonFriendsModel> commonAdapter;
@ViewInject(R.id.common_friends_grid_view)
private GridView commonGridView;
private int uid;
// private BitmapUtils bitmapUtils;
private DisplayImageOptions headImageOptions;
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_common_friends;
}
@Override
protected void setUpView() {
Intent intent = getIntent();
setUid(intent.getIntExtra(INTENT_KEY, 0));
// setBitmapUtils(BitmapManager.getInstance().getHeadPicBitmapUtils(this, R.drawable.default_avatar, true, true));
headImageOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading_default)
.showImageOnFail(R.drawable.default_avatar)
.cacheInMemory(false)
.cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
setBarText("共同关注的人 ");
initGridView();
getData();
}
//初始化
private void initGridView() {
commonAdapter = new HelloHaAdapter<CommonFriendsModel>(this, R.layout.common_friends_image_layout) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper,
final CommonFriendsModel item) {
ImageView headimImageView = helper.getView(R.id.image_item);
// bitmapUtils.display(headimImageView, JLXCConst.ATTACHMENT_ADDR+item.getHead_sub_image());
if (null != item.getHead_sub_image() && item.getHead_sub_image().length() > 0) {
ImageLoader.getInstance().displayImage(JLXCConst.ATTACHMENT_ADDR+item.getHead_sub_image(), headimImageView, headImageOptions);
}else {
headimImageView.setImageResource(R.drawable.default_avatar);
}
LinearLayout linearLayout = (LinearLayout) helper.getView();
linearLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//跳转到其他人页面
Intent intent = new Intent(CommonFriendsActivity.this, OtherPersonalActivity.class);
intent.putExtra(OtherPersonalActivity.INTENT_KEY, item.getFriend_id());
startActivityWithRight(intent);
}
});
}
};
commonGridView.setAdapter(commonAdapter);
}
//获取数据
private void getData(){
String path = JLXCConst.GET_COMMON_FRIENDS_LIST+"?"+"uid="+uid+"¤t_id="+UserManager.getInstance().getUser().getUid();
HttpManager.get(path,
new JsonRequestCallBack<String>(new LoadDataHandler<String>() {
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
String jsonString = jResult.getString(JLXCConst.HTTP_LIST);
List<CommonFriendsModel> commonsFriendslist = JSON.parseArray(jsonString, CommonFriendsModel.class);
if (commonsFriendslist.size()>0) {
setBarText("共同关注的人"+"("+commonsFriendslist.size()+")");
}
commonAdapter.replaceAll(commonsFriendslist);
}
if (status == JLXCConst.STATUS_FAIL) {
ToastUtil.show(CommonFriendsActivity.this, jsonResponse.getString(JLXCConst.HTTP_MESSAGE));
}
}
@Override
public void onFailure(HttpException arg0, String arg1,String flag) {
super.onFailure(arg0, arg1, flag);
ToastUtil.show(CommonFriendsActivity.this, "网络有毒=_=");
}
}, null));
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
}
<file_sep>package com.jlxc.app.discovery.model;
import java.util.List;
import com.jlxc.app.base.utils.LogUtils;
public class RecommendItemData {
// item的种类数
public static final int RECOMMEND_ITEM_TYPE_COUNT = 3;
// 表示推荐的人列表item
public static final int RECOMMEND_TITLE = 0;
public static final int RECOMMEND_INFO = 1;
public static final int RECOMMEND_PHOTOS = 2;
// 当前的item类型
private int itemType;
public int getItemType() {
return itemType;
}
/**
* 设置item的类型
* */
public void setItemType(int type) {
switch (type) {
case RECOMMEND_TITLE:
case RECOMMEND_INFO:
case RECOMMEND_PHOTOS:
itemType = type;
break;
default:
LogUtils.e("items type error");
break;
}
}
/**
* 动态的头部
* */
public static class RecommendTitleItem extends RecommendItemData {
}
/**
* 信息
* */
public static class RecommendInfoItem extends RecommendItemData {
// 推荐的人头像缩略图
private String headSubImage;
// 推荐的人的头像
private String headImage;
// 推荐的人的名字
private String userName;
// 推荐的人学校
private String userSchool;
// 关系的标签
private String relationTag;
// 推荐的人的id
private String userID;
// 是否添加了
private boolean isAdd;
//当前原始对象索引
private int originIndex;
public String getHeadSubImage() {
return headSubImage;
}
public void setHeadSubImage(String headSubImage) {
this.headSubImage = headSubImage;
}
public String getHeadImage() {
return headImage;
}
public void setHeadImage(String headImage) {
this.headImage = headImage;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSchool() {
return userSchool;
}
public void setUserSchool(String userSchool) {
this.userSchool = userSchool;
}
public String getRelationTag() {
return relationTag;
}
public void setRelationTag(String relationTag) {
this.relationTag = relationTag;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public boolean isAdd() {
return isAdd;
}
public void setAdd(String isadd) {
if (isadd.equals("1")) {
this.isAdd = true;
} else {
this.isAdd = false;
}
}
public int getOriginIndex() {
return originIndex;
}
public void setOriginIndex(int originIndex) {
this.originIndex = originIndex;
}
}
/**
* 照片部分
* */
public static class RecommendPhotoItem extends RecommendItemData {
// 用户id
private String userId;
// 缩略照片列表
private List<String> photoSubUrl;
// 照片列表
private List<String> photoUrl;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<String> getPhotoSubUrl() {
return photoSubUrl;
}
public void setPhotoSubUrl(List<String> photoSubUrl) {
this.photoSubUrl = photoSubUrl;
}
public List<String> getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(List<String> photoUrl) {
this.photoUrl = photoUrl;
}
}
}
<file_sep>package com.jlxc.app.personal.ui.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jlxc.app.R;
import com.jlxc.app.base.adapter.HelloHaAdapter;
import com.jlxc.app.base.adapter.HelloHaBaseAdapterHelper;
import com.jlxc.app.base.adapter.MultiItemTypeSupport;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.ui.view.CustomAlertDialog;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.TimeHandle;
import com.jlxc.app.base.utils.ToastUtil;
import com.jlxc.app.news.model.ImageModel;
import com.jlxc.app.news.model.LikeModel;
import com.jlxc.app.news.model.NewsConstants;
import com.jlxc.app.news.model.NewsModel;
import com.jlxc.app.news.ui.activity.NewsDetailActivity;
import com.jlxc.app.news.ui.view.CommentButton;
import com.jlxc.app.news.ui.view.LikeButton;
import com.jlxc.app.news.ui.view.MultiImageView;
import com.jlxc.app.news.ui.view.MultiImageView.JumpCallBack;
import com.jlxc.app.news.utils.NewsOperate;
import com.jlxc.app.news.utils.NewsOperate.LikeCallBack;
import com.jlxc.app.news.utils.NewsOperate.OperateCallBack;
import com.jlxc.app.personal.model.MyNewsListItemModel;
import com.jlxc.app.personal.model.MyNewsListItemModel.MyNewsBodyItem;
import com.jlxc.app.personal.model.MyNewsListItemModel.MyNewsOperateItem;
import com.jlxc.app.personal.model.MyNewsListItemModel.MyNewsTitleItem;
import com.jlxc.app.personal.utils.NewsToItemData;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;
//我的动态列表
public class MyNewsListActivity extends BaseActivityWithTopBar {
// 其他Activity传递进入的被查看的用户id
public final static String INTNET_KEY_UID = "user_id";
// 动态listview
@ViewInject(R.id.listview_my_news_list)
private PullToRefreshListView newsListView;
// 动态listview
@ViewInject(R.id.tv_my_news_prompt)
private TextView prompTextView;
// 时光轴
@ViewInject(R.id.iv_time_line_backgroung)
private View timeLine;
// 原始数据源
private List<NewsModel> newsList = new ArrayList<NewsModel>();
// item类型数据
private List<MyNewsListItemModel> itemDataList = null;
// 动态列表适配器
private HelloHaAdapter<MyNewsListItemModel> newsAdapter = null;
// 使支持多种item
private MultiItemTypeSupport<MyNewsListItemModel> multiItemTypeSupport = null;
// 当前的数据页
private int currentPage = 1;
// 是否是最后一页数据
private boolean islastPage = false;
// 是否下拉
private boolean isPullDowm = true;
// 是否正在请求数据
private boolean isRequestData = false;
// 点击view监听对象
private ItemViewClick itemViewClickListener;
// 当前操作的动态id
private String currentNewsId = "";
// 对动态的操作
private NewsOperate newsOPerate;
// 被查看者的用户ID
private String currentUid = "";
@Override
public int setLayoutId() {
return R.layout.activity_my_news_list;
}
@Override
protected void setUpView() {
init();
initBoradcastReceiver();
multiItemTypeSet();
newsListViewSet();
/******** 首次获取数据 ********/
showLoading("加载中...", true);
getMyNewsData(currentUid, String.valueOf(currentPage));
/*************************/
}
/**
* listView 支持多种item的设置
* */
private void multiItemTypeSet() {
multiItemTypeSupport = new MultiItemTypeSupport<MyNewsListItemModel>() {
@Override
public int getLayoutId(int position, MyNewsListItemModel itemData) {
int layoutId = 0;
switch (itemData.getItemType()) {
case MyNewsListItemModel.NEWS_TITLE:
layoutId = R.layout.my_newslist_item_title;
break;
case MyNewsListItemModel.NEWS_BODY:
layoutId = R.layout.my_newslist_item_body;
break;
case MyNewsListItemModel.NEWS_OPERATE:
layoutId = R.layout.my_newslist_item_operate;
break;
default:
break;
}
return layoutId;
}
@Override
public int getViewTypeCount() {
return MyNewsListItemModel.NEWS_ITEM_TYPE_COUNT;
}
@Override
public int getItemViewType(int postion, MyNewsListItemModel itemData) {
int itemtype = 0;
switch (itemData.getItemType()) {
case MyNewsListItemModel.NEWS_TITLE:
itemtype = MyNewsListItemModel.NEWS_TITLE;
break;
case MyNewsListItemModel.NEWS_BODY:
itemtype = MyNewsListItemModel.NEWS_BODY;
break;
case MyNewsListItemModel.NEWS_OPERATE:
itemtype = MyNewsListItemModel.NEWS_OPERATE;
break;
default:
break;
}
return itemtype;
}
};
}
/**
* listView 的设置
* */
private void newsListViewSet() {
// 设置刷新模式
newsListView.setMode(Mode.BOTH);
/**
* 刷新监听
* */
newsListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
if (!isRequestData) {
isRequestData = true;
currentPage = 1;
isPullDowm = true;
getMyNewsData(currentUid, String.valueOf(currentPage));
}
}
@Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
if (!islastPage && !isRequestData) {
isRequestData = true;
isPullDowm = false;
getMyNewsData(currentUid, String.valueOf(currentPage));
}
}
});
/**
* 设置底部自动刷新
* */
newsListView
.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
@Override
public void onLastItemVisible() {
if (!islastPage) {
newsListView.setMode(Mode.PULL_FROM_END);
newsListView.setRefreshing(true);
}
}
});
/**
* adapter的设置
* */
newsAdapter = new HelloHaAdapter<MyNewsListItemModel>(
MyNewsListActivity.this, itemDataList, multiItemTypeSupport) {
@Override
protected void convert(HelloHaBaseAdapterHelper helper,
MyNewsListItemModel item) {
switch (helper.layoutId) {
case R.layout.my_newslist_item_title:
setTitleItemView(helper, item);
break;
case R.layout.my_newslist_item_body:
setBodyItemView(helper, item);
break;
case R.layout.my_newslist_item_operate:
setOperateItemView(helper, item);
break;
default:
break;
}
}
};
// 设置不可点击
newsAdapter.setItemsClickEnable(false);
newsListView.setAdapter(newsAdapter);
}
/**
* 数据的初始化
* */
private void init() {
setBarText("个人动态");
itemViewClickListener = new ItemViewClick();
newsOperateSet();
Intent intent = this.getIntent();
if (null != intent && intent.hasExtra(INTNET_KEY_UID)) {
currentUid = intent.getStringExtra(INTNET_KEY_UID);
} else {
LogUtils.e("用户id传输错误,用户id为:" + currentUid);
}
}
/**
* 初始化广播信息
* */
private void initBoradcastReceiver() {
LocalBroadcastManager mLocalBroadcastManager;
mLocalBroadcastManager = LocalBroadcastManager
.getInstance(MyNewsListActivity.this);
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction(JLXCConst.BROADCAST_NEWS_LIST_REFRESH);
// 注册广播
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver,
myIntentFilter);
}
/**
* 动态操作类的初始化
* */
private void newsOperateSet() {
newsOPerate = new NewsOperate(MyNewsListActivity.this);
newsOPerate.setOperateListener(new OperateCallBack() {
@Override
public void onStart(int operateType) {
// 操作开始
}
@Override
public void onFinish(int operateType, boolean isSucceed,
Object resultValue) {
switch (operateType) {
case NewsOperate.OP_Type_Delete_News:
if (isSucceed) {
for (int index = 0; index < newsAdapter.getCount(); index++) {
if (newsAdapter.getItem(index).getNewsID()
.equals(currentNewsId)) {
newsAdapter.remove(index);
index--;
}
}
ToastUtil.show(MyNewsListActivity.this, "删除成功");
}
break;
default:
break;
}
}
});
}
/**
* titleItem的数据绑定与设置
* */
private void setTitleItemView(HelloHaBaseAdapterHelper helper,
MyNewsListItemModel item) {
MyNewsTitleItem titleData = (MyNewsTitleItem) item;
// 设置用户名,发布的时间
helper.setText(R.id.txt_my_news_list_name, titleData.getUserName());
helper.setText(R.id.txt_my_news_list_tiem,
TimeHandle.getShowTimeFormat(titleData.getSendTime()));
}
/**
* 设置新闻主体item
* */
private void setBodyItemView(HelloHaBaseAdapterHelper helper,
MyNewsListItemModel item) {
MyNewsBodyItem bodyData = (MyNewsBodyItem) item;
List<ImageModel> pictureList = bodyData.getNewsImageListList();
MultiImageView bodyImages = helper.getView(R.id.miv_my_newslist_images);
bodyImages.imageDataSet(pictureList);
// 快速滑动时不加载
bodyImages.loadImageOnFastSlide(newsListView, true);
bodyImages.setJumpListener(new JumpCallBack() {
@Override
public void onImageClick(Intent intentToimageoBig) {
startActivity(intentToimageoBig);
}
});
// 创建点击事件监听对象
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
// 设置 文字内容
if (bodyData.getNewsContent().equals("")) {
helper.setVisible(R.id.txt_my_news_list_content, false);
} else {
helper.setVisible(R.id.txt_my_news_list_content, true);
helper.setText(R.id.txt_my_news_list_content,
bodyData.getNewsContent());
helper.setOnClickListener(R.id.txt_my_news_list_content, listener);
}
// 设置地理位置
if (bodyData.getLocation().equals("")) {
helper.setVisible(R.id.txt_my_news_list_location, false);
} else {
helper.setVisible(R.id.txt_my_news_list_location, true);
helper.setText(R.id.txt_my_news_list_location,
bodyData.getLocation());
}
// 父布局监听
helper.setOnClickListener(R.id.layout_my_news_list_body_rootview,
listener);
}
/**
* 设置操作部分item
* */
private void setOperateItemView(HelloHaBaseAdapterHelper helper,
MyNewsListItemModel item) {
MyNewsOperateItem opData = (MyNewsOperateItem) item;
// 点赞按钮
LikeButton likeBtn = helper.getView(R.id.btn_my_news_list_like);
if (opData.getIsLike()) {
likeBtn.setStatue(true, opData.getLikeCount());
} else {
likeBtn.setStatue(false, opData.getLikeCount());
}
// 评论按钮
CommentButton commentBtn = helper.getView(R.id.btn_my_news_list_reply);
commentBtn.setContent(opData.getReplyCount());
// 设置事件监听
final int postion = helper.getPosition();
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
itemViewClickListener.onClick(view, postion, view.getId());
}
};
//
helper.setOnClickListener(R.id.btn_my_news_list_reply, listener);
helper.setOnClickListener(R.id.btn_my_news_list_like, listener);
helper.setOnClickListener(R.id.layout_my_news_list_operate_rootview,
listener);
/********隐藏操作按钮,改为显示数量********/
likeBtn.setVisibility(View.GONE);
commentBtn.setVisibility(View.GONE);
TextView likeCount = helper.getView(R.id.tv_like_count);
TextView commentCount = helper.getView(R.id.tv_comment_count);
likeCount.setText(opData.getLikeCount()+"点赞");
commentCount.setText(opData.getReplyCount()+"评论");
}
/**
* 获取动态数据
* */
private void getMyNewsData(String userID, String page) {
String path = JLXCConst.USER_NEWS_LIST + "?" + "user_id=" + userID
+ "&page=" + page + "&size=" + "";
HttpManager.get(path, new JsonRequestCallBack<String>(
new LoadDataHandler<String>() {
@SuppressWarnings("unchecked")
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
super.onSuccess(jsonResponse, flag);
int status = jsonResponse
.getInteger(JLXCConst.HTTP_STATUS);
if (status == JLXCConst.STATUS_SUCCESS) {
hideLoading();
JSONObject jResult = jsonResponse
.getJSONObject(JLXCConst.HTTP_RESULT);
// 获取动态列表
List<JSONObject> JSONList = (List<JSONObject>) jResult
.get("list");
JsonToNewsModel(JSONList);
newsListView.onRefreshComplete();
if (jResult.getString("is_last").equals("0")) {
islastPage = false;
currentPage++;
newsListView.setMode(Mode.BOTH);
} else {
islastPage = true;
newsListView.setMode(Mode.PULL_FROM_START);
}
isRequestData = false;
}
if (status == JLXCConst.STATUS_FAIL) {
hideLoading();
ToastUtil.show(MyNewsListActivity.this,
jsonResponse
.getString(JLXCConst.HTTP_MESSAGE));
newsListView.onRefreshComplete();
if (!islastPage) {
newsListView.setMode(Mode.BOTH);
}
isRequestData = false;
}
}
@Override
public void onFailure(HttpException arg0, String arg1,
String flag) {
hideLoading();
super.onFailure(arg0, arg1, flag);
ToastUtil.show(MyNewsListActivity.this,
"网络 太差,请检查 =_=||");
newsListView.onRefreshComplete();
if (!islastPage) {
newsListView.setMode(Mode.BOTH);
}
isRequestData = false;
}
}, null));
}
/**
* 点赞操作
* */
private void likeOperate(int postion, View view,
final MyNewsOperateItem operateData) {
final View oprtView = view;
newsOPerate.setLikeListener(new LikeCallBack() {
@Override
public void onOperateStart(boolean isLike) {
if (isLike) {
operateData.setLikeCount(String.valueOf(operateData
.getLikeCount() + 1));
((LikeButton) oprtView).setStatue(true,
operateData.getLikeCount());
operateData.setIsLike("1");
} else {
operateData.setLikeCount(String.valueOf(operateData
.getLikeCount() - 1));
((LikeButton) oprtView).setStatue(false,
operateData.getLikeCount());
operateData.setIsLike("0");
}
}
@Override
public void onOperateFail(boolean isLike) {
if (isLike) {
operateData.setLikeCount(String.valueOf(operateData
.getLikeCount() - 1));
((LikeButton) oprtView).setStatue(false,
operateData.getLikeCount());
operateData.setIsLike("0");
} else {
operateData.setLikeCount(String.valueOf(operateData
.getLikeCount() + 1));
((LikeButton) oprtView).setStatue(true,
operateData.getLikeCount());
operateData.setIsLike("1");
}
}
});
if (operateData.getIsLike()) {
newsOPerate.uploadLikeOperate(operateData.getNewsID(), false);
} else {
newsOPerate.uploadLikeOperate(operateData.getNewsID(), true);
}
}
/**
* 数据处理
*/
private void JsonToNewsModel(List<JSONObject> dataList) {
List<NewsModel> newDatas = new ArrayList<NewsModel>();
for (JSONObject newsObj : dataList) {
NewsModel tempNews = new NewsModel();
tempNews.setContentWithJson(newsObj);
newDatas.add(tempNews);
}
if (isPullDowm) {
newsList.clear();
newsList.addAll(newDatas);
itemDataList = NewsToItemData.newsToItem(newDatas);
newsAdapter.replaceAll(itemDataList);
} else {
newsList.addAll(newDatas);
newsAdapter.addAll(NewsToItemData.newsToItem(newDatas));
}
if (isPullDowm) {
dataList.clear();
}
if (newsAdapter.getCount() <= 0) {
prompTextView.setVisibility(View.VISIBLE);
timeLine.setVisibility(View.GONE);
} else {
prompTextView.setVisibility(View.GONE);
timeLine.setVisibility(View.VISIBLE);
}
}
/**
* item上的view点击事件
* */
public class ItemViewClick implements ListItemClickHelp {
@Override
public void onClick(View view, int postion, int viewID) {
switch (viewID) {
case R.id.layout_my_news_list_body_rootview:
case R.id.txt_my_news_list_content:
case R.id.miv_my_newslist_images:
MyNewsBodyItem bodyData = (MyNewsBodyItem) newsAdapter
.getItem(postion);
// 跳转至动态详情
jumpToNewsDetail(bodyData, NewsConstants.KEY_BOARD_CLOSE, null);
break;
case R.id.btn_my_news_list_reply:
case R.id.btn_my_news_list_like:
case R.id.layout_my_news_list_operate_rootview:
final MyNewsOperateItem operateData = (MyNewsOperateItem) newsAdapter
.getItem(postion);
if (R.id.layout_my_news_list_operate_rootview == viewID) {
// 跳转至动态详情
jumpToNewsDetail(operateData,
NewsConstants.KEY_BOARD_CLOSE, null);
} else if (R.id.btn_my_news_list_reply == viewID) {
// 跳转至评论页面并打开评论框
jumpToNewsDetail(operateData,
NewsConstants.KEY_BOARD_COMMENT, null);
} else {
// 进行点赞操作
likeOperate(postion, view, operateData);
}
break;
default:
break;
}
}
}
/**
* listview点击事件接口,用于区分不同view的点击事件
*
* @author Alan
*
*/
private interface ListItemClickHelp {
void onClick(View view, int postion, int viewID);
}
/**
* 点赞gridview监听
*/
public class LikeGridViewItemClick implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
LikeModel likeUser = (LikeModel) parent.getAdapter().getItem(
position);
jumpToHomepage(JLXCUtils.stringToInt(likeUser.getUserID()));
}
}
/**
* 跳转至用户的主页
*/
private void jumpToHomepage(int userID) {
Intent intentUsrMain = new Intent(MyNewsListActivity.this,
OtherPersonalActivity.class);
intentUsrMain.putExtra(OtherPersonalActivity.INTENT_KEY, userID);
startActivityWithRight(intentUsrMain);
}
/***
* 跳转至动态相详情
*/
private void jumpToNewsDetail(MyNewsListItemModel itemModel,
int keyBoardMode, String commentId) {
// 跳转到动态详情
Intent intentToNewsDetail = new Intent(MyNewsListActivity.this,
NewsDetailActivity.class);
switch (keyBoardMode) {
// 键盘关闭
case NewsConstants.KEY_BOARD_CLOSE:
intentToNewsDetail.putExtra(NewsConstants.INTENT_KEY_COMMENT_STATE,
NewsConstants.KEY_BOARD_CLOSE);
break;
// 键盘打开等待评论
case NewsConstants.KEY_BOARD_COMMENT:
intentToNewsDetail.putExtra(NewsConstants.INTENT_KEY_COMMENT_STATE,
NewsConstants.KEY_BOARD_COMMENT);
break;
// 键盘打开等待回复
case NewsConstants.KEY_BOARD_REPLY:
intentToNewsDetail.putExtra(NewsConstants.INTENT_KEY_COMMENT_STATE,
NewsConstants.KEY_BOARD_REPLY);
if (null != commentId) {
intentToNewsDetail.putExtra(
NewsConstants.INTENT_KEY_COMMENT_ID, commentId);
} else {
LogUtils.e("回复别人时必须要传递被评论的id.");
}
break;
default:
break;
}
// 当前操作的动态id
intentToNewsDetail.putExtra(NewsConstants.INTENT_KEY_NEWS_ID,
itemModel.getNewsID());
// 找到当前的操作对象
for (int index = 0; index < newsList.size(); ++index) {
if (newsList.get(index).getNewsID().equals(itemModel.getNewsID())) {
intentToNewsDetail.putExtra(NewsConstants.INTENT_KEY_NEWS_OBJ,
newsList.get(index));
break;
}
}
// 带有返回参数的跳转至动态详情
startActivityForResult(intentToNewsDetail, 0);
this.overridePendingTransition(R.anim.push_right_in,
R.anim.push_right_out);
}
/**
* 广播接收处理
* */
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent resultIntent) {
String action = resultIntent.getAction();
if (action.equals(JLXCConst.BROADCAST_NEWS_LIST_REFRESH)) {
if (resultIntent.hasExtra(NewsConstants.OPERATE_UPDATE)) {
// 更新动态列表
NewsModel resultNews = (NewsModel) resultIntent
.getSerializableExtra(NewsConstants.OPERATE_UPDATE);
for (int index = 0; index < newsList.size(); index++) {
if (resultNews.getNewsID().equals(
newsList.get(index).getNewsID())) {
newsList.set(index, resultNews);
newsAdapter.replaceAll(NewsToItemData
.newsToItem(newsList));
break;
}
}
} else if (resultIntent.hasExtra(NewsConstants.OPERATE_DELETET)) {
String resultID = resultIntent
.getStringExtra(NewsConstants.OPERATE_DELETET);
// 删除该动态
for (int index = 0; index < newsList.size(); index++) {
if (resultID.equals(newsList.get(index).getNewsID())) {
newsList.remove(index);
newsAdapter.replaceAll(NewsToItemData
.newsToItem(newsList));
break;
}
}
} else if (resultIntent
.hasExtra(NewsConstants.OPERATE_NO_ACTION)) {
// 无改变
} else if (resultIntent.hasExtra(NewsConstants.PUBLISH_FINISH)) {
if (!isRequestData) {
// 发布了动态
isRequestData = true;
currentPage = 1;
isPullDowm = true;
getMyNewsData(currentUid, String.valueOf(currentPage));
}
}
}
}
};
}
<file_sep>package com.jlxc.app.login.ui.activity;
import com.jlxc.app.R;
import com.jlxc.app.base.manager.ActivityManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.ui.activity.BaseActivity;
import com.jlxc.app.base.ui.activity.MainTabActivity;
import com.jlxc.app.base.utils.ConfigUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.login.ui.fragment.LaunchCircleFragment1;
import com.jlxc.app.login.ui.fragment.LaunchCircleFragment2;
import com.jlxc.app.login.ui.fragment.LaunchCircleFragment3;
import com.lidroid.xutils.view.annotation.ViewInject;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.WindowManager;
public class LaunchActivity extends BaseActivity {
@ViewInject(R.id.vPager)
private ViewPager mPager;//页卡内容
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_launch;
}
@Override
protected void setUpView() {
// 隐藏状态栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//这个名字起的有问题 因为产品已经上线了 等下一次更换启动图的时候修改
boolean launchConfig = ConfigUtils.getBooleanConfig("launchTest");
if (!launchConfig) {
ConfigUtils.saveConfig("launchTest", true);
//初始化
initViewPager();
mPager.setVisibility(View.VISIBLE);
}else {
//如果后台有程序
if (ActivityManager.getActivityStack().size()>1) {
// UserModel userModel = UserManager.getInstance().getUser();
// if (null != userModel.getUsername() && null != userModel.getLogin_token()) {
//
//// startActivity(new Intent(LaunchActivity.this, MainTabActivity.class));
//// startActivity(new Intent(LaunchActivity.this, ActivityManager.getInstence().currentActivity()));
// } else {
// startActivity(new Intent(LaunchActivity.this, LoginActivity.class));
// }
finish();
return;
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
UserModel userModel = UserManager.getInstance().getUser();
if (null != userModel.getUsername() && null != userModel.getLogin_token()) {
startActivity(new Intent(LaunchActivity.this, MainTabActivity.class));
} else {
startActivity(new Intent(LaunchActivity.this, LoginActivity.class));
}
finish();
}
}, 2000);
}
}
@Override
protected void loadLayout(View v) {
// TODO Auto-generated method stub
}
/**
* 初始化ViewPager
*/
@SuppressLint("InflateParams")
private void initViewPager() {
mPager.setAdapter(new MessageFragmentPagerAdapter(getSupportFragmentManager()));
mPager.setCurrentItem(0);
}
private class MessageFragmentPagerAdapter extends android.support.v4.app.FragmentPagerAdapter {
public MessageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment = null;
switch (i) {
case 0:
fragment = new LaunchCircleFragment1();
break;
case 1:
fragment = new LaunchCircleFragment2();
break;
case 2:
fragment = new LaunchCircleFragment3();
break;
}
return fragment;
}
@Override
public int getCount() {
return 3;
}
}
}
<file_sep>package com.jlxc.app.message.helper;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.DisplayMetrics;
import android.view.View;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.jlxc.app.base.app.JLXCApplication;
import com.jlxc.app.base.manager.ActivityManager;
import com.jlxc.app.base.ui.view.gallery.imageloader.GalleyActivity;
import com.jlxc.app.base.utils.FileUtil;
import com.jlxc.app.base.utils.JLXCUtils;
import io.rong.imkit.R;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.widget.provider.InputProvider;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.message.ImageMessage;
public class PhotoCollectionsProvider extends InputProvider.ExtendProvider {
HandlerThread mWorkThread;
Handler mUploadHandler;
private RongContext mContext;
public PhotoCollectionsProvider(RongContext context) {
super(context);
this.mContext = context;
mWorkThread = new HandlerThread("JLXC");
mWorkThread.start();
mUploadHandler = new Handler(mWorkThread.getLooper());
}
@Override
public Drawable obtainPluginDrawable(Context arg0) {
// TODO Auto-generated method stub
return arg0.getResources().getDrawable(R.drawable.rc_ic_picture);
}
@Override
public CharSequence obtainPluginTitle(Context arg0) {
return "相册";
}
@Override
public void onPluginClick(View arg0) {
// TODO Auto-generated method stub
// 点击跳转至图片选择界面
Intent intent = new Intent(mContext, GalleyActivity.class);
intent.putExtra(GalleyActivity.INTENT_KEY_SELECTED_COUNT,0);
intent.putExtra(GalleyActivity.INTENT_KEY_ONE, true);
startActivityForResult(intent, 86);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// 根据选择完毕的图片返回值,直接上传文件
if (requestCode == 86 && data != null) {
DisplayMetrics dm = new DisplayMetrics();
ActivityManager.getInstence().currentActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int[] screenSize = { dm.widthPixels, dm.heightPixels };
String tmpImageName = JLXCUtils.getPhotoFileName() + "";
@SuppressWarnings("unchecked")
List<String> resultList = (List<String>) data.getSerializableExtra(GalleyActivity.INTENT_KEY_PHOTO_LIST);
// 循环处理图片
for (String fileRealPath : resultList) {
// 用户id+时间戳
if (fileRealPath != null&& FileUtil.tempToLocalPath(fileRealPath, tmpImageName,screenSize[0], screenSize[1])) {
tmpImageName = "file://" + FileUtil.BIG_IMAGE_PATH + tmpImageName;
Uri pathUri = Uri.parse(tmpImageName);
mUploadHandler.post(new MyRunnable(pathUri));
break;
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* 用于显示文件的异步线程
*
* @ClassName: MyRunnable
* @Description: 用于显示文件的异步线程
*
*/
class MyRunnable implements Runnable {
Uri mUri;
public MyRunnable(Uri uri) {
mUri = uri;
}
@Override
public void run() {
// 封装image类型的IM消息
final ImageMessage content = ImageMessage.obtain(mUri, mUri);
if (RongIM.getInstance() != null&& RongIM.getInstance().getRongIMClient() != null)
RongIM.getInstance().getRongIMClient().sendImageMessage(getCurrentConversation().getConversationType(),getCurrentConversation().getTargetId(),content,null,null,new RongIMClient.SendImageMessageCallback() {
@Override
public void onAttached(Message message) {
}
@Override
public void onError(Message message, RongIMClient.ErrorCode code) {
}
@Override
public void onSuccess(Message message) {
}
@Override
public void onProgress(Message message, int progress) {
}
});
}
}
}
<file_sep>package com.jlxc.app.login.ui.activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.R;
import com.jlxc.app.base.helper.JsonRequestCallBack;
import com.jlxc.app.base.helper.LoadDataHandler;
import com.jlxc.app.base.manager.ActivityManager;
import com.jlxc.app.base.manager.HttpManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.ui.activity.MainTabActivity;
import com.jlxc.app.base.utils.JLXCConst;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.base.utils.Md5Utils;
import com.jlxc.app.base.utils.ToastUtil;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
public class SecondLoginActivity extends BaseActivityWithTopBar {
//用户名输入框
@ViewInject(R.id.passwordEt)
private EditText passwordEt;
//登录注册按钮
@ViewInject(R.id.loginBtn)
private Button loginBtn;
//找回密码按钮
@ViewInject(R.id.find_pwd_text_view)
private TextView findPwdTextView;
//布局文件
@ViewInject(R.id.second_login_activity)
private RelativeLayout secondLoginLayout;
private String username;
@OnClick(value={R.id.loginBtn,R.id.second_login_activity,R.id.find_pwd_text_view})
public void viewClick(View v) {
switch (v.getId()) {
case R.id.loginBtn:
//登录
login();
break;
case R.id.find_pwd_text_view:
//找回密码
findPwd();
break;
case R.id.second_login_activity:
//收键盘
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
break;
default:
break;
}
}
public void login() {
final String password = <PASSWORD>.getText().toString().trim();
if (null==password || "".equals(password)) {
Toast.makeText(SecondLoginActivity.this, "密码不能为空",
Toast.LENGTH_SHORT).show();
return;
}
//网络请求
showLoading("正在登录,请稍后", true);
RequestParams params = new RequestParams();
params.addBodyParameter("username", username);
params.addBodyParameter("password", <PASSWORD>(password));
HttpManager.post(JLXCConst.LOGIN_USER, params, new JsonRequestCallBack<String>(new LoadDataHandler<String>(){
@Override
public void onSuccess(JSONObject jsonResponse, String flag) {
// TODO Auto-generated method stub
super.onSuccess(jsonResponse, flag);
int status = jsonResponse.getInteger(JLXCConst.HTTP_STATUS);
switch (status) {
case JLXCConst.STATUS_SUCCESS:
hideLoading();
//登录成功用户信息注入
JSONObject result = jsonResponse.getJSONObject(JLXCConst.HTTP_RESULT);
UserManager.getInstance().getUser().setContentWithJson(result);
//数据持久化
UserManager.getInstance().saveAndUpdate();
Toast.makeText(SecondLoginActivity.this, "登录成功",
Toast.LENGTH_SHORT).show();
//跳转主页
Intent intent = new Intent(SecondLoginActivity.this, MainTabActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
//把前面的finish掉
for (Activity activity:ActivityManager.getActivityStack()) {
if (activity.getClass().equals(LoginActivity.class)) {
activity.finish();
break;
}
}
break;
case JLXCConst.STATUS_FAIL:
hideLoading();
Toast.makeText(SecondLoginActivity.this, jsonResponse.getString(JLXCConst.HTTP_MESSAGE),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(HttpException arg0, String arg1, String flag) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1, flag);
hideLoading();
Toast.makeText(SecondLoginActivity.this, "网络异常",
Toast.LENGTH_SHORT).show();
}
}, null));
}
//找回密码
public void findPwd() {
// showLoading("验证码获取中..", false);
// try {
// //发送验证码
// SMSSDK.getVerificationCode("86",username);
// } catch (Exception e) {
// // TODO: handle exception
// }
Intent intent = new Intent(SecondLoginActivity.this, VerifyActivity.class);
intent.putExtra("username", username);
intent.putExtra("isFindPwd", true);
startActivityWithRight(intent);
// //网络请求
// RequestParams params = new RequestParams();
// params.addBodyParameter("phone_num", username);
// HttpManager.post(JLXCConst.GET_MOBILE_VERIFY, params, new JsonRequestCallBack<String>(new LoadDataHandler<String>(){
//
// @Override
// public void onSuccess(JSONObject jsonResponse, String flag) {
// // TODO Auto-generated method stub
// super.onSuccess(jsonResponse, flag);
// LogUtils.i(jsonResponse.toJSONString(), 1);
// int status = jsonResponse.getInteger(JLXCConst.HTTP_STATUS);
// switch (status) {
// case JLXCConst.STATUS_SUCCESS:
// hideLoading();
// //跳转
// Intent intent = new Intent(SecondLoginActivity.this, RegisterActivity.class);
// intent.putExtra("username", username);
// intent.putExtra("isFindPwd", true);
// startActivityWithRight(intent);
//
// break;
// case JLXCConst.STATUS_FAIL:
// hideLoading();
// Toast.makeText(SecondLoginActivity.this, jsonResponse.getString(JLXCConst.HTTP_MESSAGE),
// Toast.LENGTH_SHORT).show();
// }
// }
// @Override
// public void onFailure(HttpException arg0, String arg1, String flag) {
// // TODO Auto-generated method stub
// super.onFailure(arg0, arg1, flag);
// hideLoading();
// Toast.makeText(SecondLoginActivity.this, "网络异常",
// Toast.LENGTH_SHORT).show();
// }
//
// }, null));
}
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_second_login;
}
@SuppressLint("ResourceAsColor") @Override
protected void setUpView() {
//设置用户名
Intent intent = getIntent();
setUsername(intent.getStringExtra("username"));
setBarText("登录");
RelativeLayout rlBar = (RelativeLayout) findViewById(R.id.layout_base_title);
rlBar.setBackgroundResource(R.color.main_clear);
// findPwdTextView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG ); //下划线
// passwordEt.setText("123456");
// EventHandler eh=new EventHandler(){
// @Override
// public void afterEvent(int event, int result, Object data) {
// Message msg = new Message();
// msg.arg1 = event;
// msg.arg2 = result;
// msg.obj = data;
// handler.sendMessage(msg);
// }
// };
// SMSSDK.registerEventHandler(eh);
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
// try {
// EventHandler eh=new EventHandler(){
// @Override
// public void afterEvent(int event, int result, Object data) {
// Message msg = new Message();
// msg.arg1 = event;
// msg.arg2 = result;
// msg.obj = data;
// handler.sendMessage(msg);
// }
// };
// SMSSDK.registerEventHandler(eh);
// } catch (Exception e) {
// System.out.println("没初始化SMSSDK 因为这个短信sdk对DEBUG有影响 所以不是RELEASE不初始化");
// }
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
// try {
// SMSSDK.unregisterAllEventHandler();
// } catch (Exception e) {
// System.out.println("没初始化SMSSDK 因为这个短信sdk对DEBUG有影响 所以不是RELEASE不初始化");
// }
}
// @SuppressLint("HandlerLeak")
// Handler handler=new Handler(){
//
// @Override
// public void handleMessage(Message msg) {
// hideLoading();
// // TODO Auto-generated method stub
// super.handleMessage(msg);
// int event = msg.arg1;
// int result = msg.arg2;
// Object data = msg.obj;
// Log.e("event", "event="+event);
// if (result == SMSSDK.RESULT_COMPLETE) {
// //短信注册成功后,返回MainActivity,然后提示新好友
// if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
//// Toast.makeText(getApplicationContext(), "提交验证码成功", Toast.LENGTH_SHORT).show();
// } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
// Intent intent = new Intent(SecondLoginActivity.this, RegisterActivity.class);
// intent.putExtra("username", username);
// intent.putExtra("isFindPwd", true);
// startActivityWithRight(intent);
//
//// SMSSDK.unregisterAllEventHandler();
// }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){//返回支持发送验证码的国家列表
//// Toast.makeText(getApplicationContext(), "获取国家列表成功", Toast.LENGTH_SHORT).show();
//
// }
// } else {
// ((Throwable) data).printStackTrace();
// ToastUtil.show(SecondLoginActivity.this, "网络有点小问题");
// }
//
// }
//
// };
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
<file_sep>package com.jlxc.app.personal.ui.activity;
import io.rong.imkit.RongIM;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import com.jlxc.app.R;
import com.jlxc.app.base.manager.ActivityManager;
import com.jlxc.app.base.manager.UserManager;
import com.jlxc.app.base.model.UserModel;
import com.jlxc.app.base.ui.activity.BaseActivityWithTopBar;
import com.jlxc.app.base.ui.view.CustomAlertDialog;
import com.jlxc.app.login.ui.activity.LoginActivity;
import com.lidroid.xutils.view.annotation.event.OnClick;
public class AccountSettingActivity extends BaseActivityWithTopBar{
@OnClick({R.id.logout_button})
private void clickMethod(View view) {
switch (view.getId()) {
case R.id.logout_button:
logout();
break;
default:
break;
}
}
@Override
public int setLayoutId() {
// TODO Auto-generated method stub
return R.layout.activity_account_setting;
}
@Override
protected void setUpView() {
setBarText("账号设置");
}
//退出
private void logout() {
// final AlertDialog.Builder alterDialog = new AlertDialog.Builder(this);
// alterDialog.setMessage("确定退出该账号吗?");
// alterDialog.setCancelable(true);
//
// alterDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// if (RongIM.getInstance() != null)
// RongIM.getInstance().logout();
// //清空数据
// UserManager.getInstance().clear();
// UserManager.getInstance().setUser(new UserModel());
//// killThisPackageIfRunning(AccountSettingActivity.this, "com.jlxc.app");
//// Process.killProcess(Process.myPid());
// Intent exit = new Intent(AccountSettingActivity.this, LoginActivity.class);
// exit.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(exit);
// ActivityManager.getInstence().exitApplication();
// }
// });
// alterDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.cancel();
// }
// });
// alterDialog.show();
final CustomAlertDialog confirmDialog = new CustomAlertDialog(
this, "确定退出该账号吗?", "确定", "取消");
confirmDialog.show();
confirmDialog.setClicklistener(new CustomAlertDialog.ClickListenerInterface() {
@Override
public void doConfirm() {
if (RongIM.getInstance() != null)
RongIM.getInstance().logout();
//清空数据
UserManager.getInstance().clear();
UserManager.getInstance().setUser(new UserModel());
Intent exit = new Intent(AccountSettingActivity.this, LoginActivity.class);
exit.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(exit);
ActivityManager.getInstence().exitApplication();
confirmDialog.dismiss();
}
@Override
public void doCancel() {
confirmDialog.dismiss();
}
});
}
// public static void killThisPackageIfRunning(final Context context, String packageName) {
// ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// activityManager.killBackgroundProcesses(packageName);
// }
}
<file_sep>package com.jlxc.app.news.model;
import com.alibaba.fastjson.JSONObject;
import com.jlxc.app.base.utils.LogUtils;
public class SchoolModel {
// 初中
public static final String JUNIOR_MIDDLE_SCHOOL = "1";
// 高中
public static final String SENIOR_MIDDLE_SCHOOL = "2";
// 学校代码
private String schoolCode;
// 学校的名字
private String schoolName;
// 区域名字
private String districtName;
// 所在城市的名字
private String cityName;
// 学校的类型
private String schoolType;
// 内容注入
public void setContentWithJson(JSONObject object) {
setSchoolCode(object.getString("code"));
setSchoolName(object.getString("name"));
setDistrictName(object.getString("district_name"));
setCityName(object.getString("city_name"));
setSchoolType(object.getString("level"));
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public String getSchoolCode() {
return schoolCode;
}
public void setSchoolCode(String schoolCode) {
this.schoolCode = schoolCode;
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
this.districtName = districtName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getSchoolType() {
return schoolType;
}
public void setSchoolType(String schoolType) {
this.schoolType = schoolType;
}
}
<file_sep>package com.jlxc.app.news.ui.fragment;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.jlxc.app.base.ui.fragment.BaseFragment;
import com.jlxc.app.news.ui.activity.PublishNewsActivity;
import com.jlxc.app.R;
import com.lidroid.xutils.view.annotation.ViewInject;
public class MainPageFragment extends BaseFragment {
// 上下文信息
private Context mContext;
// 主页viewpager
@ViewInject(R.id.viewpager_main)
private ViewPager mainPager;
// title的项目
@ViewInject(R.id.layout_title_content)
private LinearLayout titleContent;
// 主页viewpager
@ViewInject(R.id.tv_news_guid)
private TextView newsTitleTextView;
// 校园
@ViewInject(R.id.tv_campus_guid)
private TextView campusTitleTextView;
// 所有的
private List<Fragment> mFragmentList = new ArrayList<Fragment>();
// 偏移图片
@ViewInject(R.id.img_cursor)
private ImageView imageCursor;
// 通知按钮
@ViewInject(R.id.img_main_publish_btn)
private ImageView publishBtn;
// 当前页卡编号
private int currIndex;
// 横线图片宽度
private int cursorWidth;
// 图片移动的偏移量
private int offset;
@Override
public int setLayoutId() {
return R.layout.fragment_main_page;
}
@Override
public void loadLayout(View rootView) {
}
@Override
public void setUpViews(View rootView) {
mContext = this.getActivity().getApplicationContext();
InitImage();
InitViewPager();
publishBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intentUsrMain = new Intent(mContext,
PublishNewsActivity.class);
startActivityWithRight(intentUsrMain);
}
});
}
/*
* 初始化图片的位移像素
*/
public void InitImage() {
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int contentLeftMargin = ((FrameLayout.LayoutParams) titleContent
.getLayoutParams()).leftMargin;
int contentWidth = screenWidth - (2 * contentLeftMargin);
// 设置游标的尺寸与位置
LayoutParams cursorParams = (LayoutParams) imageCursor
.getLayoutParams();
cursorWidth = cursorParams.width;
offset = contentWidth / 2;
cursorParams.leftMargin = (contentWidth / 2 - cursorWidth) / 2
+ contentLeftMargin;
imageCursor.setLayoutParams(cursorParams);
}
/*
* 初始化ViewPager
*/
public void InitViewPager() {
newsTitleTextView.setOnClickListener(new ViewClickListener(0));
campusTitleTextView.setOnClickListener(new ViewClickListener(1));
mFragmentList.add(new MainNewsListFragment());
//mFragmentList.add(new CampusHomeFragment());
mainPager.setAdapter(new MainFragmentPagerAdapter(
getChildFragmentManager(), mFragmentList));
mainPager.setCurrentItem(0);
mainPager.setOnPageChangeListener(new MyOnPageChangeListener());
}
/**
* 头标点击监听
*/
private class ViewClickListener implements OnClickListener {
private int index = 0;
public ViewClickListener(int i) {
index = i;
}
public void onClick(View v) {
mainPager.setCurrentItem(index);
}
}
/**
* ViewPager的适配器
* */
class MainFragmentPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragmentList;
public MainFragmentPagerAdapter(FragmentManager fm, List<Fragment> list) {
super(fm);
fragmentList = list;
}
// 得到每个item
@Override
public Fragment getItem(int index) {
return fragmentList.get(index);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public int getItemPosition(Object object) {
//
return super.getItemPosition(object);
}
@Override
public Object instantiateItem(ViewGroup arg0, int arg1) {
// 初始化每个页卡选项
return super.instantiateItem(arg0, arg1);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//
super.destroyItem(container, position, object);
}
}
/**
* 监听选项卡改变事件
*/
public class MyOnPageChangeListener implements OnPageChangeListener {
float lastpostion = 0;
public void onPageScrollStateChanged(int index) {
currIndex = index;
}
// CurrentTab:当前页面序号
// OffsetPercent:当前页面偏移的百分比
// offsetPixel:当前页面偏移的像素位置
public void onPageScrolled(int CurrentTab, float OffsetPercent,
int offsetPixel) {
// 下标的移动动画
Animation animation = new TranslateAnimation(offset * lastpostion,
offset * (CurrentTab + OffsetPercent), 0, 0);
lastpostion = OffsetPercent + CurrentTab;
// True:图片停在动画结束位置
animation.setFillAfter(true);
animation.setDuration(300);
imageCursor.startAnimation(animation);
}
/**
* 状态改变后
* */
public void onPageSelected(int index) {
if (0 == index) {
newsTitleTextView.setTextColor(getResources().getColor(
R.color.main_brown));
campusTitleTextView.setTextColor(getResources().getColor(
R.color.main_clear_brown));
} else {
campusTitleTextView.setTextColor(getResources().getColor(
R.color.main_brown));
newsTitleTextView.setTextColor(getResources().getColor(
R.color.main_clear_brown));
}
}
}
}
<file_sep>package com.jlxc.app.news.utils;
import java.util.LinkedList;
import java.util.List;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.news.model.CampusPersonModel;
import com.jlxc.app.news.model.CommentModel;
import com.jlxc.app.news.model.ItemModel;
import com.jlxc.app.news.model.ItemModel.BodyItem;
import com.jlxc.app.news.model.ItemModel.CampusHeadItem;
import com.jlxc.app.news.model.ItemModel.CommentItem;
import com.jlxc.app.news.model.ItemModel.CommentListItem;
import com.jlxc.app.news.model.ItemModel.LikeListItem;
import com.jlxc.app.news.model.ItemModel.OperateItem;
import com.jlxc.app.news.model.ItemModel.SubCommentItem;
import com.jlxc.app.news.model.ItemModel.TitleItem;
import com.jlxc.app.news.model.NewsModel;
import com.jlxc.app.news.model.SubCommentModel;
/**
* 将新闻的数据进行转换
* */
public class DataToItem {
// 将数据转换为动态主页item形式的数据
public static List<ItemModel> newsDataToItems(List<NewsModel> orgDataList) {
LinkedList<ItemModel> itemList = new LinkedList<ItemModel>();
for (NewsModel newsMd : orgDataList) {
itemList.add(createNewsTitle(newsMd, ItemModel.NEWS_TITLE));
itemList.add(createBody(newsMd, ItemModel.NEWS_BODY));
itemList.add(createOperate(newsMd, ItemModel.NEWS_OPERATE));
itemList.add(createLikeList(newsMd, ItemModel.NEWS_LIKELIST));
itemList.add(createCommentList(newsMd, ItemModel.NEWS_COMMENT));
}
return itemList;
}
// 将数据转换为校园item形式的数据
public static List<ItemModel> campusDataToItems(List<NewsModel> newsData,
List<CampusPersonModel> personData) {
LinkedList<ItemModel> itemList = new LinkedList<ItemModel>();
if (personData.size() > 0) {
itemList.addFirst(createCampusHead(personData,
ItemModel.CAMPUS_HEAD));
}
for (NewsModel newsMd : newsData) {
itemList.add(createNewsTitle(newsMd, ItemModel.CAMPUS_TITLE));
itemList.add(createBody(newsMd, ItemModel.CAMPUS_BODY));
itemList.add(createOperate(newsMd, ItemModel.CAMPUS_OPERATE));
itemList.add(createLikeList(newsMd, ItemModel.CAMPUS_LIKELIST));
}
return itemList;
}
/**
* 将动态详细数据转换为item类型数据
* */
public static List<ItemModel> newsDetailToItems(NewsModel newsData) {
LinkedList<ItemModel> itemList = new LinkedList<ItemModel>();
itemList.add(createNewsTitle(newsData, ItemModel.NEWS_DETAIL_TITLE));
itemList.add(createBody(newsData, ItemModel.NEWS_DETAIL_BODY));
itemList.add(createLikeList(newsData, ItemModel.NEWS_DETAIL_LIKELIST));
List<CommentModel> cmtList = newsData.getCommentList();
for (CommentModel cmtMd : cmtList) {
itemList.add(createComment(cmtMd, ItemModel.NEWS_DETAIL_COMMENT));
List<SubCommentModel> subCmtList = cmtMd.getSubCommentList();
for (SubCommentModel subCmtMd : subCmtList) {
itemList.add(createSubComment(subCmtMd, newsData.getNewsID(),
ItemModel.NEWS_DETAIL_SUB_COMMENT));
}
}
return itemList;
}
// 提取新闻中的头部信息
private static ItemModel createNewsTitle(NewsModel news, int Type) {
TitleItem item = new TitleItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setHeadImage(news.getUserHeadImage());
item.setHeadSubImage(news.getUserHeadSubImage());
item.setUserName(news.getUserName());
item.setSendTime(news.getSendTime());
item.setUserSchool(news.getUserSchool());
item.setSchoolCode(news.getSchoolCode());
item.setIsLike(news.getIsLike());
item.setUserID(news.getUid());
item.setLikeCount(news.getLikeQuantity());
item.setTagContent(news.getTypeContent());
} catch (Exception e) {
LogUtils.e("createNewsTitle error.");
}
return (ItemModel) item;
}
// 提取新闻中的操作信息
private static ItemModel createOperate(NewsModel news, int Type) {
OperateItem item = new OperateItem();
try {
item.setItemType(Type);
item.setLikeCount(news.getLikeQuantity());
item.setNewsID(news.getNewsID());
item.setSendTime(news.getSendTime());
item.setIsLike(news.getIsLike());
item.setTopicID(news.getTopicID());
item.setTopicName(news.getTopicName());
} catch (Exception e) {
LogUtils.e("createOperate error.");
}
return (ItemModel) item;
}
// 提取新闻中的主体信息
private static ItemModel createBody(NewsModel news, int Type) {
BodyItem item = new BodyItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setNewsContent(news.getNewsContent());
item.setImageNewsList(news.getImageNewsList());
item.setSendTime(news.getSendTime());
item.setLocation(news.getLocation());
item.setTopicID(news.getTopicID());
item.setTopicName(news.getTopicName());
} catch (Exception e) {
LogUtils.e("createBody error.");
}
return (ItemModel) item;
}
// 提取新闻中的点赞信息
private static ItemModel createLikeList(NewsModel news, int Type) {
LikeListItem item = new LikeListItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setLikeCount(news.getLikeQuantity());
item.setLikeHeadListimage(news.getLikeHeadListimage());
} catch (Exception e) {
LogUtils.e("createBody error.");
}
return (ItemModel) item;
}
// 提取新闻中的评论列表信息
private static ItemModel createCommentList(NewsModel news, int Type) {
CommentListItem item = new CommentListItem();
try {
item.setNewsID(news.getNewsID());
item.setItemType(Type);
item.setReplyCount(news.getCommentQuantity());
item.setCommentList(news.getCommentList());
} catch (Exception e) {
LogUtils.e("createBody error.");
}
return (ItemModel) item;
}
// 提取新闻中的评论信息
public static ItemModel createComment(CommentModel cmt, int Type) {
CommentItem item = new CommentItem();
try {
item.setItemType(Type);
item.setComment(cmt);
} catch (Exception e) {
LogUtils.e("create comment error.");
}
return (ItemModel) item;
}
// 提取校园头部
private static ItemModel createCampusHead(
List<CampusPersonModel> personData, int Type) {
CampusHeadItem item = new CampusHeadItem();
try {
item.setItemType(Type);
// 校园头部动态ID
item.setPersonList(personData);
} catch (Exception e) {
LogUtils.e("create Campus Head error.");
}
return (ItemModel) item;
}
// 提取动态数据中的子评论信息
public static ItemModel createSubComment(SubCommentModel cmt,
String newsID, int Type) {
SubCommentItem item = new SubCommentItem();
try {
item.setItemType(Type);
item.setNewsID(newsID);
item.setSubCommentModel(cmt);
} catch (Exception e) {
LogUtils.e("create subcomment item error.");
}
return (ItemModel) item;
}
}
<file_sep>package com.jlxc.app.group.utils;
import java.util.LinkedList;
import java.util.List;
import com.jlxc.app.base.utils.JLXCUtils;
import com.jlxc.app.base.utils.LogUtils;
import com.jlxc.app.group.model.SchoolItemModel;
import com.jlxc.app.group.model.SchoolItemModel.SchoolNewsTitleItem;
import com.jlxc.app.group.model.SchoolItemModel.SchoolNewsBodyItem;
import com.jlxc.app.group.model.SchoolItemModel.SchoolNewsLikeListItem;
import com.jlxc.app.group.model.SchoolItemModel.SchoolNewsOperateItem;
import com.jlxc.app.news.model.NewsModel;
/**
* 将数据转换成items类型的数据
* */
public class NewsToSchoolItem {
// 将数据转换为动态item形式的数据
public static List<SchoolItemModel> newsToItem(List<NewsModel> orgDataList) {
LinkedList<SchoolItemModel> itemList = new LinkedList<SchoolItemModel>();
for (NewsModel newsMd : orgDataList) {
itemList.add(createTitle(newsMd, SchoolItemModel.SCHOOL_NEWS_TITLE));
itemList.add(createBody(newsMd, SchoolItemModel.SCHOOL_NEWS_BODY));
itemList.add(createOperate(newsMd,
SchoolItemModel.SCHOOL_NEWS_OPERATE));
itemList.add(createLikeList(newsMd,
SchoolItemModel.SCHOOL_NEWS_LIKELIST));
}
return itemList;
}
// 提取新闻中的头部信息
public static SchoolItemModel createTitle(NewsModel news, int Type) {
SchoolNewsTitleItem item = new SchoolNewsTitleItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setUserName(news.getUserName());
item.setUserID(news.getUid());
item.setHeadImage(news.getUserHeadImage());
item.setHeadSubImage(news.getUserHeadSubImage());
item.setSendTime(news.getSendTime());
} catch (Exception e) {
LogUtils.e("createNewsTitle error.");
}
return item;
}
// 提取新闻中的主体信息
public static SchoolItemModel createBody(NewsModel news, int Type) {
SchoolNewsBodyItem item = new SchoolNewsBodyItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setNewsContent(news.getNewsContent());
item.setImageNewsList(news.getImageNewsList());
item.setLocation(news.getLocation());
} catch (Exception e) {
LogUtils.e("createBody error.");
}
return (SchoolItemModel) item;
}
// 提取新闻中的操作信息
public static SchoolItemModel createOperate(NewsModel news, int Type) {
SchoolNewsOperateItem item = new SchoolNewsOperateItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setIsLike(news.getIsLike());
item.setLikeCount(news.getLikeQuantity());
item.setCommentCount(JLXCUtils.stringToInt(news
.getCommentQuantity()));
} catch (Exception e) {
LogUtils.e("createOperate error.");
}
return (SchoolItemModel) item;
}
// 提取新闻中的点赞信息
private static SchoolItemModel createLikeList(NewsModel news, int Type) {
SchoolNewsLikeListItem item = new SchoolNewsLikeListItem();
try {
item.setItemType(Type);
item.setNewsID(news.getNewsID());
item.setLikeCount(news.getLikeQuantity());
item.setLikeHeadListimage(news.getLikeHeadListimage());
} catch (Exception e) {
LogUtils.e("createBody error.");
}
return (SchoolNewsLikeListItem) item;
}
}
|
f1291b6b15654f4d3efacb15ddbcfb04fe6b6d34
|
[
"Java"
] | 45 |
Java
|
Nicky-Luis/JLXC_APP
|
8110674501161c7c85fc4c68bcb48efedaea6136
|
bb56d014da7460bebb15c36fd8e6b7b43f383171
|
refs/heads/master
|
<repo_name>simplyarjen/mybatis-memory-issue<file_sep>/README.md
# Reproduction of a mybatis memory issue
When mapping a result using a resultmap that contains a `byte[]` property
and an `<association>` mapping, mybatis allocates a `Byte` object for each
byte in the array during the mapping process. This leads to several gigabytes
of memory being allocated for the mapping of a 100 megabyte array, which makes
the difference between a memory-intensive task and an `OutOfMemoryError`.
## Steps to reproduce
Run with `gradlew demo`.
## Expected result
The demo should execute succesfully.
## Actual result
The demo fails with an `OutOfMemoryError: java heap space`.
# License
Copyright (c) 2017, <NAME>.
Distributed under the BSD-2-Clause license, see the [LICENSE](LICENSE) file
for the full license text.
<file_sep>/src/main/java/co/rngd/mybatis/SimpleFile.java
package co.rngd.mybatis;
public class SimpleFile {
private byte[] content;
private String name;
private int sizeInBytes;
}
<file_sep>/src/main/java/co/rngd/mybatis/Main.java
package co.rngd.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.sql.Statement;
public class Main {
public static void main(String... a) throws Exception {
SqlSessionFactory sessionFactory = createSqlSessionFactory();
prepareDatabase(sessionFactory);
insertAndRetrieveSimple(sessionFactory, 100_000_000);
insertAndRetrieveNested(sessionFactory, 100_000_000);
}
private static SqlSessionFactory createSqlSessionFactory() throws Exception {
InputStream inputStream = Main.class.getResourceAsStream("/mybatis.xml");
return new SqlSessionFactoryBuilder().build(inputStream);
}
private static void prepareDatabase(SqlSessionFactory sessionFactory) throws Exception {
try (SqlSession session = sessionFactory.openSession()) {
try (Statement statement = session.getConnection().createStatement()) {
statement.execute("create table file (" +
"id number auto_increment primary key, " +
"name varchar(100), size number, data blob);");
}
session.commit();
}
}
private static void insertAndRetrieveSimple(SqlSessionFactory sessionFactory, int sizeInBytes) {
String name = "file" + sizeInBytes;
File file = File.create(name, new byte[sizeInBytes]);
try (SqlSession session = sessionFactory.openSession()) {
session.insert("co.rngd.mybatis.FileMapper.insert", file);
SimpleFile result = session.selectOne("co.rngd.mybatis.FileMapper.findSimple", name);
session.rollback();
}
}
private static void insertAndRetrieveNested(SqlSessionFactory sessionFactory, int sizeInBytes) {
String name = "file" + sizeInBytes;
File file = File.create(name, new byte[sizeInBytes]);
try (SqlSession session = sessionFactory.openSession()) {
session.insert("co.rngd.mybatis.FileMapper.insert", file);
File result = session.selectOne("co.rngd.mybatis.FileMapper.findByName", name);
session.rollback();
}
}
}
<file_sep>/build.gradle
apply plugin:'java'
repositories {
mavenCentral()
}
dependencies {
compile 'org.mybatis:mybatis:3.4.2'
compile 'com.h2database:h2:1.4.193'
}
task demo(type:JavaExec) {
classpath=sourceSets.main.runtimeClasspath
main="co.rngd.mybatis.Main"
maxHeapSize="1000m"
}
|
67469519c43fba4f26c8c96ae888b5c28222076b
|
[
"Markdown",
"Java",
"Gradle"
] | 4 |
Markdown
|
simplyarjen/mybatis-memory-issue
|
7fd13524a4eb0640258b42d842dbb6f64dd90f92
|
b64fe4969c0962d0b791f0bb1b187b48bf239b24
|
refs/heads/master
|
<repo_name>zly1154367510/Provincial-competition-<file_sep>/clear_spider.log.py
#coding=utf-8
import pandas as pd
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import re
'''
电影名 上映日期 上映场次数 院线城市 导演 演员 影片类型 票房收入
'''
def tList(dateList):
with open("cc.txt","a") as f:
for i in dateList:
f.writelines(`i`.encode("utf-8"))
f.writelines("\n")
with open("spider.log","r") as f:
content = f.read();
content = content.split("\n")
dateList = []
for i in content:
if i.find("票房")!=-1:
dateList.append(i)
for i in dateList:
print i
resList = []
patten = re.compile(r".*?,.*?,(.*?);(.*?);.*?;(.*?);(.*?);(.*?);(.*?);(.*?);(.*?);(.*?)")
for i in dateList:
res = patten.findall(i)
for i in res:
i = list(i)
resList.append(i)
print resList
DF = pd.DataFrame(resList)
DF.to_csv("333.csv",encoding="utf-8")
<file_sep>/ans0303.py
#coding=utf-8
import pandas as pd
import datetime
import sys
reload(sys)
sys.setdefaultencoding("GB18030")
import matplotlib.pyplot as mp
mp.rcParams['font.sans-serif'] = ['FangSong']
A = "《冲上云霄》"
B = "《百团大战》"
C = "《简单爱》"
M = "武汉"
N = "北京"
def clearCSV(name):
content = "";
with open(name,"r") as f:
content = f.read();
content = content.replace(",","-")
content = content.replace(";",",")
content = content.replace(".", "-")
dataList = content.split("\n")
clearList = []
for i in dataList:
i = i.split(",")
clearList.append(i)
df = pd.DataFrame(clearList)
return df
def clearCSV1(name):
content = "";
with open(name,"r") as f:
content = f.read();
content = content.replace(",","-")
content = content.replace(";",",")
dataList = content.split("\n")
clearList = []
for i in dataList:
i = i.split(",")
clearList.append(i)
df = pd.DataFrame(clearList)
return df
# df.to_csv("222.csv")
def getDayNum(movieName,df):
AStartTime = df[df[0]==movieName][1].values[0].split("-")
AEndTime = df[df[0]==movieName][2].values[0].split("-")
AdayNum = (datetime.datetime(int(AEndTime[0]),int(AEndTime[1]),int(AEndTime[2]))-datetime.datetime(int(AStartTime[0]),int(AStartTime[1]),int(AStartTime[2]))).days
return AdayNum
def getAverage(Aname,df,dayNum):
dataList = list(df[df[0]==A][7])
clearList = []
he = 0
for i in dataList:
i = float(i.replace("票房(万)",""))
he += i
print round(he/dayNum,6)
def getWeekNum(num):
if num%7 != 0:
return num/7+1
else:
return num/7
def getPlot(df):
ADayNum = getDayNum(A,df)
BDayNum = getDayNum(B,df)
CDayNum = getDayNum(C,df)
'''ABC上映周数'''
AweekNum = getWeekNum(ADayNum)
BweekNum = getWeekNum(BDayNum)
CweekNum = getWeekNum(CDayNum)
'''ABC周票房'''
def clearCityData(data):
'''
按电影名去重
'''
data = data.drop_duplicates([0])
'''
按月分组
'''
dataList = []
yuefenzongList = []
cc = data[data[1] >= datetime.datetime(2015, 1, 1)]
cc = cc[cc[1] < datetime.datetime(2015, 2, 1)]
dataList.append(cc)
bb = data[data[1] >= datetime.datetime(2015, 2, 1)]
bb = bb[bb[1] < datetime.datetime(2015, 3, 1)]
dataList.append(bb)
aa = data[data[1] >= datetime.datetime(2015, 3, 1)]
aa = aa[aa[1] < datetime.datetime(2015, 4, 1)]
dataList.append(aa)
he = 0
for j in range(0,3):
for i in dataList[j][7]:
i = float(i.replace("票房(万)", ""))
he += i
yuefenzongList.append(he)
he = 0
return yuefenzongList
# for i in dataList[0][7]:
# i = float(i.replace("票房(万)",""))
# he += i
#
# for i in dataList[1][7]:
# i = float(i.replace("票房(万)",""))
# he += i
# for i in dataList[2][7]:
# i = float(i.replace("票房(万)", ""))
# he += i
def getCity(df):
df[1] = pd.to_datetime(df[1])
df = df[df[1]>datetime.datetime(2015,1,1)]
finalDf = df[df[1]<datetime.datetime(2015,4,1)]
MData = finalDf[finalDf[8]==M]
NData = finalDf[finalDf[8]==N]
Ndata = clearCityData(NData)
Mdata = clearCityData(MData)
xList = [1,2,3]
mp.subplot(2,2,1)
mp.plot(xList,Ndata)
mp.title("北京 title")
mp.subplot(2,2,2)
mp.plot(xList,Mdata)
mp.title("武汉 title")
return mp
if __name__ == '__main__':
#票房处理df
df1 = clearCSV1("film_log3.csv")
'''
处理A电影
ADayNum 上映天数
Aaverage 日均票房
'''
#Aaverage = getAverage(A,df,ADayNum)
getCity(df1).show()
|
78ef8e7c6824459cae8ffaf6642586b49b9519eb
|
[
"Python"
] | 2 |
Python
|
zly1154367510/Provincial-competition-
|
de07638a7920bdd466f61908a6f251776ef88676
|
164ac3d896df1bb8721f09f5f400ab76035105d3
|
refs/heads/master
|
<file_sep>"""driver of the program
"""
from engine import Engine
def main():
engine = Engine()
while True:
try:
message = input()
if not message: # simply ignore empty input line
continue
engine.execute(message)
except KeyboardInterrupt:
break
if __name__ == '__main__':
main()
<file_sep>"""order book implementation. contains actual order matching part
"""
from sortedcontainers import SortedList
from exceptions import UnknownOrderException, DuplicateOrderException
from order import ORDER_BUY_SIDE
from trade import Trade
class OrderBook(object):
def __init__(self):
self.buy_orders = SortedList()
self.sell_orders = SortedList()
self.buy_mapping = {}
self.sell_mapping = {}
def add_order(self, order):
if order.order_id in self.buy_mapping or order.order_id in self.sell_mapping:
raise DuplicateOrderException
if order.order_side == ORDER_BUY_SIDE:
return self._try_buy(order)
else:
return self._try_sell(order)
def cancel_order(self, order_id):
if order_id in self.buy_mapping:
order = self.buy_mapping[order_id]
self.buy_orders.discard(order)
del self.buy_mapping[order_id]
return
if order_id in self.sell_mapping:
order = self.sell_mapping[order_id]
self.sell_orders.discard(order)
del self.sell_mapping[order_id]
return
raise UnknownOrderException
def _try_buy(self, order):
trades = []
while self.sell_orders and order.price >= self.sell_orders[0].price and order.quantity > 0:
resting_order = self.sell_orders[0]
trades.append(self._trade(order, resting_order))
if resting_order.quantity == 0:
self.sell_orders.pop(0)
if order.quantity > 0:
self.buy_orders.add(order)
self.buy_mapping[order.order_id] = order
return trades
def _trade(self, order, resting_order):
quantity = min(resting_order.quantity, order.quantity)
price = resting_order.price
resting_order.quantity -= quantity
order.quantity -= quantity
return Trade(quantity, price, order, resting_order)
def _try_sell(self, order):
trades = []
while self.buy_orders and order.price <= self.buy_orders[0].price and order.quantity > 0:
resting_order = self.buy_orders[0]
trades.append(self._trade(order, resting_order))
if resting_order.quantity == 0:
self.buy_orders.pop(0)
if order.quantity > 0:
self.sell_orders.add(order)
self.sell_mapping[order.order_id] = order
return trades
<file_sep>"""parse input messages
"""
from exceptions import WrongInputFormatException, WrongMessageTypeException
from order import AddOrder, CancelOrder
from consts import ORDER_BUY_SIDE, ORDER_SELL_SIDE
def _parse_add_order_message(items, ts):
if len(items) != 5:
raise WrongInputFormatException
try:
order_id = int(items[1])
if order_id <= 0:
raise WrongInputFormatException
if items[2] not in order_sides:
raise WrongInputFormatException
order_side = order_sides[items[2]]
quantity = int(items[3])
if quantity <= 0:
raise WrongInputFormatException
price = float(items[4])
return AddOrder(order_id, order_side, quantity, price, ts)
except ValueError:
raise WrongInputFormatException
def _parse_cancel_order_message(items, _ts):
if len(items) != 2:
raise WrongInputFormatException
try:
order_id = int(items[1])
if order_id <= 0:
raise WrongInputFormatException
return CancelOrder(order_id)
except ValueError:
raise WrongInputFormatException
input_msg_types = {
'0': _parse_add_order_message,
'1': _parse_cancel_order_message,
}
order_sides = {
'0': ORDER_BUY_SIDE,
'1': ORDER_SELL_SIDE,
}
def parse_input_message(message, ts):
items = message.split(',')
if len(items) < 1:
raise WrongInputFormatException
if items[0] not in input_msg_types:
raise WrongMessageTypeException
return input_msg_types[items[0]](items, ts)
<file_sep>"""trade
"""
from consts import FILL_TYPE_PARTIAL, FILL_TYPE_FULL
class Trade(object):
def __init__(self, quantity, price, aggressive_order, resting_order):
self.quantity = quantity
self.price = price
self.aggressive_id = aggressive_order.order_id
self.aggressive_quantity = aggressive_order.quantity
if aggressive_order.quantity == 0:
self.aggressive_fill = FILL_TYPE_FULL
else:
self.aggressive_fill = FILL_TYPE_PARTIAL
self.resting_id = resting_order.order_id
self.resting_quantity = resting_order.quantity
if resting_order.quantity == 0:
self.resting_fill = FILL_TYPE_FULL
else:
self.resting_fill = FILL_TYPE_PARTIAL
<file_sep>Overview
========
A matching engine facilitates trading financial instruments at an exchange by
taking order requests from clients and matching them against one another to
produce trades. We would like you to write an application that takes a sequence
of order requests (add and remove), runs them through a matching engine, and
produces messages describing the trades and order state changes that result
from the matching operation.
The “Details” section of this document gives information about how your
application should match orders. The “Messages” section defines the input
consumed by and output produced by your application. The “Example” section
contains a simple example sequence of messages (both input and output).
Finally, the “Problem” section provides details on the requirements for your
application.
Details
=======
Orders are offers by market participants to buy (sell) up to a given quantity
at or below (above) a specified price. Generally there are a number of orders
to buy at low prices and a number of orders to sell at high prices since
everybody is trying to get a good deal. If at any point the exchange has a buy
order at the same or higher price than a sell order, the two orders are
"matched" with each other producing a trade for the smaller of the two order
quantities. An incoming order message that causes the buy and sell prices to
cross is called an aggressive order. The orders that are already in the market
are called resting or passive orders.
If there are multiple resting orders that could be matched with the aggressive
order, the resting orders are prioritized first by price and then by age. For
price, priority goes to the resting order that gives the best possible price to
the aggressive order (i.e., the lowest-price resting sell for an aggressive buy
or the highest-price resting buy for an aggressive sell). When there are
multiple resting orders at the best price, the resting order that was placed
first (the oldest resting order) matches first.
Once the correct resting order has been identified, a trade occurs at the price
of the resting order, and for the smaller of the quantities of the two orders
(aggressive and resting). A trade "fills" the orders involved - fully if the
trade quantity is equal to the order quantity and partially if the order
quantity is larger. A trade will always fully fill at least one of the orders.
A partial fill leaves the remaining quantity available to be filled later.
If matching partially fills the aggressive order, the matching procedure
continues down the list of resting orders in the sequence determined by the
price-then-age priority defined above until either the aggressive order is
fully filled, or there are no more resting orders that match. In the latter
case, if there is still quantity on the aggressive order, the remaining
quantity becomes a resting order in the book.
For example, if the resting orders are:
price orders (oldest to newest, B = buy, S = sell)
1075 S 1 // one order to sell up to 1 at 1075
1050 S 10 // one order to sell up to 10 at 1050
1025 S 2 S 5 // one order to sell up to 2 at 1025,
// and second newer order to sell up to 5
1000 B 9 B 1 // buy up to 9 at 1000, second to buy up to 1
975 B 30 // buy up to 30 at 975
The best buy order is at a price of 1000 and the best sell order is at a
price of 1025. Since no seller is willing to sell low enough to match a buyer
and no buyer is willing to buy high enough to match a seller there is no match
between any of the existing orders.
If a new buy order arrives for a quantity of 3 at a price of 1050 there will
be a match. The only sells that are willing to sell at or below a price of
1050 are the S10, S2, and S5. Since the S2 and S5 are at a better price, the
new order will match first against those. Since the S2 arrived first, the new
order will match against the full S2 and produce a trade of 2. However, the 1
remaining quantity will still match the S5, so it matches and produces a trade
of 1 and the S5 becomes an S4. Two trade messages will be generated when this
happens, indicating a trade of size 2 at price 1025 and a trade of size 1 at
price 1025. Two order-related messages will also be generated: one to remove
the S2, and one to note the modification of the S5 down to an S4. The new set
of standing orders will be:
price orders
1075 S 1
1050 S 10
1025 S 4
1000 B 9 B 1
975 B 30
950 B 10
Note that if a new sell order arrives at a price of 1025 it will be placed to
the right of the S4 (i.e. behind it in the queue). Also, although there are
only a few price levels shown here, you should bear in mind that buys and
sells can arrive at any price level.
Messages
========
MessageType
-----------
There are five types of message involved in this problem, two messages your
application shall accept as input and three that it will produce as output. The
message types are identified by integer IDs:
0: AddOrderRequest (input)
1: CancelOrderRequest (input)
2: TradeEvent (output)
3: OrderFullyFilled (output)
4: OrderPartiallyFilled (output)
Input
-----
There are two input message types (requests):
AddOrderRequest: msgtype,orderid,side,quantity,price (e.g. 0,123,0,9,1000)
msgtype = 0
orderid = unique positive integer to identify each order;
used to reference existing orders for remove/modify
side = 0 (Buy) or 1 (Sell)
quantity = positive integer indicating maximum quantity to buy/sell
price = double indicating max price at which to buy/min price to sell
CancelOrderRequest: msgtype,orderid (e.g. 1,123)
msgtype = 1
orderid = ID of the order to remove
Output
------
TradeEvent: msgtype,quantity,price (e.g. 2,2,1025)
msgtype = 2
quantity = amount that traded
price = price at which the trade happened
Every pair of orders that matches generates a TradeEvent. If an aggressive
order has enough quantity to match multiple resting orders, a TradeEvent is
output for each match.
OrderFullyFilled: msgtype,orderid (e.g. 3,123)
msgtype = 3
orderid = ID of the order that was removed
Any order that is fully satisfied by a trade is removed from the book and no
longer available to match against future orders. When that happens, an
OrderFullyFilled message is output. Every TradeEvent should result in at least
one OrderFullyFilled message.
OrderPartiallyFilled: msgtype,orderid,quantity (e.g. 4,123,3)
msgtype = 4
orderid = ID of the order to modify
quantity = The new quantity of the modified order.
Any order that has quantity remaining after a trade is only partially filled
and the remaining quantity is available for matching against other orders in
the future. When that happens, an OrderPartiallyFilled message is output. Each
TradeEvent should result in at most one OrderPartiallyFilled message.
Problem
=======
(1) Given a sequence of order messages as defined above, construct an in-memory
representation of the current state of the order book. You will need to
generate your own dataset to test your code. Messages must be read from stdin.
(2) When an aggressive order matches one or more resting orders, write the
sequence of trade messages and order removals/modifications that result to
stdout. If there are multiple trades, the output should be in the same sequence
as the resting orders were matched. For every pair of orders matched, three
messages should be output in the following sequence:
1. The TradeEvent
2. A full or partial fill message for the aggressive order
3. A full or partial fill message for the resting order
(3) Your code should be clean, easy to understand, efficient, robust, and well
designed (appropriate abstractions, code reuse, etc.). No input should cause
your application to crash; any errors should be be clearly logged to stderr.
(4) You are responsible for testing your solution. Please include any datasets
and/or supporting code that you used in your testing.
(5) Please include a description of the performance characteristics of your
solution, especially for determining whether an AddOrderRequest results in a
match, removing filled orders from the resting order book, and removing a
cancelled order (due to a CancelOrderRequest) from the orderbook.
Example
=======
This is a complete annotated example of input and output corresponding to the
example described in the Details section.
NB: Comments are not part of the input or output, they are just used to add
clarity to the example.
Input/Output:
-------------
The following messages on stdin:
0,100000,1,1,1075
0,100001,0,9,1000
0,100002,0,30,975
0,100003,1,10,1050
0,100004,0,10,950
BADMESSAGE // An erroneous input
0,100005,1,2,1025
0,100006,0,1,1000
1,100004 // remove order
0,100007,1,5,1025 // Original standing order book from Details
0,100008,0,3,1050 // Matches! Triggers trades
The final message should cause your program to produce the following output on
stdout:
2,2,1025
4,100008,1
3,100005
2,1,1025
3,100008
4,100007,4 // order quantity reduced for partial fill
In response to the erroneous input, your application should write some kind of
error message on stderr, maybe like this:
Unknown message type: BADMESSAGE // Your error message may vary
Notes
-----
The input messages up through order 1000007 build the initial book from the
example in the Details section above. Note that order 100004 is removed, so it
doesn't appear in the Details section. None of these order messages cause a
match, so they are just added to the resting order book and generate no output
on stdout, and a single error message on stderr.
The next order ( ID 100008, a buy of 3 at 1050) triggers the matching engine to
produce a trade. When this message is processed, two trades are produced
from three orders interacting (the newest order and two of the orders that are
resting in the order book). The output from this event should explicitly state
each trade as well as posting how the involved orders are affected by the
match. In this case, the inbound order is fully filled, so it no longer affects
the book (so it is removed), as is one of the two resting orders. The other
resting order is only partially filled, so part of the order is still resting
in the book, represented as a modify message in the output.
<file_sep>"""contains order details
"""
from functools import total_ordering
from consts import ORDER_BUY_SIDE, ACTION_TYPE_ADD_ORDER, ACTION_TYPE_CANCEL_ORDER
from exceptions import IllegalComparisonException
@total_ordering
class Order(object):
def __init__(self, order_id, order_side, quantity, price, ts):
self.order_id = order_id
self.order_side = order_side
self.quantity = quantity
self.price = price
self.ts = ts
def __lt__(self, other):
if self.order_side != other.order_side:
raise IllegalComparisonException
if self.order_side == ORDER_BUY_SIDE:
if self.price > other.price:
return True
else:
if self.price < other.price:
return True
if self.price == other.price:
return self.ts < other.ts
return False
def __eq__(self, other):
return self.order_id == other.order_id and self.order_side == other.order_side and \
self.quantity == other.quantity and self.price == other.price and self.ts == other.ts
def __str__(self):
return 'Order:{},{},{},{},{}'.format(self.order_id, self.order_side, self.price, self.quantity, self.ts)
def __repr__(self):
return str(self)
class AddOrder(object):
def __init__(self, order_id, order_side, quantity, price, ts):
self.action_type = ACTION_TYPE_ADD_ORDER
self.order = Order(order_id, order_side, quantity, price, ts)
class CancelOrder(object):
def __init__(self, order_id):
self.action_type = ACTION_TYPE_CANCEL_ORDER
self.order_id = order_id
<file_sep>from consts import ORDER_BUY_SIDE, ORDER_SELL_SIDE
from order import Order
def test_order_ordering():
order1 = Order(1, ORDER_BUY_SIDE, 1, 2, 1)
order2 = Order(2, ORDER_BUY_SIDE, 1, 1, 2)
assert order1 < order2
order1 = Order(1, ORDER_BUY_SIDE, 1, 1, 1)
order2 = Order(2, ORDER_BUY_SIDE, 1, 1, 2)
assert order1 < order2
order1 = Order(1, ORDER_SELL_SIDE, 1, 2, 1)
order2 = Order(2, ORDER_SELL_SIDE, 1, 1, 2)
assert order1 > order2
order1 = Order(1, ORDER_SELL_SIDE, 1, 1, 1)
order2 = Order(2, ORDER_SELL_SIDE, 1, 1, 2)
assert order1 < order2
<file_sep># order match
## program structure
main.py: driver of the whole trade engine
engine.py: trade engine. parse input and produces output
order_book.py: keeps buy and sell orders. produces trades if any
order.py: order
trade.py: trade
## instruction
`pip install -r requirements.txt` to install the requirements
`python main.py` to start running the program and Ctrl+C to exit.
`pytest` to run all the tests
## performance
order_book.py contains the most important part for the whole trade matching algorithm. it is using both dictionary and sorted list from sorted container package.
when adding an order, adding order to sorted list is O(log n) on average; removing resting order is O(log n) as well. so in total O(log n).
when removing an order, removing the order from sorted list if O(log n).
## reference
http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html#sortedlist
<file_sep>"""utilities: exceptions
"""
class WrongInputFormatException(Exception):
pass
class WrongMessageTypeException(Exception):
pass
class UnknownOrderException(Exception):
pass
class DuplicateOrderException(Exception):
pass
class IllegalComparisonException(Exception):
pass
<file_sep>from consts import ORDER_BUY_SIDE, ORDER_SELL_SIDE, FILL_TYPE_FULL, FILL_TYPE_PARTIAL
from order import Order
from trade import Trade
def test_trade():
quantity = 10
price = 10
aggressive_order = Order(1, ORDER_BUY_SIDE, 0, price, 1)
resting_order = Order(2, ORDER_SELL_SIDE, 1, price, 2)
trade = Trade(quantity, price, aggressive_order, resting_order)
assert trade.price == price
assert trade.quantity == quantity
assert trade.aggressive_fill == FILL_TYPE_FULL
assert trade.aggressive_quantity == 0
assert trade.aggressive_id == 1
assert trade.resting_fill == FILL_TYPE_PARTIAL
assert trade.resting_quantity == 1
assert trade.resting_id == 2
aggressive_order = Order(1, ORDER_BUY_SIDE, 1, price, 1)
resting_order = Order(2, ORDER_SELL_SIDE, 0, price, 2)
trade = Trade(quantity, price, aggressive_order, resting_order)
assert trade.price == price
assert trade.quantity == quantity
assert trade.aggressive_fill == FILL_TYPE_PARTIAL
assert trade.aggressive_quantity == 1
assert trade.aggressive_id == 1
assert trade.resting_fill == FILL_TYPE_FULL
assert trade.resting_quantity == 0
assert trade.resting_id == 2
<file_sep>sortedcontainers==2.3.0
pytest==6.2.2
<file_sep>import pytest
from consts import ORDER_BUY_SIDE, ORDER_SELL_SIDE, FILL_TYPE_PARTIAL, FILL_TYPE_FULL
from exceptions import UnknownOrderException, DuplicateOrderException
from order import Order
from order_book import OrderBook
def test_order_book():
order_book = OrderBook()
assert len(order_book.sell_orders) == 0
assert len(order_book.buy_orders) == 0
trades = order_book.add_order(Order(100000, ORDER_SELL_SIDE, 1, 1075, 1))
assert len(trades) == 0
assert len(order_book.sell_orders) == 1
assert len(order_book.buy_orders) == 0
assert order_book.sell_orders[0].order_id == 100000
trades = order_book.add_order(Order(100001, ORDER_BUY_SIDE, 9, 1000, 2))
assert len(trades) == 0
assert len(order_book.sell_orders) == 1
assert len(order_book.buy_orders) == 1
assert order_book.sell_orders[0].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
trades = order_book.add_order(Order(100002, ORDER_BUY_SIDE, 30, 975, 3))
assert len(trades) == 0
assert len(order_book.sell_orders) == 1
assert len(order_book.buy_orders) == 2
assert order_book.sell_orders[0].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
assert order_book.buy_orders[1].order_id == 100002
trades = order_book.add_order(Order(100003, ORDER_SELL_SIDE, 10, 1050, 3))
assert len(trades) == 0
assert len(order_book.sell_orders) == 2
assert len(order_book.buy_orders) == 2
assert order_book.sell_orders[0].order_id == 100003
assert order_book.sell_orders[1].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
assert order_book.buy_orders[1].order_id == 100002
trades = order_book.add_order(Order(100004, ORDER_BUY_SIDE, 10, 950, 4))
assert len(trades) == 0
assert len(order_book.sell_orders) == 2
assert len(order_book.buy_orders) == 3
assert order_book.sell_orders[0].order_id == 100003
assert order_book.sell_orders[1].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
assert order_book.buy_orders[1].order_id == 100002
assert order_book.buy_orders[2].order_id == 100004
trades = order_book.add_order(Order(100005, ORDER_SELL_SIDE, 2, 1025, 5))
assert len(trades) == 0
assert len(order_book.sell_orders) == 3
assert len(order_book.buy_orders) == 3
assert order_book.sell_orders[0].order_id == 100005
assert order_book.sell_orders[1].order_id == 100003
assert order_book.sell_orders[2].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
assert order_book.buy_orders[1].order_id == 100002
assert order_book.buy_orders[2].order_id == 100004
trades = order_book.add_order(Order(100006, ORDER_BUY_SIDE, 1, 1000, 6))
assert len(trades) == 0
assert len(order_book.sell_orders) == 3
assert len(order_book.buy_orders) == 4
assert order_book.sell_orders[0].order_id == 100005
assert order_book.sell_orders[1].order_id == 100003
assert order_book.sell_orders[2].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
assert order_book.buy_orders[1].order_id == 100006
assert order_book.buy_orders[2].order_id == 100002
assert order_book.buy_orders[3].order_id == 100004
order_book.cancel_order(100004)
assert len(order_book.sell_orders) == 3
assert len(order_book.buy_orders) == 3
assert order_book.sell_orders[0].order_id == 100005
assert order_book.sell_orders[1].order_id == 100003
assert order_book.sell_orders[2].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
assert order_book.buy_orders[1].order_id == 100006
assert order_book.buy_orders[2].order_id == 100002
trades = order_book.add_order(Order(100007, ORDER_SELL_SIDE, 5, 1025, 8))
assert len(trades) == 0
assert order_book.sell_orders[0].order_id == 100005
assert order_book.sell_orders[1].order_id == 100007
assert order_book.sell_orders[2].order_id == 100003
assert order_book.sell_orders[3].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
assert order_book.buy_orders[1].order_id == 100006
assert order_book.buy_orders[2].order_id == 100002
trades = order_book.add_order(Order(100008, ORDER_BUY_SIDE, 3, 1050, 9))
assert len(trades) == 2
assert trades[0].quantity == 2
assert trades[0].price == 1025
assert trades[0].aggressive_fill == FILL_TYPE_PARTIAL
assert trades[0].aggressive_quantity == 1
assert trades[0].aggressive_id == 100008
assert trades[0].resting_fill == FILL_TYPE_FULL
assert trades[0].resting_id == 100005
assert trades[1].quantity == 1
assert trades[1].price == 1025
assert trades[1].aggressive_fill == FILL_TYPE_FULL
assert trades[1].aggressive_id == 100008
assert trades[1].resting_fill == FILL_TYPE_PARTIAL
assert trades[1].resting_id == 100007
assert trades[1].resting_quantity == 4
assert order_book.sell_orders[0].order_id == 100007
assert order_book.sell_orders[1].order_id == 100003
assert order_book.sell_orders[2].order_id == 100000
assert order_book.buy_orders[0].order_id == 100001
assert order_book.buy_orders[1].order_id == 100006
assert order_book.buy_orders[2].order_id == 100002
with pytest.raises(UnknownOrderException):
order_book.cancel_order(1000004)
with pytest.raises(DuplicateOrderException):
order_book.add_order(Order(100007, ORDER_SELL_SIDE, 5, 1025, 11))
<file_sep>"""trade engine
"""
import sys
from exceptions import WrongInputFormatException, WrongMessageTypeException, UnknownOrderException, \
DuplicateOrderException
from input_parser import parse_input_message
from consts import ACTION_TYPE_ADD_ORDER, ACTION_TYPE_CANCEL_ORDER
from order_book import OrderBook
from output_formatter import output_trade
class Engine(object):
def __init__(self):
self.order_book = OrderBook()
self.ts = 0
def execute(self, message):
self.ts += 1
try:
order_action = parse_input_message(message, self.ts)
if order_action.action_type == ACTION_TYPE_ADD_ORDER:
trades = self.order_book.add_order(order_action.order)
for trade in trades:
output_trade(trade)
elif order_action.action_type == ACTION_TYPE_CANCEL_ORDER:
self.order_book.cancel_order(order_action.order_id)
except WrongInputFormatException:
sys.stderr.write('Wrong input format: {}\n'.format(message))
except WrongMessageTypeException:
sys.stderr.write('Wrong message type: {}\n'.format(message))
except UnknownOrderException:
sys.stderr.write('Unknown order: {}\n'.format(message))
except DuplicateOrderException:
sys.stderr.write('Duplicate order: {}\n'.format(message))
<file_sep>from consts import TRADE_TYPE, FILL_TYPE_FULL
def output_trade(trade):
print('{},{},{}'.format(TRADE_TYPE, trade.quantity, trade.price))
if trade.aggressive_fill == FILL_TYPE_FULL:
print('{},{}'.format(trade.aggressive_fill, trade.aggressive_id))
else:
print('{},{},{}'.format(trade.aggressive_fill, trade.aggressive_id, trade.aggressive_quantity))
if trade.resting_fill == FILL_TYPE_FULL:
print('{},{}'.format(trade.resting_fill, trade.resting_id))
else:
print('{},{},{}'.format(trade.resting_fill, trade.resting_id, trade.resting_quantity))
<file_sep>"""consts
"""
ORDER_BUY_SIDE = 0
ORDER_SELL_SIDE = 1
ACTION_TYPE_ADD_ORDER = 0
ACTION_TYPE_CANCEL_ORDER = 1
FILL_TYPE_FULL = 3
FILL_TYPE_PARTIAL = 4
TRADE_TYPE = 2
|
d490b298bc79b352711fbaf9c8d697b383bb4051
|
[
"Markdown",
"Python",
"Text"
] | 15 |
Python
|
franklingu/order_match
|
84404010c95aecc05ed47f93d345e195d1352413
|
1f3608770f9c44f3324b811b157e759d579f91cd
|
refs/heads/master
|
<repo_name>prashantv/piui<file_sep>/byte_pool.go
package main
import (
"net/http/httputil"
"sync"
)
type bytePool struct {
pool sync.Pool
}
var _ httputil.BufferPool = &bytePool{}
func newBytePool(size int) *bytePool {
return &bytePool{
sync.Pool{
New: func() interface{} {
return make([]byte, size)
},
},
}
}
func (p *bytePool) Get() []byte {
return p.pool.Get().([]byte)
}
func (p *bytePool) Put(bs []byte) {
p.pool.Put(bs)
}
<file_sep>/letsencrypt/README.md
This folder is used for letsencrypt. It should be set as the webroot.
<file_sep>/main.go
package main
import (
"flag"
"log"
"net/http"
"strings"
)
var (
httpAddr = flag.String("http", ":8080", "Host:Port to listen on for HTTP requests")
httpsAddr = flag.String("https", ":8443", "Host:Port to listen on for HTTPS requests")
gogsAddr = flag.String("gogsHttp", "127.0.0.1:3000", "Host:Port of the Gogs to forward to")
certFile = flag.String("cert", "", "SSL certificate file")
keyFile = flag.String("key", "", "SSL private key file")
)
func main() {
flag.Parse()
gogs := http.Handler(http.HandlerFunc(gogsNotInstalled))
if *gogsAddr != "" {
proxy, err := gogsProxy(*gogsAddr)
if err != nil {
log.Fatalf("Failed to create gogs proxy: %v", err)
}
gogs = proxy
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.Host, "git.") {
gogs.ServeHTTP(w, r)
return
}
w.Write([]byte("Hello world"))
})
http.Handle("/.well-known/", http.FileServer(http.Dir("./letsencrypt")))
// Start SSL if there is a port set
if *httpsAddr != "" {
go func() {
http.ListenAndServeTLS(*httpsAddr, *certFile, *keyFile, nil)
}()
}
if err := http.ListenAndServe(*httpAddr, nil); err != nil {
panic(err)
}
}
<file_sep>/gogs.go
package main
import (
"io"
"net/http"
"net/http/httputil"
"net/url"
)
const poolSliceSize = 64 * 1024
func gogsProxy(gogsHostPort string) (*httputil.ReverseProxy, error) {
u, err := url.Parse("http://" + gogsHostPort + "/")
if err != nil {
return nil, err
}
p := httputil.NewSingleHostReverseProxy(u)
p.BufferPool = newBytePool(poolSliceSize)
return p, nil
}
func gogsNotInstalled(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
io.WriteString(w, "Gogs handler is not registered")
}
|
d513003a0146dda46bf782994ede1014c2cc1d61
|
[
"Markdown",
"Go"
] | 4 |
Go
|
prashantv/piui
|
2437e9c5d2b9495c88f5c42a500d9eabc664b98c
|
b700fb68c862d4a5a78d46a676adcbeac82b1a7a
|
refs/heads/master
|
<repo_name>williamsdaniel888/cokeyco<file_sep>/Cloud/Readme.md
## Cloud Arch
All cloud backend has been done using AWS Iot, Lambda Functions and Redis as a datastore.<file_sep>/ESP8266/main.py
#import the necessary modules
import time
import math
import machine
from machine import Pin, I2C
import network
import ujson
from umqtt.simple import MQTTClient
import ubinascii
import Sensor
WIRELESS_AP_SSID = "pomelo"
WIRELESS_AP_PASSWORD = "<PASSWORD>"
#Wireless etworking
# ap_if = network.WLAN(network.AP_IF)
# ap_if.active(False)
sta_if= network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(WIRELESS_AP_SSID,WIRELESS_AP_PASSWORD)
if sta_if.isconnected():
print("Connected to Wifi")
else:
print("Failed to connect to WIFI network")
#MQTT
counter = 0
client = MQTTClient("test", "192.168.0.10")
time.sleep(5)
client.connect()
#Prevent repeat play/pause messages being picked up
Activation_Hold_Off_Counter=0
#Generic Program counter that increments with each loop
Program_Counter = 0
#Sets up the inital PIR Sensor
Pir = Sensor.PIR()
#Sets up the magentormeter
Magnet = Sensor.Magnetometer()
while True:
#Moving Average Filter
average = Magnet.GetAReading()
dataX = average[0]
dataY = average[1]
dataZ = average[2]
#print("Average is", average)
sjson = "{{'dataX':{0},'dataY':{1},'dataZ':{2}}}".format(dataX,dataY,dataZ)
# Publishes magnetic readings to mqtt for debugging
#client.publish("magReadings",bytes(sjson,'utf-8'))
#Publish on Topic if PIR Is Triggered
trig = Pir.IsTriggered(Program_Counter)
if trig[0]==True and trig[1]>200:
client.publish("showerMate/PIR",bytes("Triggered",'utf-8'))
#Ocasionally print the data to serial output
if Program_Counter %16==0:
print(sjson)
if Activation_Hold_Off_Counter>200:
# Check whether readings are above threshold
if dataX >800 and dataY >800:
#When in Quadrant x
client.publish("musicControl",bytes("next",'utf-8'))
print("Next Activated")
#Reset Activation hold off to prevent multiple quick triggers
Activation_Hold_Off_Counter = 0
elif dataX<-800 and dataY <-800:
client.publish("musicControl",bytes("previous",'utf-8'))
print("Previous Activated")
Activation_Hold_Off_Counter = 0
elif dataX< -800 and dataY> 800:
client.publish("musicControl",bytes("play",'utf-8'))
print("play Activated")
Activation_Hold_Off_Counter = 0
elif dataX> 800 and dataY< -800:
client.publish("musicControl",bytes("pause",'utf-8'))
print("pause Activated")
Activation_Hold_Off_Counter = 0
Activation_Hold_Off_Counter+=1
Program_Counter+=1
time.sleep(0.1)
<file_sep>/Raspi/master.py
# import network
# ap_if = network.WLAN(network.AP_IF)
# ap_if.active(False)
# sta_if = network.WLAN(network.STA_IF)
# sta_if.active(True)
# sta_if.connect('<essid>', '<password>')
import paho.mqtt.client as mqtt
import os
import simpleaudio as sa
from pathlib import Path
import logging
import time
import music
import mqttThread
import threading
#setup logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
def main():
# Register the signal handlers
#signal.signal(signal.SIGTERM, service_shutdown)
#signal.signal(signal.SIGINT, service_shutdown)
#Setup the music Events
eventMap = {}
for i in ["play","pause","next","previous"]:
eventMap[i] = threading.Event()
eventMap[i].clear()
#create the neccessary threads
th1 = music.MusicPlayer(eventMap)
th2 = mqttThread.MQTT(eventMap)
#Start the events
th1.start()
th2.start()
try:
while True:
pass
except:
th1.killThread.set()
th2.killThread.set()
if __name__=="__main__":
main()<file_sep>/README.md
# Aquise
Embedded Systems Project 1
## Features
### Services
- Gesture-directed audio control *(Next, Previous, Play/Pause)*
- Activity detection
- *Demo* Water usage monitoring and insight analysis
### Hardware
- Adafruit Feather HUZZAH with ESP8266
- Triple-Axis Magnetometer *HMC5883L*
- Passive Infra-red Sensor *Adafruit-189*
### Communication
- Wi-Fi *802.11b/g/n 2.4 GHz*
- MQTT Protocol *(Panel Client – Raspberry Pi Server)*
### Power
- Input Voltage: 5 VDC *via USB Micro B*
### Environment
- Temperature Range: [-30, 85] °C
- Magnetic Field Range: ± 8 G
- Weight: 19 g
<file_sep>/Raspi/RPI_Install.sh
#!/bin/bash
# Make Sure script is running as SUDO
if [[ $EUID > 0 ]]; then # we can compare directly with this syntax.
echo "Please run as root/sudo"
exit 1
fi
#Upgrade all packages
echo "Starting Package Update"
apt-get update && apt-get -y upgrade
echo "Update Complete Successfully"
#Change Passowrd
yes "<PASSWORD>" | passwd pi
echo "Password Changed Successfully"
#Enable SSH
while [ -e /var/log/regen_ssh_keys.log ] && ! grep -q "^finished" /var/log/regen_ssh_keys.log;
do
echo "Initial ssh key generation still running. Trying Again in 5 seconds"
sleep 5
fi
update-rc.d ssh enable &&
invoke-rc.d ssh start &&
echo "SSH Server Enabled"
sudo apt-get -y install git
# wget "https://raw.githubusercontent.com/williamsdaniel888/cokeyco/piers/Raspi/master.py" -O master.py
# wget "https://raw.githubusercontent.com/williamsdaniel888/cokeyco/piers/Raspi/mqttThread.py" -O mqttThread.py
# wget "https://github.com/williamsdaniel888/cokeyco/blob/piers/Raspi/music.py" -O music.py
wget ""
# Install and auto start mosquitto
apt-get -y install mosquitto
<file_sep>/Raspi/music.py
import threading
import logging
import os
from pathlib import Path
import simpleaudio as sa
import time
#setup logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
class MusicState(object):
def __init__(self):
musicDir = self.getHomeDir()+ "/music/"
if not os.path.exists(musicDir):
logger.error("Music Dir Path does not exist: %s", musicDir)
self.music_list = self.getMusicPathList(musicDir)
self.index = 0
def get_current_song(self):
playlist_length = len(self.music_list)
self.index = (self.index)
return self.music_list[self.index]
def get_next_song(self):
playlist_length = len(self.music_list)
self.index = (self.index+1)%playlist_length
return self.music_list[self.index]
def get_previous_song(self):
playlist_length = len(self.music_list)
self.index = (self.index-1)%playlist_length
return self.music_list[self.index]
def getHomeDir(self):
homeDir = str(Path.home())
logger.info("Home Directory found to be : %s",homeDir)
return homeDir
def getMusicPathList(self,musicDir):
list_of_songs = os.listdir(musicDir)
ouptut = []
for i in list_of_songs:
if i.endswith(".wav"):
p = Path(musicDir+i)
ouptut.append(p)
return ouptut
class MusicPlayer(threading.Thread):
def __init__(self,eventMap):
threading.Thread.__init__(self)
self.playEvent = threading.Event()
logger.debug("Started Music Player Thread")
self.musicState = MusicState()
self.play_obj = None
self.eventMap = eventMap
self.killThread = threading.Event()
self.PlayFlag = True
def next_song(self):
song_path = self.musicState.get_next_song()
self.pause()
self.play_obj = sa.WaveObject.from_wave_file(str(song_path)).play()
self.PlayFlag = True
def prev_song(self):
song_path = self.musicState.get_previous_song()
self.pause()
self.play_obj = sa.WaveObject.from_wave_file(str(song_path)).play()
self.PlayFlag = True
def pause(self):
if not self.play_obj == None and self.play_obj.is_playing():
self.play_obj.stop()
self.PlayFlag = False
def play(self):
if not self.play_obj.is_playing():
song_path = self.musicState.get_current_song()
self.pause()
self.play_obj = sa.WaveObject.from_wave_file(str(song_path)).play()
self.PlayFlag = True
else:
logger.info("File is already playing")
def run(self):
#Need to do this to instansiate the play_obj
self.next_song()
while not self.killThread.is_set():
for key,value in self.eventMap.items():
if value.is_set():
value.clear()
if key =="play":
self.play()
elif key =="pause":
self.pause()
elif key == "next":
self.next_song()
elif key == "previous":
self.prev_song()
else:
logger.warn("Event: %s :in eventmap not recognised",key)
if self.play_obj.is_playing()==False and self.PlayFlag == True:
self.next_song()
time.sleep(0.05)
logger.info("Kill thread Recieved, thread %s is shutting down", __name__)<file_sep>/ESP8266/Sensor.py
import machine
from machine import Pin,I2C
import time
movingAverageSampleSize=16
class PIR(object):
def __init__(self):
PIRPin = machine.Pin(7,machine.Pin.IN)
PIRPin.irq(trigger=machine.Pin.IRQ_RISING, handler=self.Callback)
self.Triggered = False
self.Program_Counter_When_Last_Triggered = 0
#Minismise ISR code
def Callback(self):
self.Triggered = True
def IsTriggered(self, program_Counter):
if self.IsTriggered:
#The program counter time since the last trigger
timeSince = program_Counter - self.Program_Counter_When_Last_Triggered
self.Program_Counter_When_Last_Triggered = program_Counter
self.Triggered = False
return (True,timeSince)
else:
return (False,0)
class Magnetometer(object):
def __init__(self):
#create the i2cport
self.i2cport = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
#send initialization command 1: 1 sample per output; 15 Hz
self.i2cport.writeto(0x1E, bytearray([0x00, 0x10]))
#send initialization command 2: gain 1090LSbit per Gauss = 0.92 mG per LSbit
self.i2cport.writeto(0x1E, bytearray([0x01, 0xE0]))
#Data Buffer to hold samples from magnetometer
self.dataBuffer = []
#Converts the 16 bit raw readings to singed intergers
def convert_mag_readings_to_int(self,byteArray):
data = int.from_bytes(byteArray, 'big', False)
if(data & 0x8000):
data = (data - 2**16)
else:
pass
return data
#function that averages the last x Results
def moving_average_filter(self,dataX,dataY,dataZ):
ls = {"dataX": dataX,"dataY":dataY,"dataZ":dataZ}
self.dataBuffer.append(ls)
tot_X = 0
tot_Y = 0
tot_Z = 0
for i in self.dataBuffer:
tot_X += i["dataX"]
tot_Y += i["dataY"]
tot_Z += i["dataZ"]
#Removes Earlyist Occurence from buffer when data buffer is full
if len(self.dataBuffer)>movingAverageSampleSize:
self.dataBuffer.pop(0)
return [tot_X,tot_Y,tot_Z]
def GetAReading(self):
#send the command for single-measurement mode
self.i2cport.writeto(0x1E, bytearray([0x02, 0x01]))
#Wait 6ms for readings to occur
time.sleep_ms(7)
#Read data from the I2C port
data = self.i2cport.readfrom(0x1E, 0x06)
#convert the six bytes to three ints
dataX = self.convert_mag_readings_to_int(bytearray([data[0],data[1]]))
dataZ = self.convert_mag_readings_to_int(bytearray([data[2],data[3]]))
dataY = self.convert_mag_readings_to_int(bytearray([data[4],data[5]]))
average = self.moving_average_filter(dataX,dataY,dataZ)
return average<file_sep>/Raspi/mqttThread.py
import logging
import threading
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import datetime
import json
import paho.mqtt.client as mqtt
#setup logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
MQTTServer = "localhost"
class MQTT(threading.Thread):
def __init__(self,eventMap):
threading.Thread.__init__(self)
logging.info("Started MQTT thread")
self.eventMap = eventMap
self.killThread = threading.Event()
def decodeEvent(self,msg):
if msg in self.eventMap.keys():
logger.info("Event %s recieved and emmitted",msg)
self.eventMap[msg].set()
else:
logger.error("Did not recognise event: %s :when decoding",msg)
def music_message(self,mosq, obj, msg):
#print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
message = msg.payload.decode("utf-8")
if message =="PIR":
j = json.dumps({"PIR":str(datetime.datetime.now()) })
self.myAWSIoTMQTTClient.publish("ShowerMate/PIR", bytes(j,"utf-8"), 1)
logger.info('Sent PIR to AWS: ShowerMate/PIR')
if message == "play" or message=="pause" or message == "next" or message == "previous":
self.decodeEvent(message)
else:
logger.warn("MQTT message not recognised, message: %s",message)
def AWSCallback(self,client, userdata, message):
print("Received a new message: ")
print(message.payload)
print("from topic: ")
print(message.topic)
print("--------------\n\n")
def run(self):
logging.info("Setting up MQTT subscribe")
music_client = mqtt.Client("music_Stream")
music_client.connect(MQTTServer)
music_client.subscribe("musicControl")
music_client.subscribe("showerMate/PIR")
music_client.on_message = self.music_message
logger.info("Started listeing to musi cMessages on %s",MQTTServer)
while not self.killThread.is_set():
#poll for events, blocks with time of 0.1s
music_client.loop(0.1)
logger.info("Kill thread Recieved, thread %s is shutting down", __name__)
#AWS Secrets
host = ""
rootCAPath = ""
certificatePath = ""
privateKeyPath = ""
clientId = "MyClient"
topic = "ShowerMate/Commands"
# Init AWSIoTMQTTClient
self.myAWSIoTMQTTClient = None
self.myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
self.myAWSIoTMQTTClient.configureEndpoint(host, 8883)
self.myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
# AWSIoTMQTTClient connection configuration
self.myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
self.myAWSIoTMQTTClient.subscribe(topic, 1, self.AWSCallback)
|
59dae8cbbb2411015a86a62e11c0281e9fd62648
|
[
"Markdown",
"Python",
"Shell"
] | 8 |
Markdown
|
williamsdaniel888/cokeyco
|
82ee05206839aa23f48a5ed778179ebaa4242cb7
|
49c6cee9c909cc93c70ef42018eb3cc757586d6b
|
refs/heads/master
|
<repo_name>luduvigo/hackathon-starter<file_sep>/README.md
# hackathon-starter
##Issue with MongoDB
There is a problem with MongoDB versions bigger than 1.3.19, related to the BSON part, in this case to avoid the problem the version 1.3.19 of MongoDB should be installed:
npm install [email protected]
<file_sep>/db.js
var mongoose = require("mongoose")
mongoose.connect("mongodb://localhost/hackathon-starter", function(req, res){
console.log("Mongo DB connected")
})
module.exports = mongoose<file_sep>/authentication/server.js
var express = require('express')
var jwt = require('jwt-simple')
var _ = require('lodash')
var bcrypt = require('bcrypt')
var app = express()
app.use(require('body-parser').json())
var users = [{username : 'luduvigo', password: <PASSWORD>'}]
var secretKey = 'supersecretkey'
function findUserByUsername(username) {
return _.find(users, {username : username })
}
function validateUser(user, password, cb) {
return bcrypt.compare(password, user.password, cb)
}
app.post('/session', function (req, res){
var user = findUserByUsername(req.body.username)
validateUser(user, req.body.password, function(err, valid){
if(err || !valid){
return res.send(401)
}
var token = jwt.encode({username : user.username}, secretKey)
res.json(token)
})
})
app.get('/user', function(req, res){
var token = req.headers['x-auth']
var user = jwt.decode(token, secretKey)
res.json(user)
})
app.listen(3000)
<file_sep>/authentication/user.js
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/auth_demo')
var user = mongoose.Schema({
username : String,
password : String
})
module.exports = mongoose.model('User', user)
|
1715906d2a55b32f18d77b2e1cb2c62bf9ec1199
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
luduvigo/hackathon-starter
|
37564f68f25a007fd3c2bb9d70af6fbe23b1917c
|
51899691c7dca4d6600d87e807762d099bee1ed8
|
refs/heads/master
|
<file_sep>-r requirements/conda.txt
chanjo>=4.1.0
Flask-WeasyPrint
Flask-Assets
Flask-Babel
Flask-DebugToolbar
Flask-Alchy
path.py
pyscss
cairocffi
tabulate
toml
toolz
pymysql
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.append('/opt/chanjo-report/chanjo_report/')
from chanjo_report.server.app import create_app
class Config:
#SQLALCHEMY_DATABASE_URI = os.environ['SQLALCHEMY_DATABASE_URI']
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = "sqlite:////opt/chanjodb/chanjo.coverage.sqlite3"
application = create_app(config=Config)
<file_sep>
# Chanjo Report [![PyPI version][fury-image]][fury-url] [![Build Status][travis-image]][travis-url]
Automatically generate basic coverage reports from Chanjo SQL databases. This plugin installs as a subcommand ("report") to the Chanjo command line interface.
## Usage
Chanjo Report supports a number of output formats: tabular, PDF, and HTML. To print a PDF coverage report for a group of samples "WGS-prep" do:
```bash
$ chanjo report --render pdf --group "WGS-prep" > ./coverage-report.pdf
```
## Features
### Supported output formats
Chanjo Reports multiple output formats:
- tabular: easily parsable and pipeable
- PDF: easily distributable (for humans)
- HTML: easily deliverable on the web
### Supported languages (translations)
The coverage report (HTML/PDF) can be render is the following languages:
- English
- Swedish
## Motivation
We are using the output from Chanjo at Clincal Genomics to report success of sequencing across the exome based on coverage. Our customers, clinicians mostly, are specifically interested in knowing to what degree their genes of interest are covered by sequencing along with some intuitive overall coverage metrics. They want the output in PDF format to file it in their system.
As a side effect of finding it easiest to convert HTML to PDF, Chanjo Report has a built in Flask server that can be used to render reports dynamically and even be plugged into other Flask servers as a Blueprint.
### Installation
Chanjo Report is distributed through pip. Install the latest release by running:
```bash
$ pip install chanjo-report
```
... or locally for development:
```bash
$ git clone https://github.com/robinandeer/chanjo-report.git
$ cd chanjo-report
$ pip install --editable .
```
> Note that I will eventually provide a fully provisioned Vagrant environment to ease development setup :smiley:
## License
MIT. See the [LICENSE](LICENSE) file for more details.
## Contributing
Anyone can help make this project better - read [CONTRIBUTING](CONTRIBUTING.md) to get started!
[fury-url]: http://badge.fury.io/py/chanjo-report
[fury-image]: https://badge.fury.io/py/chanjo-report.png
[travis-url]: https://travis-ci.org/robinandeer/chanjo-report
[travis-image]: https://img.shields.io/travis/robinandeer/chanjo-report.svg?style=flat
<file_sep># -*- coding: utf-8 -*-
"""Extensions module. Each extension is initialized in the app factory
located in app.py
"""
from chanjo.store.models import BASE
from flask_alchy import Alchy
api = Alchy(Model=BASE)
<file_sep># Change log
## 3.2.0 (2019-02-25)
### Added
POST gene_ids in genes view
## 3.0.2 (2016-03-08)
### Added
- option to pass link to gene view
## 3.0.1 (2016-03-08)
### Fixed
- minor issues in genes view
## 3.0.0 (2016-03-08)
### Adds
- Support for new transcript schema in chanjo v3.4.0
### Removed
- Support for default exon focused schema in previous version of chanjo
## 2.6.1 (2016-03-01)
### Fixed
- generate links with joined gene ids
## 2.6.0 (2016-02-29)
### Added
- Add overview of transcripts (for list of genes)
### Changed
- Show 404 if gene not found for gene overview
## 2.5.1 (2016-02-25)
### Changed
- Order completeness levels in plot and update colors
- Use CDNJS for highcharts to support also HTTPS
## 2.5.0 (2016-02-25)
### Added
- A new gene overview for all or a subset of samples
- Include chanjo repo in Vagrant environment
## 2.4.1 (2016-02-23)
### Fixed
- correctly fetch database uri using CLI
## 2.4.1 (2016-01-29)
### Fixed
- roll back after `OperationalError`
## 2.4.0 (2016-01-13)
### Added
- handle post/get requests for the coverage report (URL limits)
- new "index" blueprint which displays list of samples and genes
### Removed
- link to the "index" page from the report (security)
### Changed
- use a customized version of the HTML form for the PDF link in the navbar
- avoid searching for group id if sample ids are submitted in query
- use "select" element for picking completeness level
### Fixed
- removes the "submit" label from the customizations form
- look up "show_genes" from correct "args/form" dict
## 2.3.2 (2016-01-04)
### Fixed
- handle white-space in gene ids
## 2.3.1 (2015-12-22)
### Changed
- updates how to call diagnostic yield method to explicitly send in exon ids
## 2.3.0 (2015-11-18)
### Adds
- add ability to change sample/group id in report through query args
## 2.2.1 (2015-11-18)
### Changes
- improved phrasing of explanations and other translations
## 2.2.0 (2015-11-16)
### Added
- ability to determine lang by setting query arg in URL
- add uploaded date to report per sample
### Changed
- rename "gender" as "sex"
- clarify explanations, rename "diagnostic yield"
### Fixed
- update to Python 3.5 and fix travis test setup
- stay on "groups" route for PDF report
## 2.1.0 (2015-11-04)
### Added
- Customization options for report
- Link to PDF version of report
### Changed
- Updated chanjo requirement
## 2.0.1 (2015-11-03)
### Fixed
- Include missing template files in dist
- Include more translations
## 2.0.0 (2015-11-03)
### Changed
- Adds support for Chanjo 3
- Layout of report is more condensed
- Updated APIs across the board
## 1.0.1 (2015-06-01)
### Fixed
- Fix bug in diagnostic yield method
## 1.0.0 (2015-06-01)
### Fixed
- Fix issue in diagnostic yield for small gene panels
## 1.0.0-rc1 (2015-04-15)
### Fixed
- Changes label for gender prediction
## 0.0.13 (2015-04-13)
### Fixed
- Breaking bug in CLI when not setting gene panel
## 0.0.12 (2015-04-13)
### Added
- Add explanation of gender prediction in report
### Changed
- Handle extensions of intervals (splice sites) transparently in report
- Update text in report (eng + swe)
### Fixed
- Avoid error when not setting a gene panel + name in CLI
## 0.0.11 (2015-04-08)
### Changed
- Enable setting name of gene panel (PANEL_NAME) from command line
## 0.0.10 (2015-03-22)
### Fixed
- Remove duplicate call to ``configure_extensions``
## 0.0.9 (2015-03-21)
### Changed
- Keep scoped session chanjo api inside ``current_app`` object
## 0.0.8 (2015-03-21)
### Changed
- Change default log folder to ``/tmp/logs``
- Rename info log to more specific ``chanjo-report.info.log``
## 0.0.7 (2015-03-03)
### Changed
- Add a splash of color to HTML/PDF report (CSS only)
- Change name from ``HISTORY.md`` to ``CHANGELOG.md``
## 0.0.6 (2015-02-25)
### Fixed
- Incorrect template pointers in "package_data"
## 0.0.5 (2015-02-25)
### Fixed
- Namespace templates for "report" Blueprint under "report"
<file_sep># -*- coding: utf-8 -*-
import logging
from chanjo.store.models import Transcript, TranscriptStat, Sample
from flask import abort, Blueprint, render_template, request, url_for, session
from flask_weasyprint import render_pdf
from chanjo_report.server.extensions import api
from chanjo_report.server.constants import LEVELS
from .utils import (samplesex_rows, keymetrics_rows, transcripts_rows, map_samples,
transcript_coverage)
logger = logging.getLogger(__name__)
report_bp = Blueprint('report', __name__, template_folder='templates',
static_folder='static', static_url_path='/static/report')
@report_bp.route('/genes/<gene_id>')
def gene(gene_id):
"""Display coverage information on a gene."""
sample_ids = request.args.getlist('sample_id')
sample_dict = map_samples(sample_ids=sample_ids)
matching_tx = Transcript.filter_by(gene_id=gene_id).first()
if matching_tx is None:
return abort(404, "gene not found: {}".format(gene_id))
gene_name = matching_tx.gene_name
tx_groups = transcript_coverage(api, gene_id, *sample_ids)
link = request.args.get('link')
return render_template('report/gene.html', gene_id=gene_id,
gene_name=gene_name, link=link,
tx_groups=tx_groups, samples=sample_dict)
@report_bp.route('/genes', methods=['GET', 'POST'])
def genes():
"""Display an overview of genes that are (un)completely covered."""
skip = int(request.args.get('skip', 0))
limit = int(request.args.get('limit', 30))
exonlink = request.args.get('exonlink')
sample_ids = request.args.getlist('sample_id')
samples_q = Sample.filter(Sample.id.in_(sample_ids))
level = request.args.get('level', 10)
raw_gene_ids = request.args.get('gene_id') or request.form.get('gene_ids')
completeness_col = getattr(TranscriptStat, "completeness_{}".format(level))
query = (api.query(TranscriptStat)
.join(TranscriptStat.transcript)
.filter(completeness_col < 100)
.order_by(completeness_col))
gene_ids = raw_gene_ids.split(',') if raw_gene_ids else []
if raw_gene_ids:
query = query.filter(Transcript.gene_id.in_(gene_ids))
if sample_ids:
query = query.filter(TranscriptStat.sample_id.in_(sample_ids))
incomplete_left = query.offset(skip).limit(limit)
total = query.count()
has_next = total > skip + limit
return render_template('report/genes.html', incomplete=incomplete_left,
level=level, skip=skip, limit=limit,
has_next=has_next, gene_ids=gene_ids,
exonlink=exonlink, samples=samples_q,
sample_ids=sample_ids)
@report_bp.route('/report', methods=['GET', 'POST'])
def report():
"""Generate a coverage report for a group of samples."""
sample_ids = request.args.getlist('sample_id') or request.form.getlist('sample_id')
raw_gene_ids = (request.args.get('gene_ids') or request.form.get('gene_ids'))
if raw_gene_ids:
session['all_genes'] = raw_gene_ids
gene_ids = [int(gene_id.strip()) for gene_id in raw_gene_ids.split(',')]
else:
if request.method=='GET' and session.get('all_genes'):
gene_ids = [int(gene_id.strip()) for gene_id in session.get('all_genes').split(',')]
else:
gene_ids = []
level = int(request.args.get('level') or request.form.get('level') or 10)
extras = {
'panel_name': (request.args.get('panel_name') or request.form.get('panel_name')),
'level': level,
'gene_ids': gene_ids,
'show_genes': any([request.args.get('show_genes'), request.form.get('show_genes')]),
}
samples = Sample.query.filter(Sample.id.in_(sample_ids))
sex_rows = samplesex_rows(sample_ids)
metrics_rows = keymetrics_rows(sample_ids, genes=gene_ids)
tx_rows = transcripts_rows(sample_ids, genes=gene_ids, level=level)
return render_template('report/report.html', extras=extras,
samples=samples, sex_rows=sex_rows,
sample_ids=sample_ids, levels=LEVELS,
metrics_rows=metrics_rows, tx_rows=tx_rows)
@report_bp.route('/report/pdf', methods=['GET', 'POST'])
def pdf():
data_dict = request.form if request.method == 'POST' else request.args
# make a PDF from another view
response = render_pdf(url_for('report.report', **data_dict))
# check if the request is to download the file right away
if 'dl' in request.args:
fname = 'coverage-report.pdf'
header = "attachment; filename={}".format(fname)
response.headers['Content-Disposition'] = header
return response
|
97e49c04def98ce4d9a9980dfe447a3770545c6a
|
[
"Markdown",
"Python",
"Text"
] | 6 |
Text
|
Clinical-Genomics-Lund/chanjo-report
|
ef2fbea5d60c49f8a89fdec9331b3e8298fe9390
|
a2b8029663aae229cedd12bd9a1861b090c16097
|
refs/heads/master
|
<file_sep>var nameInput = document.getElementById("name1");
var submit= document.getElementById("submitbtn");
|
3b377ceec89276d133df5b21bff5a11aba56fa24
|
[
"JavaScript"
] | 1 |
JavaScript
|
sureshak/imad-2016-app
|
d464132384fe4c3b6ae1637f02b6c6c5b4c589d5
|
89c6f8d9580eecac77907e6ca75a4dac6b9a233b
|
refs/heads/master
|
<file_sep>var house = {
walls: 4,
windows: 12,
doors: 2,
roof: 1
}
console.log(house);
console.log(house.windows)
var steak = {
meat: "<NAME>",
grill: "Weber",
seasoning: "salt",
tools: "steak knife"
}
console.log(steak.tools)
steak.sauce="A1"
console.log (steak)
var Nina = new Object();
Nina.living = true;
Nina.age = 27;
Nina.gender = "female";
console.log(Nina);
// Nina is the name of the variable and is an object.
// Living, age and gender are properties of the object,
// and true, 27 and female are the values of those properties.
// var house = {}, and var Nina = new Object, are doing the
// same thing. Creating a new object.
Nina.getgender = function() {return Nina.gender;};
console.log(Nina.getgender());
console.log(Nina);
// Nina.getgender = ... creates a new property in the Nina object.
// This property is a function object with the purpose of operating
// on the Nina object.
var car = {
engine: 1,
seats: 4,
steeringWheel: 1,
brakes: 4,
}
console.log(car);
console.log(car.seats);
car.gloveBox= 1;
console.log(car);
car.checkEngine = function() {return car.engine;};
console.log(car.checkEngine());
function addNames(a,b) {
return a+b;
}
console.log(addNames);
addNames("luke", "Andrew");
console.log(addNames("luke", "Andrew"));
// The above was just trying to practice syntax a little.
var person = {
firstName: "David",
middleName: "Allen",
lastName: "Coe"
}
console.log(person.firstName);
person.createInitials = function() {
return this.firstName[0] + this.middleName[0] + this.lastName[0]
}
console.log(person.createInitials());
var arrayHere = [1,2,3,4,5]
console.log(arrayHere);
arrayHere = ["tim", "jim", "dan"]
console.log(arrayHere);
console.log(arrayHere.length);
console.log(arrayHere.join(""));
console.log("dollar");
console.log("dollar"[4]);
console.log("dollar"["l"]);
// I thougth that would isolate the "l's". Didn't work.
// Maybe you can only get the numaric value from
// a string in an array.
// I feel pretty lost on how and why these things work
// together.
|
c48e7dd12697ce0326f99df87d9e19135c4f3798
|
[
"JavaScript"
] | 1 |
JavaScript
|
luukeout/js-1
|
9992c18f7f0ae593b21a73ac4c5352afb6b5006e
|
e69ac8da2a7b236dcca9bdd50a1fc14c61d8c189
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\User;
use Facade\FlareClient\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class AuthController extends Controller
{
public function socialLogin(Request $request)
{
$socialUser = Socialite::driver('google')->stateless()->user();
if ($socialUser) {
$user = User::firstWhere('email', $socialUser->email);
if (!$user) {
$user = User::create([
'email' => $socialUser->email,
'name' => $socialUser->name,
'provider' => 'google',
'pictureUrl' => $socialUser->avatar,
]);
} else {
$user->email = $socialUser->email;
$user->name = $socialUser->name;
$user->pictureUrl = $socialUser->avatar;
$user->save();
}
}
Auth::login($user);
return response()->json($user);
}
public function logout() {
Auth::logout();
}
}
|
b931c35321cf342084ef5ce393393b2ff04ca9fa
|
[
"PHP"
] | 1 |
PHP
|
ghostspook/gauth2-backend
|
7f62ccd08bfb2279761c6fce1d313f51faf469c2
|
2f254b280c538c4485ebb1c997815d21d57a5c64
|
refs/heads/master
|
<file_sep>__version__ = '2023.1'<file_sep>click==6.7
demiurge==0.2
requests==2.31.0
<file_sep># -*- coding: utf-8 -*-
import codecs
import os
from setuptools import find_packages, setup
# metadata
NAME = 'fpt-cli'
DESCRIPTION = ('Estadísticas de la primera división del fútbol argentino '
'por línea de comandos.')
KEYWORDS = ['fútbol', 'argentina', 'resultados', 'estadísticas']
URL = 'https://github.com/el-ega/fpt-cli'
EMAIL = '<EMAIL>'
AUTHOR = '<NAME>'
LICENSE = 'MIT'
# deps
REQUIRED = [
'click>=5.0', 'demiurge>=0.2', 'requests>=2.7.0',
]
HERE = os.path.abspath(os.path.dirname(__file__))
# use README as the long-description
with codecs.open(os.path.join(HERE, 'README.rst'), "rb", "utf-8") as f:
long_description = f.read()
# load __version__.py module as a dictionary
about = {}
with open(os.path.join(HERE, 'fpt/__version__.py')) as f:
exec(f.read(), about)
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
keywords=KEYWORDS,
author=AUTHOR,
author_email=EMAIL,
url=URL,
packages=find_packages(exclude=('tests',)),
entry_points={
'console_scripts': ['fpt=fpt.main:main'],
},
install_requires=REQUIRED,
include_package_data=True,
license=LICENSE,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
],
zip_safe=False,
)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import click
from fpt import api
click.disable_unicode_literals_warning = True
def show_relegation():
"""Display relegation table."""
rows = api.get_relegation()
total = len(rows)
click.secho('Descenso', bold=True)
click.secho(
"%-3s %-25s %-5s %-3s %-10s" %
("POS", "EQUIPO", " PTS", " PJ", " PROMEDIO"))
for i, r in enumerate(rows, start=1):
team_str = ("{pos:<3} {row.team:<25} {row.pts:>5} "
"{row.p:>3} {row.average:>10}").format(pos=i, row=r)
color = 'blue'
if (total - 1) < i <= total:
# last one
color = 'red'
click.secho(team_str, fg=color)
click.echo()
click.secho('En zona de descenso', fg='red')
def show_standings():
"""Display standings table."""
rows = api.get_standings()
click.secho('Posiciones', bold=True)
click.secho(
"%-3s %-25s %-5s %-3s %-3s %-3s %-3s %-3s %-3s %-3s" %
("POS", "EQUIPO", " PTS",
" PJ", " PG", " PE", " PP",
" GF", " GC", " DG")
)
for i, r in enumerate(rows, start=1):
team_str = ("{pos:<3} {row.team:<25} {row.pts:>5} "
"{row.p:>3} {row.w:>3} {row.d:>3} {row.l:>3} "
"{row.f:>3} {row.a:>3} {row.gd:>3}").format(pos=i, row=r)
color = 'blue'
if i <= 3:
# libertadores
color = 'green'
elif 3 < i <= 9:
# sudamericana
color = 'yellow'
elif i == 28:
color = 'red'
click.secho(team_str, fg=color)
click.echo()
click.secho('En zona de clasificación a Copa Libertadores', fg='green')
click.secho('En zona de clasificación a Copa Sudamericana', fg='yellow')
click.secho('En zona de descenso', fg='red')
def _show_matches(matches, enum=False):
"""Display given matches."""
for i, m in enumerate(matches, start=1):
home_color = away_color = 'yellow'
if m.is_finished and m.home_goals > m.away_goals:
home_color = 'green'
away_color = 'red'
elif m.is_finished and m.home_goals < m.away_goals:
home_color = 'red'
away_color = 'green'
click.secho('%s ' % m.datetime.strftime('%a %d %b, %I:%M %p'),
nl=False, fg='cyan')
if enum:
click.secho(" Fecha %2d " % i, nl=False)
click.secho('%-25s %2s' % (m.home, m.home_goals), fg=home_color,
nl=False)
click.secho(" - ", nl=False)
click.secho('%2s %s' % (m.away_goals, m.away.rjust(25)),
fg=away_color, nl=not m.in_progress)
if m.in_progress:
click.secho(' (%s)' % m.status)
def show_in_progress():
"""Display matches in progress."""
matches = api.get_matches_in_progress()
if not matches:
click.echo('No hay partidos en juego.')
else:
click.secho('En juego', bold=True)
_show_matches(matches)
def show_team_matches(team):
"""Display matches for given team."""
matches = api.get_matches_for_team(team)
if not matches:
click.echo('No hay partidos para %s.' % team)
else:
click.secho('Fixture para %s' % team, bold=True)
_show_matches(matches, enum=True)
def show_round(n=None):
"""Display matches for given round (or current if n is None)."""
r = api.get_round(n=n)
if r is None:
click.echo('Fecha no válida.')
else:
click.secho(r.title, bold=True)
_show_matches(r.matches)
@click.command()
@click.option('-f', '--fecha-nro', default=None, metavar='<fecha número>',
help="Mostrar los partidos/resultados de la fecha dada.")
@click.option('-a', '--fecha-actual', is_flag=True,
help="Mostrar los partidos/resultados de la fecha actual.")
@click.option('-j', '--en-juego', is_flag=True,
help="Mostrar los partidos en juego.")
@click.option('-e', '--equipo', default=None, metavar='<nombre equipo>',
help="Mostrar los partidos/resultados del equipo dado.")
@click.option('-p', '--posiciones', is_flag=True,
help="Mostrar las posiciones del torneo.")
@click.option('-d', '--descenso', is_flag=True,
help="Mostrar la tabla del descenso.")
def main(fecha_nro, fecha_actual, en_juego, equipo, posiciones, descenso):
"""
Facilitame los Partidos del Torneo.
Estadísticas de la primera división del fútbol argentino.
"""
if fecha_nro:
try:
int(fecha_nro)
except ValueError:
click.echo('Fecha no válida.')
else:
show_round(n=fecha_nro)
return
if fecha_actual:
show_round()
return
if en_juego:
show_in_progress()
return
if equipo:
show_team_matches(equipo)
return
if posiciones:
show_standings()
return
if descenso:
show_relegation()
return
with click.Context(main) as ctx:
click.echo(main.get_help(ctx))
if __name__ == '__main__':
main()
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import itertools
from datetime import datetime
import demiurge
BASE_URL = ('http://staticmd1.lavozdelinterior.com.ar/sites/default/'
'files/Datafactory/html/v3/htmlCenter/data/deportes/'
'futbol/primeraa/pages/es/')
class Match(demiurge.Item):
home = demiurge.TextField(selector='div.local div.equipo')
away = demiurge.TextField(selector='div.visitante div.equipo')
home_goals = demiurge.TextField(selector='div.local div.resultado')
away_goals = demiurge.TextField(selector='div.visitante div.resultado')
status = demiurge.TextField(selector='div.detalles div.estado')
_date = demiurge.TextField(selector='div.detalles div.dia')
_time = demiurge.TextField(selector='div.detalles div.hora')
@property
def is_finished(self):
return self.status.lower() == 'finalizado'
@property
def in_progress(self):
return self.status.lower() in [
'1er tiempo', 'entretiempo', '2do tiempo']
@property
def datetime(self):
if self._time is None:
return None
if self._time.startswith('-'):
match_time = "00:00"
else:
match_time = self._time[:5]
date_and_time = "%s %s" % (self._date, match_time)
value = datetime.strptime(date_and_time, "%d-%m-%Y %H:%M")
return value
class Meta:
selector = 'div.mc-matchContainer'
encoding = 'utf-8'
class Round(demiurge.Item):
_css_class = demiurge.AttributeValueField(attr='class')
title = demiurge.TextField(selector='div.subHeader')
matches = demiurge.RelatedItem(Match)
class Meta:
selector = 'div.fase div.fecha'
encoding = 'utf-8'
base_url = BASE_URL + 'fixture.html'
@property
def is_current(self):
return 'show' in self._css_class
class StandingsRow(demiurge.Item):
team = demiurge.TextField(selector='td.team')
pts = demiurge.TextField(selector='td.puntos')
p = demiurge.TextField(selector='td.d-none:eq(0)')
w = demiurge.TextField(selector='td.d-none:eq(1)')
d = demiurge.TextField(selector='td.d-none:eq(2)')
l = demiurge.TextField(selector='td.d-none:eq(3)')
f = demiurge.TextField(selector='td.d-none:eq(4)')
a = demiurge.TextField(selector='td.d-none:eq(5)')
gd = demiurge.TextField(selector='td.d-none:eq(6)')
class Meta:
selector = 'tr.linea'
encoding = 'utf-8'
class Standings(demiurge.Item):
rows = demiurge.RelatedItem(StandingsRow)
class Meta:
selector = 'div.posiciones table.table'
encoding = 'utf-8'
base_url = BASE_URL + 'posiciones.html'
class RelegationRow(demiurge.Item):
team = demiurge.TextField(selector='td.team')
average = demiurge.TextField(selector='td.promediodescenso')
before1 = demiurge.TextField(selector='td.d-none:eq(0)')
before2 = demiurge.TextField(selector='td.d-none:eq(1)')
before3 = demiurge.TextField(selector='td.d-none:eq(2)')
current = demiurge.TextField(selector='td.puntosactual')
pts = demiurge.TextField(selector='td.puntosdescenso')
p = demiurge.TextField(selector='td.jugadosdescenso')
class Meta:
selector = 'tr.linea'
encoding = 'utf-8'
class Relegation(demiurge.Item):
rows = demiurge.RelatedItem(RelegationRow)
class Meta:
selector = 'div.descenso table.table'
encoding = 'utf-8'
base_url = BASE_URL + 'descenso.html'
# API methods
def get_standings():
"""Return tournament standings."""
standings = Standings.one()
return standings.rows
def get_relegation():
"""Return tournament relegation table."""
relegation = Relegation.one()
return relegation.rows
def get_round(n=None):
"""Return round n (or current if n is None)."""
round_n = None
fixture = Round.all()
for r in fixture:
if ((n is None and r.is_current) or
(n is not None and r.title == 'Fecha %s' % n)):
round_n = r
break
return round_n
def get_matches_in_progress():
"""Return matches in progress."""
fixture = Round.all()
matches = [m for m in itertools.chain(*(r.matches for r in fixture))
if m.in_progress]
return matches
def get_matches_for_team(team):
"""Return matches for given team."""
fixture = Round.all()
matches = [m for m in itertools.chain(*(r.matches for r in fixture))
if m.home == team or m.away == team]
return matches
<file_sep>FPT-cli
=======
*Facilitame los Partidos del Torneo*
Estadísticas de la primera división del fútbol argentino por línea de
comandos.
Instalación
===========
Usando ``pip``
~~~~~~~~~~~~~~
.. code:: bash
$ pip install fpt-cli
Desde el source
~~~~~~~~~~~~~~~
.. code:: bash
$ git clone https://github.com/el-ega/fpt-cli.git
$ cd fpt-cli
$ python setup.py install
Debería correr en Linux, Mac OS X, NetBSD, FreeBSD y Windows.
Cómo se usa?
============
Ver posiciones del torneo
~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: bash
$ fpt --posiciones
Ver tabla del descenso
~~~~~~~~~~~~~~~~~~~~~~
.. code:: bash
$ fpt --descenso
Ver fixture para un equipo particular
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: bash
$ fpt --equipo=Boca
Ver fecha actual
~~~~~~~~~~~~~~~~
.. code:: bash
$ fpt --fecha-actual
Ver resultados de partidos en juego
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: bash
$ fpt --en-juego
Ayuda
~~~~~
.. code:: bash
$ fpt --help
Licencia
========
Liberado bajo `MIT License`_
*Inspirado en https://github.com/architv/soccer-cli*
.. _MIT License: LICENSE
|
c4c54442421169fdcbe917a99c795c2085cd0cb2
|
[
"Python",
"Text",
"reStructuredText"
] | 6 |
Python
|
el-ega/fpt-cli
|
178efc09265cb409257372d65851225f4867b5db
|
9f132e6b768259a4bf4ca6c91c665f3cc40883fc
|
refs/heads/master
|
<file_sep>$(document).ready(function () {
if (localStorage['robot'] && localStorage['robot']!= 'undefined') {
console.log('voila');
var currentBot = JSON.parse( localStorage['robot'] );
var head = currentBot.parts[1];
var parts = JSON.parse(localStorage['robotParts']);
var heads = parts['heads'];
for (var i = 0; i < heads.length; i++ ){
if (heads[i].id == head) {
$('#robotHead').attr('src', 'images/robot/' + heads[i].url);
}
}
if (currentBot['name']!=$('#botName').html()) {
$('#botName').html(currentBot['name']);
}
}
});<file_sep>class RenameStateIdColumns < ActiveRecord::Migration
def self.up
rename_column :states, :state_before_id, :first_parent_state_id
rename_column :states, :state_after_id, :second_parent_state_id
end
def self.down
# rename back if you need or do something else or do nothing
end
end
<file_sep>$(document).ready(function(){
/*------------------------------------ Initialization */
robotParts = {
heads: [ { url: 'robot-head-silly.png', id: 1, position: 1, display:true},
{url: 'robot-head-blue.png', id:9, position:1, display:true},
{url: 'robot-head-dark.png', id:17, position:1, display:true }],
arms : [ { url: 'robot-arm-right.png', id: 2, position: 2, display:true},
{ url: 'robot-arm-left.png', id: 3, position: 4, display:true }],
bodies: [{ url: 'Robot-body-1.png', id: 4, position: 3, display:true},
{ url: 'Robot-body-2.png', id: 5, position: 3, display:true},
{ url: 'Robot-body-3.png', id: 11, position: 3, display:true}],
legs : [{ url: 'robot-legs-blue.png', id: 6, position: 5, display:true},
{url: 'robot-legs-hover.png', id:12, position:5, display:true},
{url: 'robot-legs-pink.png', id:13, position:5, display:true},
{url: 'robot-legs-plungers.png', id:14, position:5, display:true},
{url: 'robot-legs-springs.png', id:15, position:5, display:true},
{url: 'robot-legs-unicycle.png', id:16, position:5, display:true}],
extras : [{ url: 'tophat.png', id: 18, position: 6, display:true},
{ url: 'robot-accessories-chefHat.png', id: 8, position: 6, display:true} ]
};
defaultBot = {
parts: [1, 2, 3, 4, 6, 10],
name: "Chefbot"
};
localStorage['robot'] = localStorage['robot'] || JSON.stringify(defaultBot);
localStorage['robotParts'] = JSON.stringify(robotParts);
var currentBot = JSON.parse( localStorage['robot'] );
loadRobotParts(currentBot);
/*------------------------------------ Part switching interaction */
$('.bodypart').live("click", function() {
var position = $(this).data('position');
var target = $('#target-' + position);
target.data('id', $(this).data('id'));
target.attr('src', $(this).attr('src'));
target.show();
$('.pos-' + position).find('img').removeClass('highlighted');
$(this).addClass('highlighted');
});
$('#removeExtras').click(function() {
$('#target-6').hide();
$('#target-6').data('id', '');
});
/*------------------------------------ Saving bot */
$('#saveRobot').click(function() {
var newName = $('#nameInput').val().length >=1 ? $('#nameInput').val() : $('#userName').text();
var newBot = { name : newName, parts : [] };
$('.windowpart').each(function() {
newBot.parts.push($(this).data('id'));
});
localStorage['robot'] = JSON.stringify(newBot);
loadRobotParts(newBot);
$('#nameInput').val('');
$('#message').css('display', 'inline-block');
setTimeout( function() {
$('#message').hide() }, 1500);
return false;
});
});
//load the user's robot from localstorage and add all the body part options to the viewer
function loadRobotParts(currentBot) {
$('#userName').text(currentBot.name);
$('#partsViewer').find('img').remove();
for (partType in robotParts) {
$.each(robotParts[partType], function(index,val) {
var part = generatePart(val);
if (currentBot['parts'].indexOf(val.id) != -1) {
var targetPart = '#target-' + val.position;
$(targetPart).attr('src', part.attr('src'));
$(targetPart).data('id', part.data('id'));
$(targetPart).data('position', part.position);
part.addClass('highlighted');
}
if (val.display) {
$('.' + partType).prepend(part);
}
});
}
}
function generatePart(part) {
var el = $('<img src="images/robot/' + part.url + '" class="bodypart" data-id="'
+ part.id + '" data-position="' + part.position + '">');
return el;
}
<file_sep>class RenameRobotPartTypeColumn < ActiveRecord::Migration
def self.up
rename_column :robot_parts, :type, :part_type
end
def self.down
# rename back if you need or do something else or do nothing
end
end
<file_sep>class AddRobotIdColumnToUsers < ActiveRecord::Migration
def change
add_column :users, :robot_id, :integer
end
end
<file_sep>class ApplicationController < ActionController::Base
protect_from_forgery
def after_sign_in_path_for(resource)
case resource
when :user, User
recipebook_path
else
super
end
end
end
<file_sep>require 'test_helper'
class LevelDataItemsHelperTest < ActionView::TestCase
end
<file_sep># == Schema Information
#
# Table name: robots
#
# id :integer not null, primary key
# user_id :integer
# name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class Robot < ActiveRecord::Base
before_create :default_values
belongs_to :user
has_and_belongs_to_many :robot_parts
attr_accessible :name
def default_values
self.name ||= 'Chefbot'
[3,1,8,5,6].each do |id|
part = RobotPart.find(id)
self.robot_parts << part
end
end
end<file_sep>$(document).ready(function() {
//global data
levels = {
"Tutorial" : [
{ url : 'water.png', id : 1, type : 'ingredient', parents: [0,0]},
{ url : 'saucepan.png', id : 2, type : 'tool', parents: [0,0]},
{ url : 'cheese.png', id : 3, type : 'ingredient', parents: [0,0], last: true},
{ url: 'bowl.png', id : 4, type: 'tool', parents: [0,0]},
{ url : 'saucepan-withwater.png', id : 5, type : 'transition', parents: [1,2]},
{ url : 'saucepan-boiling.png', id: 6, type : 'transition', parents: [7, 5]},
{ url : 'heat.jpg', id : 7, type : 'transition', parents: [0,0]}
],
"Ramen" : [
{ url : 'water.png', id : 1, type : 'ingredient', parents: [0,0]},
{ url : 'ramen.png', id : 2, type : 'ingredient', parents: [0,0]},
{ url : 'saucepan.png', id : 3, type : 'tool', parents: [0,0]},
{ url : 'heat.jpg', id : 4, type : 'transition', parents: [0,0]},
{ url : 'saucepan-withwater.png', id: 5, type : 'transition', parents: [1, 3] },
{ url : 'saucepan-boiling.png', id: 6, type : 'transition', parents: [4, 5] },
{ url : 'saucepan-withramen.png', id: 7, type : 'transition', parents: [6, 2] },
{ url : 'bowl-withramen.png', id: 8, type: 'transition', parents: [7, 9], last: true},
{ url: 'bowl.png', id : 9, type: 'tool', parents: [0,0]}
],
"Pancakes" : [
{ url : 'pancakemix.png', id: 1, type: 'ingredient', parents: [0,0]},
{ url : 'mixingbowl.png', id: 2, type: 'tool', parents: [0,0]},
{ url: 'flourinbowl.png', id: 3, type:'transition', parents: [1,2]},
{ url: 'water.png', id: 4, type: 'ingredient', parents: [0,0]},
{ url: 'wetmix.png', id: 5, type:'transition', parents: [3,4]},
{ url: 'whisk.png', id: 14, type: 'tool', parents: [0,0]},
{ url: 'batter.png', id: 15, type: 'transition', parents: [5, 14]},
{ url: 'fryingpan.png', id: 6, type:'tool', parents: [0,0]},
{ url: 'butter.png', id: 7, type:'ingredient', parents: [0,0]},
{ url: 'fryingpanwithbutter.png', id: 8, type:'transition', parents: [6,7]},
{ url: 'heat.png', id: 9, type:'transition', parents: [0,0]},
{ url: 'hotskillet.png', id: 10, type:'transition', parents: [8,9]},
{ url: 'pancake-inpan.png', id: 11, type:'transition', parents: [10,15]},
{ url: 'spatula.png', id: 16, type:'tool', parents: [0,0]},
{ url: 'flippedpancake.png', id: 17, type:'transition', parents: [11,16]},
{ url: 'plate.png', id: 12, type:'tool', parents: [0,0]},
{ url: 'pancakeonplate.png', id: 13, type:'transition', parents: [17,12]},
{ url: 'syrup.png', id: 18, type:'ingredient', parents: [0,0]},
{ url: 'pancakestack.png', id: 19, type:'transition', parents: [20,7], last:true},
{ url: 'pancakesjustsyrup.png', id: 20, type:'transition', parents: [13,18]},
]
};
tutorialMessages = [
{title: "Stove", message: "Put the pot on the stove.", source: '2', location: 'burner'},
{title:"Combine", message: "Put the water in the pot.", source: '1', location: '2'},
{title: "Workspace", message: "Put the cheese in the workspace.", source: '3', location: "workSpace"},
{title: "Serve", message: "Serve the cheese!", source: '3', location: "botSpace"},
{title: "Tutorial Complete", message: "Great Job!" }];
states = [];
level = '';
zenMode = false;
tutorialStep = 0;
init();
//setup draggable and droppable items
$('.item').draggable({
helper: 'clone'
});
$('.item').droppable({
accepts : '.item',
greedy : true,
drop : function(event, ui) {
handleDrop(event,ui);
}
});
$('.dropbox').droppable({
accepts : '.item',
drop: function(event,ui) {
var id = $(ui.draggable).attr('id');
var numid = parseInt(stripClone(id));
var newPosX, newPosY = 0;
//find the correct position for the dropped element
if ( $(this).hasClass('burner') || $(this).attr('id') == 'oven') {
newPosX = ui.offset.left - $(this).parent().parent().offset().left;
newPosY = ui.offset.top - $(this).parent().parent().offset().top;
} else {
newPosX = ui.offset.left - $(this).offset().left;
newPosY
= ui.offset.top - $(this).offset().top;
}
//clone the element and append to the target droppable
var elem = ui.helper.clone()
.attr('id', (id) + "-clone")
.removeClass('ui-draggable-dragging')
.draggable({helper:'clone'})
.droppable({accepts: '.item', greedy: true, drop: handleDrop});
elem.css({
'position': 'absolute',
'left': newPosX,
'top' : newPosY
});
$(this).append(elem);
//special case for items dropped on stove, which automatically check for a match
if ($(this).hasClass('burner') || $(this).attr('id') == 'oven') {
var heatId = parseInt(lookupHeat());
for (var i =0; i < states.length; i++) {
if (states[i].parents.indexOf(numid) >= 0 && states[i].parents.indexOf(heatId) >= 0) {
$('#' + elem.attr('id')).attr(
{'src': 'images/items/' + states[i].url,
'id' : states[i].id + '-clone' });
}
}
}
//hide the original
if ( id.indexOf('clone') > 0) {
$('#' + id).hide();
}
//messy. normally we have only IDs to check, but for the stove we could drop on either one of the
//droppable burners, hence we use the class name instead
if (level == "Tutorial") {
var target = '';
if ($(this).attr('id')) {
target = $(this).attr('id');
} else {
target = $(this).attr('class').split(' ')[0];
}
handleTutorial(id, target);
}
}
});
// Restart button reloads the page
$("#restartButton").click(function(){
document.location.reload();
})
//the user can click to re-display the level card
$('#levelCard').click(function() {
$("#dialog2").dialog({width: 600, draggable:false});
$("#dialog2").dialog('option','title', 'Recipe');
$("#dialog2").append('<img src="' + $(this).attr('src') + '">');
$("#dialog2").dialog('open');
})
//when the serve button is clicked, check if the user has succesfully created the target item
$('#serve').click(function() {
var finalId = 0;
//find the final state in the list
for (var i = 0; i < states.length; i++ ){
if (states[i].last)
{
finalId = states[i].id;
}
}
// right now the user does not have to designate an item to serve.
// if the correct one is on the page it is served otherwise nothing is served
$('.item').each(function() {
if (parseInt(stripClone($(this).attr('id'))) == finalId) {
$('#overlordSpace').find('.item').remove();
$('#overlordSpace').find('img').first()
.attr('src', 'images/overlord/happy.png')
.after($(this).clone()
.css({'max-width':'100px', 'position': 'relative', 'top': 143 - $(this).height(), 'left': '20px'}))
.after($('<img src="images/items/table.png">')
.css({'width':'120px', 'position':'absolute', 'top': '190px'}));
updateDialog('You win!', 'Great job :) Click "Home" to go back to the recipe book.');
$('.ring').css('border', '2px solid #000');
if (!zenMode) {
$('#timer').countdown('pause');
}
return false;
}
//if nothing is served the overlord is angry
$('#overlordSpace').find('img').first()
.attr('src', 'images/overlord/angry.png');
setTimeout(function() {
$('#overlordSpace').find('img').first()
.attr('src', 'images/overlord/skeptical-smaller.png')
}, 1000);
});
});
});
function handleDrop(event, ui) {
var first = $(ui.draggable).attr('id');
var second = $(this).attr('id');
//check if there is a match with these two items
for (var i=0; i < states.length; i++) {
var intone = parseInt(stripClone(first));
var inttwo = parseInt(stripClone(second));
var locFirst = states[i].parents.indexOf(intone);
var locSecond = states[i].parents.indexOf(inttwo);
var newId = -1;
//if a is in the array and b is in the array and each item checked is unique
if (locFirst >= 0 && locSecond >= 0 && locFirst != locSecond) {
newId = states[i].id;
$('#' + second).attr({'src': 'images/items/' + states[i].url, 'id' : newId + '-clone'});
break;
}
}
if (level == "Tutorial") {
handleTutorial(stripClone(first), stripClone(second));
}
//special case for burner - items that change when heat is applied should automatically update after a delay
if ($(this).parent().hasClass('burner') || $(this).attr('id') == 'oven') {
var heatId = parseInt(lookupHeat());
for (var i =0; i < states.length; i++) {
if (states[i].parents.indexOf(newId) >= 0 && states[i].parents.indexOf(heatId) >= 0) {
setTimeout(function() {
$('#' + newId + '-clone').attr({'src': 'images/items/' + states[i].url, 'id' : states[i].id + '-clone'});
}, 500);
break;
}
}
}
}
function handleTutorial(source, target) {
if ( tutorialMessages[tutorialStep].source == source && tutorialMessages[tutorialStep].location == target ) {
updateDialog( tutorialMessages[tutorialStep+1].title, tutorialMessages[tutorialStep+1].message);
if (tutorialStep != tutorialMessages.length -1) {
tutorialStep++;
}
}
}
function stripClone(name) {
if (name.indexOf('-') >= 0) {
return name.split('-')[0];
}
return name;
}
function lookupHeat() {
for (var i = 0; i < states.length; i++) {
if (states[i].url.indexOf('heat') >= 0) {
return states[i].id;
}
}
}
function init() {
//pull data from url
hash = window.location.hash;
zenMode = window.location.search.split('=')[1] === 'false';
level = hash.substring(1,hash.length);
//setup level name and items
$('#recipeName').text(level);
states = levels[level];
$('#levelCard').attr('src', 'images/levelcards/' + level + '.png');
for (var i = 0; i < states.length; i++ ){
if (states[i].type == 'ingredient') {
$('#ingredients').append('<img class="item" src="' + 'images/items/' + states[i].url + '" id="' + states[i].id + '">');
}
if (states[i].type == 'tool') {
$('#tools').append('<img class="item" src="' + 'images/items/' + states[i].url + '" id="' + states[i].id + '">');
}
}
// initialize dialog
$('#dialog').dialog({
autoOpen: false,
hide: 'fold',
width: 300,
height:160,
resizable: false
});
$('#dialog').html('<p id="message">' + tutorialMessages[0].message + '</p>');
var closeButton = $('<span class="greenButton" style="width:40px;">OK</span>').bind("click", function() {
$('#dialog').dialog('close');
});
$('#dialog').append(closeButton);
if (level == 'Tutorial') {
$('#dialog').dialog('option', 'title', tutorialMessages[0].title);
$('#dialog').dialog('open');
}
//if it is zenmode, we do not have a timer, otherwise we do
if (!zenMode) {
$('#timer').countdown({
until: '+120',
format: 'MS',
description: 'Time Remaining',
onExpiry: function() {
updateDialog("Time's Up", "You ran out of time. The overlord is very displeased.");
}
});
}
//initialize robot
if (localStorage['robot'] && localStorage['robot'] != "undefined"
&& localStorage['robotParts'] && localStorage['robotParts'] != 'undefined') {
mybot = JSON.parse(localStorage['robot']);
parts = JSON.parse(localStorage['robotParts']);
robot = findUrls(parts,mybot);
$('#target-6').attr('src', robot[5]);
$('#target-1').attr('src', robot[0]);
$('#target-2').attr('src', robot[1]);
$('#target-3').attr('src', robot[3]);
$('#target-4').attr('src', robot[2]);
$('#target-5').attr('src', robot[4]);
}
}
function updateDialog(title, text) {
$('#dialog').dialog('option','title', title)
.find('#message').text(text);
$('#dialog').dialog('open');
}
function findUrls(arr, myBot) {
robotUrls = [];
for (partType in arr) {
for (var i = 0; i < arr[partType].length; i++) {
console.log(arr[partType][i]);
if (mybot.parts.indexOf(arr[partType][i].id) >= 0) {
var url = 'images/robot/' + arr[partType][i].url;
robotUrls.push(url);
hasPart = true;
}
}
}
return robotUrls;
}
<file_sep>require 'test_helper'
class LevelCategoriesHelperTest < ActionView::TestCase
end
<file_sep>require 'test_helper'
class RobotPartHelperTest < ActionView::TestCase
end
<file_sep>
$(document).ready(function() {
$( '#accordion' ).accordion({
collapsible: true,
heightStyle: "fill"
});
$( '#modalIntro' ).dialog({
modal: true,
width: '800px',
buttons: {
Play: function() {
$( this ).dialog( 'close' );
}
}
});
$('.item').css('z-index', 100)
$('.item').draggable({
helper: 'clone'
});
$('.item').droppable({
accepts : '.item',
greedy : true,
drop : handleDrop
});
$('.dropbox').droppable({
accepts : '.item',
drop: function(event,ui) {
console.log('dropped on stove');
var id = $(ui.draggable).attr('id');
if (id.indexOf('clone') < 0) {
var elem = ui.helper.clone()
.attr('id', id + "-clone")
.removeClass('ui-draggable-dragging')
.css({'left': 0, "z-index": 99})
.draggable()
.droppable({accepts: '.item', greedy: true, drop: handleDrop});
$(this).append(elem);
}
}
});
$('#serve').droppable({
accepts : 'item',
drop: function(event,ui) {
var creation = $(ui.draggable).attr('id');
var goal = $('#final_state').text();
if (creation == goal) {
alert('you won!');
}
else {
alert('not right :(');
}
}
});
function handleDrop(event, ui) {
var first = $(ui.draggable).attr('id');
var second = $(this).attr('id');
console.log(first + " " + second);
$.ajax({
url : '/states/combine',
data : { 'first': stripClone(first), 'second': stripClone(second) },
format : 'json',
success : function(data) {
if (data.length > 0) {
var src = data[0].image_url;
$('#' + first).remove();
$('#' + second).attr({'src': '/assets/' + data[0].image_url, 'id' : data[0].id});
}
}
});
}
$( "#stovecontrol" ).buttonset();
$( "#ovencontrol" ).buttonset();
$( ".controls").change(function() {
if ( $(this).children(':checked').val() == "on" ) {
var items = $(this).parent().find('.item');
if (items != "undefined" && items.length == 1) {
console.log('hi');
$.ajax({
url: '/states/heat',
data: { id : items.attr('id')},
format: 'json',
success: function(data) {
console.log('here');
setTimeout(function(data) {
$('.item').attr({'src': '/assets/' + data[0].image_url, 'id' : data[0].id});
}, 1000);
}
});
}
}
});
});
function stripClone(name) {
var index = name.indexOf('-');
if ( index >= 0 ) {
return name[0,index-1]
}
else {
return name
}
}
<file_sep># == Schema Information
#
# Table name: states
#
# id :integer not null, primary key
# name :string(255)
# image_url :string(255)
# position :integer
# state_category_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# first_parent_state_id :integer
# second_parent_state_id :integer
#
class State < ActiveRecord::Base
belongs_to :state_category
attr_accessible :name, :image_url, :position, :state_category_id, :first_parent_state_id,
:second_parent_state_id
validates :image_url, :presence => true
def transition?
self.state_category.name == "Transition"
end
end
<file_sep>class AddPositionColumnToRobotParts < ActiveRecord::Migration
def change
add_column :robot_parts, :position, :integer
end
end
<file_sep>class LevelCategoriesController < ApplicationController
# GET /level_categories
# GET /level_categories.json
def index
@level_categories = LevelCategory.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @level_categories }
end
end
# GET /level_categories/1
# GET /level_categories/1.json
def show
@level_category = LevelCategory.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @level_category }
end
end
# GET /level_categories/new
# GET /level_categories/new.json
def new
@level_category = LevelCategory.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @level_category }
end
end
# GET /level_categories/1/edit
def edit
@level_category = LevelCategory.find(params[:id])
end
# POST /level_categories
# POST /level_categories.json
def create
@level_category = LevelCategory.new(params[:level_category])
respond_to do |format|
if @level_category.save
format.html { redirect_to @level_category, notice: 'Level category was successfully created.' }
format.json { render json: @level_category, status: :created, location: @level_category }
else
format.html { render action: "new" }
format.json { render json: @level_category.errors, status: :unprocessable_entity }
end
end
end
# PUT /level_categories/1
# PUT /level_categories/1.json
def update
@level_category = LevelCategory.find(params[:id])
respond_to do |format|
if @level_category.update_attributes(params[:level_category])
format.html { redirect_to @level_category, notice: 'Level category was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @level_category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /level_categories/1
# DELETE /level_categories/1.json
def destroy
@level_category = LevelCategory.find(params[:id])
@level_category.destroy
respond_to do |format|
format.html { redirect_to level_categories_url }
format.json { head :no_content }
end
end
end
<file_sep>class RobotsRobotparts < ActiveRecord::Migration
def up
create_table "robot_parts_robots", :id => false do |t|
t.integer "robot_id"
t.integer "robot_part_id"
end
end
def down
end
end
<file_sep>class StatesController < ApplicationController
# GET /states
# GET /states.json
def index
@states = State.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @states }
end
end
# GET /states/1
# GET /states/1.json
def show
@state = State.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @state }
end
end
def combine
@combo = [params[:first], params[:second]]
@matching = State.where(:first_parent_state_id => @combo, :second_parent_state_id => @combo)
respond_to do |format|
format.json { render json: @matching}
end
end
def heat
@id = params[:id]
@heat = State.where(:name => "Heat")
@combo = [@id, @heat]
@matching = State.where(:first_parent_state_id => @id, :second_parent_state_id => @combo)
respond_to do |format|
format.json { render json: @matching}
end
end
# GET /states/new
# GET /states/new.json
def new
@state = State.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @state }
end
end
# GET /states/1/edit
def edit
@state = State.find(params[:id])
end
# POST /states
# POST /states.json
def create
@state = State.new(params[:state])
respond_to do |format|
if @state.save
format.html { redirect_to @state, notice: 'State was successfully created.' }
format.json { render json: @state, status: :created, location: @state }
else
format.html { render action: "new" }
format.json { render json: @state.errors, status: :unprocessable_entity }
end
end
end
# PUT /states/1
# PUT /states/1.json
def update
@state = State.find(params[:id])
respond_to do |format|
if @state.update_attributes(params[:state])
format.html { redirect_to @state, notice: 'State was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @state.errors, status: :unprocessable_entity }
end
end
end
# DELETE /states/1
# DELETE /states/1.json
def destroy
@state = State.find(params[:id])
@state.destroy
respond_to do |format|
format.html { redirect_to states_url }
format.json { head :no_content }
end
end
end
<file_sep>class LevelsController < ApplicationController
# Gets a list of all the levels in the game
# GET /levels
# GET /levels.json
def index
@levels = Level.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @levels }
end
end
# Recipe Book!
# GET /levels/recipebook
# GET /levels/1.json
def recipebook
@levels = Level.all
respond_to do |format|
format.html # recipebook.html.erb
format.json { render json: @levels }
end
end
# Get the game screen for a particular level.
# GET /game/id
def game
@level = Level.find(params[:id])
@items = []
@tools = []
State.all.each do |state|
if state.state_category.name == "Tools"
@tools << state
else
@items << state
end
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: @level }
end
end
# Create a new level. This will be used by administrators.
# GET /levels/new
# GET /levels/new.json
def new
@level = Level.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @level }
end
end
# Edit an existing level. This will be used by administrators.
# GET /levels/1/edit
def edit
@level = Level.find(params[:id])
end
# POST /levels
# POST /levels.json
def create
@level = Level.new(params[:level])
respond_to do |format|
if @level.save
format.html { redirect_to @level, notice: 'Level was successfully created.' }
format.json { render json: @level, status: :created, location: @level }
else
format.html { render action: "new" }
format.json { render json: @level.errors, status: :unprocessable_entity }
end
end
end
# PUT /levels/1
# PUT /levels/1.json
def update
@level = Level.find(params[:id])
respond_to do |format|
if @level.update_attributes(params[:level])
format.html { redirect_to @level, notice: 'Level was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @level.errors, status: :unprocessable_entity }
end
end
end
# DELETE /levels/1
# DELETE /levels/1.json
def destroy
@level = Level.find(params[:id])
@level.destroy
respond_to do |format|
format.html { redirect_to levels_url }
format.json { head :no_content }
end
end
end
<file_sep># == Schema Information
#
# Table name: levels
#
# id :integer not null, primary key
# name :string(255)
# final_state_id :integer
# description :string(255)
# level_category_id :string(255)
# time_limit :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Level < ActiveRecord::Base
attr_accessible :name, :description, :final_state_id, :time_limit, :level_category_id
belongs_to :level_category
end
<file_sep># == Schema Information
#
# Table name: robot_parts
#
# id :integer not null, primary key
# image_url :string(255)
# part_type :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# position :integer
#
class RobotPart < ActiveRecord::Base
attr_accessible :image_url, :part_type
has_and_belongs_to_many :robots
validates :image_url, :presence => true
def position
case (part_type)
when "head"
return 1
when "leftarm"
return 2
when "body"
return 3
when "rightarm"
return 4
when "legs"
return 5
end
end
end
<file_sep>class LevelDataItemsController < ApplicationController
before_filter :authenticate_user!
# return the level data list for the logged in user
# GET /level_data_items
# GET /level_data_items.json
def index
@level_data_items = LevelDataItem(:user_id => current_user)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @level_data_items }
end
end
# create a new level data item after a user finishes a level
# POST /level_data_items/create
def create
@level_data_item = LevelDataItem.new(params[:level_data_item])
respond_to do |format|
if @level_data_item
format.json { render json: @level_data_item, status: :created, location: @level_data_item }
else
format.json { render json: @level.errors, status: :unprocessable_entity }
end
end
end
# allow level data to be updated after the user replays the level
# PUT /level_data_items/1
# PUT /level_data_items/1.json
def update
@level_data_item = LevelDataItem.find(params[:id])
respond_to do |format|
if @level_data_item.update_attributes(params[:level_data_item])
format.json { head :no_content }
else
format.json { render json: @level_data_item.errors, status: :unprocessable_entity }
end
end
end
end
<file_sep>class AddStateBeforeColumnToStates < ActiveRecord::Migration
def change
add_column :states, :state_before_id, :integer
add_column :states, :state_after_id, :integer
end
end
<file_sep>class RobotsController < ApplicationController
before_filter :authenticate_user!
def edit
@robot = current_user.robot
@heads = RobotPart.where("part_type = ?", "head")
@torsos = RobotPart.where("part_type = ?", "body")
@arms = RobotPart.where("part_type = ? or part_type = ?", "leftarm", "rightarm")
@legs = RobotPart.where("part_type = ?", "legs")
end
# create a new robot for the logged in user
# POST /robots
def create
@robot = Robot.new(params[:robot])
@robot.user = current_user
respond_to do |format|
if @robot
format.json { render json: @robot, status: :created, location: @robot }
else
format.json { render json: @robot.errors, status: :unprocessable_entity }
end
end
end
# update the user's robot
# PUT /robots
def update
@robot = LevelDataItem.find(params[:id])
respond_to do |format|
if @robot.update_attributes(params[:robot])
format.json { head :no_content }
else
format.json { render json: @robot.errors, status: :unprocessable_entity }
end
end
end
# DELETE /robots/1
# DELETE /robots/1.json
def destroy
@robot = Robot.find(params[:id])
@robot.destroy
respond_to do |format|
format.html { redirect_to robot_url }
format.json { head :no_content }
end
end
end
<file_sep>$(function() {
$( "#tabs" ).tabs();
$('.bodypart').click(function() {
var position = $(this).data('position');
var target = $('#myrobot .' + position);
target.data('id', $(this).data('id'));
target.attr('src', $(this).attr('src'));
$('div .pos-' + position).find('img').removeClass('highlight');
$(this).addClass('highlight');
});
});
<file_sep>class RemovePositionColumnFromRobotParts < ActiveRecord::Migration
def up
def change
remove_column :robot_parts, :position
end
end
def down
end
end
<file_sep>$(document).ready(function() {
localStorage['user'] = localStorage['user'] || JSON.stringify({u : '', p : '', n : ''});
user = JSON.parse(localStorage['user']);
updatePageForSignin();
$( ".badgeText" ).popover({
placement: "top",
trigger: "hover"
});
$( ".accordion" ).accordion({
collapsible: true,
heightStyle: "fill",
});
$('#signInLink').click(function() {
$('#modalSignIn').modal('show');
return false;
});
$('#signOutLink').click(function() {
localStorage['user'] = "";
user.n, user.p, user.u = "";
updatePageForSignin();
return false;
});
$('#signInButton').click(function() {
var username = $('#inputEmail').val();
var pass = $('#inputPassword').val();
if (!username || !pass) {
$(this).after('<br>Please enter an email address and password.');
} else {
if (user.u != "" && (user.u && pass == user.p) ) {
$('#modalSignIn').modal('hide');
updatePageForSignin();
} else {
$(this).after('<br>Invalid user name or password.');
}
}
return false;
});
$('#registerButton').click(function() {
var username = $('#registerEmail').val();
var pass = $('#registerPassword').val();
var name = $('#registerName').val();
if (!username || !pass || !name) {
$(this).after('<="alert">Please fill out all fields.</span>');
} else {
user = {
u : username,
p : pass,
n : name
};
localStorage['user'] = JSON.stringify(user);
updatePageForSignin();
$('#modalSignIn').modal('hide');
}
return false;
});
});
function updatePageForSignin() {
if (user == "" || user == "undefined" || user.u == "" || user.p == "" || user.n == "") {
$('#profile').hide();
$('#profilePlaceholder').show();
$('#signOutLink').hide();
$('#signOutText').hide();
$('#signInLink').show();
return;
}
$('#profile').show();
$('#profilePlaceholder').hide();
console.log('here');
$('#signOutText').text('Signed in as ' + user.u + '.');
$('#signInLink').hide();
$('#signOutText').show();
$('#signOutLink').show();
console.log($('#signOutLink').is(":visible"));
}<file_sep><?php
/* Redirect browser */
header("Location: http://botsandpans.com/recipebook.html");
exit;
?>
<file_sep>botsnpans
=========<file_sep>class CreateLevels < ActiveRecord::Migration
def change
create_table :levels do |t|
t.string :name
t.integer :final_state_id
t.string :description
t.string :level_category_id
t.integer :time_limit
t.timestamps
end
end
end
<file_sep>class RobotPartsController < ApplicationController
before_filter :authenticate_user!
# Get all of the robot parts.
# GET /robot_parts
# GET /robot_parts.json
def index
@robot_parts = RobotPart.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @robot_parts }
end
end
# Create a new robot part. This will be used by administrators.
# GET /robot_parts/new
# GET /robot_parts/new.json
def new
@robot_part = RobotPart.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @robot_part }
end
end
# Edit an existing robot_part. This will be used by administrators.
# GET /robot_parts/1/edit
def edit
@robot_part = RobotPart.find(params[:id])
end
# Create new robot part
# POST /robot_parts
# POST /robot_parts.json
def create
@robot_part = RobotPart.new(params[:robot_part])
respond_to do |format|
if @robot_part.save
format.html { redirect_to robot_parts_path, notice: 'Part was successfully created.' }
format.json { render json: @robot_part, status: :created, location: @robot_part }
else
format.html { render action: "new" }
format.json { render json: @robot_part.errors, status: :unprocessable_entity }
end
end
end
# Update robot part
# PUT /robot_parts/1
# PUT /robot_parts/1.json
def update
@robot_part = RobotPart.find(params[:id])
respond_to do |format|
if @robot_part.update_attributes(params[:robot_part])
format.html { redirect_to robot_parts_path, notice: 'Part was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @robot_part.errors, status: :unprocessable_entity }
end
end
end
# Remove robot part
# DELETE /robot_parts/1
# DELETE /robot_parts/1.json
def destroy
@robot_part = RobotPart.find(params[:id])
@robot_part.destroy
respond_to do |format|
format.html { redirect_to robot_parts_path }
format.json { head :no_content }
end
end
end
<file_sep># == Schema Information
#
# Table name: level_data_items
#
# id :integer not null, primary key
# level_id :integer
# game_id :integer
# completed :boolean
# date_completed :datetime
# created_at :datetime not null
# updated_at :datetime not null
#
class LevelDataItem < ActiveRecord::Base
has_one :level
belongs_to :user
end
<file_sep>require 'test_helper'
class StateCategoriesHelperTest < ActionView::TestCase
end
<file_sep>class StateCategoriesController < ApplicationController
# GET /state_categories
# GET /state_categories.json
def index
@state_categories = StateCategory.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @state_categories }
end
end
# GET /state_categories/1
# GET /state_categories/1.json
def show
@state_category = StateCategory.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @state_category }
end
end
# GET /state_categories/new
# GET /state_categories/new.json
def new
@state_category = StateCategory.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @state_category }
end
end
# GET /state_categories/1/edit
def edit
@state_category = StateCategory.find(params[:id])
end
# POST /state_categories
# POST /state_categories.json
def create
@state_category = StateCategory.new(params[:state_category])
respond_to do |format|
if @state_category.save
format.html { redirect_to @state_category, notice: 'State category was successfully created.' }
format.json { render json: @state_category, status: :created, location: @state_category }
else
format.html { render action: "new" }
format.json { render json: @state_category.errors, status: :unprocessable_entity }
end
end
end
# PUT /state_categories/1
# PUT /state_categories/1.json
def update
@state_category = StateCategory.find(params[:id])
respond_to do |format|
if @state_category.update_attributes(params[:state_category])
format.html { redirect_to @state_category, notice: 'State category was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @state_category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /state_categories/1
# DELETE /state_categories/1.json
def destroy
@state_category = StateCategory.find(params[:id])
@state_category.destroy
respond_to do |format|
format.html { redirect_to state_categories_url }
format.json { head :no_content }
end
end
end
<file_sep>class UsersController < ApplicationController
before_filter :authenticate_user!, :verify_admin
# Administrators only
# GET /users/all
def all
@users = User.all
end
# GET /users/show
def show
@user = current_user
end
# DELETE /users/destroy/1
def destroy
User.find(params[:id]).destroy
redirect_to users_all_path
end
private
def verify_admin
unless current_user.admin?
flash[:error] = "You are not authorized to do this."
end
end
end
<file_sep>class CreateLevelDataItems < ActiveRecord::Migration
def change
create_table :level_data_items do |t|
t.integer :level_id
t.integer :game_id
t.boolean :completed
t.datetime :date_completed
t.timestamps
end
end
end
|
cb0f15a6006900eafcdd17e2e535d1c162e31d91
|
[
"JavaScript",
"Markdown",
"Ruby",
"PHP"
] | 35 |
JavaScript
|
morganwallace/botsnpans
|
9a13e92c583d01d9c96acd11a7d2cfd592f65add
|
510b959ccfd99c78818433e075920b02def5bfa1
|
refs/heads/master
|
<repo_name>macrouch/teamspeak-history<file_sep>/spec/fabricators/user_fabricator.rb
Fabricator(:user) do
name "User 1"
end<file_sep>/spec/models/user_spec.rb
require 'spec_helper'
describe User do
it "is valid with valid attributes" do
Fabricate(:user).should be_valid
end
it { should validate_presence_of :name }
it { should have_many :sessions }
end<file_sep>/spec/fabricators/session_fabricator.rb
Fabricator(:session) do
login 5.hours.ago
logout 1.hours.ago
idle 1800
end<file_sep>/app/controllers/users_controller.rb
require 'tzinfo'
class UsersController < ApplicationController
def index
@users = User.all.order("name")
@user = nil
@sessions = []
@session = nil
@channels = []
@month = params[:month] || 0
@user = User.find(params[:user_id]) if params[:user_id]
@sessions = Session.by_user_and_months_ago(@user, @month.to_i) if @user
@session = @user.sessions.where(id: params[:session_id]).first if params[:session_id]
@channels = @session.channels if @session
if cookies[:time_zone]
time_zone = TZInfo::Timezone.get(cookies[:time_zone])
current = time_zone.current_period
@offset = current.utc_total_offset
else
@offset = 0
end
end
def select_user
set_user
respond_to do |format|
format.js
end
end
def select_month
set_user
set_month
set_offset
respond_to do |format|
format.js
end
end
def select_session
set_user
set_month
set_session
respond_to do |format|
format.js
end
end
protected
def set_user
@user = User.find(params[:user_id]) if params[:user_id]
end
def set_month
@month = params[:month] || 0
@sessions = Session.by_user_and_months_ago(@user, @month.to_i) if @user
end
def set_session
@session = @user.sessions.where(id: params[:session_id]).first if params[:session_id]
@channels = @session.channels if @session
end
def set_offset
if cookies[:time_zone]
time_zone = TZInfo::Timezone.get(cookies[:time_zone])
current = time_zone.current_period
@offset = current.utc_total_offset
else
@offset = 0
end
end
end
<file_sep>/app/models/channel.rb
class Channel < ActiveRecord::Base
has_and_belongs_to_many :sessions
validates :name, presence: true
end
<file_sep>/spec/fabricators/channel_fabricator.rb
Fabricator(:channel) do
name "Room 1"
end<file_sep>/app/models/session.rb
class Session < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :channels
default_scope order('login DESC')
validates :login, :idle, presence: true
validate :unique_login_per_user
def closed?
logout != nil
end
def self.by_user_and_months_ago(user, month)
if user
user.sessions.where("login > ? AND login < ?", month.months.ago.beginning_of_month, month.months.ago.end_of_month)
else
[]
end
end
def idle_time
minutes, seconds = idle.divmod(60)
hours, minutes = minutes.divmod(60)
days, hours = hours.divmod(24)
"%dD %02d:%02d:%02d" %[days, hours, minutes, seconds]
end
def self.import
server_id = ENV["TS_SERVER_ID"]
doc = Nokogiri::HTML(open("http://www.tsviewer.com/index.php?page=userhistory&ID=#{server_id}&site=1&limit=1000"))
doc.css('ul.userlist li').each do |d| # each row in table
# Find the logout time
logout, logout_time = logout_from_css(d.css('div.uhist_list_time'))
# if they logged out more than a couple of days ago, don't do anything
if logout_time
# Find the user name
user = user_from_css(d.css('div.uhist_list_nick_reg strong').first)
# Find the channel name
channel = channel_from_css(d.css('div.uhist_list_channel'))
# Find the login time
login_time = login_from_css(d.css('div.uhist_list_nick_reg span'),
d.css('div.uhist_list_time_connect'),
logout_time)
# Find idle time in seconds "0D 00:41:24" -> 2484
idle = idle_from_css(d.css('div.uhist_list_nick_reg span'))
# Find the session, or create a new one
previous_session = user.sessions.order('login desc').first
session = nil
if previous_session
# if the previous session is the current session
# sometimes the seconds would be off from my conversions.
# the quick solution is don't compare seconds since I don't care about them
if previous_session.login.strftime('%Y-%m-%d %H:%M') == login_time.strftime('%Y-%m-%d %H:%M')
session = previous_session
else
# if previous session is not current session
# close previous session and start a new session
unless previous_session.closed?
previous_session.logout = login_time
previous_session.save
end
session = Session.new(login: login_time, user: user)
end
else # no previous sessions
session = Session.new(login: login_time, user: user)
end
session.idle = idle
# dont do anything if the session was already closed
if session.closed?
session.logout = logout_time
else
if logout.include?('online')
session.logout = nil
else
session.logout = logout_time
end
end
session.save
# add the channel to the session unless it is already there
session.channels << channel unless session.channels.include?(channel)
end # end unless logout
end # end userlist loop
end
def self.user_from_css(css)
# Saw a name like "cool name <-See Me". The '<' character messed everything up.
# Just in case we can split on 'Logintime:', and it will pull out only the actual name
name = css.content.split('Logintime:')[0].strip
User.find_or_create_by(name: name)
end
def self.channel_from_css(css)
channel_name = css.inner_text.gsub(/\P{ASCII}/, '').strip
Channel.find_or_create_by(name: channel_name)
end
def self.login_from_css(css, time_css, logout)
logout = logout.in_time_zone(1)
today = DateTime.now.in_time_zone(1) # in +0100 (Germany)(Where tsviewer is located)
login_time_ago = css.inner_text.split('Logintime: ')[1].split(',')[0]
logged_in_time = login_time_ago.split(' ')[1].split(':')
# login_days = logout.day - (logout - login_time_ago.split('D')[0].to_i.days).day
# login_hours = logged_in_time[0]
# login_minutes = logged_in_time[1]
login_seconds = (login_time_ago.split('D')[0].to_i * (86400)) +
(logged_in_time[0].to_i * 3600) +
(logged_in_time[1].to_i * 60) +
(logged_in_time[2].to_i)
login_days = logout.day - (logout - login_seconds.seconds).day
login = time_css.inner_text
time = login.split(' ')[1].split(':')
((today.day - logout.day).days.ago - login_days.days + (time[0].to_i - today.hour).hours +
(time[1].to_i - today.minute).minutes + (0 - today.second).seconds).in_time_zone
end
def self.logout_from_css(css)
today = DateTime.now.in_time_zone(1) # in +0100 (Germany)(Where tsviewer is located)
logout = css.inner_text.downcase
time = logout.split(' ')[1].split(':')
if logout.include?('online') || logout.include?('today')
[logout, (today + (time[0].to_i - today.hour).hours +
(time[1].to_i - today.minute).minutes + (0 - today.second).seconds).in_time_zone]
elsif logout.include?('yesterday')
[logout, (today - 1.day + (time[0].to_i - today.hour).hours +
(time[1].to_i - today.minute).minutes + (0 - today.second).seconds).in_time_zone]
else # if the session ended before 'yesterday', we don't care about it anymore
[logout, nil]
end
end
def self.idle_from_css(css)
idle = css.inner_text.split('Idletime: ')[1]
# number of days * 86400
# number of hours * 3600
# number of minutes * 60
time = idle.split(' ')[1].split(':')
idle = (idle.split('D')[0].to_i * (86400)) +
(time[0].to_i * 3600) +
(time[1].to_i * 60) +
(time[2].to_i)
end
def self.session_from_css(css)
end
protected
def unique_login_per_user
if user && user.sessions.where(login: login).size > 0 && new_record?
errors.add(:login, 'has to be unique per user')
end
end
end
<file_sep>/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file.
TeamspeakHistory::Application.config.session_store :cookie_store, key: '_teamspeak-history_session'
<file_sep>/app/helpers/users_helper.rb
module UsersHelper
def display_time(time)
(time + @offset).strftime("%m/%-d %H:%M")
end
end
<file_sep>/db/migrate/20130726010343_create_channels_sessions.rb
class CreateChannelsSessions < ActiveRecord::Migration
def change
create_table :channels_sessions, id: false do |t|
t.references :channel, null: false
t.references :session, null: false
end
end
end
<file_sep>/README.rdoc
== teamspeak-history
teamspeak-history is a small Ruby on Rails app that will build a database of a TeamSpeak server's user activity over time.
It will achieve this by parsing the information listed on http://www.tsviewer.com
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_many :sessions
validates :name, presence: true
end
<file_sep>/spec/models/session_spec.rb
require 'spec_helper'
describe Session do
def user_css(name)
Nokogiri::HTML("<strong>#{name}</strong>")
end
def channel_css(name)
Nokogiri::HTML("<div class='uhist_list_channel'><img src='http://static.tsviewer.com/images/teamspeak3/standard/16x16_channel_open.png' alt='' width='10' height='10'> #{name}</div>")
end
def login_css(total_time, time)
[Nokogiri::HTML("<span>Logintime: #{total_time}, Idletime: 0D 01:29:05</span>"),
Nokogiri::HTML("<div class='uhist_list_time_connect'><strong>Today</strong>, #{time}</div>")]
end
def logout_css(day, time)
Nokogiri::HTML("<div class='uhist_list_time'><strong><font color='#c80007'>#{day}</font></strong>, #{time}</div>")
end
def idle_css(time)
Nokogiri::HTML("<span>Logintime: 0D 00:29:38, Idletime: #{time}</span>")
end
it "is valid with valid attributes" do
Fabricate(:session).should be_valid
end
it { should validate_presence_of :login }
it { should validate_presence_of :idle }
it { should belong_to :user }
it "selects user correctly" do
user = Session.user_from_css(user_css("User 1"))
user.should be_valid
end
it "selects channel correctly" do
channel = Session.channel_from_css(channel_css("Channel 1"))
channel.should be_valid
end
it "converts idle time correctly" do
idle = Session.idle_from_css(idle_css("0D 00:41:24"))
idle.should eq(2484)
end
it "converts times correctly" do
time = DateTime.now.in_time_zone(1)
today = time.strftime("%Y-%m-%d")
yesterday = (time - 1.days).strftime("%Y-%m-%d")
two_days_ago = (time - 2.days).strftime("%Y-%m-%d")
three_days_ago = (time - 3.days).strftime("%Y-%m-%d")
four_days_ago = (time - 4.days).strftime("%Y-%m-%d")
logout = (time + (23 - time.hour).hours + (0 - time.minute).minutes + (0 - time.second).seconds).in_time_zone
css = login_css("0D 01:00:00", "22:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{today} 20:00:00 UTC")
css = login_css("1D 01:00:00", "22:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{yesterday} 20:00:00 UTC")
css = login_css("2D 01:00:00", "22:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{two_days_ago} 20:00:00 UTC")
css = login_css("3D 01:00:00", "22:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{three_days_ago} 20:00:00 UTC")
logout = (time + (2 - time.hour).hours + (0 - time.minute).minutes + (0 - time.second).seconds).in_time_zone
css = login_css("0D 01:00:00", "01:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{yesterday} 23:00:00 UTC")
css = login_css("1D 01:00:00", "01:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{two_days_ago} 23:00:00 UTC")
css = login_css("2D 01:00:00", "01:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{three_days_ago} 23:00:00 UTC")
css = login_css("3D 01:00:00", "01:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{four_days_ago} 23:00:00 UTC")
logout = (time + (2 - time.hour).hours + (0 - time.minute).minutes + (0 - time.second).seconds).in_time_zone
css = login_css("0D 01:00:00", "00:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{yesterday} 22:00:00 UTC")
css = login_css("1D 01:00:00", "00:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{two_days_ago} 22:00:00 UTC")
css = login_css("2D 01:00:00", "00:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{three_days_ago} 22:00:00 UTC")
css = login_css("3D 01:00:00", "00:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{four_days_ago} 22:00:00 UTC")
logout = (time + (2 - time.hour).hours + (0 - time.minute).minutes + (0 - time.second).seconds).in_time_zone
css = login_css("0D 03:00:00", "23:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{yesterday} 21:00:00 UTC")
css = login_css("1D 03:00:00", "23:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{two_days_ago} 21:00:00 UTC")
css = login_css("2D 03:00:00", "23:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{three_days_ago} 21:00:00 UTC")
css = login_css("3D 03:00:00", "23:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{four_days_ago} 21:00:00 UTC")
logout = (time + (3 - time.hour).hours + (0 - time.minute).minutes + (0 - time.second).seconds).in_time_zone
css = login_css("0D 01:00:00", "02:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{today} 00:00:00 UTC")
css = login_css("1D 01:00:00", "02:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{yesterday} 00:00:00 UTC")
css = login_css("2D 01:00:00", "02:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{two_days_ago} 00:00:00 UTC")
css = login_css("3D 01:00:00", "02:00")
login = Session.login_from_css(css[0], css[1], logout)
login.to_s.should eq("#{three_days_ago} 00:00:00 UTC")
end
it "converts logout correctly" do
time = DateTime.now.in_time_zone(1)
today = time.strftime("%Y-%m-%d")
tomorrow = (time + 1.day).strftime("%Y-%m-%d")
yesterday = (time - 1.days).strftime("%Y-%m-%d")
two_days_ago = (time - 2.days).strftime("%Y-%m-%d")
logout, logout_time = Session.logout_from_css(logout_css("ONLINE","23:00"))
logout_time.to_s.should eq("#{today} 21:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Today","23:00"))
logout_time.to_s.should eq("#{today} 21:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Yesterday","23:00"))
logout_time.to_s.should eq("#{yesterday} 21:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("ONLINE","00:00"))
logout_time.to_s.should eq("#{yesterday} 22:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Today","00:00"))
logout_time.to_s.should eq("#{yesterday} 22:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Yesterday","00:00"))
logout_time.to_s.should eq("#{two_days_ago} 22:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("ONLINE","00:30"))
logout_time.to_s.should eq("#{yesterday} 22:30:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Today","00:30"))
logout_time.to_s.should eq("#{yesterday} 22:30:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Yesterday","00:30"))
logout_time.to_s.should eq("#{two_days_ago} 22:30:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("ONLINE","01:00"))
logout_time.to_s.should eq("#{yesterday} 23:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Today","01:00"))
logout_time.to_s.should eq("#{yesterday} 23:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Yesterday","01:00"))
logout_time.to_s.should eq("#{two_days_ago} 23:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("ONLINE","02:00"))
logout_time.to_s.should eq("#{today} 00:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Today","02:00"))
logout_time.to_s.should eq("#{today} 00:00:00 UTC")
logout, logout_time = Session.logout_from_css(logout_css("Yesterday","02:00"))
logout_time.to_s.should eq("#{yesterday} 00:00:00 UTC")
end
it "should enforce unique logins per user" do
user = User.create(name: "User 1")
channel = Channel.create(name: "Channel 1")
time = DateTime.now.in_time_zone(1)
logout = (time + (7 - time.hour).hours + (12 - time.minute).minutes + (0 - time.second).seconds).in_time_zone
css = login_css("0D 01:00:00", "06:37")
login = Session.login_from_css(css[0], css[1], logout)
idle = 42
session = Session.create(user: user, login: login, logout: logout, idle: idle)
session.should be_valid
Session.count.should eq(1)
session2 = Session.create(user: user, login: login, logout: logout, idle: idle)
session2.should_not be_valid
session2.errors[:login].should include("has to be unique per user")
Session.count.should eq(1)
end
end<file_sep>/lib/tasks/tsviewer.rake
require 'nokogiri'
require 'open-uri'
namespace :ts do
task :import => :environment do
Session.import
end # end task :import
end # end namespace
<file_sep>/spec/models/channel_spec.rb
require 'spec_helper'
describe Channel do
it "is valid with valid attributes" do
Fabricate(:channel).should be_valid
end
it { should validate_presence_of :name }
end
|
a0738dc6091394c10d5941037ee4c8e2365ab37b
|
[
"RDoc",
"Ruby"
] | 15 |
Ruby
|
macrouch/teamspeak-history
|
e146648a60f0cd140f0f3d1bd7d1452220f9530d
|
8ffca9f078b009e7914f705a21079481d364d86e
|
refs/heads/master
|
<repo_name>slorello89/nexmo-xamarin-poc<file_sep>/NexmoXamarinTest/NexmoXamarinTest.Android/CallListener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Com.Nexmo.Client;
namespace NexmoXamarinTest.Droid
{
public class CallListener : Java.Lang.Object, INexmoIncomingCallListener
{
public void OnIncomingCall(NexmoCall p0)
{
p0.Answer(new CallDelegate());
}
}
}<file_sep>/NexmoXamarinIOS/NexmoClient.linkwith.cs
using ObjCRuntime;
[assembly: LinkWith("NexmoClient.a", SmartLink = true, ForceLoad = true)]<file_sep>/NexmoXamarinTest/NexmoXamarinTest.iOS/CallHandler.cs
using System;
using Foundation;
using NexmoXamarinIOS;
namespace NexmoXamarinTest.iOS
{
public class CallHandler : NXMClientDelegate, ICallHandler
{
private NXMCall _call;
public enum CallStatus
{
CallInitiated,
CallStatusCompleted,
CallStatusError,
CallStatusRejected
}
public CallStatus HandlerCallStatus { get; set; }
public CallHandler()
{
HandlerCallStatus = CallStatus.CallStatusCompleted;
}
public void Login(string jwt)
{
//if(NXMClient.Shared == null)
// NXMClient.Shared = new NXMClient();
NXMLogger.SetLogLevel(NXMLoggerLevel.Verbose);
var client = NXMClient.Shared;
client.SetDelegate(this);
client.LoginWithAuthToken(jwt);
}
public void StartCall(string name)
{
HandlerCallStatus = CallStatus.CallInitiated;
var client = NXMClient.Shared;
client.Call(name, NXMCallHandler.InApp, new Action<NSError, NXMCall>(((error, call) =>
{
if (error != null && error.Code != 0)
{
Console.WriteLine("error encountered " + error.Code);
}
else
{
_call = call;
_call.SetDelegate(new CallDelegate(this));
}
})));
}
public void EndCall()
{
if(_call != null)
_call.Hangup();
}
public override void DidChangeConnectionStatus(NXMClient client, NXMConnectionStatus status, NXMConnectionStatusReason reason)
{
Console.WriteLine("Connection Status Changed: " + status + " Reason: " + reason);
//do nothing for now
}
public override void DidReceiveError(NXMClient client, NSError error)
{
Console.WriteLine("Error received " + error.Code);
//do nothing for now
}
public override void DidReceiveCall(NXMClient client, NXMCall call)
{
call.Answer(OnComplete);
}
public void OnComplete(NSError error)
{
Console.WriteLine(error);
}
public void StartCallPstn()
{
HandlerCallStatus = CallStatus.CallInitiated;
var client = NXMClient.Shared;
client.Call("A Number", NXMCallHandler.Server, new Action<NSError, NXMCall>(((error, call) =>
{
if (error != null && error.Code != 0)
{
Console.WriteLine("error encountered " + error.Code);
}
else
{
_call = call;
_call.SetDelegate(new CallDelegate(this));
}
})));
}
}
}
<file_sep>/NexmoXamarinTest/NexmoXamarinTest.Android/NexmoClientHolder.cs
using System;
using Com.Nexmo.Client;
namespace NexmoXamarinTest.Droid
{
public class NexmoClientHolder
{
public static NexmoClient Client { get; set; }
}
}
<file_sep>/NexmoXamarinTest/NexmoXamarinTest/MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Net.Http;
using Newtonsoft.Json;
namespace NexmoXamarinTest
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
string _loggedInUser;
HttpClient _httpClient;
ICallHandler _handler;
public MainPage(ICallHandler handler)
{
InitializeComponent();
_httpClient = new HttpClient();
_handler = handler;
}
void OnLoginButtonClicked(object sender, EventArgs e)
{
var siteBase = "SITE_BASE";
var name = NameEntry.Text.ToLower();
_loggedInUser = name.ToLower();
//var strResult = _httpClient.GetAsync($"{siteBase}/token?name={name}").Result.Content.ReadAsStringAsync().Result;
//var token = JsonConvert.DeserializeObject<TokenRet>(strResult).Token;
var token = _httpClient.GetAsync($"{siteBase}/token?name={name}").Result.Content.ReadAsStringAsync().Result;
_handler.Login(token);
}
void OnCallButtonClicked(object sender, EventArgs e)
{
var callee = _loggedInUser == "steve" ? "joe" : "steve";
_handler.StartCall(callee);
}
void OnCallPstnButtonClicked(object sender, EventArgs e)
{
var callee = _loggedInUser == "steve" ? "joe" : "steve";
_handler.StartCallPstn();
}
public class TokenRet
{
[JsonProperty("token")]
public string Token { get; set; }
}
private void OnHangupButtonClicked(object sender, EventArgs e)
{
_handler.EndCall();
}
}
}
<file_sep>/NexmoXamarinTest/NexmoXamarinTest.Android/ConnectionListener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Com.Nexmo.Client.Request_listener;
namespace NexmoXamarinTest.Droid
{
public class ConnectionListener : Java.Lang.Object, INexmoConnectionListener
{
public void Dispose()
{
//throw new NotImplementedException();
}
public void OnConnectionStatusChange(NexmoConnectionListenerConnectionStatus p0, NexmoConnectionListenerConnectionStatusReason p1)
{
Console.WriteLine(p0.ToString() + " " + p1.ToString());
}
}
}<file_sep>/NexmoXamarinTest/NexmoXamarinTest.iOS/CallDelegate.cs
using Foundation;
using NexmoXamarinIOS;
namespace NexmoXamarinTest.iOS
{
public class CallDelegate : NXMCallDelegate
{
private CallHandler _handler;
// public NXMCall Call { get; set; }
public CallDelegate(CallHandler handler)
{
_handler = handler;
}
public override void DidUpdate(NXMCall call, NXMCallMember callMember, bool muted)
{
// throw new System.NotImplementedException();
}
public override void DidReceive(NXMCall call, NSError error)
{
// throw new System.NotImplementedException();
}
public override void DidUpdate(NXMCall call, NXMCallMember callMember, NXMCallMemberStatus status)
{
System.Console.WriteLine("Call status changed " + status);
if (status == NXMCallMemberStatus.Completed || status == NXMCallMemberStatus.Canceled)
{
_handler.HandlerCallStatus = CallHandler.CallStatus.CallStatusCompleted;
call?.Hangup();
call = null;
}
if (callMember.MemberId != call?.MyCallMember.MemberId &&
(status == NXMCallMemberStatus.Failed || status == NXMCallMemberStatus.Busy))
{
_handler.HandlerCallStatus = CallHandler.CallStatus.CallStatusError;
call?.Hangup();
call = null;
}
if (call?.MyCallMember.MemberId != callMember.MemberId && (status == NXMCallMemberStatus.Rejected))
{
_handler.HandlerCallStatus = CallHandler.CallStatus.CallStatusRejected;
call?.Hangup();
call = null;
}
}
}
}<file_sep>/NexmoXamarinTest/NexmoXamarinTest.Android/CallHandler.cs
using System;
using Com.Nexmo.Client;
using Com.Nexmo.Clientcore;
namespace NexmoXamarinTest.Droid
{
public class CallHandler : ICallHandler
{
public CallDelegate _Delegate = new CallDelegate();
public CallHandler()
{
}
public void EndCall()
{
_Delegate.HangUp();
}
public void Login(string jwt)
{
var factory = Retrofit2.Converter.Gson.GsonConverterFactory.Create();
//var client = NexmoClientHolder.Client;
NexmoClient.Get().Login(jwt);
NexmoClient.Get().AddIncomingCallListener(new CallListener());
//client.Login(jwt);
}
public void StartCall(string name)
{
NexmoClient.Get().Call(name, NexmoCallHandler.InApp, _Delegate);
}
public void StartCallPstn()
{
NexmoClient.Get().Call("A number", NexmoCallHandler.Server, _Delegate);
}
}
}
<file_sep>/NexmoXamarinIOS/StructsAndEnums.cs
using ObjCRuntime;
namespace NexmoXamarinIOS
{
[Native]
public enum NXMConnectionStatus : long
{
Disconnected,
Connecting,
Connected
}
[Native]
public enum NXMConnectionStatusReason : long
{
Unknown,
Login,
Logout,
TokenRefreshed,
TokenInvalid,
TokenExpired,
UserNotFound,
Terminated
}
[Native]
public enum NXMPushTemplate : long
{
Default,
Custom
}
[Native]
public enum NXMMemberUpdateType : long
{
State,
Media,
Leg
}
[Native]
public enum NXMMediaType : long
{
None = (0),
Audio = (1L << 0),
Video = (1L << 1)
}
[Native]
public enum NXMEventType : long
{
General,
Custom,
Text,
Image,
MessageStatus,
TextTyping,
Media,
Member,
Sip,
Dtmf,
LegStatus,
Unknown
}
[Native]
public enum NXMSipStatus : long
{
Ringing,
Answered,
Status,
Hangup
}
[Native]
public enum NXMMessageStatusType : long
{
None,
Seen,
Delivered,
Deleted
}
[Native]
public enum NXMTextTypingEventStatus : long
{
n,
ff
}
[Native]
public enum NXMMemberState : long
{
Invited,
Joined,
Left
}
[Native]
public enum NXMDirectionType : long
{
App,
Phone,
Sip,
Websocket,
Vbc,
Unknown
}
[Native]
public enum NXMMediaStreamType : long
{
None,
Send,
Receive,
SendReceive
}
[Native]
public enum NXMLegStatus : long
{
Ringing,
Started,
Answered,
Canceled,
Failed,
Busy,
Timeout,
Rejected,
Completed
}
[Native]
public enum NXMLegType : long
{
App,
Phone,
Unknown
}
[Native]
public enum NXMPageOrder : long
{
Asc,
Desc
}
[Native]
public enum NXMImageSize : long
{
Medium,
Original,
Thumbnail
}
[Native]
public enum NXMAttachmentType : long
{
NXMAttachmentTypeImage
}
[Native]
public enum NXMCallMemberStatus : long
{
Ringing,
Started,
Answered,
Canceled,
Failed,
Busy,
Timeout,
Rejected,
Completed
}
[Native]
public enum NXMCallHandler : long
{
InApp,
Server
}
[Native]
public enum NXMErrorCode : long
{
None,
Unknown,
SessionUnknown,
SessionInvalid,
SessionDisconnected,
MaxOpenedSessions,
TokenUnknown,
TokenInvalid,
TokenExpired,
MemberUnknown,
MemberNotFound,
MemberAlreadyRemoved,
NotAMemberOfTheConversation,
EventUnknown,
EventUserNotFound,
EventUserAlreadyJoined,
EventInvalid,
EventBadPermission,
EventNotFound,
EventsPageNotFound,
ConversationRetrievalFailed,
ConversationNotFound,
ConversationInvalidMember,
ConversationExpired,
ConversationsPageNotFound,
MediaNotSupported,
MediaNotFound,
InvalidMediaRequest,
MediaTooManyRequests,
MediaBadRequest,
MediaInternalError,
PushNotANexmoPush,
PushParsingFailed,
NotImplemented,
MissingDelegate,
PayloadTooBig,
SDKDisconnected,
UserNotFound,
DTMFIllegal
}
[Native]
public enum NXMLoggerLevel : long
{
None,
Error,
Debug,
Info,
Verbose
}
}
<file_sep>/NexmoXamarinTest/NexmoXamarinTest.Android/CallDelegate.cs
using System;
using Com.Nexmo.Client;
using Com.Nexmo.Client.Request_listener;
using Java.Interop;
namespace NexmoXamarinTest.Droid
{
public class CallDelegate : Java.Lang.Object, Com.Nexmo.Client.Request_listener.INexmoRequestListener
{
NexmoCall _call;
public CallDelegate()
{
}
//public JniManagedPeerStates JniManagedPeerState => this.JniManagedPeerState;
public void HangUp()
{
if (_call != null)
{
_call.Hangup(new CallDelegate());
}
}
public void Disposed()
{
//throw new NotImplementedException();
}
public void DisposeUnlessReferenced()
{
//throw new NotImplementedException();
}
public void Finalized()
{
//throw new NotImplementedException();
}
public void OnError(NexmoApiError p0)
{
Console.WriteLine("error encounterd " + p0.Message);
}
public void OnSuccess(Java.Lang.Object p0)
{
if (p0 is NexmoCall)
{
_call = (NexmoCall)p0;
}
}
public void SetJniIdentityHashCode(int value)
{
//throw new NotImplementedException();
}
public void SetJniManagedPeerState(JniManagedPeerStates value)
{
//throw new NotImplementedException();
}
public void SetPeerReference(JniObjectReference reference)
{
//throw new NotImplementedException();
}
public void UnregisterFromRuntime()
{
//throw new NotImplementedException();
}
}
}
<file_sep>/NexmoXamarinTest/NexmoXamarinTest/ICallHandler.cs
using System;
namespace NexmoXamarinTest
{
public interface ICallHandler
{
void Login(string jwt);
void StartCall(string name);
void StartCallPstn();
void EndCall();
}
}
<file_sep>/NexmoXamarinIOS/ApiDefinition.cs
using System;
using Foundation;
//using NexmoClient;
using ObjCRuntime;
namespace NexmoXamarinIOS
{
[Static]
partial interface Constants
{
// extern double NexmoClientVersionNumber;
[Field("NexmoClientVersionNumber", "__Internal")]
double NexmoClientVersionNumber { get; }
// extern const unsigned char [] NexmoClientVersionString;
[Field("NexmoClientVersionString", "__Internal")]
IntPtr NexmoClientVersionString { get; }
// extern NSString *const _Nonnull NXMErrorDomain;
[Field("NXMErrorDomain", "__Internal")]
NSString NXMErrorDomain { get; }
}
// @interface NXMUser : NSObject
[BaseType(typeof(NSObject))]
interface NXMUser
{
// @property (copy, nonatomic) NSString * _Nonnull uuid;
[Export("uuid")]
string Uuid { get; set; }
// @property (copy, nonatomic) NSString * _Nonnull name;
[Export("name")]
string Name { get; set; }
// @property (copy, nonatomic) NSString * _Nonnull displayName;
[Export("displayName")]
string DisplayName { get; set; }
}
// @protocol NXMClientDelegate <NSObject>
[Protocol, Model(AutoGeneratedName = true)]
[BaseType(typeof(NSObject))]
interface NXMClientDelegate
{
// @required -(void)client:(NXMClient * _Nonnull)client didChangeConnectionStatus:(NXMConnectionStatus)status reason:(NXMConnectionStatusReason)reason;
[Abstract]
[Export("client:didChangeConnectionStatus:reason:")]
void DidChangeConnectionStatus(NXMClient client, NXMConnectionStatus status, NXMConnectionStatusReason reason);
// @required -(void)client:(NXMClient * _Nonnull)client didReceiveError:(NSError * _Nonnull)error;
[Abstract]
[Export("client:didReceiveError:")]
void DidReceiveError(NXMClient client, NSError error);
// @optional -(void)client:(NXMClient * _Nonnull)client didReceiveCall:(NXMCall * _Nonnull)call;
[Export("client:didReceiveCall:")]
void DidReceiveCall(NXMClient client, NXMCall call);
// @optional -(void)client:(NXMClient * _Nonnull)client didReceiveConversation:(NXMConversation * _Nonnull)conversation;
[Export("client:didReceiveConversation:")]
void DidReceiveConversation(NXMClient client, NXMConversation conversation);
}
// @interface NXMMediaSettings : NSObject
[BaseType(typeof(NSObject))]
interface NXMMediaSettings
{
// @property (readonly, nonatomic) _Bool isEnabled;
[Export("isEnabled")]
bool IsEnabled { get; }
// @property (readonly, nonatomic) _Bool isSuspended;
[Export("isSuspended")]
bool IsSuspended { get; }
}
// @interface NXMLeg : NSObject
[BaseType(typeof(NSObject))]
interface NXMLeg : INativeObject
{
// @property (copy, nonatomic) NSString * _Nonnull uuid;
[Export("uuid")]
string Uuid { get; set; }
// @property (assign, nonatomic) NXMLegType type;
[Export("type", ArgumentSemantic.Assign)]
NXMLegType Type { get; set; }
// @property (assign, nonatomic) NXMLegStatus status;
[Export("status", ArgumentSemantic.Assign)]
NXMLegStatus Status { get; set; }
// @property (copy, nonatomic) NSString * _Nullable conversationUuid;
[NullAllowed, Export("conversationUuid")]
string ConversationUuid { get; set; }
// @property (copy, nonatomic) NSString * _Nullable memberUUid;
[NullAllowed, Export("memberUUid")]
string MemberUUid { get; set; }
// @property (copy, nonatomic) NSDate * _Nullable date;
[NullAllowed, Export("date", ArgumentSemantic.Copy)]
NSDate Date { get; set; }
}
// @interface NXMDirection : NSObject
[BaseType(typeof(NSObject))]
interface NXMDirection
{
// @property (assign, nonatomic) NXMDirectionType type;
[Export("type", ArgumentSemantic.Assign)]
NXMDirectionType Type { get; set; }
// @property (copy, nonatomic) NSString * _Nullable data;
[NullAllowed, Export("data")]
string Data { get; set; }
}
// @interface NXMChannel : NSObject
[BaseType(typeof(NSObject))]
interface NXMChannel
{
// @property (readonly, nonatomic) NXMDirection * _Nonnull from;
[Export("from")]
NXMDirection From { get; }
// @property (readonly, nonatomic) NXMDirection * _Nullable to;
[NullAllowed, Export("to")]
NXMDirection To { get; }
// @property (readonly, nonatomic) NXMLeg * _Nullable leg;
[NullAllowed, Export("leg")]
NXMLeg Leg { get; }
}
// @interface NXMInitiator : NSObject
[BaseType(typeof(NSObject))]
interface NXMInitiator
{
// @property (readonly, nonatomic) BOOL isSystem;
[Export("isSystem")]
bool IsSystem { get; }
// @property (copy, nonatomic) NSString * _Nullable userId;
[NullAllowed, Export("userId")]
string UserId { get; set; }
// @property (copy, nonatomic) NSString * _Nullable memberId;
[NullAllowed, Export("memberId")]
string MemberId { get; set; }
// @property (copy, nonatomic) NSDate * _Nonnull time;
[Export("time", ArgumentSemantic.Copy)]
NSDate Time { get; set; }
}
// @interface NXMMember : NSObject
[BaseType(typeof(NSObject))]
interface NXMMember
{
// @property (copy, nonatomic) NSString * _Nonnull conversationUuid;
[Export("conversationUuid")]
string ConversationUuid { get; set; }
// @property (copy, nonatomic) NSString * _Nonnull memberUuid;
[Export("memberUuid")]
string MemberUuid { get; set; }
// @property (readonly, nonatomic) NXMUser * _Nonnull user;
[Export("user")]
NXMUser User { get; }
// @property (readonly, nonatomic) NXMMemberState state;
[Export("state")]
NXMMemberState State { get; }
// @property (readonly, nonatomic) NXMMediaSettings * _Nullable media;
[NullAllowed, Export("media")]
NXMMediaSettings Media { get; }
// @property (readonly, nonatomic) NXMChannel * _Nullable channel;
[NullAllowed, Export("channel")]
NXMChannel Channel { get; }
}
// @interface NXMEvent : NSObject
[BaseType(typeof(NSObject))]
interface NXMEvent
{
// @property (copy, nonatomic) NSString * _Nonnull conversationUuid;
[Export("conversationUuid")]
string ConversationUuid { get; set; }
// @property (readonly, nonatomic) NXMMember * _Nullable fromMember;
[NullAllowed, Export("fromMember")]
NXMMember FromMember { get; }
// @property (copy, nonatomic) NSDate * _Nonnull creationDate;
[Export("creationDate", ArgumentSemantic.Copy)]
NSDate CreationDate { get; set; }
// @property (copy, nonatomic) NSDate * _Nullable deletionDate;
[NullAllowed, Export("deletionDate", ArgumentSemantic.Copy)]
NSDate DeletionDate { get; set; }
// @property (readonly, nonatomic) NXMEventType type;
[Export("type")]
NXMEventType Type { get; }
// @property (readonly, nonatomic) NSInteger uuid;
[Export("uuid")]
nint Uuid { get; }
}
// @interface NXMMessageEvent : NXMEvent
[BaseType(typeof(NXMEvent))]
interface NXMMessageEvent
{
// @property (readonly, nonatomic) NSDictionary<NSNumber *,NSDictionary<NSString *,NSDate *> *> * _Nonnull state;
[Export("state")]
NSDictionary<NSNumber, NSDictionary<NSString, NSDate>> State { get; }
}
// @interface NXMTextEvent : NXMMessageEvent
[BaseType(typeof(NXMMessageEvent))]
interface NXMTextEvent
{
// @property (readonly, nonatomic) NSString * _Nullable text;
[NullAllowed, Export("text")]
string Text { get; }
}
// @interface NXMTextTypingEvent : NXMEvent
[BaseType(typeof(NXMEvent))]
interface NXMTextTypingEvent
{
// @property (readonly, nonatomic) NXMTextTypingEventStatus status;
[Export("status")]
NXMTextTypingEventStatus Status { get; }
}
// @interface NXMImageInfo : NSObject
[BaseType(typeof(NSObject))]
interface NXMImageInfo
{
// @property (readonly, nonatomic) NSString * _Nonnull imageUuid;
[Export("imageUuid")]
string ImageUuid { get; }
// @property (readonly, nonatomic) NSURL * _Nonnull url;
[Export("url")]
NSUrl Url { get; }
// @property (readonly) NSInteger sizeInBytes;
[Export("sizeInBytes")]
nint SizeInBytes { get; }
// @property (readonly) NXMImageSize size;
[Export("size")]
NXMImageSize Size { get; }
}
// @interface NXMImageEvent : NXMMessageEvent
[BaseType(typeof(NXMMessageEvent))]
interface NXMImageEvent
{
// @property (readonly, nonatomic) NSString * _Nonnull imageUuid;
[Export("imageUuid")]
string ImageUuid { get; }
// @property (readonly, nonatomic) NXMImageInfo * _Nonnull mediumImage;
[Export("mediumImage")]
NXMImageInfo MediumImage { get; }
// @property (readonly, nonatomic) NXMImageInfo * _Nonnull originalImage;
[Export("originalImage")]
NXMImageInfo OriginalImage { get; }
// @property (readonly, nonatomic) NXMImageInfo * _Nonnull thumbnailImage;
[Export("thumbnailImage")]
NXMImageInfo ThumbnailImage { get; }
}
// @interface NXMMessageStatusEvent : NXMEvent
[BaseType(typeof(NXMEvent))]
interface NXMMessageStatusEvent
{
// @property (readonly, nonatomic) NSInteger referenceEventUuid;
[Export("referenceEventUuid")]
nint ReferenceEventUuid { get; }
// @property (readonly, nonatomic) NXMMessageStatusType status;
[Export("status")]
NXMMessageStatusType Status { get; }
}
// @interface NXMMemberEvent : NXMEvent
[BaseType(typeof(NXMEvent))]
interface NXMMemberEvent
{
// @property (readonly, nonatomic) NXMMember * _Nonnull member;
[Export("member")]
NXMMember Member { get; }
// @property (nonatomic) NXMMemberState state;
[Export("state", ArgumentSemantic.Assign)]
NXMMemberState State { get; set; }
// @property (readonly, nonatomic) NXMMediaSettings * _Nullable media;
[NullAllowed, Export("media")]
NXMMediaSettings Media { get; }
// @property (readonly, nonatomic) NXMChannel * _Nullable channel;
[NullAllowed, Export("channel")]
NXMChannel Channel { get; }
// @property (copy, nonatomic) NSString * _Nullable knockingId;
[NullAllowed, Export("knockingId")]
string KnockingId { get; set; }
}
// @interface NXMMediaEvent : NXMEvent
[BaseType(typeof(NXMEvent))]
interface NXMMediaEvent
{
// @property (readonly, nonatomic) _Bool isEnabled;
[Export("isEnabled")]
bool IsEnabled { get; }
// @property (readonly, nonatomic) _Bool isSuspended;
[Export("isSuspended")]
bool IsSuspended { get; }
}
// @interface NXMDTMFEvent : NXMEvent
[BaseType(typeof(NXMEvent))]
interface NXMDTMFEvent
{
// @property (readonly, copy, nonatomic) NSString * _Nullable digit;
[NullAllowed, Export("digit")]
string Digit { get; }
// @property (readonly, copy, nonatomic) NSNumber * _Nullable duration;
[NullAllowed, Export("duration", ArgumentSemantic.Copy)]
NSNumber Duration { get; }
}
// @interface NXMLegStatusEvent : NXMEvent
[BaseType(typeof(NXMEvent))]
interface NXMLegStatusEvent
{
// @property (readonly, nonatomic) NSMutableArray<NXMLeg *> * _Nonnull history;
[Export("history")]
NSMutableArray<NXMLeg> History { get; }
// @property (readonly, nonatomic) NXMLeg * _Nonnull current;
[Export("current")]
NXMLeg Current { get; }
}
// @interface NXMCustomEvent : NXMEvent
[BaseType(typeof(NXMEvent))]
interface NXMCustomEvent
{
// @property (copy, nonatomic) NSString * _Nullable customType;
[NullAllowed, Export("customType")]
string CustomType { get; set; }
// @property (readonly, nonatomic) NSString * _Nullable data;
[NullAllowed, Export("data")]
string Data { get; }
}
// @protocol NXMConversationUpdateDelegate <NSObject>
[Protocol, Model(AutoGeneratedName = true)]
[BaseType(typeof(NSObject))]
interface NXMConversationUpdateDelegate
{
// @required -(void)conversation:(NXMConversation * _Nonnull)conversation didUpdateMember:(NXMMember * _Nonnull)member withType:(NXMMemberUpdateType)type;
[Abstract]
[Export("conversation:didUpdateMember:withType:")]
void DidUpdateMember(NXMConversation conversation, NXMMember member, NXMMemberUpdateType type);
}
// @protocol NXMConversationDelegate <NSObject>
[Protocol, Model(AutoGeneratedName = true)]
[BaseType(typeof(NSObject))]
interface NXMConversationDelegate
{
// @required -(void)conversation:(NXMConversation * _Nonnull)conversation didReceive:(NSError * _Nonnull)error;
[Abstract]
[Export("conversation:didReceive:")]
void DidReceive(NXMConversation conversation, NSError error);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveCustomEvent:(NXMCustomEvent * _Nonnull)event;
[Export("conversation:didReceiveCustomEvent:")]
void DidReceiveCustomEvent(NXMConversation conversation, NXMCustomEvent @event);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveTextEvent:(NXMTextEvent * _Nonnull)event;
[Export("conversation:didReceiveTextEvent:")]
void DidReceiveTextEvent(NXMConversation conversation, NXMTextEvent @event);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveImageEvent:(NXMImageEvent * _Nonnull)event;
[Export("conversation:didReceiveImageEvent:")]
void DidReceiveImageEvent(NXMConversation conversation, NXMImageEvent @event);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveMessageStatusEvent:(NXMMessageStatusEvent * _Nonnull)event;
[Export("conversation:didReceiveMessageStatusEvent:")]
void DidReceiveMessageStatusEvent(NXMConversation conversation, NXMMessageStatusEvent @event);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveTypingEvent:(NXMTextTypingEvent * _Nonnull)event;
[Export("conversation:didReceiveTypingEvent:")]
void DidReceiveTypingEvent(NXMConversation conversation, NXMTextTypingEvent @event);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveMemberEvent:(NXMMemberEvent * _Nonnull)event;
[Export("conversation:didReceiveMemberEvent:")]
void DidReceiveMemberEvent(NXMConversation conversation, NXMMemberEvent @event);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveLegStatusEvent:(NXMLegStatusEvent * _Nonnull)event;
[Export("conversation:didReceiveLegStatusEvent:")]
void DidReceiveLegStatusEvent(NXMConversation conversation, NXMLegStatusEvent @event);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveMediaEvent:(NXMMediaEvent * _Nonnull)event;
[Export("conversation:didReceiveMediaEvent:")]
void DidReceiveMediaEvent(NXMConversation conversation, NXMMediaEvent @event);
// @optional -(void)conversation:(NXMConversation * _Nonnull)conversation didReceiveDTMFEvent:(NXMDTMFEvent * _Nonnull)event;
[Export("conversation:didReceiveDTMFEvent:")]
void DidReceiveDTMFEvent(NXMConversation conversation, NXMDTMFEvent @event);
}
// @interface NXMPage : NSObject
[BaseType(typeof(NSObject))]
interface NXMPage
{
// @property (readonly, assign, nonatomic) NSUInteger size;
[Export("size")]
nuint Size { get; }
// @property (readonly, assign, nonatomic) NXMPageOrder order;
[Export("order", ArgumentSemantic.Assign)]
NXMPageOrder Order { get; }
// -(BOOL)hasNextPage;
[Export("hasNextPage")]
bool HasNextPage { get; }
// -(BOOL)hasPreviousPage;
[Export("hasPreviousPage")]
bool HasPreviousPage { get; }
}
// @interface NXMEventsPage : NXMPage
[BaseType(typeof(NXMPage))]
interface NXMEventsPage
{
// @property (readonly, nonatomic) NSArray<NXMEvent *> * _Nonnull events;
[Export("events")]
NXMEvent[] Events { get; }
// -(void)nextPage:(void (^ _Nonnull)(NSError * _Nullable, NXMEventsPage * _Nullable))completionHandler;
[Export("nextPage:")]
void NextPage(Action<NSError, NXMEventsPage> completionHandler);
// -(void)previousPage:(void (^ _Nonnull)(NSError * _Nullable, NXMEventsPage * _Nullable))completionHandler;
[Export("previousPage:")]
void PreviousPage(Action<NSError, NXMEventsPage> completionHandler);
}
// @interface NXMConversation : NSObject
[BaseType(typeof(NSObject))]
interface NXMConversation
{
// @property (readonly, nonatomic) NSString * _Nonnull uuid;
[Export("uuid")]
string Uuid { get; }
// @property (readonly, nonatomic) NSString * _Nonnull name;
[Export("name")]
string Name { get; }
// @property (readonly, nonatomic) NSString * _Nullable displayName;
[NullAllowed, Export("displayName")]
string DisplayName { get; }
// @property (readonly, nonatomic) NSInteger lastEventId;
[Export("lastEventId")]
nint LastEventId { get; }
// @property (readonly, nonatomic) NSDate * _Nonnull creationDate;
[Export("creationDate")]
NSDate CreationDate { get; }
// @property (readonly, nonatomic) NXMMember * _Nullable myMember;
[NullAllowed, Export("myMember")]
NXMMember MyMember { get; }
// @property (readonly, nonatomic) NSArray<NXMMember *> * _Nonnull allMembers;
[Export("allMembers")]
NXMMember[] AllMembers { get; }
[Wrap("WeakDelegate")]
[NullAllowed]
NXMConversationDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<NXMConversationDelegate> _Nullable delegate;
[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
[Wrap("WeakUpdatesDelegate")]
[NullAllowed]
NXMConversationUpdateDelegate UpdatesDelegate { get; set; }
// @property (nonatomic, weak) id<NXMConversationUpdateDelegate> _Nullable updatesDelegate;
[NullAllowed, Export("updatesDelegate", ArgumentSemantic.Weak)]
NSObject WeakUpdatesDelegate { get; set; }
// -(void)inviteMemberWithUsername:(NSString * _Nonnull)username completion:(void (^ _Nullable)(NSError * _Nullable))completion;
[Export("inviteMemberWithUsername:completion:")]
void InviteMemberWithUsername(string username, [NullAllowed] Action<NSError> completion);
// -(void)join:(void (^ _Nullable)(NSError * _Nullable, NXMMember * _Nullable))completionHandler;
[Export("join:")]
void Join([NullAllowed] Action<NSError, NXMMember> completionHandler);
// -(void)joinMemberWithUsername:(NSString * _Nonnull)username completion:(void (^ _Nullable)(NSError * _Nullable, NXMMember * _Nullable))completion;
[Export("joinMemberWithUsername:completion:")]
void JoinMemberWithUsername(string username, [NullAllowed] Action<NSError, NXMMember> completion);
// -(void)leave:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("leave:")]
void Leave([NullAllowed] Action<NSError> completionHandler);
// -(void)kickMemberWithMemberId:(NSString * _Nonnull)memberId completion:(void (^ _Nullable)(NSError * _Nullable))completion;
[Export("kickMemberWithMemberId:completion:")]
void KickMemberWithMemberId(string memberId, [NullAllowed] Action<NSError> completion);
// -(void)enableMedia;
[Export("enableMedia")]
void EnableMedia();
// -(void)disableMedia;
[Export("disableMedia")]
void DisableMedia();
// -(void)sendCustomWithEvent:(NSString * _Nonnull)customType data:(NSDictionary * _Nonnull)data completionHandler:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("sendCustomWithEvent:data:completionHandler:")]
void SendCustomWithEvent(string customType, NSDictionary data, [NullAllowed] Action<NSError> completionHandler);
// -(void)sendText:(NSString * _Nonnull)text completionHandler:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("sendText:completionHandler:")]
void SendText(string text, [NullAllowed] Action<NSError> completionHandler);
// -(void)sendAttachmentWithType:(NXMAttachmentType)type name:(NSString * _Nonnull)name data:(NSData * _Nonnull)data completionHandler:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("sendAttachmentWithType:name:data:completionHandler:")]
void SendAttachmentWithType(NXMAttachmentType type, string name, NSData data, [NullAllowed] Action<NSError> completionHandler);
// -(void)sendMarkSeenMessage:(NSInteger)message completionHandler:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("sendMarkSeenMessage:completionHandler:")]
void SendMarkSeenMessage(nint message, [NullAllowed] Action<NSError> completionHandler);
// -(void)sendStartTyping:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("sendStartTyping:")]
void SendStartTyping([NullAllowed] Action<NSError> completionHandler);
// -(void)sendStopTyping:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("sendStopTyping:")]
void SendStopTyping([NullAllowed] Action<NSError> completionHandler);
// -(void)getEventsPage:(void (^ _Nullable)(NSError * _Nullable, NXMEventsPage * _Nullable))completionHandler;
[Export("getEventsPage:")]
void GetEventsPage([NullAllowed] Action<NSError, NXMEventsPage> completionHandler);
// -(void)getEventsPageWithSize:(NSUInteger)size order:(NXMPageOrder)order completionHandler:(void (^ _Nullable)(NSError * _Nullable, NXMEventsPage * _Nullable))completionHandler;
[Export("getEventsPageWithSize:order:completionHandler:")]
void GetEventsPageWithSize(nuint size, NXMPageOrder order, [NullAllowed] Action<NSError, NXMEventsPage> completionHandler);
// -(void)getEventsPageWithSize:(NSUInteger)size order:(NXMPageOrder)order eventType:(NSString * _Nullable)eventType completionHandler:(void (^ _Nullable)(NSError * _Nullable, NXMEventsPage * _Nullable))completionHandler;
[Export("getEventsPageWithSize:order:eventType:completionHandler:")]
void GetEventsPageWithSize(nuint size, NXMPageOrder order, [NullAllowed] string eventType, [NullAllowed] Action<NSError, NXMEventsPage> completionHandler);
}
// @interface NXMCallMember : NSObject
[BaseType(typeof(NSObject))]
interface NXMCallMember : INativeObject
{
// @property (copy, nonatomic) NSString * _Nonnull memberId;
[Export("memberId")]
string MemberId { get; set; }
// @property (readonly, nonatomic) NXMUser * _Nonnull user;
[Export("user")]
NXMUser User { get; }
// @property (readonly, nonatomic) NXMChannel * _Nullable channel;
[NullAllowed, Export("channel")]
NXMChannel Channel { get; }
// @property (readonly, nonatomic) BOOL isMuted;
[Export("isMuted")]
bool IsMuted { get; }
// @property (readonly, nonatomic) NXMCallMemberStatus status;
[Export("status")]
NXMCallMemberStatus Status { get; }
// @property (copy, nonatomic) NSString * _Nonnull statusDescription;
[Export("statusDescription")]
string StatusDescription { get; set; }
// -(void)hold:(BOOL)isHold;
[Export("hold:")]
void Hold(bool isHold);
// -(void)mute:(BOOL)isMute;
[Export("mute:")]
void Mute(bool isMute);
// -(void)earmuff:(BOOL)isEarmuff;
[Export("earmuff:")]
void Earmuff(bool isEarmuff);
}
// typedef void (^NXMSuccessCallback)();
delegate void NXMSuccessCallback();
// typedef void (^NXMSuccessCallbackWithId)(NSString * _Nullable);
delegate void NXMSuccessCallbackWithId([NullAllowed] string arg0);
// typedef void (^NXMSuccessCallbackWithObject)(NSObject * _Nullable);
delegate void NXMSuccessCallbackWithObject([NullAllowed] NSObject arg0);
// typedef void (^NXMSuccessCallbackWithObjects)(NSArray * _Nullable);
delegate void NXMSuccessCallbackWithObjects([NullAllowed] NSObject[] arg0);
// typedef void (^NXMErrorCallback)(NSError * _Nullable);
delegate void NXMErrorCallback([NullAllowed] NSError arg0);
// typedef void (^NXMCompletionCallback)(NSError * _Nullable);
delegate void NXMCompletionCallback([NullAllowed] NSError arg0);
// @protocol NXMCallDelegate <NSObject>
[Protocol, Model(AutoGeneratedName = true)]
[BaseType(typeof(NSObject))]
interface NXMCallDelegate
{
// @required -(void)call:(NXMCall * _Nonnull)call didUpdate:(NXMCallMember * _Nonnull)callMember withStatus:(NXMCallMemberStatus)status;
[Abstract]
[Export("call:didUpdate:withStatus:")]
void DidUpdate(NXMCall call, NXMCallMember callMember, NXMCallMemberStatus status);
// @required -(void)call:(NXMCall * _Nonnull)call didUpdate:(NXMCallMember * _Nonnull)callMember isMuted:(BOOL)muted;
[Abstract]
[Export("call:didUpdate:isMuted:")]
void DidUpdate(NXMCall call, NXMCallMember callMember, bool muted);
// @required -(void)call:(NXMCall * _Nonnull)call didReceive:(NSError * _Nonnull)error;
[Abstract]
[Export("call:didReceive:")]
void DidReceive(NXMCall call, NSError error);
// @optional -(void)call:(NXMCall * _Nonnull)call didReceive:(NSString * _Nonnull)dtmf fromCallMember:(NXMCallMember * _Nullable)callMember;
[Export("call:didReceive:fromCallMember:")]
void DidReceive(NXMCall call, string dtmf, [NullAllowed] NXMCallMember callMember);
}
// @interface NXMCall : NSObject
[BaseType(typeof(NSObject))]
interface NXMCall
{
// @property (readonly, nonatomic) NSMutableArray<NXMCallMember *> * _Nonnull otherCallMembers;
[Export("otherCallMembers")]
NSMutableArray<NXMCallMember> OtherCallMembers { get; }
// @property (readonly, nonatomic) NXMCallMember * _Nonnull myCallMember;
[Export("myCallMember")]
NXMCallMember MyCallMember { get; }
// -(void)setDelegate:(id<NXMCallDelegate> _Nonnull)delegate;
[Export("setDelegate:")]
void SetDelegate(NXMCallDelegate @delegate);
// -(void)answer:(NXMCompletionCallback _Nullable)completionHandler;
[Export("answer:")]
void Answer([NullAllowed] NXMCompletionCallback completionHandler);
// -(void)reject:(NXMCompletionCallback _Nullable)completionHandler;
[Export("reject:")]
void Reject([NullAllowed] NXMCompletionCallback completionHandler);
// -(void)addCallMemberWithUsername:(NSString * _Nonnull)username completionHandler:(NXMCompletionCallback _Nullable)completionHandler;
[Export("addCallMemberWithUsername:completionHandler:")]
void AddCallMemberWithUsername(string username, [NullAllowed] NXMCompletionCallback completionHandler);
// -(void)addCallMemberWithNumber:(NSString * _Nonnull)number completionHandler:(NXMCompletionCallback _Nullable)completionHandler;
[Export("addCallMemberWithNumber:completionHandler:")]
void AddCallMemberWithNumber(string number, [NullAllowed] NXMCompletionCallback completionHandler);
// -(void)sendDTMF:(NSString * _Nonnull)dtmf;
[Export("sendDTMF:")]
void SendDTMF(string dtmf);
// -(void)hangup;
[Export("hangup")]
void Hangup();
}
// @interface NXMConversationsPage : NXMPage
[BaseType(typeof(NXMPage))]
interface NXMConversationsPage
{
// @property (readonly, nonatomic) NSArray<NXMConversation *> * _Nonnull conversations;
[Export("conversations")]
NXMConversation[] Conversations { get; }
// -(void)nextPage:(void (^ _Nonnull)(NSError * _Nullable, NXMConversationsPage * _Nullable))completionHandler;
[Export("nextPage:")]
void NextPage(Action<NSError, NXMConversationsPage> completionHandler);
// -(void)previousPage:(void (^ _Nonnull)(NSError * _Nullable, NXMConversationsPage * _Nullable))completionHandler;
[Export("previousPage:")]
void PreviousPage(Action<NSError, NXMConversationsPage> completionHandler);
}
// @interface NXMClientConfig : NSObject
[BaseType(typeof(NSObject))]
interface NXMClientConfig
{
// @property (readonly, nonatomic) NSString * _Nonnull apiUrl;
[Export("apiUrl")]
string ApiUrl { get; }
// @property (readonly, nonatomic) NSString * _Nonnull websocketUrl;
[Export("websocketUrl")]
string WebsocketUrl { get; }
// @property (readonly, nonatomic) NSString * _Nonnull ipsUrl;
[Export("ipsUrl")]
string IpsUrl { get; }
// @property (readonly, nonatomic) NSArray<NSString *> * _Nonnull iceServerUrls;
[Export("iceServerUrls")]
string[] IceServerUrls { get; }
// -(instancetype _Nonnull)initWithApiUrl:(NSString * _Nonnull)apiURL websocketUrl:(NSString * _Nonnull)websocketUrl ipsUrl:(NSString * _Nonnull)ipsUrl;
[Export("initWithApiUrl:websocketUrl:ipsUrl:")]
IntPtr Constructor(string apiURL, string websocketUrl, string ipsUrl);
// -(instancetype _Nonnull)initWithApiUrl:(NSString * _Nonnull)apiURL websocketUrl:(NSString * _Nonnull)websocketUrl ipsUrl:(NSString * _Nonnull)ipsUrl iceServerUrls:(NSArray<NSString *> * _Nonnull)iceServerUrls;
[Export("initWithApiUrl:websocketUrl:ipsUrl:iceServerUrls:")]
IntPtr Constructor(string apiURL, string websocketUrl, string ipsUrl, string[] iceServerUrls);
// +(NXMClientConfig * _Nonnull)LON;
[Static]
[Export("LON")]
NXMClientConfig LON { get; }
// +(NXMClientConfig * _Nonnull)SNG;
[Static]
[Export("SNG")]
NXMClientConfig SNG { get; }
// +(NXMClientConfig * _Nonnull)DAL;
[Static]
[Export("DAL")]
NXMClientConfig DAL { get; }
// +(NXMClientConfig * _Nonnull)WDC;
[Static]
[Export("WDC")]
NXMClientConfig WDC { get; }
}
// @interface NXMPushPayload : NSObject
[BaseType(typeof(NSObject))]
interface NXMPushPayload
{
// @property (readonly, nonatomic) NSDictionary * _Nullable customData;
[NullAllowed, Export("customData")]
NSDictionary CustomData { get; }
// @property (readonly, nonatomic) NSDictionary * _Nullable eventData;
[NullAllowed, Export("eventData")]
NSDictionary EventData { get; }
// @property (readonly, nonatomic) NXMPushTemplate template;
[Export("template")]
NXMPushTemplate Template { get; }
}
// @interface NXMClient : NSObject
[BaseType(typeof(NSObject))]
interface NXMClient
{
// @property (readonly, nonatomic, class) NXMClient * _Nonnull shared;
[Static]
[Export("shared")]
NXMClient Shared { get; set; }
// @property (readonly, getter = getConnectionStatus, assign, nonatomic) NXMConnectionStatus connectionStatus;
[Export("connectionStatus", ArgumentSemantic.Assign)]
NXMConnectionStatus ConnectionStatus { [Bind("getConnectionStatus")] get; }
// @property (readonly, getter = getUser, nonatomic) NXMUser * _Nullable user;
[NullAllowed, Export("user")]
NXMUser User { [Bind("getUser")] get; }
// @property (readonly, getter = getToken, nonatomic) NSString * _Nullable authToken;
[NullAllowed, Export("authToken")]
string AuthToken { [Bind("getToken")] get; }
// @property (readonly, getter = getConfiguration, nonatomic) NXMClientConfig * _Nullable configuration;
[NullAllowed, Export("configuration")]
NXMClientConfig Configuration { [Bind("getConfiguration")] get; }
// +(void)setConfiguration:(NXMClientConfig * _Nonnull)configuration;
[Static]
[Export("setConfiguration:")]
void SetConfiguration(NXMClientConfig configuration);
// -(void)setDelegate:(id<NXMClientDelegate> _Nonnull)delegate;
[Export("setDelegate:")]
void SetDelegate(NXMClientDelegate @delegate);
// -(void)loginWithAuthToken:(NSString * _Nonnull)authToken;
[Export("loginWithAuthToken:")]
void LoginWithAuthToken(string authToken);
// -(void)updateAuthToken:(NSString * _Nonnull)authToken;
[Export("updateAuthToken:")]
void UpdateAuthToken(string authToken);
// -(void)logout;
[Export("logout")]
void Logout();
// -(void)getConversationWithUuid:(NSString * _Nonnull)uuid completionHandler:(void (^ _Nullable)(NSError * _Nullable, NXMConversation * _Nullable))completionHandler;
[Export("getConversationWithUuid:completionHandler:")]
void GetConversationWithUuid(string uuid, [NullAllowed] Action<NSError, NXMConversation> completionHandler);
// -(void)createConversationWithName:(NSString * _Nonnull)name completionHandler:(void (^ _Nullable)(NSError * _Nullable, NXMConversation * _Nullable))completionHandler;
[Export("createConversationWithName:completionHandler:")]
void CreateConversationWithName(string name, [NullAllowed] Action<NSError, NXMConversation> completionHandler);
// -(void)getConversationsPageWithSize:(NSInteger)size order:(NXMPageOrder)order completionHandler:(void (^ _Nullable)(NSError * _Nullable, NXMConversationsPage * _Nullable))completionHandler __attribute__((deprecated("use getConversationsPageWithSize:(NSInteger) order:(NXMPageOrder) filter:(NSString*) completionHandler instead")));
[Export("getConversationsPageWithSize:order:completionHandler:")]
void GetConversationsPageWithSize(nint size, NXMPageOrder order, [NullAllowed] Action<NSError, NXMConversationsPage> completionHandler);
// -(void)getConversationsPageWithSize:(NSInteger)size order:(NXMPageOrder)order filter:(NSString * _Nullable)filter completionHandler:(void (^ _Nullable)(NSError * _Nullable, NXMConversationsPage * _Nullable))completionHandler;
[Export("getConversationsPageWithSize:order:filter:completionHandler:")]
void GetConversationsPageWithSize(nint size, NXMPageOrder order, [NullAllowed] string filter, [NullAllowed] Action<NSError, NXMConversationsPage> completionHandler);
// -(void)call:(NSString * _Nonnull)callee callHandler:(NXMCallHandler)callHandler completionHandler:(void (^ _Nullable)(NSError * _Nullable, NXMCall * _Nullable))completionHandler;
[Export("call:callHandler:completionHandler:")]
void Call(string callee, NXMCallHandler callHandler, [NullAllowed] Action<NSError, NXMCall> completionHandler);
// -(void)enablePushNotificationsWithPushKitToken:(NSData * _Nullable)pushKitToken userNotificationToken:(NSData * _Nullable)userNotificationToken isSandbox:(BOOL)isSandbox completionHandler:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("enablePushNotificationsWithPushKitToken:userNotificationToken:isSandbox:completionHandler:")]
void EnablePushNotificationsWithPushKitToken([NullAllowed] NSData pushKitToken, [NullAllowed] NSData userNotificationToken, bool isSandbox, [NullAllowed] Action<NSError> completionHandler);
// -(void)disablePushNotifications:(void (^ _Nullable)(NSError * _Nullable))completionHandler;
[Export("disablePushNotifications:")]
void DisablePushNotifications([NullAllowed] Action<NSError> completionHandler);
// -(BOOL)isNexmoPushWithUserInfo:(NSDictionary * _Nonnull)userInfo;
[Export("isNexmoPushWithUserInfo:")]
bool IsNexmoPushWithUserInfo(NSDictionary userInfo);
// -(void)processNexmoPushWithUserInfo:(NSDictionary * _Nonnull)userInfo completionHandler:(void (^ _Nullable)(NSError * _Nullable))completionHandler __attribute__((deprecated("Use processNexmoPushPayload instead.")));
[Export("processNexmoPushWithUserInfo:completionHandler:")]
void ProcessNexmoPushWithUserInfo(NSDictionary userInfo, [NullAllowed] Action<NSError> completionHandler);
// -(NXMPushPayload * _Nullable)processNexmoPushPayload:(NSDictionary * _Nonnull)pushInfo;
[Export("processNexmoPushPayload:")]
[return: NullAllowed]
NXMPushPayload ProcessNexmoPushPayload(NSDictionary pushInfo);
}
// @interface NXMLogger : NSObject
[BaseType(typeof(NSObject))]
interface NXMLogger
{
// +(void)setLogLevel:(NXMLoggerLevel)logLevel;
[Static]
[Export("setLogLevel:")]
void SetLogLevel(NXMLoggerLevel logLevel);
// +(NSMutableArray * _Nonnull)getLogFileNames;
[Static]
[Export("getLogFileNames")]
NSMutableArray LogFileNames { get; }
}
// @interface NXMHelper : NSObject
[BaseType(typeof(NSObject))]
interface NXMHelper
{
// +(NSString * _Nonnull)descriptionForEventType:(NXMEventType)eventType;
[Static]
[Export("descriptionForEventType:")]
string DescriptionForEventType(NXMEventType eventType);
}
}
<file_sep>/NexmoXamarinTest/NexmoXamarinTest.iOS/Main.cs
using System;
using System.Collections.Generic;
using System.Linq;
using AVFoundation;
using Foundation;
using UIKit;
using NexmoXamarinIOS;
namespace NexmoXamarinTest.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
Console.WriteLine("hello world");
AVAudioSession.SharedInstance().RequestRecordPermission(
new AVPermissionGranted((bool granted) =>
{
Console.WriteLine("Record permission grainting is: " + granted);
}));
//var logFileName = NXMLogger.LogFileNames;
//Console.WriteLine(logFileName[0])
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
<file_sep>/NexmoXamarinTest/NexmoXamarinTest.Android/MainActivity.cs
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Content;
using Com.Nexmo.Client;
using Android.Support.V4.App;
using Android;
using Android.Support.Design.Widget;
namespace NexmoXamarinTest.Droid
{
[Activity(Label = "NexmoXamarinTest", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
var context = Android.App.Application.Context;
NexmoClient.Builder builder = new NexmoClient.Builder();
var client = builder.LogLevel(Com.Nexmo.Utils.Logger.LoggerELogLevel.Verbose).Build(context);
NexmoClient.Get().SetConnectionListener(new ConnectionListener());
NexmoClientHolder.Client = client;
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
string[] requiredPermissions = new string[]
{
Manifest.Permission.RecordAudio,
Manifest.Permission.Internet,
Manifest.Permission.AccessWifiState,
Manifest.Permission.ChangeWifiState,
Manifest.Permission.AccessNetworkState,
Manifest.Permission.ModifyAudioSettings
};
ActivityCompat.RequestPermissions(this, requiredPermissions, 123);
LoadApplication(new App(new CallHandler()));
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
|
db341e5299bfed205858491edd448f28603af0ed
|
[
"C#"
] | 14 |
C#
|
slorello89/nexmo-xamarin-poc
|
e29a2de9307f39fef18dd522b82ed8fa031894a9
|
cffac8a8c43d2c1bc9da5a7fe4ef0e6df9c0c519
|
refs/heads/master
|
<file_sep>"use strict";
define(function(){
return {
"option" :
{
title : "JavaScript" ,
width : 850 ,
height : 500 ,
delay : 1000 ,
to : "#slides-1" ,
fn : {
setStyle : function ( styles ) {
var css = "style=";
$.each( styles , function( key, value ) {
css += [key, value].join(":") + ";";
});
return css;
}
}
} ,
slides : [
{
title : "JavaScript is a dynamic computer programming language.",
image :
[{
src : "../img/sign.png",
style :
{
position : "absolute" ,
bottom : "0px" ,
right : "15px"
}
} , {
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
text :
{
body : "It is most commonly used as part of web browsers, whose implementations allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed. It is also used in server-side network programming with runtime environments such as Node.js, game development and the creation of desktop and mobile applications." ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
}
} , {
title : "History",
text : {
"position" : "bottom",
"body" : "JavaScript was originally developed by <NAME>, while working for Netscape Communications Corporation. While competing with Microsoft for user adoption of web technologies and platforms, Netscape considered their client-server offering a distributed OS with a portable version of Sun Microsystems' Java providing an environment in which applets could be run.[citation needed] Because Java was a competitor of C++ and aimed at professional programmers, Netscape also wanted a lightweight interpreted language that would complement Java by appealing to nonprofessional programmers, like Microsoft's Visual Basic (see JavaScript and Java)." ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
} ,
image :
[{
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
} , {
title : "Features",
text : {
"body" : "The following features are common to all conforming ECMAScript implementations, unless explicitly specified otherwise. Imperative and structured[edit] JavaScript supports much of the structured programming syntax from C (e.g., if statements, while loops, switch statements,do while loops, etc.). One partial exception is scoping: C-style block scoping is not supported. Instead, JavaScript has function scoping (although, block scoping using the let keyword was added in JavaScript 1.7). Like C, JavaScript makes a distinction between expressions and statements. One syntactic difference from C is automatic semicolon insertion, which allows the semicolons that would normally terminate statements to be omitted." ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
} ,
image :
[{
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
} , {
title : "Syntax",
text : {
"body" : "As of 2011, the latest version of the language is JavaScript 1.8.5. It is a superset of ECMAScript (ECMA-262) Edition 3. Extensions to the language, including partial ECMAScript for XML (E4X) (ECMA-357) support and experimental features considered for inclusion into future ECMAScript editions, are documented here." ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
} ,
image :
[{
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
} , {
title : "Use in web pages",
text : {
"body" : "As of 2011, the latest version of the language is JavaScript 1.8.5. It is a superset of ECMAScript (ECMA-262) Edition 3. Extensions to the language, including partial ECMAScript for XML (E4X) (ECMA-357) support and experimental features considered for inclusion into future ECMAScript editions, are documented here." ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
} ,
image :
[{
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
} , {
title : "Security",
text : {
"body" : "JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-related actions, not general-purpose programming tasks like creating files. Second, scripts are constrained by the same origin policy: scripts from one web site do not have access to information such as usernames, passwords, or cookies sent to another site. Most JavaScript-related security bugs are breaches of either the same origin policy or the sandbox." ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
} ,
image :
[{
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
} , {
title : "Uses outside web pages",
text : {
"body" : "In addition to web browsers and servers, JavaScript interpreters are embedded in a number of tools. Each of these applications provides its own object model which provides access to the host environment. The core JavaScript language remains mostly the same in each application." ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
} ,
image :
[{
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
} , {
title : "Development tools",
text : {
"body" : "Within JavaScript, access to a debugger becomes invaluable when developing large, non-trivial programs. Because there can be implementation differences between the various browsers (particularly within the Document Object Model), it is useful to have access to a debugger for each of the browsers that a web application targets.[97] Script debuggers are available for Internet Explorer, Firefox, Safari, Google Chrome, Opera and Node.js" ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
} ,
image :
[{
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
} , {
title : "Criticisms",
text : {
"body" : "JavaScript is a loosely typed language (see Dynamic typing above). Loose typing places a majority responsibility for static type management on programmer discipline, very little on the compiler, and late reporting of type safety violation on the run-time. The result is a development environment where type bugs can be easily introduced due to human fallibility. The bugs may be difficult to detect or may go undetected by the run-time for several reasons:" ,
style :
{
"color" : "#000" ,
"font-size" : "23px" ,
"text-align" : "justify" ,
"padding" : "7px"
}
} ,
image :
[{
src : "../img/js.png" ,
style : {
position : "absolute" ,
bottom : "10px" ,
left : "10px" ,
float : "left" ,
width : "50px" ,
height : "50px"
}
}],
}
]
}
});<file_sep># slide-show
I suppose it is necessary to add in templates disc inheritance, common blocks, pre-parsing... Soon I'll make... :)
<file_sep>"use strict";
define([
"jquery",
"common",
"class",
"jquery.tmpl",
"jquery.draggable"], function( $, common, Class ) {
var Slides = new Class;
// create new class
Slides.extend({
initialize: function( attr, cTemplate, sTemplate ) {
this.slides = attr.slides;
// check that our presentaion has at least one slide to show
if( !this.slides.length )
throw new Error("It should be passed at least one slide discription");
this.option = $.extend( {}, common.DEFAULTS.option , attr.option );
this.wrap = $( "<div class=\"slide-wrap\"><div></div><\/div>" ).children();
this.$Slides;
this.$Container;
this.$items;
// get templates or selectors to get
this.cTemplate = cTemplate;
this.sTemplate = sTemplate;
// define some props for slides control
this.$currentSlide = 0;
this.$playing = false;
this.to = $( this.option.to );
// create slides review; It is possible to do using
// logic in templates. However, I think this is a bad idea
// to put a lot of logic in templates
this.option.slides = (function( slides ) {
var array = [];
$.each( slides , function( index, value ) {
array.push({
title : common._case("up", value.title).cut( null, 0, 25 )[0] + common.DELIM.ellipsis,
shorts : common.cut( value.text.body, 0, 51 )[0] + common.DELIM.ellipsis
});
});
return array;
}( this.slides ));
} ,
createContainer : function() {
// create main container for the current slideshow
// #1 compile template
$.template( "static-main", common.expect(
this.cTemplate , "array" ) && this.cTemplate[0] || $("#containerTmpl").html() );
// #2 render and append to... by default to body
this.$Container = $.tmpl( "static-main", this.option ).appendTo( this.option.to );
// #3 add some useful utils
this.$Container.find(".drag").tinyDraggable( null, this.$Container.find(".slides-nav-left") );
this.$items = this.$Container.find(".slides-nav-outer > div");
return this;
} ,
renderSlides : function() {
// start to render slides
$.template( "slides-each", common.expect(
this.sTemplate , "array" ) && this.sTemplate[0] || $("#slidesTmpl").html() );
// render
this.$Slides = $.tmpl( "slides-each", this.slides, this.option );
// wrap our slides
this.wrap
.append( this.$Slides )
.parent()
.css({
width : this.option.width,
height : this.option.height
})
.appendTo( this.$Container );
return this;
} ,
jumpTo : function( event, guid ) {
var $index = this.$currentSlide = event ? +$( event.delegateTarget ).attr("data-slide") : guid;
this.to.trigger("slides")
this.$items
.removeClass("curren-slide")
.slice( $index, $index + 1 )
.addClass("curren-slide");
this.wrap
[this.option.animation ? "animate" : "css"]({top: -$index * this.option.height});
return false;
},
control : function() {
var $this = this
, $btn = this.$Container.find(".slide-show-play")
, timerId;
return {
next : function() {
if( !$this.balance( 1 ) ) return;
$this.jumpTo( null, ($this.$currentSlide += 1));
},
prev : function() {
if( !$this.balance( -1 ) ) return;
$this.jumpTo( null, ($this.$currentSlide -= 1));
},
play : function() {
if( $this.$playing ) {
$btn.css( "background-image", common.DEFAULTS.bg.play );
clearInterval( timerId );
$this.$playing = false;
$this.to.trigger("pause");
} else {
$btn.css( "background-image", common.DEFAULTS.bg.pause );
$this.$playing = true;
$this.to.trigger("play");
timerId = setInterval($.proxy(function(){
if(!$this.balance( 1 )) return clearInterval( timerId ) || this.play();
this.next();
},
this ),
$this.option.delay
);
}
}
}
},
balance : function( x ) {
var $vector = common.sum( x , this.$currentSlide );
return $vector < this.slides.length && $vector >= 0;
},
addControllers : function() {
this.$Container.find(".slides-item").bind("click", $.proxy(this.jumpTo, this));
// add controls
var Controls = this.control();
$.each([
"next" ,
"prev" ,
"play"
], $.proxy(function( index, value ) {
this.$Container
.on("click", ".slide-show-" + value, $.proxy(Controls[value], Controls));
}, this));
// set current slide
this.jumpTo( null, 0 );
return this;
}
});
return function( attr, remote ) {
if( common.expect( remote , "object" ) ) {
var opt = $.extend( common.DEFAULTS.setting, remote );
var deferred = new $.Deferred();
$.when(
$.ajax({url: opt.cTemplateUrl}) ,
$.ajax({url: opt.sTemplateUrl})
)
.done(function( containerTemplate, slidesTemplate ) {
var res = (new Slides( attr, containerTemplate, slidesTemplate ))
.createContainer()
.renderSlides()
.addControllers();
deferred.resolve( res );
})
.fail(function(event){
deferred.reject(event.statusText);
});
return deferred;
}
// or load from html
return (new Slides( attr )).createContainer().renderSlides()
.addControllers();
}
});<file_sep>"use strict";
require.config({
shim : {
"jquery.tmpl" : ["jquery"] ,
"jquery.draggable" : ["jquery"]
},
paths : {
"jquery" : "../vendor/jquery/jquery.min" ,
"jquery.tmpl" : "../vendor/render/jquery.tmpl.min" ,
"jquery.draggable" : "../vendor/jquery/jquery.draggable" ,
"attribute" : "data-1" ,
"attr" : "data-2"
}
});
require(["slides", "attribute", "attr"], function( Slides, attributes, attrs ) {
// run
Slides( attributes, {} ).done(function( res ){
// success
// you can set props to any object of presentaion
$( res.option.to ).on("play", function(e) {
console.log( "Slideshow #1 is started" );
})
.on("pause" , function(e) {
console.log( "Slideshow #1 is paused" );
})
.on("slides", function(e) {
//if( res.$currentSlide === res.slides.length - 1 )
//res.jumpTo( null, 0 );
})
})
.fail(function( err ) {
// failed
console.log( "Error", err );
});
// create one more slideshow without remote templates
var $slide = Slides( attrs );
$slide.to.on("play", function(e) {
console.log( "Slideshow #2 is started" );
})
.on("pause" , function(e) {
console.log( "Slideshow #2 is paused" );
})
});<file_sep>define(function(){
return {
"option" :
{
"width" : "550" ,
"height" : "350" ,
"delay" : "1000" ,
"to" : "#slides-2" ,
"animation" : true
} ,
"slides" : [
{
title : "A road is a thoroughfare" ,
image : { url : "../img/nature/1.jpg" } ,
text : { body : "Route, or way on land between two places that has been paved" }
} , {
title : "A Forest " ,
image : { url : "../img/nature/2.jpg" } ,
text : { body : "A large area of land covered with trees or other woody vegetation" }
} , {
title : "A park" ,
image : { url : "../img/nature/3.jpg" } ,
text : { body : "An area of open space provided for recreational use" }
} , {
title : "The tiger" ,
image : { url : "../img/nature/4.jpg" } ,
text : { body : "The largest cat species, reaching a total body length of up to 3.38 m" }
} , {
title : "A rainforest " ,
image : { url : "../img/nature/5.jpg" } ,
text : { body : "Forests characterized by high rainfall, with annual rainfall" }
}
]
}
});
|
cfb5c69009bada8d0f82de05394318ba5247ae45
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
zhakroman/slide-show
|
c760335fbaa8b04fb467e0e82c6c7ea9f1f36d95
|
7a51e30dede81467fee261ca5e27f0c9f6417f8c
|
refs/heads/master
|
<repo_name>victor-tsisar/weatherApp<file_sep>/script.js
'use strict';
window.addEventListener('load', () => {
const ACCESS_KEY = 'c0183ea59ff959ec94df2ec3818ae631';
const locationTimezone = document.querySelector('.location__timezone');
const locationPlace = document.querySelector('.location__place');
const iconBlock = document.querySelector('.icon');
const temperatureDegree = document.querySelector('.temperature__degree');
const characteristicsPrecip = document.querySelector('.characteristics__precip');
const characteristicsWind = document.querySelector('.characteristics__wind');
const characteristicsPressure = document.querySelector('.characteristics__pressure');
const update = document.querySelector('.update');
let long;
let lat;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
long = position.coords.longitude; // get longitude
lat = position.coords.latitude; // get latitude
const api = `http://api.weatherstack.com/current?access_key=${ACCESS_KEY}&query=${lat},${long}`;
try {
getWeatherData(api);
} catch (error) {
console.log('error: ', error);
document.body.textContent = "Oops! The app did not get data. Please, try again later!";
}
// update data
setTimeout(() => update.disabled = false, 2500);
update.addEventListener('click', () => {
getWeatherData(api);
})
});
} else {
locationTimezone.textContent = "Oops! The app is not working. Cannot determine your geolocation. Maybe, you closed access!"
}
// fetchAPI
function getWeatherData(url) {
fetch(url)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
const { temperature, pressure, precip, wind_speed: windSpeed, weather_icons: icon, weather_code: code } = data.current; // get present weather's data
const { country, name, region, timezone_id: timezone, localtime: time } = data.location; // get user location
// Set DOM elements
locationTimezone.textContent = `${timezone}, ${time.substr(-5, 5)}`;
locationPlace.textContent = `${name}, ${region}, ${country}`;
temperatureDegree.innerHTML = `${temperature}<span class="temperature__system"> Celsius</span>`;
characteristicsPrecip.textContent = `Probability of precipitation - ${precip} millimeters`;
characteristicsWind.textContent = `Speed of wind - ${windSpeed} km/hours`;
characteristicsPressure.textContent = `Atmospheric pressure - ${pressure} millibar`;
setIcons(icon, code);
})
.catch(err => console.log(err));
}
// Set weather's icons
function setIcons(icon, code) {
let skycons = new Skycons({ 'color': '#FFFFFF' });
let night = icon[0].includes('night', 0);
skycons.play();
let weatherCodes = {
CLEAR: [113],
PARTLY_CLOUDY: [116],
CLOUDY: [119, 122],
FOG: [143, 248, 260],
RAIN: [176, 200, 263, 266, 293, 296, 299, 302, 305, 308, 353, 356, 359, 386, 389],
SLEET: [179, 182, 185, 281, 284, 311, 314, 317, 320, 350, 362, 365, 374, 377],
SNOW: [227, 230, 323, 326, 329, 332, 335, 338, 368, 371, 392, 395],
}
for (const key in weatherCodes) {
const element = weatherCodes[key];
if (element.includes(code)) {
switch (key) {
case 'CLEAR':
night ? skycons.add(iconBlock, Skycons.CLEAR_NIGHT)
: skycons.add(iconBlock, Skycons.CLEAR_DAY);
break;
case 'PARTLY_CLOUDY':
night ? skycons.add(iconBlock, Skycons.PARTLY_CLOUDY_NIGHT)
: skycons.add(iconBlock, Skycons.PARTLY_CLOUDY_DAY);
break;
case 'CLOUDY':
skycons.add(iconBlock, Skycons.CLOUDY);
break;
case 'FOG':
skycons.add(iconBlock, Skycons.FOG);
break;
case 'RAIN':
skycons.add(iconBlock, Skycons.RAIN);
break;
case 'SLEET':
skycons.add(iconBlock, Skycons.SLEET);
break;
case 'SNOW':
skycons.add(iconBlock, Skycons.SNOW);
break;
default:
break;
}
break;
} else {
skycons.remove(iconBlock);
}
}
}
});
<file_sep>/README.md
Simple weather web-application on javascript (weather in your location - using geolocation).
I used skycons for weather's icons and API weatherstack.com (free version).
<img src="promo.png" alt="preview"><br>
Demonstration can be on localhost on your computer or on the real host, becouse weatherstack.com don't give access to the weather's data for Github Pages (consider as an insecure resource).
|
5e76a4a48cb86dd6e39fa535538f1349688273b6
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
victor-tsisar/weatherApp
|
6de8ad27e0ac59fdeb7064783af016d2627238d9
|
0582219d923be4ca27ad4ddea8d21edeb02a744c
|
refs/heads/master
|
<repo_name>mallorybucell/The_IronBoard<file_sep>/spec/controllers/tokens_controller_spec.rb
require 'rails_helper'
RSpec.describe TokensController, type: :controller do
fit 'only allows admins to access its actions' do
u1 = FactoryGirl.create :user
login u1
get :create
expect(response.code.to_i).to eq 302
#TODO make redirect hidden
end
it 'can destroy tokens' do
end
it 'is only accessible to admins'
end
<file_sep>/app/controllers/v1/games_controller.rb
module V1
class GamesController < ApiController
def create
data = params
Game.new_game data
if response.status == 200
head :ok
end
end
def list
@games = Game.all
end
def show
@game = Game.find(params[:id])
end
def index
@games = Game.where(name: params[:gamename])
end
def recent
@games = Game.all.reverse.take(15)
end
def recent_game
@games = Game.where(name: params[:gamename]).reverse.take(5)
end
end
end<file_sep>/spec/factories/games.rb
FactoryGirl.define do
factory :game do
name { ["Splendor", "Race for the Galaxy"].sample }
game_data "none"
game_summary "placeholder text"
sequence(:date_played) { |n| DateTime.new(2015, 3, n, 22, 49, 31) }
end
end
<file_sep>/spec/models/user_game_spec.rb
require 'rails_helper'
RSpec.describe UserGame, type: :model do
it 'can not have the same user more than once per game' do
u1 = FactoryGirl.create :user
u2 = FactoryGirl.create :user
g1 = FactoryGirl.create :game
g2 = FactoryGirl.create :game
UserGame.create!(user_id: u1.id, game_id: g1.id)
UserGame.create!(user_id: u2.id, game_id: g1.id)
expect(UserGame.count).to eq 2
UserGame.create!(user_id: u1.id, game_id: g2.id)
expect(UserGame.count).to eq 3
expect(u1.games.count).to eq 2
expect do
UserGame.create!(user_id: u1.id, game_id: g1.id)
end.to raise_error
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
rescue_from StandardError do |e|
render json: {
error: e.message,
location: e.backtrace.first
#FIXME ?backtrace: e.backtrace # if in development?
}, status: 500
end
def after_sign_in_path_for(resource)
"https://quiet-refuge-3512.herokuapp.com/index2.html"
end
end
<file_sep>/app/controllers/tokens_controller.rb
class TokensController < ApplicationController
before_filter :authenticate_admin!
def create
current_admin.generate_api_token!(params[:description])
redirect_to :back, notice: "Token generated"
end
def destroy
token = current_admin.tokens.find params[:id] #check this
token.disable!
redirect_to :back, notice: "Token disabled"
end
end
<file_sep>/spec/factories/tokens.rb
FactoryGirl.define do
factory :token do
key SecureRandom.hex 24
admin
end
end
<file_sep>/app/controllers/api_controller.rb
class ApiController < ActionController::Base
before_action :hardcode_json_format
before_action :authenticate_token!
rescue_from StandardError do |e|
render json: {
error: e.message,
location: e.backtrace.first
#FIXME ?backtrace: e.backtrace # if in development?
}, status: 500
end
rescue_from Token::Invalid do |e|
render json: { error: "Token invalid" }, status: 404
end
private
def hardcode_json_format
request.format = :json
end
def authenticate_token!
raise Token::Invalid unless Rack::Utils.
secure_compare(params[:token], ENV['IRONBOARD_API_TOKEN']) && Token.find_by(key: params[:token]).disabled? == false
# :all, :conditions => [:key => ?, params[:token]])
end
end
<file_sep>/spec/models/token_spec.rb
require 'rails_helper'
RSpec.describe Token, type: :model do
it 'can be created' do
a = FactoryGirl.create :admin
token = a.generate_api_token!("This is a test token.")
expect(token.key.chars.count).to eq 48
expect(token.disabled?).to be false
expect(a.tokens).to include token
end
it 'can be deactivated' do
a = FactoryGirl.create :admin
token = a.generate_api_token!("This is a test token.")
expect(token.disabled?).to eq false
token.disable!
expect(token.disabled?).to eq true
end
it 'has a unique key' do
a = FactoryGirl.create :admin
t1 = a.generate_api_token!("This is a test token.")
t2 = a.generate_api_token!("This is a 2nd token.")
#FIXME
expect do
t2.update!(key: t1.key)
end.to raise_error ActiveRecord::RecordInvalid
expect(t2.valid?).not_to be true
t2.reload
#FIXME
expect(a.tokens.count).to eq 2
expect(t2.key_changed?).to be false
expect(t2.key).not_to eq t1.key
end
end
<file_sep>/app/models/admin.rb
class Admin < ActiveRecord::Base
devise :database_authenticatable, :timeoutable, :registerable
has_many :tokens
def generate_api_token!(description)
begin
key = SecureRandom.hex 24 # TODO: what if this collides?
end while Token.exists?(key: key)
tokens.create!(key: key, description: description)
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :admins
devise_for :users, controllers: { omniauth_callbacks: "omniauth_callbacks" }
authenticated :admin do
resources :tokens, only: [:new, :create, :destroy]
get '/tokens/manage'
end
scope :api do
namespace :v1 do
get '/players' => 'players#index'
get '/players/:id' => 'players#show'
get '/players/:id/recent_games' => 'players#recent_games'
get '/games' => 'games#list'
post '/games' => 'games#create'
get '/games/:id' => 'games#show'
get '/games/:gamename' => 'games#index'
get '/games/recent' => 'games#recent'
get '/games/:gamename/recent' => 'games#recent_game'
end
end
get '/invite' => 'static_pages#new', as: 'new_invite'
post '/invite' => 'static_pages#create', as: 'create_invite'
root 'static_pages#home'
end
<file_sep>/app/models/game.rb
class Game < ActiveRecord::Base
has_many :user_games
has_many :users, through: :user_games
def self.generate_games user_id, number
number.times do |g|
g = User.find(user_id).games.new
g.name = ["splendor", "race for the galaxy"].sample
g.game_data = Faker::Lorem.words(4)
g.game_summary = "#{Faker::Lorem.paragraph}\n#{Faker::Lorem.paragraph}"
g.date_played = Faker::Time.between(2.days.ago, Time.now)
g.save!
end
end
def self.new_game data
g = Game.new
g.name = data["game_name"]
g.game_data = data["gamedata"]
g.game_summary = data["Game_Summary"]
g.date_played = data["date"]
g.winner = data["Winner"]
g.save!
data[:gamedata].each do |x|
unless x[:user_name] == ""
user = User.where(username: x[:user_name]).first
user.games << g
UserGame.update_wins data["Winner"]
end
end
end
end<file_sep>/spec/controllers/players_controller_spec.rb
require 'rails_helper'
RSpec.describe V1::PlayersController do
render_views
#FIXME Specs fail b/c Time weirdness, NOT return vals on manual check.
it "can get specific users recent games with no limit" do
u1 = FactoryGirl.create :user
n = 1
#15 games in March
1.upto 15 do |i|
FactoryGirl.create :game do |g|
g.update! date_played: (Date.new(2015, 3, n) + Time.new(22, 49, 31))
n += 1
UserGame.create(user_id: u1.id, game_id: g.id)
end
end
#5 games in April
1.upto 7 do |i|
FactoryGirl.create :game do |g|
g.update! date_played: (Date.new(2015, 3, n) + Time.new(22, 49, 31))
n += 1
UserGame.create(user_id: u1.id, game_id: g.id)
end
end
id = u1.id
get(:recent_games, { id: id })
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Array
expect(json.count).to eq 20
expect(json.first["date_played"]).to be > json.last["date_played"]
#FIXME this last assertion seems wonky
end
it "can get specific users recent games with limit" do
u1 = FactoryGirl.create :user
n = 0
n += 1
#10 games in March
1.upto 10 do |i|
FactoryGirl.create :game do |g|
g.update! date_played: (DateTime.new(2015, 3, n, 00, 49, 21))
n += 1
UserGame.create(user_id: u1.id, game_id: g.id)
end
end
#15 games in February
1.upto 15 do |i|
FactoryGirl.create :game do |g|
g.update! date_played: (DateTime.new(2015, 2, n, 00, 49, 21))
n += 1
UserGame.create(user_id: u1.id, game_id: g.id)
end
end
id = u1.id
get(:recent_games, { id: id, limit: 15 })
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Array
expect(json.count).to eq 15
expect(json.first["date_played"]).to be > json.last["date_played"]
#FIXME this last assertion seems wonky
end
# it 'requires a valid token before performing actions' do
# key = "<KEY>"
# token = Token.create!(admin_id: 1, key: key, description: "test")
# get :index, { token: token.key }
# expect(response.code.to_i).to eq 200
# token.update!(active: false)
# get :index, { token: token.key }
# expect(response.code.to_i).to eq 404
# end
# it 'handles errors gracefully' do
# end
end<file_sep>/spec/controllers/games_controller_spec.rb
require 'rails_helper'
describe V1::GamesController do
render_views
it "can list all games" do
much_splendor
FactoryGirl.create :game, name: "RftG"
get :list
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Array
expect(json.count).to eq 6
expect(json.first["name"]).to eq "Splendor"
expect(json.last["name"]).to eq "RftG"
end
it "can show a specific game" do
FactoryGirl.create :game, name: "Splendor"
FactoryGirl.create :game, name: "RftG"
FactoryGirl.create :game, name: "MtG"
get(:show, {:id => "3"})
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Hash
expect(json["name"]).to eq "MtG"
expect(json["id"]).to eq 3
end
it "can list all instances of a specific game" do
much_splendor
FactoryGirl.create :game, name: "MtG"
FactoryGirl.create :game, name: "MtG"
get(:index, {:gamename => "Splendor"})
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Array
expect(json.count).to eq 5
expect(json.first["name"]).to eq "Splendor"
expect(json.last["name"]).to eq "Splendor"
get(:index, {:gamename => "MtG"})
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Array
expect(json.count).to eq 2
expect(json.first["name"]).to eq "MtG"
expect(json.last["name"]).to eq "MtG"
end
it "can list a number of recent games" do
2.times do
much_splendor
end
FactoryGirl.create :game, name: "RftG"
FactoryGirl.create :game, name: "MtG"
get(:recent)
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Array
expect(json.count).to eq 12
expect(json.first["name"]).to eq "MtG"
expect(json[1]["name"]).to eq "RftG"
expect(json.last["name"]).to eq "Splendor"
end
it "can list a number of a game's recent games" do
2.times do
much_splendor
end
FactoryGirl.create :game, name: "RftG"
FactoryGirl.create :game, name: "MtG"
get(:recent_game, {:gamename => "Splendor"})
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Array
expect(json.count).to eq 5
expect(json.first["name"]).to eq "Splendor"
expect(json.last["name"]).to eq "Splendor"
get(:recent_game, {:gamename => "MtG"})
expect(response.code.to_i).to eq 200
json = response_json
expect(json.class).to eq Array
expect(json.count).to eq 1
expect(json.first["name"]).to eq "MtG"
end
it "can add a game instance to the database" do
User.create(email:"<EMAIL>", password: "<PASSWORD>", username: "thomas1")
User.create(email:"<EMAIL>", password: "<PASSWORD>", username: "gina")
post(:create, {:data => { :gamedata => [{"user_name":"thomas1","score":15},{"user_name":"gina","score":10}],:game_name => "Splendor", :winner => "thomas1", :date => "2015/3/15", :game_summary => "blahblahblahblah"} })
expect(response.code.to_i).to eq 200
expect(User.count).to eq 2
expect(User.last.username).to eq "gina"
expect(Game.count).to eq 1
expect(Game.first.name).to eq "Splendor"
expect(UserGame.count).to eq 2
expect(UserGame.first.winner).to eq true
end
end<file_sep>/app/views/v1/players/show.json.jbuilder
json.(@user, :username, :sex, :avatar_url, :total_wins, :total_losses)
<file_sep>/app/views/v1/players/index.json.jbuilder
json.array! @users do |user|
json.user_id user.id
json.username user.username
json.sex user.sex
json.avatar_url user.avatar_url
json.wins user.total_wins
json.losses user.total_losses
end<file_sep>/app/models/user_game.rb
class UserGame < ActiveRecord::Base
belongs_to :user
belongs_to :game
validates_uniqueness_of :user, scope: :game
def self.update_wins winner
entry = self.last
if User.find(entry.user_id).username == winner
entry.update(winner: true)
else
entry.update(winner: false)
end
end
def self.generate_user_games number
number.times do |u|
ug = UserGame.new
ug.user_id = User.all.pluck(:id).sample
ug.game_id = Game.all.pluck(:id).sample
ug.winner = [true, false].sample
ug.save!
end
end
end
<file_sep>/app/views/v1/players/recent_games.json.jbuilder
json.array! @games do |game|
json.name game.name
json.game_data game.game_data
json.game_summary game.game_summary
json.date_played game.date_played
end<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:github]
has_many :user_games
has_many :games, through: :user_games
after_initialize :defaults
def defaults
case self.sex
when "male"
self.avatar_url = 'http://icons.iconarchive.com/icons/aha-soft/iron-man/256/Tony-Stark-icon.png'
when "female"
self.avatar_url = 'http://icons.iconarchive.com/icons/aha-soft/iron-man/256/Pepper-Potts-icon.png'
else
self.avatar_url = 'http://www.medgadget.com/wp-content/uploads/2013/05/Iron-Yard.png'
end
end
def self.from_omniauth(auth)
User.where(email: auth.info.email).first_or_create! do |u|
u.email = auth.info.email
u.username = auth.info.nickname
u.password = <PASSWORD>.friendly_token[0,20]
u.github_data = auth.to_h
end
end
def total_wins
user_games.where(winner: true).count
end
def total_losses
user_games.where(winner: false).count
end
def wins_by_gametype
end
def losses_by_gametype
end
def generate_invite_email params
{
:subject => "Join the IronBoard",
:from_name => "The IronBoard",
:text => "Hello fellow IronYarder!\n\nI love playing games and would like to keep track of our game history. Visit our website so we can log our plays.\n\nFrom #{username},\n\nThanks, The IronBoard.",
:to => [
{
:email=> "#{params['email']}",
:name => "#{params['name']}"
}
],
:from_email=>"<EMAIL>"
}
end
def self.generate_users number
number.times do |u|
u = User.new
u.email = Faker::Internet.email
u.password = <PASSWORD>.password(8)
u.username = Faker::Internet.user_name
u.sex = ["male", "female"].sample
u.save!
end
end
end
<file_sep>/app/views/v1/games/list.json.jbuilder
json.array! @games do |game|
# json(game, :name, :game_data, :game_summary, :date_played)
json.name game.name
json.game_data game.game_data
json.game_summary game.game_summary
json.date_played game.date_played
end<file_sep>/app/views/v1/games/show.json.jbuilder
json.extract! @game, :id, :name, :game_data, :game_summary, :date_played, :created_at, :updated_at<file_sep>/app/controllers/v1/players_controller.rb
module V1
class PlayersController < ApiController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
#FIXME Fix specs for recent_games
def recent_games
lim = if params[:limit].to_i > 0
params[:limit].to_i
else
20
end
user = User.find(params[:id].to_i)
@games = user.games.order(created_at: :desc).limit(lim)
end
end
end<file_sep>/app/controllers/static_pages_controller.rb
require 'mandrill'
class StaticPagesController < ApplicationController
def home
end
def new
end
def create
m = Mandrill::API.new(ENV.fetch "MANDRILL_APIKEY")
m.messages.send(current_user.generate_invite_email(static_page_params))
flash["success"] = "Your email has been sent!"
redirect_to new_invite_path
end
private
def static_page_params
params.permit(:email, :name)
end
end
<file_sep>/README.md
# The_IronBoard
Group project working with 2 other backend engineers and a front-end engineer to build a scoreboard to be used during IronYard cohort gaming sessions.
We worked well together building out a data model, discussing how data would be passed, and creating a working API for the front-end to call.
Most recent commit is not currently functional- mostly because this was a lesson in learning when to 'git add ., vs git add -A'.
|
45ebfe808f2845661bf93f1675df9ff206f55406
|
[
"Markdown",
"Ruby"
] | 24 |
Ruby
|
mallorybucell/The_IronBoard
|
adf14223d2cb622d8994c751c8314b24b08baf04
|
932ce6dff0db38a5a8039014635e9de9b871eea9
|
refs/heads/master
|
<repo_name>fateeq/vueLearnBasics<file_sep>/main.js
Vue.component('product', {
props: {
premium: {
type: Boolean,
required: true
}
},
template: `
<div class="product">
<h1>{{ title }}</h1>
<img :src="image">
<div>
<p v-if="inStock">In Stock</p>
<p v-else>Out of Stock</p>
</div>
<div>
<p>Shipping: {{ shipping }}</p>
</div>
<div class="align-left">
<p>Details:</p>
<ul>
<li v-for="detail in details">{{ detail }}</li>
</ul>
</div>
<div class="flex-container">
<div v-for="(variant, index) in variants"
:key="variant.variantId"
class="color-box"
:style="{ backgroundColor: variant.variantColor }"
@mouseover="updateProduct(index)">
</div>
</div>
<div>
<button
v-on:click="addToCart"
:disabled="!inStock"
>Add to cart
</button>
</div>
</div>
`,
data() {
return {
brand: 'Vue Master',
product: 'Socks',
selectedVariant: 0,
details: ["80% cotton","20% wool","gender neutral"],
variants: [
{
variantId: 2234,
variantColor: "green",
variantImage: 'https://www.sockittome.com/images/detailed/6/MEF0209.jpg',
variantQty: 10
},
{
variantId: 2235,
variantColor: "blue",
variantImage: 'http://ilovethosesocks.com/wp-content/uploads/2017/08/mustache-socks-blue.jpg',
variantQty: 0
}
]
}
},
methods: {
addToCart() {
this.$emit('add-to-cart', this.variants[this.selectedVariant].variantId)
},
updateProduct(x) {
this.selectedVariant = x
console.log(x)
}
},
computed: {
title() {
return this.brand + ' ' + this.product
},
image() {
return this.variants[this.selectedVariant].variantImage
},
inStock() {
return this.variants[this.selectedVariant].variantQty
},
shipping() {
if (this.premium) {
return "Free"
} else
return "$2.99"
}
}
})
var app = new Vue({
el: '#app',
data: {
premium: true,
cart: []
},
methods: {
updateCart(id) {
this.cart.push(id)
}
}
})<file_sep>/README.md
# vueLearnBasics
## Coding along Vue Mastery's "Intro to Vue.js" course.
This app features socks as a product. It lets you select from two different colors, lets you know whether the sock type is in stock or not, and lets you add the product to your cart.
**Screenshot**
<img src="images/screenshot.jpg" alt="main-page-screenshot" width="100%"/>
|
193c5e2a56608fb6b99d4ae852d8c35a42078749
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
fateeq/vueLearnBasics
|
9018bc274a26011f4d580c9520522fd34952afa5
|
3a9ab4788ccf81b141eddf885585879d574794c9
|
refs/heads/master
|
<file_sep># Baby_Vibes_Pytorch_Azure_Webservice
Webservice deployed in Azure. Built in Pytorch Fastai . Makes crying babies happy by playing Tom and Jerry!!

<file_sep>import os
import urllib
from io import BytesIO
#from PIL import Image
from flask import Flask,request,redirect,url_for,render_template,flash
from werkzeug.utils import secure_filename
import json, requests
import os, base64
import urllib
#from PIL import Image
scoring_uri = 'http://7724f32c-4659-4a04-823d-39ef71e678c5.westus.azurecontainer.io/score'
headers = {'Content-Type': 'application/json'}
def preprocess(image):
# Image = requests.get(url)
# with open("test.jpg","wb") as f:
# f.write(Image.content)
with open(image , mode='rb') as file:
test = file.read()
data = str(base64.b64encode(test), encoding='utf-8')
input_data = json.dumps({'data': data})
return input_data
# create the application project
app = Flask(__name__)
@app.route("/", methods=['GET'])
def home():
return render_template('index.html')
@app.route("/predict", methods=['GET','POST'])
def upload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
print(str(file_path))
# Make prediction
input_data = preprocess(str(file_path))
preds = requests.post(scoring_uri,input_data,headers=headers)
result = preds.text
return result
return None
# if __name__=='__main__':
# app.run(debug=True)<file_sep>
import os
import torch
import numpy as np
import fastai
from fastai import *
from fastai.vision import *
print("PyTorch version %s" % torch.__version__)
print("fastai version: %s" % fastai.__version__)
print("CUDA supported: %s" % torch.cuda.is_available())
print("CUDNN enabled: %s" % torch.backends.cudnn.enabled)
def download_data():
"""Download and extract the training data."""
import urllib
from zipfile import ZipFile
from pathlib import Path
# download data
data_file = './Babies.zip'
download_url = 'http://p0f.310.myftpupload.com/wp-content/uploads/2020/02/Babies.zip'
urllib.request.urlretrieve(download_url, filename=data_file)
# extract files
with ZipFile(data_file, 'r') as zip:
print('extracting files...')
zip.extractall()
print('finished extracting')
data_dir = Path('.' + '/Babies')
# delete zip file
os.remove(data_file)
return data_dir
path = download_data()
data = ImageDataBunch.from_folder(path,valid_pct=0.05,ds_tfms=get_transforms(),size=224).normalize(imagenet_stats)
learn = create_cnn(data, models.resnet50, metrics=accuracy)
learn.fit_one_cycle(1)
learn.unfreeze()
learn.fit_one_cycle(1, slice(1e-5,3e-4), pct_start=0.05)
saved_model_path = learn.save('Babies', return_path = True)
learn.export()
saved_model_pkl = str(learn.path) + '/export.pkl'
from azureml.core import Run
run = Run.get_context()
def reduce_list(all_values):
return [np.max(all_values[i:i+10]) for i in range(0,len(all_values)-1,10)]
losses_values = [tensor.item() for tensor in learn.recorder.losses]
accuracy_value = np.float(accuracy(*learn.TTA()))
run.log('training_acc', accuracy_value)
run.log('pytorch', torch.__version__)
run.log('fastai', fastai.__version__)
run.log('base_model', 'resnet50')
#run.log_list('Learning_rate', reduce_list(learn.recorder.lrs))
run.log_list('Loss', reduce_list(losses_values))
from shutil import copyfile
copyfile(saved_model_pkl, './outputs/Babies.pkl')
|
8cb61211ccc0cda208a6adccd830961a7e885b18
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
SriramyaK/Baby_Vibes_Pytorch_Azure_Webservice
|
9df64f6bf8629dbbaa9023fac67237661c571ebe
|
bf91ee4e29e72af331f3ab8b6e181e62af9b6c3b
|
refs/heads/master
|
<repo_name>alonmelon25/dig4e_audio<file_sep>/index.php
<?php
use \Tsugi\Util\Net;
use \Tsugi\Core\LTIX;
use \Tsugi\UI\Output;
// Help the installer through the setup process
require "check.php" ;
require "top.php";
require "nav.php";
// Help the installer through the setup process
require_once "tsugi/admin/sanity-db.php";
?>
<div id="container">
<!--
<div style="margin-left: 10px; float:right">
<iframe width="400" height="225" src="" frameborder="0" allowfullscreen></iframe>
</div>
-->
<div id="grid-container" style="display: grid; grid-template-columns: 10% 90%;">
<img src="https://image.dig4e.com/images/imaginglogo.png" alt="Dig4E Imaging Logo" style = "width: 8em; height: 8em; grid-column: 1/2; border: 10 px; margin: 20px;"/>
<h1 style="color: #0D805B; font-weight: 600; font-family: Raleway, Sans-Serif; font-size: 3em;grid-column: 2/2; padding-top: 1em; padding-left: 1em;">Digitization for Everybody - Audio</h1>
</div>
<div id="container" style="dispalay: container; background-color: #0D805B; height: 1em; margin-top: 1em; margin-bottom: 1em;">
</div>
<div id="container" style= "color: #555555; font-family: Lusitana, Serif; font-weight: 500; font-size: 18px; margin-bottom: 1em;" >
In the Dig4E Audio module, you learn about the present state of standards and recommended best practices for the digital re-recording of analog audio signals stored on magnetic tape. In most cases, the underlying technical standards for audio digitization are stable and complete, although professionals debate how to apply the standards to a wide variety of audio media. For the vast majority of the audio holdings in cultural heritage organizations, archival quality digitization is technically and administratively feasible.</div>
<div id="container" style="dispalay: container; background-color: #0D805B; height: 1em; margin-top: 1em; margin-bottom: 1em;">
</div>
<div id="grid-container" style="display: grid; grid-template-columns: 30% 70%;">
<iframe width="300" height="200" src="https://www.youtube.com/embed/QhcWu-2dOxU" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><p style="color: #555555; font-family: Lusitana, Serif; font-weight: 500; font-size: 18px;grid-column: 2/2; padding-top: 1em;">This video introduces the Audio module in the broader context of the risks and challenges to audio heritage. The primary points are the consequences of inaction, the critical value of digital processes for rescuing audio content, and the complexities of legacy playback. The video also introduces the top level learning goals for the Audio module.</p>
</div>
<div id="container" style="dispalay: container; background-color: #0D805B; height: 1em; margin-top: 1em; margin-bottom: 1em;">
</div>
<div id="grid-container" style ="display: grid; grid-template-columns: 50% 50%; grid-row-gap: 1em;" hover="background-color: rgba(158, 79, 0, 0.2);">
<a href="https://audio.dig4e.com/lessons"><img src="https://image.dig4e.com/images/lessons.png" alt="Lessons Logo" style= "width: 10em; height 10em; position: inline; margin-left: 35%; margin-right: 35%; hover: #9E4F002E"/></a>
<a href="https://audio.dig4e.com/assignments"><img src="https://image.dig4e.com/images/quizzes.png" alt="Quizzes Logo" style= "width: 10em; height 10em; position: inline; margin-left: 35%; margin-right: 50%;"/></a>
<a href="https://audio.dig4e.com/lessons" style="color: #00274C; font-family: Raleway, Sans-Serif; font-weight: 500; font-size: 2em; position: inline; margin-left: 39%; margin-right: 46%; grid-column: 1; grid-row: 2">Lessons</a>
<a href="https://audio.dig4e.com/assignments" style="color: #00274C; font-family: Raleway, Sans-Serif; font-weight: 500; font-size: 2em; position: inline; margin-left: 39%; margin-right: 46%; grid-column: 2; grid-row: 2">Quizzes</a>
</div>
<?php if ( isset($_SESSION['id']) ) { ?>
<?php } else { ?>
<?php } ?>
<!--
<?php
echo("IP Address: ".Net::getIP()."\n");
echo(Output::safe_var_dump($_SESSION));
var_dump($USER);
?>
-->
</div>
<?php
require "foot.php";
|
b763e24256b5d58883de1ecdcf26d72eb8b8421a
|
[
"PHP"
] | 1 |
PHP
|
alonmelon25/dig4e_audio
|
12238c20c2a79064f7252f9633efc4651ea8522b
|
e8b8b664df037f05dc6299653bfbf6cd6102674a
|
refs/heads/master
|
<file_sep>SMS ONE TIME
-------------
This is a private members script that uses PHP, MYSQL, JQUERY MOBILE and SMS.
The login is nice and secure and members can only access the site if they hold a valid mobile number.
It will text them a one time code to access the site and then allow them to view the private.php file's contents.
No Mobile numbers are stored in the database so you do not have to worry if you server gets hacked some other way.
It is based on a how to from [here] (http://forums.devshed.com/php-faqs-and-stickies-167/how-to-program-a-basic-but-secure-login-system-using-891201.html)
I have integrated textlocal to send the SMS but you can easily alter this in the functions file.
Edit the common.php file to enter your mysql details and fill in your textlocal account details.
Don't forget to import the users.sql file!
tested on lighthttpd but apache should work fine.
Any Issues or happy to donate via paypal <EMAIL>
<file_sep><?php
require_once('common.php');
require_once('function.php');
// Is user logged in?
loggedin();
if ($_REQUEST['submit'] == "")
{ header ('location: sms.php'); }
if ($_POST['submit'] == "Submit Number") {
// Submit Number has been hit...
$number = $_POST['number'];
$userid = $_POST['user'];
//Check Number Length
$count = strlen($number);
if ($count != "11" ) {
header ('location: sms.php?error=shortnum');
die();
}
// Check Number Starts with 07
if (!preg_match('/^07/', $number))
{
header ('location: sms.php?error=startnum');
die();
}
// Grab the verified Code to send to user.
GLOBAL $db;
$sth2 = $db->prepare('SELECT * FROM users WHERE id = :userid ');
$sth2->bindParam(':userid', $userid);
$sth2->execute();
$row2 = $sth2->fetch();
$smskey = $row2['smskey'];
$message = 'Your SMS Verification Code: '.$smskey.''; // SMS message that is sent to the user
sendsms ($smskey,$number,$message);
}
if ($_POST['submit'] == "Submit Code") {
// confirm verified code
GLOBAL $db;
$code = $_POST['code'];
$sth3 = $db->prepare('SELECT * FROM users WHERE smskey = :smskey ');
$sth3->bindParam(':smskey', $code);
$sth3->execute();
$count = $sth3->rowCount();
if ($count == "0") {
header ('location: sms.php?error=wrong');
die();
} else {
$sth4 = $db->prepare('UPDATE users SET active = 1 WHERE smskey = :smskey ');
$sth4->bindParam(':smskey', $code);
$sth4->execute();
header ('location: private.php');
}
}
?><file_sep><?php
######################################################
# function.php by <NAME> #
# #
# questions or donate <EMAIL> #
######################################################
function header2()
{
echo '
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<br>';
}
function footer2()
{
echo '
</div>
</body>
</html>';
}
function loggedin()
{
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// Everything below this point in the file is secured by the login system
}
// If user has just registered redirect to sms.php
function is_active ($user)
{
GLOBAL $db;
$sth = $db->prepare('SELECT * FROM users WHERE username = :username ');
$sth->bindParam(':username', $user);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
if ($row['active'] == "0") {
header('location: sms.php');
}
}
}
function active_level ($user)
{
GLOBAL $db;
$sth = $db->prepare('SELECT * FROM users WHERE username = :username ');
$sth->bindParam(':username', $user);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$level = $row['active'];
return $level;
}
function sendsms ($smskey,$number,$message)
{
include ('common.php');
GLOBAL $test;
GLOBAL $smsid;
GLOBAL $tlhash;
GLOBAL $tlusername;
// Prepare data for POST request
$data = array('username' => $tlusername, 'hash' => $tlhash, 'numbers' => $number, "sender" => $smsid, "message" => $message, "test" => $test);
// Send the POST request with cURL
$ch = curl_init('https://api.txtlocal.com/send/');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process your response here
$json = json_decode($response, true);
$sent = $json['status'];
if ($sent === "success"){
header ('location: sms.php?confirm=yes');
} else {
header ('location: sms.php?error=api');
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<file_sep><?php
// First we execute our common code to connection to the database and start the session
require_once("common.php");
//ERROR MESSAGES
$shortnum = "<strong>ERROR: Number should be 11 digits </strong>";
$startnum = "<strong>ERROR: Number must start 07</strong>";
$apierror = "<strong>ERROR: Please contact support SMS API error has occurred</strong>";
$wrongsmskey = "<strong>ERROR: The key you have entered is not valid</strong>";
// Is user logged in?
loggedin();
// We can display the user's username to them by reading it from the session array. Remember that because
// a username is user submitted content we must use htmlentities on it before displaying it to the user.
$user = $_SESSION['user']['id'];
function entermob() {
header2();
$user = $_SESSION['user']['id'];
echo'
<div data-role="page" data-theme="b" align="center">
<div id="mobile">
<form action="validate.php" method="post" id="numberconfirm">
<h2><label>Enter Mobile Number</label></h2>
Mobile Number: <input type="text" name="number">
<input type="hidden" name="user" value="'.$user.'">
<br><br>
<input type="submit" name="submit" data-inline="true" value="Submit Number">
</form><div id="results">'; if ((isset($error) ));
footer2();
}
function entercode () {
GLOBAL $error;
header2();
echo '
<div data-role="page" id="newsms" data-theme="b" align="center">
<div id="code">
<form action="validate.php" method="post" id="numberconfirm">
<h2><label>Enter Verification Code</label></h2>
Verification Code: <input type="text" name="code">
<br><br>
<input type="submit" name="submit" data-inline="true" value="Submit Code">
</form><div id="results">';
if ((isset($error) ));
footer2();
}
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'shortnum') {
entermob();
echo $shortnum;
}
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'startnum') {
entermob();
echo $startnum;
}
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'api') {
entermob();
echo $apierror;
}
if (empty($_GET)) {
entermob();
}
if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 'yes') {
entercode();
}
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'wrong') {
entercode();
echo $wrongsmskey;
}
?>
|
143270646521458990e9995c96708a58ce2bd2a1
|
[
"Markdown",
"PHP"
] | 4 |
Markdown
|
random-robbie/smsonetime
|
64f1aa825e601b54671f9305d0119c0d1c19db17
|
c26251741b7aa77261b84472f303ebc28c829113
|
refs/heads/master
|
<file_sep>package compile
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"github.com/monax/bosmarmot/bos/util"
log "github.com/sirupsen/logrus"
)
type Response struct {
Objects []ResponseItem `json:"objects"`
Warning string `json:"warning"`
Version string `json:"version"`
Error string `json:"error"`
}
type BinaryResponse struct {
Binary string `json:"binary"`
Error string `json:"error"`
}
// Compile response object
type ResponseItem struct {
Objectname string `json:"objectname"`
Bytecode string `json:"bytecode"`
ABI string `json:"abi"` // json encoded
}
func (resp Response) CacheNewResponse(req util.Request) {
objects := resp.Objects
//log.Debug(objects)
cacheLocation := util.Languages[req.Language].CacheDir
cur, _ := os.Getwd()
os.Chdir(cacheLocation)
defer func() {
os.Chdir(cur)
}()
for fileDir, metadata := range req.Includes {
dir := path.Join(cacheLocation, strings.TrimRight(fileDir, "."+req.Language))
os.MkdirAll(dir, 0700)
objectNames := metadata.ObjectNames
for _, name := range objectNames {
for _, object := range objects {
if object.Objectname == name {
//log.WithField("=>", resp.Objects).Debug("Response objects over the loop")
CacheResult(object, dir, resp.Warning, resp.Version, resp.Error)
break
}
}
}
}
}
func linkBinaries(req *util.BinaryRequest) *BinaryResponse {
// purely for solidity and solidity alone as this is soon to be deprecated.
if req.Libraries == "" {
return &BinaryResponse{
Binary: req.BinaryFile,
Error: "",
}
}
buf := bytes.NewBufferString(req.BinaryFile)
var output bytes.Buffer
var stderr bytes.Buffer
args := []string{"--link"}
for _, l := range strings.Split(req.Libraries, " ") {
if len(l) > 0 {
args = append(args, "--libraries", l)
}
}
linkCmd := exec.Command("solc", args...)
linkCmd.Stdin = buf
linkCmd.Stderr = &stderr
linkCmd.Stdout = &output
linkCmd.Start()
linkCmd.Wait()
return &BinaryResponse{
Binary: strings.TrimSpace(output.String()),
Error: stderr.String(),
}
}
func RequestBinaryLinkage(file string, libraries string) (*BinaryResponse, error) {
//Create Binary Request, send it off
code, err := ioutil.ReadFile(file)
if err != nil {
return &BinaryResponse{}, err
}
request := &util.BinaryRequest{
BinaryFile: string(code),
Libraries: libraries,
}
return linkBinaries(request), nil
}
//todo: Might also need to add in a map of library names to addrs
func RequestCompile(file string, optimize bool, libraries string) (*Response, error) {
util.InitScratchDir()
request, err := CreateRequest(file, libraries, optimize)
if err != nil {
return nil, err
}
//todo: check server for newer version of same files...
// go through all includes, check if they have changed
cached := CheckCached(request.Includes, request.Language)
log.WithField("cached?", cached).Debug("Cached Item(s)")
/*for k, v := range request.Includes {
log.WithFields(log.Fields{
"k": k,
"v": string(v.Script),
}).Debug("check request loop")
}*/
var resp *Response
// if everything is cached, no need for request
if cached {
// TODO: need to return all contracts/libs tied to the original src file
resp, err = CachedResponse(request.Includes, request.Language)
if err != nil {
return nil, err
}
} else {
log.Debug("Could not find cached object, compiling...")
resp = compile(request)
resp.CacheNewResponse(*request)
}
PrintResponse(*resp, false)
return resp, nil
}
// Compile takes a dir and some code, replaces all includes, checks cache, compiles, caches
func compile(req *util.Request) *Response {
if _, ok := util.Languages[req.Language]; !ok {
return compilerResponse("", "", "", "", "", fmt.Errorf("No script provided"))
}
lang := util.Languages[req.Language]
includes := []string{}
currentDir, _ := os.Getwd()
defer os.Chdir(currentDir)
for k, v := range req.Includes {
os.Chdir(lang.CacheDir)
file, err := CreateTemporaryFile(k, v.Script)
if err != nil {
return compilerResponse("", "", "", "", "", err)
}
defer os.Remove(file.Name())
includes = append(includes, file.Name())
log.WithField("Filepath of include: ", file.Name()).Debug("To Cache")
}
libsFile, err := CreateTemporaryFile("monax-libs", []byte(req.Libraries))
if err != nil {
return compilerResponse("", "", "", "", "", err)
}
defer os.Remove(libsFile.Name())
command := lang.Cmd(includes, libsFile.Name(), req.Optimize)
log.WithField("Command: ", command).Debug("Command Input")
output, err := runCommand(command...)
var warning string
jsonBeginsCertainly := strings.Index(output, `{"contracts":`)
if jsonBeginsCertainly > 0 {
warning = output[:jsonBeginsCertainly]
output = output[jsonBeginsCertainly:]
}
//cleanup
log.WithField("=>", output).Debug("Output from command: ")
if err != nil {
for _, str := range includes {
output = strings.Replace(output, str, req.FileReplacement[str], -1)
}
log.WithFields(log.Fields{
"err": err,
"command": command,
"response": output,
}).Debug("Could not compile")
return compilerResponse("", "", "", "", "", fmt.Errorf("%v: %v", err, output))
}
solcResp := util.BlankSolcResponse()
//todo: provide unmarshalling for serpent and lll
log.WithField("Json: ", output).Debug("Command Output")
err = json.Unmarshal([]byte(output), solcResp)
if err != nil {
log.Debug("Could not unmarshal json")
return compilerResponse("", "", "", "", "", err)
}
respItemArray := make([]ResponseItem, 0)
for contract, item := range solcResp.Contracts {
respItem := ResponseItem{
Objectname: objectName(contract),
Bytecode: strings.TrimSpace(item.Bin),
ABI: strings.TrimSpace(item.Abi),
}
respItemArray = append(respItemArray, respItem)
}
for _, re := range respItemArray {
log.WithFields(log.Fields{
"name": re.Objectname,
"bin": re.Bytecode,
"abi": re.ABI,
}).Debug("Response formulated")
}
return &Response{
Objects: respItemArray,
Warning: warning,
Error: "",
}
}
func objectName(contract string) string {
if contract == "" {
return ""
}
parts := strings.Split(strings.TrimSpace(contract), ":")
return parts[len(parts)-1]
}
func runCommand(tokens ...string) (string, error) {
cmd := tokens[0]
args := tokens[1:]
shellCmd := exec.Command(cmd, args...)
output, err := shellCmd.CombinedOutput()
s := strings.TrimSpace(string(output))
return s, err
}
func CreateRequest(file string, libraries string, optimize bool) (*util.Request, error) {
var includes = make(map[string]*util.IncludedFiles)
//maps hashes to original file name
var hashFileReplacement = make(map[string]string)
language, err := LangFromFile(file)
if err != nil {
return &util.Request{}, err
}
compiler := &util.Compiler{
Config: util.Languages[language],
Lang: language,
}
code, err := ioutil.ReadFile(file)
if err != nil {
return &util.Request{}, err
}
dir := path.Dir(file)
//log.Debug("Before parsing includes =>\n\n%s", string(code))
code, err = compiler.ReplaceIncludes(code, dir, file, includes, hashFileReplacement)
if err != nil {
return &util.Request{}, err
}
return compiler.CompilerRequest(file, includes, libraries, optimize, hashFileReplacement), nil
}
// New response object from bytecode and an error
func compilerResponse(objectname, bytecode, abi, warning, version string, err error) *Response {
e := ""
if err != nil {
e = err.Error()
}
respItem := ResponseItem{
Objectname: objectname,
Bytecode: bytecode,
ABI: abi}
respItemArray := make([]ResponseItem, 1)
respItemArray[0] = respItem
return &Response{
Objects: respItemArray,
Warning: warning,
Version: version,
Error: e,
}
}
func PrintResponse(resp Response, cli bool) {
if resp.Error != "" {
log.Warn(resp.Error)
} else {
for _, r := range resp.Objects {
message := log.WithFields((log.Fields{
"name": r.Objectname,
"bin": r.Bytecode,
"abi": r.ABI,
}))
if cli {
message.Warn("Response")
} else {
message.Info("Response")
}
}
}
}
<file_sep>package loader
import (
"fmt"
"path/filepath"
"github.com/monax/bosmarmot/bos/def"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
func LoadPackage(fileName string) (*def.Package, error) {
log.Info("Loading monax Jobs Definition File.")
var pkg = def.BlankPackage()
var epmJobs = viper.New()
// setup file
abs, err := filepath.Abs(fileName)
if err != nil {
return nil, fmt.Errorf("Sorry, the marmots were unable to find the absolute path to the monax jobs file.")
}
path := filepath.Dir(abs)
file := filepath.Base(abs)
extName := filepath.Ext(file)
bName := file[:len(file)-len(extName)]
log.WithFields(log.Fields{
"path": path,
"name": bName,
}).Debug("Loading monax jobs file")
epmJobs.SetConfigType("yaml")
epmJobs.AddConfigPath(path)
epmJobs.SetConfigName(bName)
// load file
if err := epmJobs.ReadInConfig(); err != nil {
return nil, fmt.Errorf("Sorry, the marmots were unable to load the monax jobs file. Please check your path: %v", err)
}
// marshall file
if err := epmJobs.Unmarshal(pkg); err != nil {
return nil, fmt.Errorf(`Sorry, the marmots could not figure that monax jobs file out.
Please check that your epm.yaml is properly formatted: %v`, err)
}
// TODO more file sanity check (fail before running)
return pkg, nil
}
<file_sep>package jobs
import (
"fmt"
"strings"
"github.com/monax/bosmarmot/bos/def"
log "github.com/sirupsen/logrus"
)
func RunJobs(do *def.Packages) error {
// Dial the chain
err := do.Dial()
if err != nil {
return err
}
// ADD DefaultAddr and DefaultSet to jobs array....
// These work in reverse order and the addendums to the
// the ordering from the loading process is lifo
if len(do.DefaultSets) >= 1 {
defaultSetJobs(do)
}
if do.Address != "" {
defaultAddrJob(do)
}
for _, job := range do.Package.Jobs {
switch {
// Meta Job
case job.Meta != nil:
announce(job.JobName, "Meta")
do.CurrentOutput = fmt.Sprintf("%s.output.json", job.JobName)
job.JobResult, err = MetaJob(job.Meta, do)
// Util jobs
case job.Account != nil:
announce(job.JobName, "Account")
job.JobResult, err = SetAccountJob(job.Account, do)
case job.Set != nil:
announce(job.JobName, "Set")
job.JobResult, err = SetValJob(job.Set, do)
// Transaction jobs
case job.Send != nil:
announce(job.JobName, "Sent")
job.JobResult, err = SendJob(job.Send, do)
case job.RegisterName != nil:
announce(job.JobName, "RegisterName")
job.JobResult, err = RegisterNameJob(job.RegisterName, do)
case job.Permission != nil:
announce(job.JobName, "Permission")
job.JobResult, err = PermissionJob(job.Permission, do)
// Contracts jobs
case job.Deploy != nil:
announce(job.JobName, "Deploy")
job.JobResult, err = DeployJob(job.Deploy, do)
case job.Call != nil:
announce(job.JobName, "Call")
job.JobResult, job.JobVars, err = CallJob(job.Call, do)
if len(job.JobVars) != 0 {
for _, theJob := range job.JobVars {
log.WithField("=>", fmt.Sprintf("%s,%s", theJob.Name, theJob.Value)).Info("Job Vars")
}
}
// State jobs
case job.RestoreState != nil:
announce(job.JobName, "RestoreState")
job.JobResult, err = RestoreStateJob(job.RestoreState, do)
case job.DumpState != nil:
announce(job.JobName, "DumpState")
job.JobResult, err = DumpStateJob(job.DumpState, do)
// Test jobs
case job.QueryAccount != nil:
announce(job.JobName, "QueryAccount")
job.JobResult, err = QueryAccountJob(job.QueryAccount, do)
case job.QueryContract != nil:
announce(job.JobName, "QueryContract")
job.JobResult, job.JobVars, err = QueryContractJob(job.QueryContract, do)
if len(job.JobVars) != 0 {
for _, theJob := range job.JobVars {
log.WithField("=>", fmt.Sprintf("%s,%s", theJob.Name, theJob.Value)).Info("Job Vars")
}
}
case job.QueryName != nil:
announce(job.JobName, "QueryName")
job.JobResult, err = QueryNameJob(job.QueryName, do)
case job.QueryVals != nil:
announce(job.JobName, "QueryVals")
job.JobResult, err = QueryValsJob(job.QueryVals, do)
case job.Assert != nil:
announce(job.JobName, "Assert")
job.JobResult, err = AssertJob(job.Assert, do)
}
if err != nil {
return err
}
}
postProcess(do)
return nil
}
func announce(job, typ string) {
log.Warn("\n*****Executing Job*****\n")
log.WithField("=>", job).Warn("Job Name")
log.WithField("=>", typ).Info("Type")
}
func defaultAddrJob(do *def.Packages) {
oldJobs := do.Package.Jobs
newJob := &def.Job{
JobName: "defaultAddr",
Account: &def.Account{
Address: do.Address,
},
}
do.Package.Jobs = append([]*def.Job{newJob}, oldJobs...)
}
func defaultSetJobs(do *def.Packages) {
oldJobs := do.Package.Jobs
newJobs := []*def.Job{}
for _, setr := range do.DefaultSets {
blowdUp := strings.Split(setr, "=")
if blowdUp[0] != "" {
newJobs = append(newJobs, &def.Job{
JobName: blowdUp[0],
Set: &def.SetJob{
Value: blowdUp[1],
},
})
}
}
do.Package.Jobs = append(newJobs, oldJobs...)
}
func postProcess(do *def.Packages) error {
// Formulate the results map
results := make(map[string]string)
for _, job := range do.Package.Jobs {
results[job.JobName] = job.JobResult
}
// check do.YAMLPath and do.DefaultOutput
var yaml string
yamlName := strings.LastIndexByte(do.YAMLPath, '.')
if yamlName >= 0 {
yaml = do.YAMLPath[:yamlName]
} else {
return fmt.Errorf("invalid jobs file path (%s)", do.YAMLPath)
}
// if do.YAMLPath is not default and do.DefaultOutput is default, over-ride do.DefaultOutput
if yaml != "epm" && do.DefaultOutput == "epm.output.json" {
do.DefaultOutput = fmt.Sprintf("%s.output.json", yaml)
}
// if CurrentOutput set, we're in a meta job
if do.CurrentOutput != "" {
log.Warn(fmt.Sprintf("Writing meta output of [%s] to current directory", do.CurrentOutput))
return WriteJobResultJSON(results, do.CurrentOutput)
}
// Write the output
log.Warn(fmt.Sprintf("Writing [%s] to current directory", do.DefaultOutput))
return WriteJobResultJSON(results, do.DefaultOutput)
}
<file_sep>#!/usr/bin/env bash
# ----------------------------------------------------------
# PURPOSE
# This is the test manager for monax jobs. It will run the testing
# sequence for monax jobs referencing test fixtures in this tests directory.
# ----------------------------------------------------------
# REQUIREMENTS
# m
# ----------------------------------------------------------
# USAGE
# run_pkgs_tests.sh [appXX]
# Various required binaries locations can be provided by wrapper
bos_bin=${bos_bin:-bos}
burrow_bin=${burrow_bin:-burrow}
# currently we must use 'solc' as hardcoded by compilers
solc_bin=solc
# If false we will not try to start Burrow and expect them to be running
boot=${boot:-true}
debug=${debug:-false}
test_exit=0
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [[ "$debug" = true ]]; then
set -o xtrace
fi
# ----------------------------------------------------------
# Constants
# Ports etc must match those in burrow.toml
grpc_port=20997
tendermint_port=36656
chain_dir="$script_dir/chain"
burrow_root="$chain_dir/.burrow"
# Temporary logs
burrow_log=burrow.log
#
# ----------------------------------------------------------
# ---------------------------------------------------------------------------
# Needed functionality
goto_base(){
cd ${script_dir}/jobs_fixtures
}
pubkey_of() {
jq -r ".Accounts | map(select(.Name == \"$1\"))[0].PublicKey.PublicKey" chain/genesis.json
}
address_of() {
jq -r ".Accounts | map(select(.Name == \"$1\"))[0].Address" chain/genesis.json
}
test_setup(){
echo "Setting up..."
cd "$script_dir"
echo
echo "Using binaries:"
echo " $(type ${solc_bin}) (version: $(${solc_bin} --version))"
echo " $(type ${bos_bin}) (version: $(${bos_bin} version))"
echo " $(type ${burrow_bin}) (version: $(${burrow_bin} --version))"
echo
# start test chain
if [[ "$boot" = true ]]; then
echo "Starting Burrow with tendermint port: $tendermint_port, GRPC port: $grpc_port"
rm -rf ${burrow_root}
$(cd "$chain_dir" && ${burrow_bin} start -v0 2> "$burrow_log")&
burrow_pid=$!
else
echo "Not booting Burrow, but expecting Burrow to be running with tm RPC on port $grpc_port"
fi
key1_addr=$(address_of "Full_0")
key2_addr=$(address_of "Participant_0")
key2_pub=$(pubkey_of "Participant_0")
echo -e "Default Key =>\t\t\t\t$key1_addr"
echo -e "Backup Key =>\t\t\t\t$key2_addr"
sleep 4 # boot time
echo "Setup complete"
echo ""
}
run_test(){
# Run the jobs test
echo ""
echo -e "Testing $bos_bin jobs using fixture =>\t$1"
goto_base
cd $1
echo
cat readme.md
echo
echo ${bos_bin} --chain-url="localhost:$grpc_port" --address "$key1_addr" \
--set "addr1=$key1_addr" --set "addr2=$key2_addr" --set "addr2_pub=$key2_pub" #--debug
${bos_bin} --chain-url="localhost:$grpc_port" --address "$key1_addr" \
--set "addr1=$key1_addr" --set "addr2=$key2_addr" --set "addr2_pub=$key2_pub" #--debug
test_exit=$?
git clean -fdx ../**/abi ../**/bin ./jobs_output.csv
rm ./*.output.json
# Reset for next run
goto_base
return $test_exit
}
perform_tests(){
echo ""
goto_base
apps=($1*/)
echo $apps
repeats=${2:-1}
# Useful for soak testing/generating background requests to trigger concurrency issues
for rep in `seq ${repeats}`
do
for app in "${apps[@]}"
do
echo "Test: $app, Repeat: $rep"
run_test ${app}
# Set exit code properly
test_exit=$?
if [ ${test_exit} -ne 0 ]
then
break
fi
done
done
}
perform_tests_that_should_fail(){
echo ""
goto_base
apps=($1*/)
for app in "${apps[@]}"
do
run_test ${app}
# Set exit code properly
test_exit=$?
if [ ${test_exit} -ne 0 ]
then
# actually, this test is meant to pass
test_exit=0
else
break
fi
done
}
test_teardown(){
echo "Cleaning up..."
if [[ "$boot" = true ]]; then
kill ${burrow_pid}
echo "Waiting for burrow to shutdown..."
wait ${burrow_pid} 2> /dev/null &
rm -rf "$burrow_root"
fi
echo ""
if [[ "$test_exit" -eq 0 ]]
then
[[ "$boot" = true ]] && rm -f "$burrow_log"
echo "Tests complete! Tests are Green. :)"
else
echo "Tests complete. Tests are Red. :("
echo "Failure in: $app"
fi
exit ${test_exit}
}
# ---------------------------------------------------------------------------
# Setup
echo "Hello! I'm the marmot that tests the $bos_bin jobs tooling."
echo
echo "testing with target $bos_bin"
echo
test_setup
# ---------------------------------------------------------------------------
# Go!
if [[ "$1" != "setup" ]]
then
# Cleanup
trap test_teardown EXIT
if ! [ -z "$1" ]
then
echo "Running tests beginning with $1..."
perform_tests "$1" "$2"
else
echo "Running tests that should fail"
perform_tests_that_should_fail expected-failure
echo "Running tests that should pass"
perform_tests app
fi
fi
<file_sep>package commands
import "github.com/spf13/cobra"
const helpTemplate = `Usage: {{.UseLine}}{{if .Runnable}}{{if .HasSubCommands}} COMMAND{{end}}{{if .HasFlags}} [FLAG...]{{end}}{{end}}
{{.Long}}
{{if gt .Aliases 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
Available commands:{{range .Commands}}{{if .IsAvailableCommand}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}}
Global flags:
{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}{{end}}
`
var Help = &cobra.Command{
Use: "help COMMAND",
Short: "Help about a command",
Long: `Provide help for any command in the application.
Type monax help COMMAND for full details.`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {},
PersistentPostRun: func(cmd *cobra.Command, args []string) {},
Run: func(c *cobra.Command, args []string) {
cmd, _, e := c.Root().Find(args)
if cmd == nil || e != nil {
c.Printf("Unknown help topic %#q.", args)
c.Root().Usage()
} else {
helpFunc := cmd.HelpFunc()
helpFunc(cmd, args)
}
},
}
<file_sep>[prune]
unused-packages = true
go-tests = true
non-go = true
[[prune.project]]
name = "github.com/hyperledger/burrow"
unused-packages = false
non-go = false
[[override]]
name = "github.com/hyperledger/burrow"
version = "=0.20.0"
[[override]]
name = "github.com/tendermint/tendermint"
version = "=0.22.4"
[[override]]
name = "github.com/gogo/protobuf"
version = "~1.1.0"
[[override]]
name = "github.com/golang/protobuf"
version = "~1.1.0"
[[override]]
name = "google.golang.org/grpc"
version = "~1.13.0"
<file_sep>package jobs
import (
"encoding/hex"
"fmt"
"strconv"
"github.com/monax/bosmarmot/bos/abi"
"github.com/monax/bosmarmot/bos/def"
"github.com/monax/bosmarmot/bos/util"
log "github.com/sirupsen/logrus"
)
func QueryContractJob(query *def.QueryContract, do *def.Packages) (string, []*def.Variable, error) {
// Preprocess variables. We don't preprocess data as it is processed by ReadAbiFormulateCall
query.Source, _ = util.PreProcess(query.Source, do)
query.Destination, _ = util.PreProcess(query.Destination, do)
query.ABI, _ = util.PreProcess(query.ABI, do)
var queryDataArray []string
var err error
query.Function, queryDataArray, err = util.PreProcessInputData(query.Function, query.Data, do, false)
if err != nil {
return "", nil, err
}
// Get the packed data from the ABI functions
var data string
var packedBytes []byte
if query.ABI == "" {
packedBytes, err = abi.ReadAbiFormulateCall(query.Destination, query.Function, queryDataArray, do)
data = hex.EncodeToString(packedBytes)
} else {
packedBytes, err = abi.ReadAbiFormulateCall(query.ABI, query.Function, queryDataArray, do)
data = hex.EncodeToString(packedBytes)
}
if err != nil {
var str, err = util.ABIErrorHandler(do, err, nil, query)
return str, nil, err
}
// Call the client
txe, err := do.QueryContract(def.QueryArg{
Input: query.Source,
Address: query.Destination,
Data: data,
})
if err != nil {
return "", nil, err
}
// Formally process the return
log.WithField("res", txe.Result.Return).Debug("Decoding Raw Result")
if query.ABI == "" {
log.WithField("abi", query.Destination).Debug()
query.Variables, err = abi.ReadAndDecodeContractReturn(query.Destination, query.Function, txe.Result.Return, do)
} else {
log.WithField("abi", query.ABI).Debug()
query.Variables, err = abi.ReadAndDecodeContractReturn(query.ABI, query.Function, txe.Result.Return, do)
}
if err != nil {
return "", nil, err
}
result2 := util.GetReturnValue(query.Variables)
// Finalize
if result2 != "" {
log.WithField("=>", result2).Warn("Return Value")
} else {
log.Debug("No return.")
}
return result2, query.Variables, nil
}
func QueryAccountJob(query *def.QueryAccount, do *def.Packages) (string, error) {
// Preprocess variables
query.Account, _ = util.PreProcess(query.Account, do)
query.Field, _ = util.PreProcess(query.Field, do)
// Perform Query
arg := fmt.Sprintf("%s:%s", query.Account, query.Field)
log.WithField("=>", arg).Info("Querying Account")
result, err := util.AccountsInfo(query.Account, query.Field, do)
if err != nil {
return "", err
}
// Result
if result != "" {
log.WithField("=>", result).Warn("Return Value")
} else {
log.Debug("No return.")
}
return result, nil
}
func QueryNameJob(query *def.QueryName, do *def.Packages) (string, error) {
// Preprocess variables
query.Name, _ = util.PreProcess(query.Name, do)
query.Field, _ = util.PreProcess(query.Field, do)
// Peform query
log.WithFields(log.Fields{
"name": query.Name,
"field": query.Field,
}).Info("Querying")
result, err := util.NamesInfo(query.Name, query.Field, do)
if err != nil {
return "", err
}
if result != "" {
log.WithField("=>", result).Warn("Return Value")
} else {
log.Debug("No return.")
}
return result, nil
}
func QueryValsJob(query *def.QueryVals, do *def.Packages) (string, error) {
var result string
// Preprocess variables
query.Field, _ = util.PreProcess(query.Field, do)
// Peform query
log.WithField("=>", query.Field).Info("Querying Vals")
result, err := util.ValidatorsInfo(query.Field, do)
if err != nil {
return "", err
}
if result != "" {
log.WithField("=>", result).Warn("Return Value")
} else {
log.Debug("No return.")
}
return result, nil
}
func AssertJob(assertion *def.Assert, do *def.Packages) (string, error) {
var result string
// Preprocess variables
assertion.Key, _ = util.PreProcess(assertion.Key, do)
assertion.Relation, _ = util.PreProcess(assertion.Relation, do)
assertion.Value, _ = util.PreProcess(assertion.Value, do)
// Switch on relation
log.WithFields(log.Fields{
"key": assertion.Key,
"relation": assertion.Relation,
"value": assertion.Value,
}).Info("Assertion =>")
switch assertion.Relation {
case "==", "eq":
/*log.Debug("Compare", strings.Compare(assertion.Key, assertion.Value))
log.Debug("UTF8?: ", utf8.ValidString(assertion.Key))
log.Debug("UTF8?: ", utf8.ValidString(assertion.Value))
log.Debug("UTF8?: ", utf8.RuneCountInString(assertion.Key))
log.Debug("UTF8?: ", utf8.RuneCountInString(assertion.Value))*/
if assertion.Key == assertion.Value {
return assertPass("==", assertion.Key, assertion.Value)
} else {
return assertFail("==", assertion.Key, assertion.Value)
}
case "!=", "ne":
if assertion.Key != assertion.Value {
return assertPass("!=", assertion.Key, assertion.Value)
} else {
return assertFail("!=", assertion.Key, assertion.Value)
}
case ">", "gt":
k, v, err := bulkConvert(assertion.Key, assertion.Value)
if err != nil {
return convFail()
}
if k > v {
return assertPass(">", assertion.Key, assertion.Value)
} else {
return assertFail(">", assertion.Key, assertion.Value)
}
case ">=", "ge":
k, v, err := bulkConvert(assertion.Key, assertion.Value)
if err != nil {
return convFail()
}
if k >= v {
return assertPass(">=", assertion.Key, assertion.Value)
} else {
return assertFail(">=", assertion.Key, assertion.Value)
}
case "<", "lt":
k, v, err := bulkConvert(assertion.Key, assertion.Value)
if err != nil {
return convFail()
}
if k < v {
return assertPass("<", assertion.Key, assertion.Value)
} else {
return assertFail("<", assertion.Key, assertion.Value)
}
case "<=", "le":
k, v, err := bulkConvert(assertion.Key, assertion.Value)
if err != nil {
return convFail()
}
if k <= v {
return assertPass("<=", assertion.Key, assertion.Value)
} else {
return assertFail("<=", assertion.Key, assertion.Value)
}
default:
return "", fmt.Errorf("Error: Bad assert relation: \"%s\" is not a valid relation. See documentation for more information.", assertion.Relation)
}
return result, nil
}
func bulkConvert(key, value string) (int, int, error) {
k, err := strconv.Atoi(key)
if err != nil {
return 0, 0, err
}
v, err := strconv.Atoi(value)
if err != nil {
return 0, 0, err
}
return k, v, nil
}
func assertPass(typ, key, val string) (string, error) {
log.WithField("=>", fmt.Sprintf("%s %s %s", key, typ, val)).Warn("Assertion Succeeded")
return "passed", nil
}
func assertFail(typ, key, val string) (string, error) {
log.WithField("=>", fmt.Sprintf("%s %s %s", key, typ, val)).Warn("Assertion Failed")
return "failed", fmt.Errorf("assertion failed")
}
func convFail() (string, error) {
return "", fmt.Errorf("The Key of your assertion cannot be converted into an integer.\nFor string conversions please use the equal or not equal relations.")
}
<file_sep>package util
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
log "github.com/sirupsen/logrus"
)
type Compiler struct {
Config LangConfig
Lang string
}
// New Request object from script and map of include files
func (c *Compiler) CompilerRequest(file string,
includes map[string]*IncludedFiles, libs string, optimize bool,
hashFileReplacement map[string]string) *Request {
if includes == nil {
includes = make(map[string]*IncludedFiles)
}
return &Request{
Language: c.Lang,
Includes: includes,
Libraries: libs,
Optimize: optimize,
FileReplacement: hashFileReplacement,
}
}
// Compile request object
type Request struct {
ScriptName string `json:"name"`
Language string `json:"language"`
Includes map[string]*IncludedFiles `json:"includes"` // our required files and metadata
Libraries string `json:"libraries"` // string of libName:LibAddr separated by comma
Optimize bool `json:"optimize"` // run with optimize flag
FileReplacement map[string]string `json:"replacement"`
}
type BinaryRequest struct {
BinaryFile string `json:"binary"`
Libraries string `json:"libraries"`
}
// this handles all of our imports
type IncludedFiles struct {
ObjectNames []string `json:"objectNames"` //objects in the file
Script []byte `json:"script"` //actual code
}
const (
SOLIDITY = "sol"
)
type LangConfig struct {
CacheDir string `json:"cache"`
IncludeRegex string `json:"regex"`
CompileCmd []string `json:"cmd"`
}
// Fill in the filename and return the command line args
func (l LangConfig) Cmd(includes []string, libraries string, optimize bool) (args []string) {
for _, s := range l.CompileCmd {
if s == "_" {
if optimize {
args = append(args, "--optimize")
}
if libraries != "" {
for _, l := range strings.Split(libraries, " ") {
if len(l) > 0 {
args = append(args, "--libraries")
args = append(args, libraries)
}
}
}
args = append(args, includes...)
} else {
args = append(args, s)
}
}
return
}
// todo: add indexes for where to find certain parts in submatches (quotes, filenames, etc.)
// Global variable mapping languages to their configs
var Languages = map[string]LangConfig{
SOLIDITY: {
CacheDir: SolcScratchPath,
IncludeRegex: `import (.+?)??("|')(.+?)("|')(as)?(.+)?;`,
CompileCmd: []string{
"solc",
"--combined-json", "bin,abi",
"_",
},
},
}
// individual contract items
type SolcItem struct {
Bin string `json:"bin"`
Abi string `json:"abi"`
}
// full solc response object
type SolcResponse struct {
Contracts map[string]*SolcItem `mapstructure:"contracts" json:"contracts"`
Version string `mapstructure:"version" json:"version"` // json encoded
}
func BlankSolcItem() *SolcItem {
return &SolcItem{}
}
func BlankSolcResponse() *SolcResponse {
return &SolcResponse{
Version: "",
Contracts: make(map[string]*SolcItem),
}
}
// Find all matches to the include regex
// Replace filenames with hashes
func (c *Compiler) ReplaceIncludes(code []byte, dir, file string,
includes map[string]*IncludedFiles,
hashFileReplacement map[string]string) ([]byte, error) {
// find includes, load those as well
regexPattern := c.IncludeRegex()
var regExpression *regexp.Regexp
var err error
if regExpression, err = regexp.Compile(regexPattern); err != nil {
return nil, err
}
OriginObjectNames, err := c.extractObjectNames(code)
if err != nil {
return nil, err
}
// replace all includes with hash of included imports
// make sure to return hashes of includes so we can cache check them too
// do it recursively
code = regExpression.ReplaceAllFunc(code, func(s []byte) []byte {
log.WithField("=>", string(s)).Debug("Include Replacer result")
s, err := c.includeReplacer(regExpression, s, dir, includes, hashFileReplacement)
if err != nil {
log.Error("ERR!:", err)
}
return s
})
originHash := sha256.Sum256(code)
origin := hex.EncodeToString(originHash[:])
origin += "." + c.Lang
includeFile := &IncludedFiles{
ObjectNames: OriginObjectNames,
Script: code,
}
includes[origin] = includeFile
hashFileReplacement[origin] = file
return code, nil
}
// read the included file, hash it; if we already have it, return include replacement
// if we don't, run replaceIncludes on it (recursive)
// modifies the "includes" map
func (c *Compiler) includeReplacer(r *regexp.Regexp, originCode []byte, dir string, included map[string]*IncludedFiles, hashFileReplacement map[string]string) ([]byte, error) {
// regex look for strings that would match the import statement
m := r.FindStringSubmatch(string(originCode))
match := m[3]
log.WithField("=>", match).Debug("Match")
// load the file
newFilePath := path.Join(dir, match)
incl_code, err := ioutil.ReadFile(newFilePath)
if err != nil {
log.Errorln("failed to read include file", err)
return nil, fmt.Errorf("Failed to read include file: %s", err.Error())
}
// take hash before replacing includes to see if we've already parsed this file
hash := sha256.Sum256(incl_code)
includeHash := hex.EncodeToString(hash[:])
log.WithField("=>", includeHash).Debug("Included Code's Hash")
if _, ok := included[includeHash]; ok {
//then replace
fullReplacement := strings.SplitAfter(m[0], m[2])
fullReplacement[1] = includeHash + "." + c.Lang + "\""
ret := strings.Join(fullReplacement, "")
return []byte(ret), nil
}
// recursively replace the includes for this file
this_dir := path.Dir(newFilePath)
incl_code, err = c.ReplaceIncludes(incl_code, this_dir, newFilePath, included, hashFileReplacement)
if err != nil {
return nil, err
}
// compute hash
hash = sha256.Sum256(incl_code)
h := hex.EncodeToString(hash[:])
//Starting with full regex string,
//Split strings from the quotation mark and then,
//assuming 3 array cells, replace the middle one.
fullReplacement := strings.SplitAfter(m[0], m[2])
fullReplacement[1] = h + "." + c.Lang + m[4]
ret := []byte(strings.Join(fullReplacement, ""))
return ret, nil
}
// Return the regex string to match include statements
func (c *Compiler) IncludeRegex() string {
return c.Config.IncludeRegex
}
func (c *Compiler) extractObjectNames(script []byte) ([]string, error) {
regExpression, err := regexp.Compile("(contract|library) (.+?) (is)?(.+?)?({)")
if err != nil {
return nil, err
}
objectNamesList := regExpression.FindAllSubmatch(script, -1)
var objects []string
for _, objectNames := range objectNamesList {
objects = append(objects, string(objectNames[2]))
}
return objects, nil
}
var (
BosRoot = ResolveBosRoot()
SolcScratchPath = filepath.Join(BosRoot, "sol")
)
func ResolveBosRoot() string {
var bos string
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
bos = filepath.Join(home, ".bos")
} else {
bos = filepath.Join(os.Getenv("HOME"), ".bos")
}
return bos
}
// InitScratchDir creates an Monax directory hierarchy under BosRoot dir.
func InitScratchDir() (err error) {
for _, d := range []string{
BosRoot,
SolcScratchPath,
} {
if _, err := os.Stat(d); err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(d, 0777); err != nil {
return err
}
}
}
}
return
}
<file_sep>package jobs
import (
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hyperledger/burrow/crypto"
"github.com/hyperledger/burrow/txs/payload"
"github.com/monax/bosmarmot/bos/abi"
compilers "github.com/monax/bosmarmot/bos/compile"
"github.com/monax/bosmarmot/bos/def"
"github.com/monax/bosmarmot/bos/util"
log "github.com/sirupsen/logrus"
)
func DeployJob(deploy *def.Deploy, do *def.Packages) (result string, err error) {
// Preprocess variables
deploy.Source, _ = util.PreProcess(deploy.Source, do)
deploy.Contract, _ = util.PreProcess(deploy.Contract, do)
deploy.Instance, _ = util.PreProcess(deploy.Instance, do)
deploy.Libraries, _ = util.PreProcessLibs(deploy.Libraries, do)
deploy.Amount, _ = util.PreProcess(deploy.Amount, do)
deploy.Sequence, _ = util.PreProcess(deploy.Sequence, do)
deploy.Fee, _ = util.PreProcess(deploy.Fee, do)
deploy.Gas, _ = util.PreProcess(deploy.Gas, do)
// trim the extension
contractName := strings.TrimSuffix(deploy.Contract, filepath.Ext(deploy.Contract))
// Use defaults
deploy.Source = useDefault(deploy.Source, do.Package.Account)
deploy.Instance = useDefault(deploy.Instance, contractName)
deploy.Amount = useDefault(deploy.Amount, do.DefaultAmount)
deploy.Fee = useDefault(deploy.Fee, do.DefaultFee)
deploy.Gas = useDefault(deploy.Gas, do.DefaultGas)
// assemble contract
var contractPath string
if _, err := os.Stat(deploy.Contract); err != nil {
if _, secErr := os.Stat(filepath.Join(do.BinPath, deploy.Contract)); secErr != nil {
if _, thirdErr := os.Stat(filepath.Join(do.BinPath, filepath.Base(deploy.Contract))); thirdErr != nil {
return "", fmt.Errorf("Could not find contract in\n* primary path: %v\n* binary path: %v\n* tertiary path: %v", deploy.Contract, filepath.Join(do.BinPath, deploy.Contract), filepath.Join(do.BinPath, filepath.Base(deploy.Contract)))
} else {
contractPath = filepath.Join(do.BinPath, filepath.Base(deploy.Contract))
}
} else {
contractPath = filepath.Join(do.BinPath, deploy.Contract)
}
} else {
contractPath = deploy.Contract
}
// compile
if filepath.Ext(deploy.Contract) == ".bin" {
log.Info("Binary file detected. Using binary deploy sequence.")
log.WithField("=>", contractPath).Info("Binary path")
binaryResponse, err := compilers.RequestBinaryLinkage(contractPath, deploy.Libraries)
if err != nil {
return "", fmt.Errorf("Something went wrong with your binary deployment: %v", err)
}
if binaryResponse.Error != "" {
return "", fmt.Errorf("Something went wrong when you were trying to link your binaries: %v", binaryResponse.Error)
}
contractCode := binaryResponse.Binary
tx, err := deployTx(do, deploy, contractName, string(contractCode))
if err != nil {
return "could not deploy binary contract", err
}
result, err := deployFinalize(do, tx)
if err != nil {
return "", fmt.Errorf("Error finalizing contract deploy from path %s: %v", contractPath, err)
}
return result.String(), err
} else {
contractPath = deploy.Contract
log.WithField("=>", contractPath).Info("Contract path")
// normal compilation/deploy sequence
resp, err := compilers.RequestCompile(contractPath, false, deploy.Libraries)
if err != nil {
log.Errorln("Error compiling contracts: Compilers error:")
return "", err
} else if resp.Error != "" {
log.Errorln("Error compiling contracts: Language error:")
return "", fmt.Errorf("%v", resp.Error)
} else if resp.Warning != "" {
log.WithField("=>", resp.Warning).Warn("Warning during contract compilation")
}
// loop through objects returned from compiler
switch {
case len(resp.Objects) == 1:
log.WithField("path", contractPath).Info("Deploying the only contract in file")
response := resp.Objects[0]
log.WithField("=>", response.ABI).Info("Abi")
log.WithField("=>", response.Bytecode).Info("Bin")
if response.Bytecode != "" {
result, err = deployContract(deploy, do, response)
if err != nil {
return "", err
}
}
case deploy.Instance == "all":
log.WithField("path", contractPath).Info("Deploying all contracts")
var baseObj string
for _, response := range resp.Objects {
if response.Bytecode == "" {
continue
}
result, err = deployContract(deploy, do, response)
if err != nil {
return "", err
}
if strings.ToLower(response.Objectname) == strings.ToLower(strings.TrimSuffix(filepath.Base(deploy.Contract), filepath.Ext(filepath.Base(deploy.Contract)))) {
baseObj = result
}
}
if baseObj != "" {
result = baseObj
}
default:
log.WithField("contract", deploy.Instance).Info("Deploying a single contract")
for _, response := range resp.Objects {
if response.Bytecode == "" {
continue
}
if matchInstanceName(response.Objectname, deploy.Instance) {
result, err = deployContract(deploy, do, response)
if err != nil {
return "", err
}
}
}
}
}
return result, nil
}
func matchInstanceName(objectName, deployInstance string) bool {
if objectName == "" {
return false
}
// Ignore the filename component that newer versions of Solidity include in object name
objectNameParts := strings.Split(objectName, ":")
return strings.ToLower(objectNameParts[len(objectNameParts)-1]) == strings.ToLower(deployInstance)
}
// TODO [rj] refactor to remove [contractPath] from functions signature => only used in a single error throw.
func deployContract(deploy *def.Deploy, do *def.Packages, compilersResponse compilers.ResponseItem) (string, error) {
log.WithField("=>", string(compilersResponse.ABI)).Debug("ABI Specification (From Compilers)")
contractCode := compilersResponse.Bytecode
// Save ABI
if _, err := os.Stat(do.ABIPath); os.IsNotExist(err) {
if err := os.Mkdir(do.ABIPath, 0775); err != nil {
return "", err
}
}
if _, err := os.Stat(do.BinPath); os.IsNotExist(err) {
if err := os.Mkdir(do.BinPath, 0775); err != nil {
return "", err
}
}
// saving contract/library abi
var abiLocation string
if compilersResponse.Objectname != "" {
abiLocation = filepath.Join(do.ABIPath, compilersResponse.Objectname)
log.WithField("=>", abiLocation).Warn("Saving ABI")
if err := ioutil.WriteFile(abiLocation, []byte(compilersResponse.ABI), 0664); err != nil {
return "", err
}
} else {
log.Debug("Objectname from compilers is blank. Not saving abi.")
}
// additional data may be sent along with the contract
// these are naively added to the end of the contract code using standard
// mint packing
if deploy.Data != nil {
_, callDataArray, err := util.PreProcessInputData(compilersResponse.Objectname, deploy.Data, do, true)
if err != nil {
return "", err
}
packedBytes, err := abi.ReadAbiFormulateCall(compilersResponse.Objectname, "", callDataArray, do)
if err != nil {
return "", err
}
callData := hex.EncodeToString(packedBytes)
contractCode = contractCode + callData
}
tx, err := deployTx(do, deploy, compilersResponse.Objectname, contractCode)
if err != nil {
return "", err
}
// Sign, broadcast, display
contractAddress, err := deployFinalize(do, tx)
if err != nil {
return "", fmt.Errorf("Error finalizing contract deploy %s: %v", deploy.Contract, err)
}
// saving contract/library abi at abi/address
if contractAddress != nil {
abiLocation := filepath.Join(do.ABIPath, contractAddress.String())
log.WithField("=>", abiLocation).Debug("Saving ABI")
if err := ioutil.WriteFile(abiLocation, []byte(compilersResponse.ABI), 0664); err != nil {
return "", err
}
// saving binary
if deploy.SaveBinary {
contractName := filepath.Join(do.BinPath, fmt.Sprintf("%s.bin", compilersResponse.Objectname))
log.WithField("=>", contractName).Warn("Saving Binary")
if err := ioutil.WriteFile(contractName, []byte(contractCode), 0664); err != nil {
return "", err
}
} else {
log.Debug("Not saving binary.")
}
return contractAddress.String(), nil
} else {
// we shouldn't reach this point because we should have an error before this.
return "", fmt.Errorf("The contract did not deploy. Unable to save abi to abi/contractAddress.")
}
}
func deployTx(do *def.Packages, deploy *def.Deploy, contractName, contractCode string) (*payload.CallTx, error) {
// Deploy contract
log.WithFields(log.Fields{
"name": contractName,
}).Warn("Deploying Contract")
log.WithFields(log.Fields{
"source": deploy.Source,
"code": contractCode,
"chain-url": do.ChainURL,
}).Info()
return do.Call(def.CallArg{
Input: deploy.Source,
Amount: deploy.Amount,
Fee: deploy.Fee,
Gas: deploy.Gas,
Data: contractCode,
Sequence: deploy.Sequence,
})
}
func CallJob(call *def.Call, do *def.Packages) (string, []*def.Variable, error) {
var err error
var callData string
var callDataArray []string
// Preprocess variables
call.Source, _ = util.PreProcess(call.Source, do)
call.Destination, _ = util.PreProcess(call.Destination, do)
//todo: find a way to call the fallback function here
call.Function, callDataArray, err = util.PreProcessInputData(call.Function, call.Data, do, false)
if err != nil {
return "", nil, err
}
call.Function, _ = util.PreProcess(call.Function, do)
call.Amount, _ = util.PreProcess(call.Amount, do)
call.Sequence, _ = util.PreProcess(call.Sequence, do)
call.Fee, _ = util.PreProcess(call.Fee, do)
call.Gas, _ = util.PreProcess(call.Gas, do)
call.ABI, _ = util.PreProcess(call.ABI, do)
// Use default
call.Source = useDefault(call.Source, do.Package.Account)
call.Amount = useDefault(call.Amount, do.DefaultAmount)
call.Fee = useDefault(call.Fee, do.DefaultFee)
call.Gas = useDefault(call.Gas, do.DefaultGas)
// formulate call
var packedBytes []byte
if call.ABI == "" {
packedBytes, err = abi.ReadAbiFormulateCall(call.Destination, call.Function, callDataArray, do)
callData = hex.EncodeToString(packedBytes)
} else {
packedBytes, err = abi.ReadAbiFormulateCall(call.ABI, call.Function, callDataArray, do)
callData = hex.EncodeToString(packedBytes)
}
if err != nil {
if call.Function == "()" {
log.Warn("Calling the fallback function")
} else {
var str, err = util.ABIErrorHandler(do, err, call, nil)
return str, nil, err
}
}
log.WithFields(log.Fields{
"destination": call.Destination,
"function": call.Function,
"data": callData,
}).Info("Calling")
tx, err := do.Call(def.CallArg{
Input: call.Source,
Amount: call.Amount,
Address: call.Destination,
Fee: call.Fee,
Gas: call.Gas,
Data: callData,
Sequence: call.Sequence,
})
if err != nil {
return "", nil, err
}
// Sign, broadcast, display
txe, err := do.SignAndBroadcast(tx)
if err != nil {
var err = util.MintChainErrorHandler(do, err)
return "", nil, err
}
var result string
log.Debug(txe.Result.Return)
// Formally process the return
if txe.Result.Return != nil {
log.WithField("=>", result).Debug("Decoding Raw Result")
if call.ABI == "" {
call.Variables, err = abi.ReadAndDecodeContractReturn(call.Destination, call.Function, txe.Result.Return, do)
} else {
call.Variables, err = abi.ReadAndDecodeContractReturn(call.ABI, call.Function, txe.Result.Return, do)
}
if err != nil {
return "", nil, err
}
log.WithField("=>", call.Variables).Debug("call variables:")
result = util.GetReturnValue(call.Variables)
if result != "" {
log.WithField("=>", result).Warn("Return Value")
} else {
log.Debug("No return.")
}
} else {
log.Debug("No return from contract.")
}
if call.Save == "tx" {
log.Info("Saving tx hash instead of contract return")
result = fmt.Sprintf("%X", txe.Receipt.TxHash)
}
return result, call.Variables, nil
}
func deployFinalize(do *def.Packages, tx payload.Payload) (*crypto.Address, error) {
txe, err := do.SignAndBroadcast(tx)
if err != nil {
return nil, util.MintChainErrorHandler(do, err)
}
if err := util.ReadTxSignAndBroadcast(txe, err); err != nil {
return nil, err
}
if !txe.Receipt.CreatesContract || txe.Receipt.ContractAddress == crypto.ZeroAddress {
// Shouldn't get ZeroAddress when CreatesContract is true, but still
return nil, fmt.Errorf("result from SignAndBroadcast does not contain address for the deployed contract")
}
return &txe.Receipt.ContractAddress, nil
}
<file_sep>package commands
import (
"bytes"
"fmt"
"github.com/monax/bosmarmot/bos"
"github.com/monax/bosmarmot/bos/def"
"github.com/monax/bosmarmot/bos/util"
"github.com/monax/bosmarmot/project"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// Defines the root command
var BosCmd = &cobra.Command{
Use: "bos COMMAND [FLAG ...]",
Long: `bos is an application for deploying and testing packages to Hyperledger Burrow.
It is used to test and deploy smart contract packages for use by your application.
Bos will perform the required functionality included in a package definition file.
Made with <3 by Monax Industries.
` + "\nVersion:\n " + project.History.CurrentVersion().String(),
Run: func(cmd *cobra.Command, args []string) {
util.IfExit(ArgCheck(0, "eq", cmd, args))
log.SetFormatter(new(PlainFormatter))
log.SetLevel(log.WarnLevel)
if do.Verbose {
log.SetLevel(log.InfoLevel)
} else if do.Debug {
log.SetLevel(log.DebugLevel)
}
util.IfExit(pkgs.RunPackage(do))
},
}
// Global Do struct
var do *def.Packages
// Controls the execution sequence of the cobra global runner
func Execute() {
do = def.NewPackage()
AddGlobalFlags()
AddCommands()
util.IfExit(BosCmd.Execute())
}
// Flags that are to be used by commands are handled by the Do struct
func AddGlobalFlags() {
BosCmd.Flags().StringVarP(&do.ChainURL, "chain-url", "u", "localhost:20997", "chain-url to be used in IP:PORT format")
BosCmd.Flags().StringVarP(&do.Signer, "keys", "s", "", "IP:PORT of burrow keys server which jobs should use (defaults to --chain-url)")
BosCmd.Flags().StringVarP(&do.Path, "dir", "i", "", "root directory of app (will use pwd by default)")
BosCmd.Flags().StringVarP(&do.DefaultOutput, "output", "o", "epm.output.json", "filename for jobs output file. by default, this name will reflect the name passed in on the optional [--file]")
BosCmd.Flags().StringVarP(&do.YAMLPath, "file", "f", "epm.yaml", "path to package file which jobs should use. if also using the --dir flag, give the relative path to jobs file, which should be in the same directory")
BosCmd.Flags().StringSliceVarP(&do.DefaultSets, "set", "e", []string{}, "default sets to use; operates the same way as the [set] jobs, only before the jobs file is ran (and after default address")
BosCmd.Flags().StringVarP(&do.BinPath, "bin-path", "b", "[dir]/bin", "path to the bin directory jobs should use when saving binaries after the compile process defaults to --dir + /bin")
BosCmd.Flags().StringVarP(&do.ABIPath, "abi-path", "p", "[dir]/abi", "path to the abi directory jobs should use when saving ABIs after the compile process defaults to --dir + /abi")
BosCmd.Flags().StringVarP(&do.DefaultGas, "gas", "g", "1111111111", "default gas to use; can be overridden for any single job")
BosCmd.Flags().StringVarP(&do.Address, "address", "a", "", "default address to use; operates the same way as the [account] job, only before the epm file is ran")
BosCmd.Flags().StringVarP(&do.DefaultFee, "fee", "n", "9999", "default fee to use")
BosCmd.Flags().StringVarP(&do.DefaultAmount, "amount", "m", "9999", "default amount to use")
BosCmd.Flags().BoolVarP(&do.Verbose, "verbose", "v", false, "verbose output")
BosCmd.Flags().BoolVarP(&do.Debug, "debug", "d", false, "debug level output")
}
// Define the sub-commands
func AddCommands() {
BosCmd.AddCommand(&cobra.Command{
Use: "version",
Short: "Print Version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(project.FullVersion())
},
})
BosCmd.SetHelpCommand(Help)
BosCmd.SetHelpTemplate(helpTemplate)
}
// Utility helpers
func ArgCheck(num int, comp string, cmd *cobra.Command, args []string) error {
switch comp {
case "eq":
if len(args) != num {
cmd.Help()
return fmt.Errorf("\n**Note** you sent our marmots the wrong number of arguments.\nPlease send the marmots %d arguments only.", num)
}
case "ge":
if len(args) < num {
cmd.Help()
return fmt.Errorf("\n**Note** you sent our marmots the wrong number of arguments.\nPlease send the marmots at least %d argument(s).", num)
}
}
return nil
}
type PlainFormatter struct{}
func (f *PlainFormatter) Format(entry *log.Entry) ([]byte, error) {
var b *bytes.Buffer
keys := make([]string, 0, len(entry.Data))
for k := range entry.Data {
keys = append(keys, k)
}
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
f.appendMessage(b, entry.Message)
for _, key := range keys {
f.appendMessageData(b, key, entry.Data[key])
}
b.WriteByte('\n')
return b.Bytes(), nil
}
func (f *PlainFormatter) appendMessage(b *bytes.Buffer, message string) {
fmt.Fprintf(b, "%-44s", message)
}
func (f *PlainFormatter) appendMessageData(b *bytes.Buffer, key string, value interface{}) {
switch key {
case "":
b.WriteString("=> ")
case "=>":
b.WriteString(key)
b.WriteByte(' ')
default:
b.WriteString(key)
b.WriteString(" => ")
}
stringVal, ok := value.(string)
if !ok {
stringVal = fmt.Sprint(value)
}
b.WriteString(stringVal)
}
<file_sep>package util
import (
"fmt"
"os"
"regexp"
"github.com/monax/bosmarmot/bos/def"
log "github.com/sirupsen/logrus"
)
func Exit(err error) {
status := 0
if err != nil {
fmt.Fprintln(os.Stderr, err)
status = 1
}
os.Exit(status)
}
func IfExit(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func MintChainErrorHandler(do *def.Packages, err error) error {
log.WithFields(log.Fields{
"defAddr": do.Package.Account,
"rawErr": err,
}).Error("")
return fmt.Errorf(`
There has been an error talking to your monax chain.
%v
Debugging this error is tricky, but don't worry the marmot recovery checklist is...
* is the %s account right?
* is the account you want to use in your keys service: burrow keys list ?
* is the account you want to use in your genesis.json: see http://localhost:46657/genesis
* do you have permissions to do what you're trying to do on the chain?
`, err, do.Package.Account)
}
func KeysErrorHandler(do *def.Packages, err error) (string, error) {
log.WithFields(log.Fields{
"defAddr": do.Package.Account,
}).Error("")
r := regexp.MustCompile(fmt.Sprintf("open /home/monax/.monax/keys/data/%s/%s: no such file or directory", do.Package.Account, do.Package.Account))
if r.MatchString(fmt.Sprintf("%v", err)) {
return "", fmt.Errorf(`
Unfortunately the marmots could not find the key you are trying to use in the keys service.
There is one way to fix this.
* Import your keys from your host: monax keys import %s
Now, run monax keys ls to check that the keys are available. If they are not there
then change the account. Once you have verified that the keys for account
%s
are in the keys service, then rerun me.
`, do.Package.Account, do.Package.Account)
}
return "", fmt.Errorf(`
There has been an error talking to your burrow keys service.
%v
Debugging this error is tricky, but don't worry the marmot recovery checklist is...
* is your %s account right?
* is the key for %s in your keys service: burrow keys list ?
`, err, do.Package.Account, do.Package.Account)
}
func ABIErrorHandler(do *def.Packages, err error, call *def.Call, query *def.QueryContract) (string, error) {
switch {
case call != nil:
log.WithFields(log.Fields{
"data": call.Data,
"abi": call.ABI,
"dest": call.Destination,
"rawErr": err,
}).Error("ABI Error")
case query != nil:
log.WithFields(log.Fields{
"data": query.Data,
"abi": query.ABI,
"dest": query.Destination,
"rawErr": err,
}).Error("ABI Error")
}
return "", fmt.Errorf(`
There has been an error in finding or in using your ABI. ABI's are "Application Binary
Interface" and they are what let us know how to talk to smart contracts.
These little json files can be read by a variety of things which need to talk to smart
contracts so they are quite necessary to be able to find and use properly.
The ABIs are saved after the deploy events. So if there was a glitch in the matrix,
we apologize in advance.
The marmot recovery checklist is...
* ensure your chain is running and you have enough validators online
* ensure that your contracts successfully deployed
* if you used imports or have multiple contracts in one file check the instance
variable in the deploy and the abi variable in the call/query-contract
* make sure you're calling or querying the right function
* make sure you're using the correct variables for job results
`)
}
<file_sep>package util
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
"strings"
"github.com/hyperledger/burrow/execution/exec"
log "github.com/sirupsen/logrus"
"github.com/tmthrgd/go-hex"
)
// This is a closer function which is called by most of the tx_run functions
func ReadTxSignAndBroadcast(txe *exec.TxExecution, err error) error {
// if there's an error just return.
if err != nil {
return err
}
// if there is nothing to unpack then just return.
if txe == nil {
return nil
}
// Unpack and display for the user.
hash := fmt.Sprintf("%X", txe.Receipt.TxHash)
height := fmt.Sprintf("%d", txe.Height)
if txe.Receipt.CreatesContract {
log.WithField("addr", txe.Receipt.ContractAddress).Warn()
log.WithField("txHash", hash).Info()
} else {
log.WithField("=>", hash).Warn("Transaction Hash")
log.WithField("=>", height).Debug("Block height")
ret := txe.GetResult().GetReturn()
if len(ret) != 0 {
log.WithField("=>", hex.EncodeUpperToString(ret)).Warn("Return Value")
log.WithField("=>", txe.Exception).Debug("Exception")
}
}
return nil
}
func ReadAbi(root, contract string) (string, error) {
p := path.Join(root, stripHex(contract))
if _, err := os.Stat(p); err != nil {
return "", fmt.Errorf("Abi doesn't exist for =>\t%s", p)
}
b, err := ioutil.ReadFile(p)
if err != nil {
return "", err
}
return string(b), nil
}
func GetStringResponse(question string, defaultAnswer string, reader *os.File) (string, error) {
readr := bufio.NewReader(reader)
log.Warn(question)
text, _ := readr.ReadString('\n')
text = strings.Replace(text, "\n", "", 1)
if text == "" {
return defaultAnswer, nil
}
return text, nil
}
func GetIntResponse(question string, defaultAnswer int64, reader *os.File) (int64, error) {
readr := bufio.NewReader(reader)
log.Warn(question)
text, _ := readr.ReadString('\n')
text = strings.Replace(text, "\n", "", 1)
if text == "" {
return defaultAnswer, nil
}
result, err := strconv.ParseInt(text, 10, 64)
if err != nil {
return 0, nil
}
return result, nil
}
// displays the question, scans for the response, if the response is an empty
// string will return default, otherwise will parseBool and return the result.
func GetBoolResponse(question string, defaultAnswer bool, reader *os.File) (bool, error) {
var result bool
readr := bufio.NewReader(reader)
log.Warn(question)
text, _ := readr.ReadString('\n')
text = strings.Replace(text, "\n", "", 1)
if text == "" {
return defaultAnswer, nil
}
if text == "Yes" || text == "YES" || text == "Y" || text == "y" {
result = true
} else {
result = false
}
return result, nil
}
func stripHex(s string) string {
if len(s) > 1 {
if s[:2] == "0x" {
s = s[2:]
if len(s)%2 != 0 {
s = "0" + s
}
return s
}
}
return s
}
<file_sep>package abi
import (
"fmt"
"github.com/monax/bosmarmot/bos/def"
"github.com/monax/bosmarmot/bos/util"
log "github.com/sirupsen/logrus"
)
func ReadAbiFormulateCall(abiLocation string, funcName string, args []string, do *def.Packages) ([]byte, error) {
abiSpecBytes, err := util.ReadAbi(do.ABIPath, abiLocation)
if err != nil {
return []byte{}, err
}
log.WithField("=>", string(abiSpecBytes)).Debug("ABI Specification (Formulate)")
log.WithFields(log.Fields{
"function": funcName,
"arguments": fmt.Sprintf("%v", args),
}).Debug("Packing Call via ABI")
return Packer(abiSpecBytes, funcName, args...)
}
func ReadAndDecodeContractReturn(abiLocation, funcName string, resultRaw []byte, do *def.Packages) ([]*def.Variable, error) {
abiSpecBytes, err := util.ReadAbi(do.ABIPath, abiLocation)
if err != nil {
return nil, err
}
log.WithField("=>", abiSpecBytes).Debug("ABI Specification (Decode)")
// Unpack the result
return Unpacker(abiSpecBytes, funcName, resultRaw)
}
//Convenience Packing Functions
func Packer(abiData, funcName string, args ...string) ([]byte, error) {
abiSpec, err := ReadAbiSpec([]byte(abiData))
if err != nil {
return nil, err
}
iArgs := make([]interface{}, len(args))
for i, s := range args {
iArgs[i] = interface{}(s)
}
packedBytes, err := abiSpec.Pack(funcName, iArgs...)
if err != nil {
return nil, err
}
return packedBytes, nil
}
func Unpacker(abiData, name string, data []byte) ([]*def.Variable, error) {
abiSpec, err := ReadAbiSpec([]byte(abiData))
if err != nil {
return nil, err
}
var args []Argument
if name == "" {
args = abiSpec.Constructor.Outputs
} else {
if _, ok := abiSpec.Functions[name]; ok {
args = abiSpec.Functions[name].Outputs
} else {
args = abiSpec.Fallback.Outputs
}
}
if args == nil {
return nil, fmt.Errorf("no such function")
}
vars := make([]*def.Variable, len(args))
if len(args) == 0 {
return nil, nil
}
vals := make([]interface{}, len(args))
for i, _ := range vals {
vals[i] = new(string)
}
err = Unpack(args, data, vals...)
if err != nil {
return nil, err
}
for i, a := range args {
if a.Name != "" {
vars[i] = &def.Variable{Name: a.Name, Value: *(vals[i].(*string))}
} else {
vars[i] = &def.Variable{Name: fmt.Sprintf("%d", i), Value: *(vals[i].(*string))}
}
}
return vars, nil
}
<file_sep># Bosmarmot
|[](https://godoc.org/github.com/monax/bosmarmot/bos/cmd) | Linux |
|---|-------|
| Master | [](https://circleci.com/gh/monax/bosmarmot/tree/master) |
| Develop | [](https://circleci.com/gh/monax/bosmarmot/tree/develop) |
Bosmarmot is a monorepo containing condensed and updated versions of the basic tooling required to interact with a [Burrow](https://github.com/hyperledger/burrow) chain.
It also contains the interpreter for the burrow packages specification language (previously known as 'epm'). This README will cover setting up a Burrow chain with the bosmarmot tooling from start to finish.
## Install
We're going to need three (3) binaries:
```
burrow
bos
solc
```
First, ensure you have `go` installed and `$GOPATH` set
For `burrow`:
```
go get github.com/hyperledger/burrow
cd $GOPATH/src/github.com/hyperledger/burrow
make build
```
which will put the `burrow` binary in `/bin`. Move it onto your `$PATH`
For `bos`:
```
go get github.com/monax/bosmarmot
cd $GOPATH/src/github.com/monax/bosmarmot
make build
```
and move these onto your `$PATH` as well.
To install the solidity compiler - `solc` - see [here](https://solidity.readthedocs.io/en/develop/installing-solidity.html) for platform specific instructions.
## Configure
The end result will be a `burrow.toml` which contains the genesis spec and burrow configuration options required when starting the `burrow` node.
### Accounts
First, let's create some accounts. In this case, we're creating one of each a Participant and Full account:
```
burrow spec --participant-accounts=1 --full-accounts=1 > genesis-spec.json
```
and writing the output to an `genesis-spec.json`. This file should look like:
```
{
Accounts": [
{
"Amount": 99999999999999,
"AmountBonded": 9999999999,
"Name": "Full_0",
"Permissions": [
"all"
]
},
{
"Amount": 9999999999,
"Name": "Participant_0",
"Permissions": [
"send",
"call",
"name",
"hasRole"
]
}
]
}
```
Then, we pass the `genesis-spec.json` in the following command:
```
burrow configure --genesis-spec=genesis-spec.json > burrow.toml
```
which creates `burrow.toml` that looks like:
```
[GenesisDoc]
GenesisTime = 2018-05-24T16:12:34Z
ChainName = "BurrowChain_2BE507"
[GenesisDoc.GlobalPermissions]
Roles = []
[GenesisDoc.GlobalPermissions.Base]
Perms = 2302
SetBit = 16383
[[GenesisDoc.Accounts]]
Address = "84276E34B8F3C4166F61878473AEC831A5CF5444"
PublicKey = "{\"type\":\"ed25519\",\"data\":\"8C245576A2A0299DF0B760C55EF366D281B914FADBE03571FC1901FCAADA067F\"}"
Amount = 99999999999999
Name = "Full_0"
[GenesisDoc.Accounts.Permissions]
[GenesisDoc.Accounts.Permissions.Base]
Perms = 16383
SetBit = 16383
[[GenesisDoc.Accounts]]
Address = "8F573B59FE9D0886CB525069E7E16C1997E8A126"
PublicKey = "{\"type\":\"ed25519\",\"data\":\"15989611C2670C248F81070F7E94E824B527E6CA80C4F4EE05414C82F9DA18E3\"}"
Amount = 9999999999
Name = "Participant_0"
[GenesisDoc.Accounts.Permissions]
[GenesisDoc.Accounts.Permissions.Base]
Perms = 2118
SetBit = 2118
[[GenesisDoc.Validators]]
Address = "84276E34B8F3C4166F61878473AEC831A5CF5444"
PublicKey = "{\"type\":\"ed25519\",\"data\":\"8C245576A2A0299DF0B760C55EF366D281B914FADBE03571FC1901FCAADA067F\"}"
Amount = 9999999999
Name = "Full_0"
[[GenesisDoc.Validators.UnbondTo]]
Address = "84276E34B8F3C4166F61878473AEC831A5CF5444"
PublicKey = "{\"type\":\"ed25519\",\"data\":\"8C245576A2A0299DF0B760C55EF366D281B914FADBE03571FC1901FCAADA067F\"}"
Amount = 9999999999
[Tendermint]
Seeds = ""
PersistentPeers = ""
ListenAddress = "tcp://0.0.0.0:46656"
Moniker = ""
TendermintRoot = ".burrow"
[Keys]
URL = "http://localhost:4767"
[RPC]
[RPC.V0]
Disabled = false
[RPC.V0.Server]
[RPC.V0.Server.bind]
address = "localhost"
port = 1337
[RPC.V0.Server.TLS]
tls = false
cert_path = ""
key_path = ""
[RPC.V0.Server.CORS]
enable = false
allow_credentials = false
max_age = 0
[RPC.V0.Server.HTTP]
json_rpc_endpoint = "/rpc"
[RPC.V0.Server.web_socket]
websocket_endpoint = "/socketrpc"
max_websocket_sessions = 50
read_buffer_size = 4096
write_buffer_size = 4096
[RPC.TM]
Disabled = false
ListenAddress = "tcp://localhost:46657"
[RPC.Profiler]
Disabled = true
ListenAddress = "tcp://localhost:6060"
[Logging]
ExcludeTrace = false
NonBlocking = false
[Logging.RootSink]
[Logging.RootSink.Output]
OutputType = "stderr"
Format = "json"
```
## Keys
The previous command (`burrow configure --genesis-spec`) created two keys. Let's look at them:
```
ls .keys/data
```
will show you the existing keys that the `burrow` can use to sign transactions. In this example, signing happens under-the-hood.
## Run Burrow
Now we can run `burrow`:
```
burrow start --validator-index=0 2>burrow.log &
```
See [burrow's README](https://github.com/hyperledger/burrow) for more information on tweaking the logs.
## Deploy Contracts
Now that the burrow node is running, we can deploy contracts.
For this step, we need two things: one or more solidity contracts, and an `epm.yaml`.
Let's take a simple example, found in [this directory](tests/jobs_fixtures/app06-deploy_basic_contract_and_different_solc_types_packed_unpacked/).
The `epm.yaml` should look like:
```
jobs:
- name: deployStorageK
deploy:
contract: storage.sol
- name: setStorageBaseBool
set:
val: "true"
- name: setStorageBool
call:
destination: $deployStorageK
function: setBool
data:
- $setStorageBaseBool
- name: queryStorageBool
query-contract:
destination: $deployStorageK
function: getBool
- name: assertStorageBool
assert:
key: $queryStorageBool
relation: eq
val: $setStorageBaseBool
# tests string bools: #71
- name: setStorageBool2
call:
destination: $deployStorageK
function: setBool2
data:
- true
- name: queryStorageBool2
query-contract:
destination: $deployStorageK
function: getBool2
- name: assertStorageBool2
assert:
key: $queryStorageBool2
relation: eq
val: "true"
- name: setStorageBaseInt
set:
val: 50000
- name: setStorageInt
call:
destination: $deployStorageK
function: setInt
data:
- $setStorageBaseInt
- name: queryStorageInt
query-contract:
destination: $deployStorageK
function: getInt
- name: assertStorageInt
assert:
key: $queryStorageInt
relation: eq
val: $setStorageBaseInt
- name: setStorageBaseUint
set:
val: 9999999
- name: setStorageUint
call:
destination: $deployStorageK
function: setUint
data:
- $setStorageBaseUint
- name: queryStorageUint
query-contract:
destination: $deployStorageK
function: getUint
- name: assertStorageUint
assert:
key: $queryStorageUint
relation: eq
val: $setStorageBaseUint
- name: setStorageBaseAddress
set:
val: "1040E6521541DAB4E7EE57F21226DD17CE9F0FB7"
- name: setStorageAddress
call:
destination: $deployStorageK
function: setAddress
data:
- $setStorageBaseAddress
- name: queryStorageAddress
query-contract:
destination: $deployStorageK
function: getAddress
- name: assertStorageAddress
assert:
key: $queryStorageAddress
relation: eq
val: $setStorageBaseAddress
- name: setStorageBaseBytes
set:
val: marmatoshi
- name: setStorageBytes
call:
destination: $deployStorageK
function: setBytes
data:
- $setStorageBaseBytes
- name: queryStorageBytes
query-contract:
destination: $deployStorageK
function: getBytes
- name: assertStorageBytes
assert:
key: $queryStorageBytes
relation: eq
val: $setStorageBaseBytes
- name: setStorageBaseString
set:
val: nakaburrow
- name: setStorageString
call:
destination: $deployStorageK
function: setString
data:
- $setStorageBaseString
- name: queryStorageString
query-contract:
destination: $deployStorageK
function: getString
- name: assertStorageString
assert:
key: $queryStorageString
relation: eq
val: $setStorageBaseString
```
while our Solidity contract (`storage.sol`) looks like:
```
pragma solidity >=0.0.0;
contract SimpleStorage {
bool storedBool;
bool storedBool2;
int storedInt;
uint storedUint;
address storedAddress;
bytes32 storedBytes;
string storedString;
function setBool(bool x) {
storedBool = x;
}
function getBool() constant returns (bool retBool) {
return storedBool;
}
function setBool2(bool x) {
storedBool2 = x;
}
function getBool2() constant returns (bool retBool) {
return storedBool2;
}
function setInt(int x) {
storedInt = x;
}
function getInt() constant returns (int retInt) {
return storedInt;
}
function setUint(uint x) {
storedUint = x;
}
function getUint() constant returns (uint retUint) {
return storedUint;
}
function setAddress(address x) {
storedAddress = x;
}
function getAddress() constant returns (address retAddress) {
return storedAddress;
}
function setBytes(bytes32 x) {
storedBytes = x;
}
function getBytes() constant returns (bytes32 retBytes) {
return storedBytes;
}
function setString(string x) {
storedString = x;
}
function getString() constant returns (string retString) {
return storedString;
}
}
```
Both files (`epm.yaml` & `storage.sol`) should be in the same directory with nothing else in it.
From inside that directory, we are ready to deploy.
```
bos --keys="localhost:10997" \
--chain-url="tcp://localhost:46657" \
--address=0A40DC874BC932B78AC390EAD1C1BF33469597AB
```
where the field in `--address` is the `ValidatorAddress` at the top of your `burrow.toml`.
That's it! You've succesfully deployed (and tested) a Soldity contract to a Burrow node.
## Working with Javascript
Currently the javascript libraries are being rebuilt. The master branch of this repository works against the master branch of burrow.
Please use the versions within the package.json of this repo on master branch for fully compatible and tested versions.
<file_sep>package def
type Packages struct {
ABIPath string `mapstructure:"," json:"," yaml:"," toml:","`
Address string `mapstructure:"," json:"," yaml:"," toml:","`
BinPath string `mapstructure:"," json:"," yaml:"," toml:","`
ChainURL string `mapstructure:"," json:"," yaml:"," toml:","`
CurrentOutput string `mapstructure:"," json:"," yaml:"," toml:","`
Debug bool `mapstructure:"," json:"," yaml:"," toml:","`
DefaultAmount string `mapstructure:"," json:"," yaml:"," toml:","`
DefaultFee string `mapstructure:"," json:"," yaml:"," toml:","`
DefaultGas string `mapstructure:"," json:"," yaml:"," toml:","`
DefaultOutput string `mapstructure:"," json:"," yaml:"," toml:","`
DefaultSets []string `mapstructure:"," json:"," yaml:"," toml:","`
Path string `mapstructure:"," json:"," yaml:"," toml:","`
Signer string `mapstructure:"," json:"," yaml:"," toml:","`
Verbose bool `mapstructure:"," json:"," yaml:"," toml:","`
YAMLPath string `mapstructure:"," json:"," yaml:"," toml:","`
Package *Package
Client
}
func NewPackage() *Packages {
return &Packages{}
}
func (do *Packages) Dial() error {
return do.Client.Dial(do.ChainURL, do.Signer)
}
<file_sep>// +build go1.6
package main
import (
"github.com/monax/bosmarmot/bos/cmd"
)
func main() {
commands.Execute()
}
<file_sep>#!/usr/bin/env bash
set -e
# The version of solc we will fetch and install into ./bin/ for integration testsS
# Our custom build of solidity fixing linking issue; https://github.com/monax/solidity/tree/truncate-beginning-v0.4.22
SOLC_URL="https://pkgs.monax.io/apt/solc/0.4.24/linux-amd64/solc"
SOLC_BIN="$1"
wget -O "$SOLC_BIN" "$SOLC_URL"
chmod +x "$SOLC_BIN"
<file_sep>#
# |_ _ _ _ _ _ _ _ _ _ _|_
# |_)(_)_\| | |(_|| | | |(_) |
#
# Bosmarmot Makefile
#
# Requires go version 1.8 or later.
#
SHELL := /bin/bash
REPO := $(shell pwd)
GO_FILES := $(shell go list -f "{{.Dir}}" ./...)
GOPACKAGES_NOVENDOR := $(shell go list ./...)
COMMIT := $(shell git rev-parse --short HEAD)
BURROW_PACKAGE := github.com/hyperledger/burrow
### Integration test binaries
# We make the relevant targets for building/fetching these depend on the Makefile itself - if unnecessary rebuilds
# when changing the Makefile become a problem we can move these values into individual files elsewhere and make those
# files specific targets for their respective binaries
### Tests and checks
# Run goimports (also checks formatting) first display output first, then check for success
.PHONY: check
check:
@go get golang.org/x/tools/cmd/goimports
@goimports -l -d ${GO_FILES}
@goimports -l ${GO_FILES} | read && echo && \
echo "Your marmot has found a problem with the formatting style of the code."\
1>&2 && exit 1 || true
# Just fix it
.PHONY: fix
fix:
@goimports -l -w ${GO_FILES}
.PHONY: test_js
test_js:
@cd burrow.js && npm test
# Run tests
.PHONY: test_bos
test_bos: check bin/solc
@tests/scripts/bin_wrapper.sh go test ${GOPACKAGES_NOVENDOR}
.PHONY: test
test: test_bos
# Run tests for development (noisy)
.PHONY: test_dev
test_dev:
@go test -v ${GOPACKAGES_NOVENDOR}
# Install dependency
.PHONY: npm_install
npm_install:
@cd burrow.js && npm install
# Run tests including integration tests
.PHONY: test_integration_bos
test_integration_bos: build_bin bin/solc bin/burrow
@tests/scripts/bin_wrapper.sh tests/run_pkgs_tests.sh
.PHONY: test_burrow_js
test_burrow_js: build_bin bin/solc bin/burrow
@cd burrow.js && ../tests/scripts/bin_wrapper.sh npm test
.PHONY: test_integration
test_integration: test_integration_bos test_burrow_js
# Use a provided/local Burrow
.PHONY: test_burrow_js_no_burrow
test_burrow_js_no_burrow: build_bin bin/solc
@cd burrow.js && ../tests/scripts/bin_wrapper.sh npm test
.PHONY: test_integration_bos_no_burrow
test_integration_bos_no_burrow: build_bin bin/solc
@tests/scripts/bin_wrapper.sh tests/run_pkgs_tests.sh
PHONY: test_integration_no_burrow
test_integration_no_burrow: test_integration_bos_no_burrow test_burrow_js_no_burrow
### Vendoring
# erase vendor wipes the full vendor directory
.PHONY: erase_vendor
erase_vendor:
rm -rf ${REPO}/vendor/
# install vendor uses dep to install vendored dependencies
.PHONY: reinstall_vendor
reinstall_vendor: erase_vendor
@dep ensure -v
# delete the vendor directy and pull back using dep lock and constraints file
# will exit with an error if the working directory is not clean (any missing files or new
# untracked ones)
.PHONY: ensure_vendor
ensure_vendor: reinstall_vendor
@tests/scripts/is_checkout_dirty.sh
### Builds
.PHONY: build_bin
build_bin:
@go build -a -tags netgo \
-ldflags "-w -extldflags '-static' \
-X github.com/monax/bosmarmot/project.commit=${COMMIT}" \
-o bin/bos ./bos/cmd/bos
bin/solc: ./tests/scripts/deps/solc.sh
@mkdir -p bin
@tests/scripts/deps/solc.sh bin/solc
@touch bin/solc
tests/scripts/deps/burrow.sh: Gopkg.lock
@go get -u github.com/golang/dep/cmd/dep
@tests/scripts/deps/burrow-gen.sh > tests/scripts/deps/burrow.sh
@chmod +x tests/scripts/deps/burrow.sh
.PHONY: burrow_local
burrow_local:
@rm -rf .gopath_burrow
@mkdir -p .gopath_burrow/src/${BURROW_PACKAGE}
@cp -r ${GOPATH}/src/${BURROW_PACKAGE}/. .gopath_burrow/src/${BURROW_PACKAGE}
bin/burrow: ./tests/scripts/deps/burrow.sh
mkdir -p bin
@GOPATH="${REPO}/.gopath_burrow" \
tests/scripts/go_get_revision.sh \
https://github.com/hyperledger/burrow.git \
${BURROW_PACKAGE} \
$(shell ./tests/scripts/deps/burrow.sh) \
"make build_db" && \
cp .gopath_burrow/src/${BURROW_PACKAGE}/bin/burrow ./bin/burrow
# Build all the things
.PHONY: build
build: build_bin
# Build binaries for all architectures
.PHONY: build_dist
build_dist:
@goreleaser --rm-dist --skip-publish --skip-validate
# Do all available tests and checks then build
.PHONY: build_ci
build_ci: check test build
### Release and versioning
# Print version
.PHONY: version
version:
@go run ./project/cmd/version/main.go
# Generate full changelog of all release notes
CHANGELOG.md: ./project/history.go ./project/cmd/changelog/main.go
@go run ./project/cmd/changelog/main.go > CHANGELOG.md
# Generated release notes for this version
NOTES.md: ./project/history.go ./project/cmd/notes/main.go
@go run ./project/cmd/notes/main.go > NOTES.md
# Generate all docs
.PHONY: docs
docs: CHANGELOG.md NOTES.md
# Tag the current HEAD commit with the current release defined in
# ./release/release.go
.PHONY: tag_release
tag_release: test check CHANGELOG.md build_bin
@tests/scripts/tag_release.sh
# If the checked out commit is tagged with a version then release to github
.PHONY: release
release: NOTES.md
@tests/scripts/release.sh
<file_sep>package util
import (
"fmt"
"strconv"
"strings"
"github.com/monax/bosmarmot/bos/def"
"github.com/hyperledger/burrow/crypto"
)
func GetBlockHeight(do *def.Packages) (latestBlockHeight uint64, err error) {
stat, err := do.Status()
if err != nil {
return 0, err
}
return stat.LatestBlockHeight, nil
}
func AccountsInfo(account, field string, do *def.Packages) (string, error) {
address, err := crypto.AddressFromHexString(account)
if err != nil {
return "", err
}
acc, err := do.GetAccount(address)
if err != nil {
return "", err
}
if acc == nil {
return "", fmt.Errorf("Account %s does not exist", account)
}
var s string
if strings.Contains(field, "permissions") {
fields := strings.Split(field, ".")
if len(fields) > 1 {
switch fields[1] {
case "roles":
s = strings.Join(acc.Permissions.Roles, ",")
case "base", "perms":
s = strconv.Itoa(int(acc.Permissions.Base.Perms))
case "set":
s = strconv.Itoa(int(acc.Permissions.Base.SetBit))
}
}
} else if field == "balance" {
s = itoaU64(acc.Balance)
}
if err != nil {
return "", err
}
return s, nil
}
func NamesInfo(name, field string, do *def.Packages) (string, error) {
entry, err := do.GetName(name)
if err != nil {
return "", err
}
switch strings.ToLower(field) {
case "name":
return name, nil
case "owner":
return entry.Owner.String(), nil
case "data":
return entry.Data, nil
case "expires":
return itoaU64(entry.Expires), nil
default:
return "", fmt.Errorf("Field %s not recognized", field)
}
}
func ValidatorsInfo(field string, do *def.Packages) (string, error) {
// Currently there is no notion of 'unbonding validators' we can revisit what should go here or whether this deserves
// to exist as a job
if field == "bonded_validators" {
set, err := do.GetValidatorSet()
if err != nil {
return "", err
}
return set.String(), nil
}
return "", nil
}
func itoaU64(i uint64) string {
return strconv.FormatUint(i, 10)
}
<file_sep>package jobs
import (
"github.com/monax/bosmarmot/bos/def"
"github.com/monax/bosmarmot/bos/util"
log "github.com/sirupsen/logrus"
)
func SetAccountJob(account *def.Account, do *def.Packages) (string, error) {
var result string
// Preprocess
account.Address, _ = util.PreProcess(account.Address, do)
// Set the Account in the Package & Announce
do.Package.Account = account.Address
log.WithField("=>", do.Package.Account).Info("Setting Account")
// Set result and return
result = account.Address
return result, nil
}
func SetValJob(set *def.SetJob, do *def.Packages) (string, error) {
var result string
set.Value, _ = util.PreProcess(set.Value, do)
log.WithField("=>", set.Value).Info("Setting Variable")
result = set.Value
return result, nil
}
<file_sep>package compile
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"github.com/monax/bosmarmot/bos/util"
)
var (
ext string
)
// clear a directory of its contents
func ClearCache(dir string) error {
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
names, err := d.Readdirnames(-1)
if err != nil {
return err
}
for _, name := range names {
err = os.RemoveAll(filepath.Join(dir, name))
if err != nil {
return err
}
}
return nil
}
// Get language from filename extension
func LangFromFile(filename string) (string, error) {
ext := path.Ext(filename)
ext = strings.Trim(ext, ".")
if _, ok := util.Languages[ext]; ok {
return ext, nil
}
return "", unknownLang(ext)
}
// Unknown language error
func unknownLang(lang string) error {
return fmt.Errorf("Unknown language %s", lang)
}
func CreateTemporaryFile(name string, code []byte) (*os.File, error) {
file, err := os.Create(name)
if err != nil {
return nil, err
}
_, err = file.Write(code)
if err != nil {
return nil, err
}
if err = file.Close(); err != nil {
return nil, err
}
return file, nil
}
<file_sep>Big improvements to performance across bos, including:
- Implement our own ABI library rather than relying on 2.7M lines of go-ethereum code for a fairly simple library.
- Migrate bos to leveraging burrow's GPRC framework entirely.
<file_sep>FROM golang:1.10.1-alpine3.7
MAINTAINER Monax <<EMAIL>>
# This is the image used by the Circle CI config in this directory pushed to quay.io/monax/bosmarmot:ci
# docker build -t quay.io/monax/bosmarmot:ci -f ./.circleci/Dockerfile .
RUN apk add --update --no-cache nodejs netcat-openbsd git make bash gcc g++ jq
RUN go get github.com/jstemmer/go-junit-report
RUN go get -u github.com/golang/dep/cmd/dep
RUN npm install -g mocha
RUN npm install -g standard
RUN npm install -g mocha-circleci-reporter<file_sep>#!/usr/bin/env bash
# ----------------------------------------------------------
# PURPOSE
# This is the test manager for monax jobs. It will run the testing
# sequence for monax jobs referencing test fixtures in this tests directory.
# ----------------------------------------------------------
# REQUIREMENTS
# m
# ----------------------------------------------------------
# USAGE
# run_pkgs_tests.sh [appXX]
# Various required binaries locations can be provided by wrapper
burrow_bin=${burrow_bin:-burrow}
# If false we will not try to start Burrow and expect them to be running
boot=${boot:-true}
debug=${debug:-false}
test_exit=0
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
chain_dir="${script_dir}/chain"
log_dir="${script_dir}/logs"
mkdir -p ${log_dir}
js_dir="${script_dir}/../burrow.js"
if [[ "$debug" = true ]]; then
set -o xtrace
fi
set -e
# ----------------------------------------------------------
# Constants
# Ports etc must match those in burrow.toml
keys_port=48002
rpc_tm_port=48003
export BURROW_HOST='127.0.0.1'
export BURROW_GRPC_PORT='20997'
burrow_root="${chain_dir}/.burrow"
# Temporary logs
burrow_log="${log_dir}/burrow.log"
#
# ----------------------------------------------------------
# ---------------------------------------------------------------------------
# Needed functionality
account_data(){
test_account=$(jq -r "." ${chain_dir}/account.json)
}
test_setup(){
echo "Setting up..."
echo
echo "Using binaries:"
echo " $(type ${burrow_bin}) (version: $(${burrow_bin} --version))"
echo
# start test chain
if [[ "$boot" = true ]]; then
rm -rf ${burrow_root}
cd "$chain_dir"
${burrow_bin} start -v0 -c "${chain_dir}/burrow.toml" -g "${chain_dir}/genesis.json" 2> "$burrow_log" &
burrow_pid=$!
sleep 1
else
echo "Not booting Burrow, but expecting Burrow to be running"
fi
account_data
sleep 4 # boot time
echo "Setup complete"
echo ""
}
perform_tests(){
cd "$js_dir"
account=$test_account mocha --bail --recursive ${1}
# SIGNBYADDRESS=true account=$test_account mocha --bail --recursive ${1}
}
test_teardown(){
test_exit=$?
cd "$script_dir"
echo "Cleaning up..."
if [[ "$boot" = true ]]; then
kill ${burrow_pid}
echo "Waiting for burrow to shutdown..."
wait ${burrow_pid} 2> /dev/null &
rm -rf "$burrow_root"
fi
echo ""
if [[ "$test_exit" -eq 0 ]]
then
[[ "$boot" = true ]] && rm -rf "$log_dir"
echo "Tests complete! Tests are Green. :)"
else
echo "Tests complete. Tests are Red. :("
echo "Failure in: $app"
fi
exit ${test_exit}
}
# ---------------------------------------------------------------------------
# Setup
echo "Hello! I'm the marmot that tests the $bos_bin jobs tooling."
echo
echo "testing with target $bos_bin"
echo
test_setup
trap test_teardown EXIT
echo "Running js Tests..."
perform_tests "$1"
<file_sep>package compile
import (
"encoding/json"
"io/ioutil"
"os"
"path"
"github.com/monax/bosmarmot/bos/util"
)
// check/cache all includes, hash the code, return whether or not there was a full cache hit
func CheckCached(includes map[string]*util.IncludedFiles, lang string) bool {
cached := true
for name, metadata := range includes {
hashPath := path.Join(util.Languages[lang].CacheDir, name)
if _, scriptErr := os.Stat(hashPath); os.IsNotExist(scriptErr) {
cached = false
break
}
for _, object := range metadata.ObjectNames {
objectFile := path.Join(hashPath, object+".json")
if _, objErr := os.Stat(objectFile); objErr != nil {
cached = false
break
}
}
if cached == false {
break
}
}
return cached
}
// return cached byte code as a response
func CachedResponse(includes map[string]*util.IncludedFiles, lang string) (*Response, error) {
var resp *Response
var respItemArray []ResponseItem
for name, metadata := range includes {
dir := path.Join(util.Languages[lang].CacheDir, name)
for _, object := range metadata.ObjectNames {
jsonBytes, err := ioutil.ReadFile(path.Join(dir, object+".json"))
if err != nil {
return nil, err
}
respItem := &ResponseItem{}
err = json.Unmarshal(jsonBytes, respItem)
if err != nil {
return nil, err
}
respItemArray = append(respItemArray, *respItem)
}
}
resp = &Response{
Objects: respItemArray,
Warning: "",
Error: "",
}
return resp, nil
}
// cache ABI and Binary to
func CacheResult(object ResponseItem, cacheLocation, warning, version, errorString string) error {
os.Chdir(cacheLocation)
fullResponse := Response{[]ResponseItem{object}, warning, version, errorString}
cachedObject, err := json.Marshal(fullResponse)
ioutil.WriteFile(object.Objectname+".json", []byte(cachedObject), 0644)
return err
}
<file_sep>package util
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/monax/bosmarmot/bos/def"
log "github.com/sirupsen/logrus"
)
func PreProcess(toProcess string, do *def.Packages) (string, error) {
// $block.... $account.... etc. should be caught. hell$$o should not
// :$libAddr needs to be caught
catchEr := regexp.MustCompile(`(^|\s|:)\$([a-zA-Z0-9_.]+)`)
// If there's a match then run through the replacement process
if catchEr.MatchString(toProcess) {
log.WithField("match", toProcess).Debug("Replacement Match Found")
// find what we need to catch.
processedString := toProcess
for _, jobMatch := range catchEr.FindAllStringSubmatch(toProcess, -1) {
jobName := jobMatch[2]
varName := "$" + jobName
var innerVarName string
var wantsInnerValues bool = false
// first parse the reserved words.
if strings.Contains(jobName, "block") {
block, err := replaceBlockVariable(toProcess, do)
if err != nil {
log.WithField("err", err).Error("Error replacing block variable.")
return "", err
}
/*log.WithFields(log.Fields{
"var": toProcess,
"res": block,
}).Debug("Fixing Variables =>")*/
processedString = strings.Replace(processedString, toProcess, block, 1)
}
if strings.Contains(jobName, ".") { //for functions with multiple returns
wantsInnerValues = true
var splitStr = strings.Split(jobName, ".")
jobName = splitStr[0]
innerVarName = splitStr[1]
}
// second we loop through the jobNames to do a result replace
for _, job := range do.Package.Jobs {
if string(jobName) == job.JobName {
if wantsInnerValues {
for _, innerVal := range job.JobVars {
if innerVal.Name == innerVarName { //find the value we want from the bunch
processedString = strings.Replace(processedString, varName, innerVal.Value, 1)
log.WithFields(log.Fields{
"job": string(jobName),
"varName": innerVarName,
"result": innerVal.Value,
}).Debug("Fixing Inner Vars =>")
}
}
} else {
log.WithFields(log.Fields{
"var": string(jobName),
"res": job.JobResult,
}).Debug("Fixing Variables =>")
processedString = strings.Replace(processedString, varName, job.JobResult, 1)
}
}
}
}
return processedString, nil
}
// if no matches, return original
return toProcess, nil
}
func replaceBlockVariable(toReplace string, do *def.Packages) (string, error) {
log.WithFields(log.Fields{
"var": toReplace,
}).Debug("Correcting $block variable")
blockHeight, err := GetBlockHeight(do)
block := itoaU64(blockHeight)
log.WithField("=>", block).Debug("Current height is")
if err != nil {
return "", err
}
if toReplace == "$block" {
log.WithField("=>", block).Debug("Replacement (=)")
return block, nil
}
catchEr := regexp.MustCompile(`\$block\+(\d*)`)
if catchEr.MatchString(toReplace) {
height := catchEr.FindStringSubmatch(toReplace)[1]
h1, err := strconv.Atoi(height)
if err != nil {
return "", err
}
h2, err := strconv.Atoi(block)
if err != nil {
return "", err
}
height = strconv.Itoa(h1 + h2)
log.WithField("=>", height).Debug("Replacement (+)")
return height, nil
}
catchEr = regexp.MustCompile(`\$block\-(\d*)`)
if catchEr.MatchString(toReplace) {
height := catchEr.FindStringSubmatch(toReplace)[1]
h1, err := strconv.Atoi(height)
if err != nil {
return "", err
}
h2, err := strconv.Atoi(block)
if err != nil {
return "", err
}
height = strconv.Itoa(h1 - h2)
log.WithField("=>", height).Debug("Replacement (-)")
return height, nil
}
log.WithField("=>", toReplace).Debug("Replacement (unknown)")
return toReplace, nil
}
func PreProcessInputData(function string, data interface{}, do *def.Packages, constructor bool) (string, []string, error) {
var callDataArray []string
var callArray []string
if function == "" && !constructor {
if reflect.TypeOf(data).Kind() == reflect.Slice {
return "", []string{""}, fmt.Errorf("Incorrect formatting of epm.yaml. Please update it to include a function field.")
}
function = strings.Split(data.(string), " ")[0]
callArray = strings.Split(data.(string), " ")[1:]
for _, val := range callArray {
output, _ := PreProcess(val, do)
callDataArray = append(callDataArray, output)
}
} else if data != nil {
if reflect.TypeOf(data).Kind() != reflect.Slice {
if constructor {
log.Warn("Deprecation Warning: Your deploy job is currently using a soon to be deprecated way of declaring constructor values. Please remember to update your run file to store them as a array rather than a string. See documentation for further details.")
callArray = strings.Split(data.(string), " ")
for _, val := range callArray {
output, _ := PreProcess(val, do)
callDataArray = append(callDataArray, output)
}
return function, callDataArray, nil
} else {
return "", make([]string, 0), fmt.Errorf("Incorrect formatting of epm.yaml file. Please update it to include a function field.")
}
}
val := reflect.ValueOf(data)
for i := 0; i < val.Len(); i++ {
s := val.Index(i)
var newString string
switch s.Interface().(type) {
case bool:
newString = strconv.FormatBool(s.Interface().(bool))
case int, int32, int64:
newString = strconv.FormatInt(int64(s.Interface().(int)), 10)
case []interface{}:
var args []string
for _, index := range s.Interface().([]interface{}) {
value := reflect.ValueOf(index)
var stringified string
switch value.Kind() {
case reflect.Int:
stringified = strconv.FormatInt(value.Int(), 10)
case reflect.String:
stringified = value.String()
}
index, _ = PreProcess(stringified, do)
args = append(args, stringified)
}
newString = "[" + strings.Join(args, ",") + "]"
log.Debug(newString)
default:
newString = s.Interface().(string)
}
newString, _ = PreProcess(newString, do)
callDataArray = append(callDataArray, newString)
}
}
return function, callDataArray, nil
}
func PreProcessLibs(libs string, do *def.Packages) (string, error) {
libraries, _ := PreProcess(libs, do)
if libraries != "" {
pairs := strings.Split(libraries, ",")
libraries = strings.Join(pairs, " ")
}
log.WithField("=>", libraries).Debug("Library String")
return libraries, nil
}
func GetReturnValue(vars []*def.Variable) string {
var result []string
if len(vars) > 1 {
for _, value := range vars {
log.WithField("=>", []byte(value.Value)).Debug("Value")
result = append(result, value.Value)
}
return "(" + strings.Join(result, ", ") + ")"
} else if len(vars) == 1 {
log.Debug("Debugging: ", vars[0].Value)
return vars[0].Value
} else {
return ""
}
}
<file_sep>package project
import (
"github.com/monax/relic"
)
// Can be used to set the commit hash version of the binary at build time with:
// `go build -ldflags "-X github.com/hyperledger/burrow/project.commit=$(git rev-parse --short HEAD)" ./cmd/burrow`
var commit = ""
func Commit() string {
return commit
}
func FullVersion() string {
version := History.CurrentVersion().String()
if commit != "" {
return version + "+commit." + commit
}
return version
}
// The releases described by version string and changes, newest release first.
// The current release is taken to be the first release in the slice, and its
// version determines the single authoritative version for the next release.
//
// To cut a new release add a release to the front of this slice then run the
// release tagging script: ./scripts/tag_release.sh
var History relic.ImmutableHistory = relic.NewHistory("Bosmarmot").MustDeclareReleases(
"0.4.0",
`Big improvements to performance across bos, including:
- Implement our own ABI library rather than relying on 2.7M lines of go-ethereum code for a fairly simple library.
- Migrate bos to leveraging burrow's GPRC framework entirely.
`,
"0.3.0",
`Add meta job; simplify run_packages significantly; js upgrades; routine burrow compatibility upgrades`,
"0.2.1",
`Fix release to harmonize against burrow versions > 0.18.0`,
"0.2.0",
`Simplify repository by removing latent tooling and consolidating compilers and bos,
as well as removing keys completely which have been migrated to burrow`,
"0.1.0",
`Major release of Bosmarmot tooling including updated javascript libraries for Burrow 0.18.*`,
"0.0.1",
`Initial Bosmarmot combining and refactoring Monax tooling, including:
- The monax tool (just 'monax pkgs do')
- The monax-keys signing daemon
- Monax compilers
- A basic legacy-contracts.js integration test (merging in JS libs is pending)`,
)
<file_sep>package compile
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"strings"
"testing"
"github.com/monax/bosmarmot/bos/util"
"github.com/stretchr/testify/assert"
)
func TestRequestCreation(t *testing.T) {
os.Chdir(testContractPath()) // important to maintain relative paths
var err error
contractCode := `pragma solidity ^0.4.0;
contract c {
function f() {
uint8[5] memory foo3 = [1, 1, 1, 1, 1];
}
}`
var testMap = map[string]*util.IncludedFiles{
"27fbf28c5dfb221f98526c587c5762cdf4025e85809c71ba871caa2ca42a9d85.sol": {
ObjectNames: []string{"c"},
Script: []byte(contractCode),
},
}
req, err := CreateRequest("simpleContract.sol", "", false)
if err != nil {
t.Fatal(err)
}
if req.Libraries != "" {
t.Errorf("Expected empty libraries, got %s", req.Libraries)
}
if req.Language != "sol" {
t.Errorf("Expected Solidity file, got %s", req.Language)
}
if req.Optimize != false {
t.Errorf("Expected false optimize, got true")
}
if !reflect.DeepEqual(req.Includes, testMap) {
t.Errorf("Got incorrect Includes map, expected %v, got %v", testMap, req.Includes)
}
}
func TestLocalMulti(t *testing.T) {
ClearCache(util.SolcScratchPath)
expectedSolcResponse := util.BlankSolcResponse()
actualOutput, err := exec.Command("solc", "--combined-json", "bin,abi", "contractImport1.sol").CombinedOutput()
if err != nil {
t.Fatal(err)
}
warning, responseJSON := extractWarningJSON(strings.TrimSpace(string(actualOutput)))
err = json.Unmarshal([]byte(responseJSON), expectedSolcResponse)
respItemArray := make([]ResponseItem, 0)
for contract, item := range expectedSolcResponse.Contracts {
respItem := ResponseItem{
Objectname: objectName(strings.TrimSpace(contract)),
Bytecode: trimAuxdata(strings.TrimSpace(item.Bin)),
ABI: strings.TrimSpace(item.Abi),
}
respItemArray = append(respItemArray, respItem)
}
expectedResponse := &Response{
Objects: respItemArray,
Warning: warning,
Version: "",
Error: "",
}
ClearCache(util.SolcScratchPath)
resp, err := RequestCompile("contractImport1.sol", false, "")
if err != nil {
t.Fatal(err)
}
fixupCompilersResponse(resp, "contractImport1.sol")
allClear := true
for _, object := range expectedResponse.Objects {
if !contains(resp.Objects, object) {
allClear = false
}
}
if !allClear {
t.Errorf("Got incorrect response, expected %v, \n\n got %v", expectedResponse, resp)
}
ClearCache(util.SolcScratchPath)
}
func TestLocalSingle(t *testing.T) {
ClearCache(util.SolcScratchPath)
expectedSolcResponse := util.BlankSolcResponse()
shellCmd := exec.Command("solc", "--combined-json", "bin,abi", "simpleContract.sol")
actualOutput, err := shellCmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
warning, responseJSON := extractWarningJSON(strings.TrimSpace(string(actualOutput)))
err = json.Unmarshal([]byte(responseJSON), expectedSolcResponse)
respItemArray := make([]ResponseItem, 0)
for contract, item := range expectedSolcResponse.Contracts {
respItem := ResponseItem{
Objectname: objectName(strings.TrimSpace(contract)),
Bytecode: trimAuxdata(strings.TrimSpace(item.Bin)),
ABI: strings.TrimSpace(item.Abi),
}
respItemArray = append(respItemArray, respItem)
}
expectedResponse := &Response{
Objects: respItemArray,
Warning: warning,
Version: "",
Error: "",
}
ClearCache(util.SolcScratchPath)
resp, err := RequestCompile("simpleContract.sol", false, "")
if err != nil {
t.Fatal(err)
}
fixupCompilersResponse(resp, "simpleContract.sol")
assert.Equal(t, expectedResponse, resp)
ClearCache(util.SolcScratchPath)
}
func TestFaultyContract(t *testing.T) {
ClearCache(util.SolcScratchPath)
var expectedSolcResponse Response
actualOutput, err := exec.Command("solc", "--combined-json", "bin,abi", "faultyContract.sol").CombinedOutput()
err = json.Unmarshal(actualOutput, expectedSolcResponse)
t.Log(expectedSolcResponse.Error)
resp, err := RequestCompile("faultyContract.sol", false, "")
t.Log(resp.Error)
if err != nil {
if expectedSolcResponse.Error != resp.Error {
t.Errorf("Expected %v got %v", expectedSolcResponse.Error, resp.Error)
}
}
output := strings.TrimSpace(string(actualOutput))
err = json.Unmarshal([]byte(output), expectedSolcResponse)
}
func testContractPath() string {
baseDir, _ := os.Getwd()
return filepath.Join(baseDir, "..", "..", "tests", "compilers_fixtures")
}
// The solidity 0.4.21 compiler appends something called auxdata to the end of the bin file (this is visible with
// solc --asm). This is a swarm hash of the metadata, and it's always at the end. This includes the path of the
// solidity source file, so it will differ.
func trimAuxdata(bin string) string {
return bin[:len(bin)-86]
}
func extractWarningJSON(output string) (warning string, json string) {
jsonBeginsCertainly := strings.Index(output, `{"contracts":`)
if jsonBeginsCertainly > 0 {
warning = output[:jsonBeginsCertainly]
json = output[jsonBeginsCertainly:]
} else {
json = output
}
return
}
func fixupCompilersResponse(resp *Response, filename string) {
for i := range resp.Objects {
resp.Objects[i].Bytecode = trimAuxdata(resp.Objects[i].Bytecode)
}
// compilers changes the filename, change it back again in the warning
re := regexp.MustCompile("[0-9a-f]+\\.sol")
resp.Warning = re.ReplaceAllString(resp.Warning, filename)
}
func contains(s []ResponseItem, e ResponseItem) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
<file_sep>package def
//TODO: Interface all the jobs, determine if they should remain in definitions or get their own package
type Job struct {
// Name of the job
JobName string `mapstructure:"name" json:"name" yaml:"name" toml:"name"`
// Not marshalled
JobResult string
// For multiple values
JobVars []*Variable
// Sets/Resets the primary account to use
Account *Account `mapstructure:"account" json:"account" yaml:"account" toml:"account"`
// Set an arbitrary value
Set *SetJob `mapstructure:"set" json:"set" yaml:"set" toml:"set"`
// Run a sequence of other epm.yamls
Meta *Meta `mapstructure:"meta" json:"meta" yaml:"meta" toml:"meta"`
// Contract compile and send to the chain functions
Deploy *Deploy `mapstructure:"deploy" json:"deploy" yaml:"deploy" toml:"deploy"`
// Send tokens from one account to another
Send *Send `mapstructure:"send" json:"send" yaml:"send" toml:"send"`
// Utilize monax:db's native name registry to register a name
RegisterName *RegisterName `mapstructure:"register" json:"register" yaml:"register" toml:"register"`
// Sends a transaction which will update the permissions of an account. Must be sent from an account which
// has root permissions on the blockchain (as set by either the genesis.json or in a subsequence transaction)
Permission *Permission `mapstructure:"permission" json:"permission" yaml:"permission" toml:"permission"`
// Sends a bond transaction
Bond *Bond `mapstructure:"bond" json:"bond" yaml:"bond" toml:"bond"`
// Sends an unbond transaction
Unbond *Unbond `mapstructure:"unbond" json:"unbond" yaml:"unbond" toml:"unbond"`
// Sends a transaction to a contract. Will utilize monax-abi under the hood to perform all of the heavy lifting
Call *Call `mapstructure:"call" json:"call" yaml:"call" toml:"call"`
// Wrapper for mintdump dump. WIP
DumpState *DumpState `mapstructure:"dump-state" json:"dump-state" yaml:"dump-state" toml:"dump-state"`
// Wrapper for mintdum restore. WIP
RestoreState *RestoreState `mapstructure:"restore-state" json:"restore-state" yaml:"restore-state" toml:"restore-state"`
// Sends a "simulated call" to a contract. Predominantly used for accessor functions ("Getters" within contracts)
QueryContract *QueryContract `mapstructure:"query-contract" json:"query-contract" yaml:"query-contract" toml:"query-contract"`
// Queries information from an account.
QueryAccount *QueryAccount `mapstructure:"query-account" json:"query-account" yaml:"query-account" toml:"query-account"`
// Queries information about a name registered with monax:db's native name registry
QueryName *QueryName `mapstructure:"query-name" json:"query-name" yaml:"query-name" toml:"query-name"`
// Queries information about the validator set
QueryVals *QueryVals `mapstructure:"query-vals" json:"query-vals" yaml:"query-vals" toml:"query-vals"`
// Makes and assertion (useful for testing purposes)
Assert *Assert `mapstructure:"assert" json:"assert" yaml:"assert" toml:"assert"`
}
type Package struct {
// from epm
Account string
Jobs []*Job
Libraries map[string]string
}
func BlankPackage() *Package {
return &Package{}
}
|
993f010e325528beca46bff8284a0a742055c818
|
[
"TOML",
"Markdown",
"Makefile",
"Go",
"Dockerfile",
"Shell"
] | 29 |
Go
|
hiturria/bosmarmot
|
ffe2499fed4e085ce9d76c660f9f34eb6e7382c5
|
91fdc9a066330a77a4f5a1cb7327ccdda0c53567
|
refs/heads/master
|
<repo_name>cfadnavis/ExData_Plotting1<file_sep>/plot2.R
# Read data
# TODO: Figure out how to specify colClasses to read in data appropriately
# TODO: Figure out how to extract only a subset of records based on date criteria
d <- read.csv(file="household_power_consumption.txt",header=TRUE,sep=";",na.strings = "?")
# Convert Date to strptime to filter data for relevant dates
d$Date <- strptime(d$Date,"%d/%m/%Y")
# Create date objects for relevant dates
d1 <- strptime("2007-02-01","%Y-%m-%d")
d2 <- strptime("2007-02-02","%Y-%m-%d")
# Extract subset of data for matching dates
subd <- subset(d,Date==d1|Date==d2)
# Convert Global_active_power from factor to numeric
subd$Global_active_power <- as.numeric(subd$Global_active_power)
# Print PNG. Default settings for width and height match assignment specs.
# TODO: Remove the "Index" label from the plot
png("plot2.png")
plot(subd$Global_active_power,type="l",lty="solid",xlab="",ylab="Global Active Power (kilowatts)",xaxt="n")
l <- length(subd$Global_active_power)
axis(side=1,labels=c("Thu","Fri","Sat"),at=c(0,l/2,l))
dev.off()
<file_sep>/plot4.R
# Read data
# TODO: Figure out how to specify colClasses to read in data appropriately
# TODO: Figure out how to extract only a subset of records based on date criteria
d <- read.csv(file="household_power_consumption.txt",header=TRUE,sep=";",na.strings = "?")
# Convert Date to strptime to filter data for relevant dates
d$Date <- strptime(d$Date,"%d/%m/%Y")
# Create date objects for relevant dates
d1 <- strptime("2007-02-01","%Y-%m-%d")
d2 <- strptime("2007-02-02","%Y-%m-%d")
# Extract subset of data for matching dates
subd <- subset(d,Date==d1|Date==d2)
# Convert Global_active_power from factor to numeric
subd$Global_active_power <- as.numeric(subd$Global_active_power)
# Print PNG. Default settings for width and height match assignment specs.
png("plot4.png")
par(mfrow=c(2,2))
# plot 1,1
plot(subd$Global_active_power,type="l",lty="solid",xlab="",ylab="Global Active Power (kilowatts)",xaxt="n")
l <- length(subd$Global_active_power)
axis(side=1,labels=c("Thu","Fri","Sat"),at=c(0,l/2,l))
# plot 1,2
plot(subd$Voltage,type="l",lty="solid",xlab="datetime",ylab="Voltage",xaxt="n")
axis(side=1,labels=c("Thu","Fri","Sat"),at=c(0,l/2,l))
# plot 2,1
plot(subd$Sub_metering_1,type="l",col="black",lty="solid",xlab="",ylab="Energy sub metering",xaxt="n")
lines(subd$Sub_metering_2,type="l",col="red",lty="solid",xlab="",ylab="Energy sub metering",xaxt="n")
lines(subd$Sub_metering_3,type="l",col="blue",lty="solid",xlab="",ylab="Energy sub metering",xaxt="n")
axis(side=1,labels=c("Thu","Fri","Sat"),at=c(0,l/2,l))
legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red", "blue"), lty="solid")
# plot 2,2
plot(subd$Global_reactive_power,type="l",lty="solid",xlab="",ylab="Global Reactive Power (kilowatts)",xaxt="n")
axis(side=1,labels=c("Thu","Fri","Sat"),at=c(0,l/2,l))
dev.off()<file_sep>/plot3.R
# Read data
# TODO: Figure out how to specify colClasses to read in data appropriately
# TODO: Figure out how to extract only a subset of records based on date criteria
d <- read.csv(file="household_power_consumption.txt",header=TRUE,sep=";",na.strings = "?")
# Convert Date to strptime to filter data for relevant dates
d$Date <- strptime(d$Date,"%d/%m/%Y")
# Create date objects for relevant dates
d1 <- strptime("2007-02-01","%Y-%m-%d")
d2 <- strptime("2007-02-02","%Y-%m-%d")
# Extract subset of data for matching dates
subd <- subset(d,Date==d1|Date==d2)
# Print PNG. Default settings for width and height match assignment specs.
# TODO: Remove the "Index" label from the plot
png("plot3.png")
plot(subd$Sub_metering_1,type=n)
plot(subd$Sub_metering_1,type="l",col="black",lty="solid",xlab="",ylab="Energy sub metering",xaxt="n")
lines(subd$Sub_metering_2,type="l",col="red",lty="solid",xlab="",ylab="Energy sub metering",xaxt="n")
lines(subd$Sub_metering_3,type="l",col="blue",lty="solid",xlab="",ylab="Energy sub metering",xaxt="n")
l <- length(subd$Global_active_power)
axis(side=1,labels=c("Thu","Fri","Sat"),at=c(0,l/2,l))
legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red", "blue"), lty="solid")
dev.off()<file_sep>/plot1.R
# Read data
# TODO: Figure out how to specify colClasses to read in data appropriately
# TODO: Figure out how to extract only a subset of records based on date criteria
d <- read.csv(file="household_power_consumption.txt",header=TRUE,sep=";",na.strings = "?")
# Convert Date to strptime to filter data for relevant dates
d$Date <- strptime(d$Date,"%d/%m/%Y")
# Create date objects for relevant dates
d1 <- strptime("2007-02-01","%Y-%m-%d")
d2 <- strptime("2007-02-02","%Y-%m-%d")
# Extract subset of data for matching dates
subd <- subset(d,Date==d1|Date==d2)
# Convert Global_active_power from factor to numeric
subd$Global_active_power <- as.numeric(subd$Global_active_power)
# Print PNG. Default settings for width and height match assignment specs.
png("plot1.png")
hist(subd$Global_active_power,col="red",xlab="Global Active Power (kilowatts)",main="Global Active Power")
dev.off()
|
664ddcbf52040053548c264e51f1643732a522d3
|
[
"R"
] | 4 |
R
|
cfadnavis/ExData_Plotting1
|
40745400db52f7fc36bacad1a50bed214eb8ab94
|
77a71835345f026ba2861053bb252612c65a3f7a
|
refs/heads/master
|
<file_sep> package com.czmodding.evilcraft;
import com.czmodding.evilcraft.proxy.CommonProxy;
import com.czmodding.evilcraft.util.Reference;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
@Mod(modid=Reference.MODID, name=Reference.MODNAME, version=Reference.VERSION, acceptedMinecraftVersions=Reference.ACCEPTED_MINECRAFT_VERSIONS)
public class Main {
@Instance
public static Main instance;
@SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.COMMON_PROXY_CLASS)
public static CommonProxy proxy;
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
System.out.println(Reference.MODID + ":preInit");
}
@EventHandler
public void init(FMLInitializationEvent event) {
System.out.println(Reference.MODID + ":init");
}
@EventHandler
public void postInit(FMLPostInitializationEvent event) {
System.out.println(Reference.MODID + ":postInit");
}
}
<file_sep># EvilCraft-1.12.2
A mod based on the game SimpleCraft 2: Biomes
|
9b273c379ad6981b8954d7322aacfb44bd99bc00
|
[
"Markdown",
"Java"
] | 2 |
Java
|
CZModding/EvilCraft-1.12.2
|
933a92831d93f166baafed70df6c2f2d13d1922e
|
aae3d7b2f9b17c95d48f94f856a09f06abf5ab64
|
refs/heads/master
|
<file_sep>/**
* 包含n个mutation的type 名称常量
*/
export const RECEIVE_ADDRESS = 'receive_address' //接收地址
export const RECEIVE_CATEGORYS = 'receive_categorys' //接收食品分类数组
export const RECEIVE_SHOPS = 'receive_shops' //接收商家数组
export const RECEIVE_USER_INFO = 'receive_user_info' //接收用户信息
export const RESET_USER_INFO = 'reset_user_info' //重置用户信息<file_sep>/**
* 状态对象
*/
export default {
latitude: 30.545972962, //经度
longitude: 104.1002032619, // 维度
address: {}, //地址相关信息
categorys: [], //食品分类数组
shops: [], // 商家数组
userInfo: {}, //用户信息
}
|
c6b949fc4aee7f70c4065193f307524cb38b6c27
|
[
"JavaScript"
] | 2 |
JavaScript
|
WilsonLiao1/waimai
|
3f9a728ffb8be105c43df9b4f961e76e86fc2721
|
b7da94671da115dee266473bed9774b88dd9b913
|
refs/heads/master
|
<file_sep>package com.titchyrascal.json.read;
import java.io.IOException;
import java.io.InputStream;
import com.titchyrascal.json.read.Event.EventType;
import streams.StringInputStream;
/**
* Wraps the Puller to push events to the event handler
*/
public class Pusher {
// INTERFACES
/**
* Implement to receive all the json events from a document
*/
public interface IEventHandler {
public void handleEvent(Event event);
}
// CONSTRUCTION
public Pusher() {
}
// PUBLIC METHODS
/**
* Runs through a json document passing all events to the handler
* @param json
* @param handler
* @throws IOException
*/
public void parse(String json, IEventHandler handler) throws IOException {
parse( new StringInputStream(json), handler );
}
/**
* Runs through a json document passing all events to the handler
* @param stream
* @param handler
* @throws IOException
*/
public void parse(InputStream stream, IEventHandler handler) throws IOException {
Event event;
Puller puller = new Puller(stream);
while(true) {
handler.handleEvent(event = puller.next());
if(event.getEventType() == EventType.DocumentFinished) {
return;
}
}
}
}
<file_sep>package com.titchyrascal.tt;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Test;
import com.titchyrascal.json.read.Event;
import com.titchyrascal.json.read.Puller;
public class PullerTest extends BaseJsonTest {
protected static Event[] EVENTS = {
new Event(Event.EventType.StartObject),
new Event(Event.EventType.Key, "Name"),
new Event(Event.EventType.Value, "Dave"),
new Event(Event.EventType.Key, "Surname"),
new Event(Event.EventType.Value, "Davidson"),
new Event(Event.EventType.Key, "Age"),
new Event(Event.EventType.Value, "30"),
new Event(Event.EventType.Key, "Children"),
new Event(Event.EventType.StartArray),
new Event(Event.EventType.StartObject),
new Event(Event.EventType.Key, "Name"),
new Event(Event.EventType.Value, "Phil"),
new Event(Event.EventType.Key, "Surname"),
new Event(Event.EventType.Value, "Davidson"),
new Event(Event.EventType.EndObject),
new Event(Event.EventType.StartObject),
new Event(Event.EventType.Key, "Name"),
new Event(Event.EventType.Value, "Steve"),
new Event(Event.EventType.Key, "Surname"),
new Event(Event.EventType.Value, "Davidson"),
new Event(Event.EventType.EndObject),
new Event(Event.EventType.EndArray),
new Event(Event.EventType.Key, "Hobbies"),
new Event(Event.EventType.StartArray),
new Event(Event.EventType.Value, "Snowboarding"),
new Event(Event.EventType.Value, "Skateboarding"),
new Event(Event.EventType.Value, "Surfing"),
new Event(Event.EventType.EndArray),
new Event(Event.EventType.EndObject),
new Event(Event.EventType.DocumentFinished)
};
@Test
public void testJsonDocument() throws IOException {
InputStream doc = getJsonInputStream();
testJsonDocument(doc);
}
protected void testJsonDocument(InputStream is) throws IOException {
Puller pp = new Puller(is);
for(int i = 0; i < EVENTS.length; i++) {
Event lhs = pp.next();
Event rhs = EVENTS[i];
Assert.assertEquals( lhs.toString() + " vs " + rhs.toString(), lhs, rhs );
}
is.close();
}
}
<file_sep>package com.titchyrascal.json.read;
/**
* Represents an event as we're parsing a json document
*/
public class Event {
// ENUMS
/**
* Represent the various events we can encounter while parsing document
*/
public enum EventType { StartObject, EndObject, StartArray, EndArray, Key, Value, DocumentFinished }
// MEMEBER DATA
/*
* Current key/val or null if another event
*/
private String mValue;
/**
* Type of json event
*/
private EventType mEvent;
// CONSTRUCTION
public Event() {
}
public Event(EventType event) {
mEvent = event;
}
public Event(EventType event, String val) {
mEvent = event;
mValue = val;
}
// PUBLIC METHODS
/**
* @return Valid string if Key/Value event, otherwise null
*/
public String getValue() {
return mValue;
}
/**
* @return Current json event
*/
public EventType getEventType() {
return mEvent;
}
/**
* Sets the event/value
* @param event
* @param value
*/
public void set(EventType event, String value) {
mEvent = event;
mValue = value;
}
/**
* Sets the event, value is set to null
* @param event
*/
public void set(EventType event) {
set(event, null);
}
// FROM OBJECT
/**
* @return True if events match
*/
public boolean equals(Object rhs) {
if(rhs instanceof Event) {
Event eRhs = (Event)rhs;
return mEvent == eRhs.mEvent &&
( ( mValue == null && eRhs.mValue == null ) || ( mValue != null && eRhs.mValue != null && mValue.equals(eRhs.mValue) ) );
}
return false;
}
public String toString() {
return "EventType: " + mEvent.toString() + " Value: " + mValue == null ? "null" : mValue;
}
}
<file_sep>## TommyTugger
#### Version 0.1
A JSON pull parser, sax style push parser and a JSON writer
### Puller
```java
Event next;
Puller jsonPuller = new Puller(/*Your string or InputStream*/);
while((next = jsonPuller.next()).getEventType() != EventType.DocumentFinished) {
/* If event type is key or value then next.getValue() will be populated */
}
```
### Pusher
```java
Pusher pusher = new Pusher();
pusher.parse(/* Your string or InputStream */, (event) -> {
/* If event type is key or value then next.getValue() will be populated */
});
```
<file_sep>package com.titchyrascal.tt;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Test;
import com.titchyrascal.json.read.Pusher;
public class PusherTest extends PullerTest {
private int mCurrent;
@Test
public void testPusher() throws IOException {
mCurrent = 0;
InputStream json = getJsonInputStream();
Pusher pusher = new Pusher();
pusher.parse(json, (event) -> {
Assert.assertEquals(event, EVENTS[mCurrent]);
mCurrent++;
});
}
}
<file_sep>// START SNIPPET use-plugin
apply plugin: 'java'
// END SNIPPET use-plugin
// START SNIPPET use-eclipse-plugin
apply plugin: 'eclipse'
// END SNIPPET use-eclipse-plugin
// START SNIPPET customization
sourceCompatibility = 1.8
version = '0.1'
jar {
manifest {
attributes 'Implementation-Title': 'TommyTugger',
'Implementation-Version': version
}
}
// END SNIPPET customization
// START SNIPPET repo
repositories {
mavenCentral()
}
// END SNIPPET repo
// START SNIPPET dependencies
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.+'
}
// END SNIPPET dependencies
// START SNIPPET task-customization
test {
systemProperties 'property': 'value'
}
// END SNIPPET task-customization<file_sep>package streams;
import java.io.IOException;
import java.io.InputStream;
/**
* Wraps a String in an InputStream
*/
public class StringInputStream extends InputStream {
// MEMBER DATA
/**
* Length of string (just so we're not calling the length method each time during the read)
*/
private int mLen;
/**
* String we're wrapping
*/
private String mStr;
/**
* Current character index
*/
private int mIndex;
// CONSTRUCTION
/**
* Construction
* @param str String to wrap
*/
public StringInputStream(String str) {
mStr = str;
mLen = str.length();
}
// PUBLIC METHODS
/**
* @return Next character in string or -1 if finished
*/
@Override
public int read() throws IOException {
return mIndex < mLen ? mStr.charAt(mIndex++) : -1;
}
}
|
70ebc320cedd57905ca1b7720684a63d6d66a0d3
|
[
"Markdown",
"Java",
"Gradle"
] | 7 |
Java
|
seanjohnno/tommytugger
|
9c9386cff4b929dd30ceb3ba2862c5a1a2f9d0e0
|
939f16300414381fa1dd688ffdfce9bc78856ee3
|
refs/heads/master
|
<file_sep>package tw.com.ruten.ts.mapreduce;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import tw.com.ruten.ts.mapreduce.JImageHashClusterTest.SortedKey.GroupComparator;
import tw.com.ruten.ts.mapreduce.JImageHashClusterTest.SortedKey.SortComparator;
import tw.com.ruten.ts.utils.JobUtils;
import tw.com.ruten.ts.utils.TsConf;
public class JImageHashClusterTest extends Configured implements Tool {
public static Logger LOG = Logger.getLogger(ProdClusteringJob.class);
public Configuration conf;
public static class SortedKey implements WritableComparable<SortedKey> {
Text sortValue = new Text();
Text defaultKey = new Text();
SortedKey() {
}
@Override
public void readFields(DataInput in) throws IOException {
defaultKey.set(Text.readString(in));
sortValue.set(in.readLine());
}
@Override
public void write(DataOutput out) throws IOException {
Text.writeString(out, defaultKey.toString());
out.writeBytes(sortValue.toString());
}
@Override
public int compareTo(SortedKey other) { /// default
return this.defaultKey.compareTo(other.defaultKey);
}
public int sort(SortedKey other) { /// for sort
int r = this.defaultKey.compareTo(other.defaultKey);
if (r == 0) {
return this.sortValue.toString().compareTo(other.sortValue.toString());
}
return r;
}
public int group(SortedKey other) { /// for group
return compareTo(other);
}
@Override
public int hashCode() { /// for partition
return this.defaultKey.toString().hashCode();
}
public static class SortComparator extends WritableComparator {
SortComparator() {
super(SortedKey.class, true);
}
@Override
public int compare(WritableComparable o1, WritableComparable o2) {
if (o1 instanceof SortedKey && o2 instanceof SortedKey) {
SortedKey k1 = (SortedKey) o1;
SortedKey k2 = (SortedKey) o2;
return k1.sort(k2);
}
return o1.compareTo(o2);
}
}
public static class GroupComparator extends WritableComparator {
GroupComparator() {
super(SortedKey.class, true);
}
@Override
public int compare(WritableComparable o1, WritableComparable o2) {
if (o1 instanceof SortedKey && o2 instanceof SortedKey) {
SortedKey k1 = (SortedKey) o1;
SortedKey k2 = (SortedKey) o2;
return k1.group(k2);
}
return o1.compareTo(o2);
}
}
}
public static class JImageHashClusterMapper extends Mapper<LongWritable, Text, SortedKey, MapWritable> {
private Configuration conf;
private JSONParser parser = new JSONParser();
String IMG_HASH = null;
@Override
public void setup(Context context) throws IOException, InterruptedException {
conf = context.getConfiguration();
IMG_HASH = conf.get("hashkey", "IMG_HASH_V2");
}
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String v = value.toString();
try {
Object obj = parser.parse(v);
JSONObject jsonObject = (JSONObject) obj;
SortedKey outKey = new SortedKey();
outKey.defaultKey.set(jsonObject.get(IMG_HASH).toString());
outKey.sortValue.set(jsonObject.get("G_NO").toString());
MapWritable outValue = new MapWritable();
// outValue.put(new Text("G_NO"), new Text(jsonObject.get("G_NO").toString()));
context.write(outKey, outValue);
context.getCounter("Mapper", "out").increment(1);
} catch (ParseException e) {
e.printStackTrace();
context.getCounter("Mapper", "parse.exception").increment(1);
}
}
}
public static class JImageHashClusterReducer extends Reducer<SortedKey, MapWritable, Text, Text> {
private Configuration conf;
private Text keyText = new Text();
private Text valueText = new Text();
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
int threshold = 0;
@Override
public void setup(Context context) throws IOException, InterruptedException {
conf = context.getConfiguration();
threshold = conf.getInt("threshold", 1);
}
public void reduce(SortedKey key, Iterable<MapWritable> values, Context context)
throws IOException, InterruptedException {
String preHashKey = null;
String preGno = null;
boolean cluster = false;
for (MapWritable val : values) {
String hashKey = key.defaultKey.toString();
if (preHashKey == null) {
preHashKey = hashKey;
preGno = key.sortValue.toString();
} else {
if (hammingDistance(hashKey, preHashKey) < threshold) {
context.write(new Text(preHashKey), new Text(key.sortValue)); // HASHKEY, GNO
cluster = true;
} else {
preHashKey = hashKey;
preGno = key.sortValue.toString();
cluster = false;
}
}
}
if (cluster == true) {
context.write(new Text(preHashKey), new Text(preGno));
}
}
static BigInteger hexToBigInt(String s) { // hex to binary
return new BigInteger(s, 16);
}
static int hammingDistance(String i, String i2) { // hamming distance
return hexToBigInt(i).xor(hexToBigInt(i2)).bitCount();
// return i.xor(i2).bitCount();
}
}
public int run(String[] args) throws Exception {
conf = getConf();
String jobtime = String.valueOf(System.currentTimeMillis());
if (args.length < 2) {
System.err.println("Usage: JImageHashCluster <input path> <output path>");
return -1;
}
FileSystem fs = FileSystem.get(conf);
Path outputPath = new Path(args[1],jobtime);
fs.delete(outputPath, true);
Job job = Job.getInstance(conf, "JImageHashCluster");
job.setJarByClass(JImageHashClusterTest.class);
job.setInputFormatClass(TextInputFormat.class);
job.setJobName("JImageHash Clustering");
// mapper
job.setMapperClass(JImageHashClusterMapper.class);
// job.setMapOutputKeyClass(Text.class);
job.setMapOutputKeyClass(SortedKey.class);
job.setMapOutputValueClass(MapWritable.class);
// reducer
job.setReducerClass(JImageHashClusterReducer.class);
job.setMapOutputKeyClass(SortedKey.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setOutputFormatClass(TextOutputFormat.class);
// job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setSortComparatorClass(SortComparator.class);
job.setGroupingComparatorClass(GroupComparator.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, outputPath);
MultipleOutputs.addNamedOutput(job, "result", TextOutputFormat.class, NullWritable.class, Text.class);
job.waitForCompletion(true);
return JobUtils.sumbitJob(job, true) ? 0 : -1;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(TsConf.create(), new JImageHashClusterTest(), args);
System.exit(res);
}
}
<file_sep>package tw.com.ruten.ts.mapreduce;
import com.google.common.collect.Lists;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import org.json.simple.parser.ParseException;
import tw.com.ruten.ts.utils.JobUtils;
import tw.com.ruten.ts.utils.TsConf;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* 計算 Group 相關資訊(GROUP_NUM、GROUP_HEAD)
* Created by jia03740 on 2017/6/12.
*/
public class ProdClusteringRefineJob extends Configured implements Tool {
public static Logger LOG = Logger.getLogger(ProdClusteringRefineJob.class);
public Configuration conf;
private static String CLUSTERING_FORMAT = "clustering.file.format";
public static SimpleDateFormat sdfSolr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
public static class SortedKey implements WritableComparable<SortedKey> {
Text sortValue = new Text();
Text defaultKey = new Text();
SortedKey() {
}
@Override
public void readFields(DataInput in) throws IOException {
defaultKey.set(Text.readString(in));
sortValue.set(in.readLine());
}
@Override
public void write(DataOutput out) throws IOException {
Text.writeString(out, defaultKey.toString());
out.writeBytes(sortValue.toString());
}
@Override
public int compareTo(SortedKey other) { /// default
return this.defaultKey.compareTo(other.defaultKey);
}
public int sort(SortedKey other) { /// for sort
int r = this.defaultKey.compareTo(other.defaultKey);
try {
if (r == 0) {
String[] data1 = this.sortValue.toString().split("\t");
String[] data2 = other.sortValue.toString().split("\t");
Double directPrice1 = Double.parseDouble(data1[0]);
Double directPrice2 = Double.parseDouble(data2[0]);
int r1 = directPrice2.compareTo(directPrice1);
if (r1 == 0 && !data1[1].isEmpty() && !data2[1].isEmpty()) {
BigInteger gPostTime1 = new BigInteger(data1[1]);
BigInteger gPostTime2 = new BigInteger(data2[1]);
int r2 = gPostTime2.compareTo(gPostTime1);
if(r2 == 0 && !data1[2].isEmpty() && !data2[2].isEmpty()){
BigInteger gno1 = new BigInteger(data1[2]);
BigInteger gno2 = new BigInteger(data2[2]);
return gno2.compareTo(gno1);
}
return r2;
}
return r1;
}
}catch (Exception e){
LOG.error("{}",e);
}
return r;
}
public int group(SortedKey other) { /// for group
return compareTo(other);
}
@Override
public int hashCode() { /// for partition
return this.defaultKey.toString().hashCode();
}
public static class SortComparator extends WritableComparator {
SortComparator() {
super(SortedKey.class, true);
}
@Override
public int compare(WritableComparable o1, WritableComparable o2) {
if (o1 instanceof SortedKey && o2 instanceof SortedKey) {
SortedKey k1 = (SortedKey) o1;
SortedKey k2 = (SortedKey) o2;
return k1.sort(k2);
}
return o1.compareTo(o2);
}
}
public static class GroupComparator extends WritableComparator {
GroupComparator() {
super(SortedKey.class, true);
}
@Override
public int compare(WritableComparable o1, WritableComparable o2) {
if (o1 instanceof SortedKey && o2 instanceof SortedKey) {
SortedKey k1 = (SortedKey) o1;
SortedKey k2 = (SortedKey) o2;
return k1.group(k2);
}
return o1.compareTo(o2);
}
}
}
public static class ProdClusteringRefineJobMapper extends Mapper<Object, Text, SortedKey, MapWritable> {
private Configuration conf;
private List<String> clusterField;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
@Override
public void setup(Context context) throws IOException, InterruptedException {
conf = context.getConfiguration();
clusterField = Arrays.asList(conf.getStrings(CLUSTERING_FORMAT));
}
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
try {
String[] data = value.toString().split("\t");
if (clusterField != null && clusterField.size() == data.length) {
SortedKey outKey = new SortedKey();
outKey.defaultKey.set(data[clusterField.indexOf("FINGERPRINT")]);
String rank = data[clusterField.indexOf("RANK")].equalsIgnoreCase("(null)") ? "0" : data[clusterField.indexOf("RANK")];
outKey.sortValue.set(rank + "\t" + sdf.parse(data[clusterField.indexOf("G_POST_TIME")]).getTime() + "\t" + data[clusterField.indexOf("G_NO")]);
MapWritable outValue = new MapWritable();
for (String keyField : clusterField) {
outValue.put(new Text(keyField), new Text(data[clusterField.indexOf(keyField)]));
}
outValue.remove(new Text("GROUP_NUM"));
context.write(outKey, outValue);
} else if (data.length == 2) {
SortedKey outKey = new SortedKey();
outKey.defaultKey.set(data[0]);
outKey.sortValue.set("9999999999999");
MapWritable outValue = new MapWritable();
outValue.put(new Text("GROUP_NUM"), new Text(data[1]));
context.write(outKey, outValue);
}
}catch (Exception e){
LOG.error(e.getMessage());
}
}
}
public static class ProdClusteringRefineJobReducer extends Reducer<SortedKey, MapWritable, NullWritable, Text> {
private Configuration conf;
private List<String> clusterField;
private Text result = new Text();
@Override
public void setup(Context context) throws IOException, InterruptedException {
conf = context.getConfiguration();
clusterField = Arrays.asList(conf.getStrings(CLUSTERING_FORMAT));
}
public void reduce(SortedKey key, Iterable<MapWritable> values, Context context) throws IOException, InterruptedException {
String clusterNum = "";
int i = 0;
for (MapWritable val : values) {
MapWritable map = new MapWritable(val);
if (i == 0) {
if(!map.containsKey(new Text("GROUP_NUM"))){
break;
}
clusterNum = map.get(new Text("GROUP_NUM")).toString();
i++;
continue;
}
if (i == 1) {
val.put(new Text("GROUP_HEAD"), new Text("Y"));
} else {
val.put(new Text("GROUP_HEAD"), new Text("N"));
}
val.put(new Text("GROUP_NUM"), new Text(clusterNum));
String outValue = "";
for (String keyField : clusterField) {
Text tmp = new Text(keyField);
if (!outValue.isEmpty()) {
outValue += "\t";
}
if (val.containsKey(tmp)) {
Writable writable = val.get(tmp);
outValue += writable.toString();
} else {
outValue += "(null)";
}
}
result.set(outValue);
context.write(NullWritable.get(), result);
i++;
}
}
}
@Override
public int run(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: ProdClusteringRefineJob <in> <out>");
return -1;
}
conf = getConf();
Job job = Job.getInstance(conf, "ProdClusteringRefineJob");
job.setJarByClass(ProdClusteringRefineJob.class);
job.setInputFormatClass(TextInputFormat.class);
job.setMapperClass(ProdClusteringRefineJobMapper.class);
/// map reduce change
job.setMapOutputKeyClass(SortedKey.class);
job.setMapOutputValueClass(MapWritable.class);
job.setReducerClass(ProdClusteringRefineJobReducer.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setSortComparatorClass(SortedKey.SortComparator.class);
job.setGroupingComparatorClass(SortedKey.GroupComparator.class);
FileInputFormat.addInputPaths(job, args[0]);
FileOutputFormat.setOutputPath(job, new Path(args[1], "current"));
return JobUtils.sumbitJob(job, true) ? 0 : -1;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(TsConf.create(), new ProdClusteringRefineJob(), args);
System.exit(res);
}
}
<file_sep>package tw.com.ruten.ts.mapreduce;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import tw.com.ruten.ts.model.GroupTagUpdateModel;
import tw.com.ruten.ts.utils.JobUtils;
import tw.com.ruten.ts.utils.SolrConnectUtils;
import tw.com.ruten.ts.utils.TsConf;
import org.json.simple.parser.JSONParser;
import org.mortbay.log.Log;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 與上次的計算結果比對後,輸出本次的集群狀態
* Created by jia03740 on 2017/6/5.
*/
public class ProdClusteringUpdateListJob extends Configured implements Tool {
public final static int MULTI_NUM = 3;
private static String CLUSTERING_FORMAT = "clustering.file.format";
public static Logger LOG = Logger.getLogger(ProdClusteringUpdateListJob.class);
public Configuration conf;
public static int getPartition(Text key) {
int hash = org.apache.solr.common.util.Hash.murmurhash3_x86_32(key.toString(), 0, key.toString().length(), 0);
return getPartition(hash);
}
public static int getPartition(int hash) {
if (hash <= 0x9554ffff) {
return 0;
} else if (hash <= 0xaaa9ffff) {
return 1;
} else if (hash <= 0xbfffffff) {
return 2;
} else if (hash <= 0xd554ffff) {
return 3;
} else if (hash <= 0xeaa9ffff) {
return 4;
} else if (hash <= 0xffffffff) {
return 5;
} else if (hash <= 0x1554ffff) {
return 6;
} else if (hash <= 0x2aa9ffff) {
return 7;
} else if (hash <= 0x3fffffff) {
return 8;
} else if (hash <= 0x5554ffff) {
return 9;
} else if (hash <= 0x6aa9ffff) {
return 10;
} else {
return 11;
}
}
public static class SolrShardPartitioner extends Partitioner<Text, MapWritable> {
@Override
public int getPartition(Text key, MapWritable value, int reduceNum) {
int hash = org.apache.solr.common.util.Hash.murmurhash3_x86_32(key.toString(), 0, key.toString().length(), 0);
return ProdClusteringUpdateListJob.getPartition(hash) + ((hash & 0x7FFFFFFF) % 3) * 12;
}
}
public static class UpdateListJobNewMapper extends Mapper<Object, Text, Text, MapWritable> {
private Configuration conf;
private Text outKey = new Text();
private List<String> clusterField;
@Override
public void setup(Context context) throws IOException, InterruptedException {
conf = context.getConfiguration();
clusterField = Arrays.asList(conf.getStrings(CLUSTERING_FORMAT));
}
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String[] data = value.toString().split("\t");
if (clusterField != null && clusterField.size() == data.length) {
MapWritable outValue = new MapWritable();
outKey.set(data[clusterField.indexOf("G_NO")]);
outValue.put(new Text("FINGERPRINT"), new Text(data[clusterField.indexOf("FINGERPRINT")]));
outValue.put(new Text("G_LASTUPDATE"), new Text(data[clusterField.indexOf("G_LASTUPDATE")]));
outValue.put(new Text("GROUP_HEAD"), new Text(data[clusterField.indexOf("GROUP_HEAD")]));
outValue.put(new Text("GROUP_NUM"), new Text(data[clusterField.indexOf("GROUP_NUM")]));
outValue.put(new Text("UPDATE"), new Text(data[clusterField.indexOf("UPDATE")]));
outValue.put(new Text("IS_OLD"), new Text("N"));
context.write(outKey, outValue);
}
}
}
public static class UpdateListJobOldMapper extends Mapper<Object, Text, Text, MapWritable> {
private Configuration conf;
private Text outKey = new Text();
private List<String> clusterField;
@Override
public void setup(Context context) throws IOException, InterruptedException {
conf = context.getConfiguration();
clusterField = Arrays.asList(conf.getStrings(CLUSTERING_FORMAT));
}
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String[] data = value.toString().split("\t");
if (clusterField != null && clusterField.size() == data.length) {
MapWritable outValue = new MapWritable();
outKey.set(data[clusterField.indexOf("G_NO")]);
outValue.put(new Text("FINGERPRINT"), new Text(data[clusterField.indexOf("FINGERPRINT")]));
outValue.put(new Text("G_LASTUPDATE"), new Text(data[clusterField.indexOf("G_LASTUPDATE")]));
outValue.put(new Text("GROUP_HEAD"), new Text(data[clusterField.indexOf("GROUP_HEAD")]));
outValue.put(new Text("GROUP_NUM"), new Text(data[clusterField.indexOf("GROUP_NUM")]));
outValue.put(new Text("UPDATE"), new Text(data[clusterField.indexOf("UPDATE")]));
outValue.put(new Text("IS_OLD"), new Text("Y"));
context.write(outKey, outValue);
}
}
}
public static class ProdClusteringUpdateListJobReducer extends Reducer<Text, MapWritable, Text, Text> {
private Configuration conf;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
private Comparator<MapWritable> selfComparator = new Comparator<MapWritable>() {
@Override
public int compare(MapWritable o1, MapWritable o2) {
Text o1Time = (Text) o1.get(new Text("UPDATE"));
Text o2Time = (Text) o2.get(new Text("UPDATE"));
try {
long t1 = sdf.parse(o1Time.toString()).getTime();
long t2 = sdf.parse(o2Time.toString()).getTime();
if (t1 > t2) {
return -1;
} else if (t1 < t2) {
return 1;
}
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
};
private Text result = new Text();
private Gson gson = new GsonBuilder().serializeNulls().create();
private Queue<JSONObject> groupTagUpdateModels = new LinkedList<>();
private JSONParser jsonParser = new JSONParser();
private int insertKey = -1;
private boolean isWrite2Solr = false;
private String collection = "";
protected void setup(Context context) {
conf = context.getConfiguration();
isWrite2Solr = context.getConfiguration().getBoolean("isWrite2Solr", false);
collection = context.getConfiguration().get("collection");
}
public void reduce(Text key, Iterable<MapWritable> values, Context context) throws IOException, InterruptedException {
if (insertKey == -1) {
insertKey = getPartition(key);
}
List<MapWritable> list = new LinkedList<>();
for (MapWritable val : values) {
list.add(new MapWritable(val));
}
Collections.sort(list, selfComparator);
MapWritable current = list.get(0);
Text currentIsOld = (Text) current.get(new Text("IS_OLD"));
Text currentFingerprint = (Text) current.get(new Text("FINGERPRINT"));
boolean current_group_head = ((Text) current.get(new Text("GROUP_HEAD"))).toString().equals("Y") ? true : false;
int current_group_num = Integer.parseInt(((Text) current.get(new Text("GROUP_NUM"))).toString());
try {
if (list.size() > 1) {
MapWritable last = list.get(1);
Text lastFingerprint = (Text) last.get(new Text("FINGERPRINT"));
int last_group_num = Integer.parseInt(((Text) last.get(new Text("GROUP_NUM"))).toString());
boolean last_group_head = ((Text) last.get(new Text("GROUP_HEAD"))).toString().equals("Y") ? true : false;
if (current_group_num > 1 && last_group_num > 1 && (!lastFingerprint.toString().equalsIgnoreCase(currentFingerprint.toString()) || (current_group_head ^ last_group_head))) { //集群大於1 & (群集更動 | head 更動)
result.set(currentFingerprint.toString() + "\t" + current_group_head + "\t" + current_group_num + "\t" + currentIsOld.toString() + "\tupdate");
if (isWrite2Solr) {
groupTagUpdateModels.add((JSONObject) jsonParser.parse(gson.toJson(new GroupTagUpdateModel(key.toString(), currentFingerprint.toString(), current_group_head, current_group_num))));
}
} else if (last_group_num <= 1 && current_group_num > 1) {// 變集群大於1
result.set(currentFingerprint.toString() + "\t" + current_group_head + "\t" + current_group_num + "\t" + currentIsOld.toString() + "\tinsert");
if (isWrite2Solr) {
groupTagUpdateModels.add((JSONObject) jsonParser.parse(gson.toJson(new GroupTagUpdateModel(key.toString(), currentFingerprint.toString(), current_group_head, current_group_num))));
}
} else if (last_group_num > 1 && current_group_num <= 1) {// 變集群小於1
result.set(currentFingerprint.toString() + "\t" + current_group_head + "\t" + current_group_num + "\t" + currentIsOld.toString() + "\tdelete");
if (isWrite2Solr) {
groupTagUpdateModels.add((JSONObject) jsonParser.parse(gson.toJson(new GroupTagUpdateModel(key.toString(), null, null, null))));
}
}
} else {
if (currentIsOld.toString().equals("N") && current_group_num > 1) { // 變上架且集群大於1
result.set(currentFingerprint.toString() + "\t" + current_group_head + "\t" + current_group_num + "\t" + currentIsOld.toString() + "\tinsert");
if (isWrite2Solr) {
groupTagUpdateModels.add((JSONObject) jsonParser.parse(gson.toJson(new GroupTagUpdateModel(key.toString(), currentFingerprint.toString(), current_group_head, current_group_num))));
}
} else if (currentIsOld.toString().equals("Y")) {//變下架
result.set(currentFingerprint.toString() + "\t" + current_group_head + "\t" + current_group_num + "\t" + currentIsOld.toString() + "\tdelete");
if (isWrite2Solr) {
groupTagUpdateModels.add((JSONObject) jsonParser.parse(gson.toJson(new GroupTagUpdateModel(key.toString(), null, null, null))));
}
}
}
} catch (org.json.simple.parser.ParseException e) {
LOG.error(e.toString());
}
if (result.toString().length() > 0) {
if (isWrite2Solr && groupTagUpdateModels.size() >= 1000) { /// flush
if ( "all".equals(collection) == true ) {
try {
SolrConnectUtils.sendToSolr("172.25.8.223:2181,172.25.8.224:2181,172.25.8.225:2181", "psearch1", groupTagUpdateModels, false);
groupTagUpdateModels = new LinkedList<>();
} catch (Exception e) {
context.write(key, new Text(e.toString()));
}
} else {
try {
SolrConnectUtils.sendToSolr("172.25.8.223:2181,172.25.8.224:2181,172.25.8.225:2181", collection, groupTagUpdateModels, false);
groupTagUpdateModels = new LinkedList<>();
} catch (Exception e) {
context.write(key, new Text(e.toString()));
}
}
Thread.sleep(100);
}
context.write(key, result);
result.clear();
}
}
public void cleanup(Context context) throws IOException, InterruptedException {
try {
if (isWrite2Solr && groupTagUpdateModels.size() > 0) {
if ( "all".equals(collection) == true ) {
SolrConnectUtils.sendToSolr("172.25.8.223:2181,172.25.8.224:2181,172.25.8.225:2181", "psearch1", groupTagUpdateModels, false);
groupTagUpdateModels = new LinkedList<>();
} else {
SolrConnectUtils.sendToSolr("172.25.8.223:2181,172.25.8.224:2181,172.25.8.225:2181", collection, groupTagUpdateModels, false);
groupTagUpdateModels = new LinkedList<>();
}
}
} catch (Exception e) {
context.write(new Text("final"), new Text(e.toString()));
}
SolrConnectUtils.closeZkClient();
}
}
@Override
public int run(String[] args) throws Exception {
conf = getConf();
if (args.length < 2) {
System.err.println("Usage: ProdClusteringUpdateListJob <current cluster file path> <output file path> <isWrite2Solr> <old cluster file path> [solr update collection]");
return -1;
}
Path currentFilePath = new Path(args[0]);
Path outputFilePath = new Path(args[1]);
conf.setBoolean("isWrite2Solr", args.length < 3 ? false : Boolean.parseBoolean(args[2]));
Path oldFilePath = args.length < 4 ? null : new Path(args[3]);
String collection = args.length == 5 ? args[4] : "all";
if ( collection != null ) {
conf.set("collection", collection);
LOG.info("set solr update collection: "+ collection);
} else {
conf.set("collection", "all");
LOG.info("set solr update collection: all");
}
FileSystem fs = FileSystem.get(conf);
fs.delete(outputFilePath, true);
Job job = Job.getInstance(conf, "ProdClusteringUpdateListJob");
job.setJarByClass(ProdClusteringUpdateListJob.class);
// job.setInputFormatClass(TextInputFormat.class);
// job.setMapperClass(ProdClusteringUpdateListJobMapper.class);
// job.setPartitionerClass(SolrShardPartitioner.class);
job.setReducerClass(ProdClusteringUpdateListJobReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(MapWritable.class);
job.setOutputFormatClass(TextOutputFormat.class);
// job.setNumReduceTasks(12 * MULTI_NUM);
// job.setNumReduceTasks(37);
MultipleInputs.addInputPath(job, currentFilePath, TextInputFormat.class, UpdateListJobNewMapper.class);
if (oldFilePath != null) {
MultipleInputs.addInputPath(job, oldFilePath, TextInputFormat.class, UpdateListJobOldMapper.class);
}
FileOutputFormat.setOutputPath(job, outputFilePath);
return JobUtils.sumbitJob(job, true, args[0].split(",")) ? 0 : -1;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(TsConf.create(), new ProdClusteringUpdateListJob(), args);
System.exit(res);
}
}
<file_sep>package tw.com.ruten.ts.model;
/**
* Created by jia03740 on 2017/6/8.
*/
import com.google.gson.JsonNull;
import com.google.gson.annotations.SerializedName;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* {
"id":"21608865035093",
"GROUP_TAG":{"set":null}
}
*/
public class GroupTagUpdateModel {
private String id;
@SerializedName("GROUP_TAG")
private Map<String,String> gTag = new HashMap<>();
@SerializedName("GROUP_HEAD")
private Map<String,Object> gHead = new HashMap<>();
@SerializedName("GROUP_NUM")
private Map<String,Object> gNum = new HashMap<>();
@SerializedName("_IMPORT")
private Map<String,String> _import = new HashMap<>();
@SerializedName("_SOURCE_TIME")
private Map<String,String> sourceTime = new HashMap<>();
private transient SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
public transient SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public GroupTagUpdateModel(String id, String group_tag, Boolean grepu_head, Integer group_num){
Date date = new Date();
this.id = id;
this.gTag.put("set", group_tag);
this.gHead.put("set", grepu_head);
this.gNum.put("set", group_num);
this._import.put("add", "group_tag." + sdf1.format(date));
this.sourceTime.put("add", sdf2.format(date));
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setgTag(String gTag){
this.gTag.put("set", gTag);
}
public Map<String, String> getgTag() {
return gTag;
}
}
<file_sep><?xml version="1.0"?>
<project name="${name}" default="runtime" xmlns:ivy="antlib:org.apache.ivy.ant" xmlns:artifact="antlib:org.apache.maven.artifact.ant">
<!-- Load all the default properties, and any the user wants -->
<!-- to contribute (without having to type -D or edit this file -->
<property file="${user.home}/build.properties" />
<property file="${basedir}/build.properties" />
<property file="${basedir}/default.properties" />
<property name="test.junit.output.format" value="plain" />
<property name="release.dir" value="${build.dir}/release" />
<!-- define Maven coordinates, repository url and artifacts name etc -->
<property name="groupId" value="tw.com.ruten.ts.mapreduce" />
<property name="artifactId" value="MRSimpleCode" />
<property name="maven-repository-url" value="https://repository.apache.org/service/local/staging/deploy/maven2" />
<property name="maven-repository-id" value="apache.releases.https" />
<property name="maven-jar" value="${release.dir}/${artifactId}-${version}.jar" />
<property name="maven-javadoc-jar" value="${release.dir}/${artifactId}-${version}-javadoc.jar" />
<property name="maven-sources-jar" value="${release.dir}/${artifactId}-${version}-sources.jar" />
<!-- the normal classpath -->
<path id="classpath">
<pathelement location="${build.classes}" />
<fileset dir="${build.lib.dir}">
<include name="*.jar" />
</fileset>
</path>
<presetdef name="javac">
<javac includeantruntime="false" />
</presetdef>
<!-- the unit test classpath -->
<dirname property="plugins.classpath.dir" file="${build.plugins}" />
<path id="test.classpath">
<pathelement location="${test.build.classes}" />
<pathelement location="${conf.dir}" />
<pathelement location="${test.src.dir}" />
<pathelement location="${plugins.classpath.dir}" />
<path refid="classpath" />
<pathelement location="${build.dir}/${final.name}.job" />
<fileset dir="${build.lib.dir}">
<include name="*.jar" />
</fileset>
</path>
<!-- ====================================================== -->
<!-- Stuff needed by all targets -->
<!-- ====================================================== -->
<target name="init" depends="ivy-init" description="--> stuff required by all targets">
<mkdir dir="${build.dir}" />
<mkdir dir="${build.classes}" />
<mkdir dir="${release.dir}" />
<mkdir dir="lib/native" />
<mkdir dir="${test.build.dir}" />
<mkdir dir="${test.build.classes}" />
<touch datetime="01/25/1971 2:00 pm">
<fileset dir="${conf.dir}" includes="**/*.template" />
</touch>
<copy todir="${conf.dir}" verbose="true">
<fileset dir="${conf.dir}" includes="**/*.template" />
<mapper type="glob" from="*.template" to="*" />
</copy>
</target>
<!-- ====================================================== -->
<!-- Compile the Java files -->
<!-- ====================================================== -->
<target name="compile-core" depends="init, resolve-default" description="--> compile core Java files only">
<javac
encoding="${build.encoding}"
srcdir="${src.dir}"
destdir="${build.classes}"
debug="${javac.debug}"
optimize="${javac.optimize}"
target="${javac.version}"
source="${javac.version}"
deprecation="${javac.deprecation}">
<compilerarg value="-Xlint:-path"/>
<classpath refid="classpath" />
</javac>
<copy todir="${build.classes}">
<fileset dir="${src.dir}" includes="**/*.html" />
<fileset dir="${src.dir}" includes="**/*.css" />
<fileset dir="${src.dir}" includes="**/*.properties" />
</copy>
</target>
<!-- ================================================================== -->
<!-- Make jar -->
<!-- ================================================================== -->
<!-- -->
<!-- ================================================================== -->
<target name="jar" depends="compile-core" description="--> make jar">
<copy file="${conf.dir}/job-default.xml" todir="${build.classes}" />
<copy file="${conf.dir}/job-site.xml" todir="${build.classes}" />
<jar jarfile="${build.dir}/${final.name}.jar" basedir="${build.classes}">
<manifest>
</manifest>
</jar>
</target>
<!-- ================================================================== -->
<!-- Make Maven Central Release -->
<!-- ================================================================== -->
<!-- -->
<!-- ================================================================== -->
<target name="release" depends="compile-core"
description="--> generate the release distribution">
<copy file="${conf.dir}/job-default.xml" todir="${build.classes}" />
<copy file="${conf.dir}/job-site.xml" todir="${build.classes}" />
<!-- build the main artifact -->
<jar jarfile="${maven-jar}" basedir="${build.classes}" />
<fail message="Unsupported Java version: ${java.version}. Javadoc requires Java version 7u25 or greater. ">
<condition>
<or>
<matches string="${java.version}" pattern="1.7.0_2[01234].+" casesensitive="false" />
<matches string="${java.version}" pattern="1.7.0_1.+" casesensitive="false" />
<equals arg1="${ant.java.version}" arg2="1.6" />
<equals arg1="${ant.java.version}" arg2="1.5" />
</or>
</condition>
</fail>
<jar jarfile="${maven-javadoc-jar}">
<fileset dir="${release.dir}/javadoc" />
</jar>
<!-- build the sources artifact -->
<jar jarfile="${maven-sources-jar}">
<fileset dir="${src.dir}" />
</jar>
</target>
<!-- ================================================================== -->
<!-- Deploy to Apache Nexus -->
<!-- ================================================================== -->
<!-- -->
<!-- ================================================================== -->
<target name="deploy" depends="release" description="--> deploy to Apache Nexus">
<!-- generate a pom file -->
<ivy:makepom ivyfile="${ivy.file}" pomfile="${basedir}/pom.xml"
templatefile="ivy/mvn.template">
<mapping conf="default" scope="compile" />
<mapping conf="runtime" scope="runtime" />
</ivy:makepom>
<!-- sign and deploy the main artifact -->
<artifact:mvn>
<arg
value="org.apache.maven.plugins:maven-gpg-plugin:1.4:sign-and-deploy-file" />
<arg value="-Durl=${maven-repository-url}" />
<arg value="-DrepositoryId=${maven-repository-id}" />
<arg value="-DpomFile=pom.xml" />
<arg value="-Dfile=${maven-jar}" />
<arg value="-Papache-release" />
</artifact:mvn>
<!-- sign and deploy the sources artifact -->
<artifact:mvn>
<arg value="org.apache.maven.plugins:maven-gpg-plugin:1.4:sign-and-deploy-file" />
<arg value="-Durl=${maven-repository-url}" />
<arg value="-DrepositoryId=${maven-repository-id}" />
<arg value="-DpomFile=pom.xml" />
<arg value="-Dfile=${maven-sources-jar}" />
<arg value="-Dclassifier=sources" />
<arg value="-Papache-release" />
</artifact:mvn>
<!-- sign and deploy the javadoc artifact -->
<artifact:mvn>
<arg value="org.apache.maven.plugins:maven-gpg-plugin:1.4:sign-and-deploy-file" />
<arg value="-Durl=${maven-repository-url}" />
<arg value="-DrepositoryId=${maven-repository-id}" />
<arg value="-DpomFile=pom.xml" />
<arg value="-Dfile=${maven-javadoc-jar}" />
<arg value="-Dclassifier=javadoc" />
<arg value="-Papache-release" />
</artifact:mvn>
</target>
<!-- ================================================================== -->
<!-- Make job jar -->
<!-- ================================================================== -->
<!-- -->
<!-- ================================================================== -->
<target name="job" depends="compile-core" description="--> make job">
<jar jarfile="${build.dir}/${final.name}.job">
<!--
If the build.classes has the config files because the jar command
command has run, exclude them. The conf directory has them.
-->
<zipfileset dir="${build.classes}" excludes="job-default.xml,job-site.xml" />
<zipfileset dir="${conf.dir}" excludes="*.template,hadoop*.*" />
<!--
need to exclude hsqldb.jar due to a conflicting version already present
in Hadoop/lib.
-->
<zipfileset dir="${build.lib.dir}" prefix="lib" includes="**/*.jar"
excludes="jasper*.jar,jsp-*.jar,hadoop-*.jar,hbase*test*.jar,ant*jar,hsqldb*.jar,slf4j*.jar,log4j*.jar" />
</jar>
</target>
<target name="runtime" depends="jar, job" description="--> depoly">
<mkdir dir="${runtime.dir}" />
<mkdir dir="${runtime.local}" />
<mkdir dir="${runtime.deploy}" />
<!-- deploy area -->
<copy file="${build.dir}/${final.name}.job" todir="${runtime.deploy}" />
<!-- local area -->
<copy file="${build.dir}/${final.name}.jar" todir="${runtime.local}/lib" failonerror="false"/>
<copy todir="${runtime.local}/lib/native" failonerror="false">
<fileset dir="lib/native" />
</copy>
<copy todir="${runtime.local}/conf">
<fileset dir="${conf.dir}" excludes="*.template" />
</copy>
<copy todir="${runtime.local}/lib" failonerror="false">
<fileset dir="${build.dir}/lib"
excludes="ant*.jar,jasper*.jar,jsp-*.jar,hadoop*test*.jar,hbase*test*.jar" />
</copy>
<copy todir="${runtime.local}/test">
<fileset dir="${build.dir}/test" />
</copy>
</target>
<!-- ================================================================== -->
<!-- Compile test code -->
<!-- ================================================================== -->
<target name="compile-core-test" depends="compile-core, resolve-test" description="--> compile test code">
<javac
encoding="${build.encoding}"
srcdir="${test.src.dir}"
destdir="${test.build.classes}"
debug="${javac.debug}"
optimize="${javac.optimize}"
target="${javac.version}"
source="${javac.version}"
deprecation="${javac.deprecation}">
<compilerarg value="-Xlint:-path"/>
<classpath refid="test.classpath" />
</javac>
</target>
<!-- ================================================================== -->
<!-- Run unit tests -->
<!-- ================================================================== -->
<target name="test-core" depends="job, compile-core-test" description="--> run JUnit tests only">
<delete dir="${test.build.data}" />
<mkdir dir="${test.build.data}" />
<!--
copy resources needed in junit tests
-->
<copy todir="${test.build.data}">
<fileset dir="src/testresources" includes="**/*" />
</copy>
<copy file="${test.src.dir}/log4j.properties"
todir="${test.build.classes}" />
<copy file="${test.src.dir}/gora.properties"
todir="${test.build.classes}" />
<copy file="${test.src.dir}/crawl-tests.xml"
todir="${test.build.classes}"/>
<copy file="${test.src.dir}/domain-urlfilter.txt"
todir="${test.build.classes}"/>
<copy file="${test.src.dir}/filter-all.txt"
todir="${test.build.classes}"/>
<junit printsummary="yes" haltonfailure="no" fork="yes" dir="${basedir}"
errorProperty="tests.failed" failureProperty="tests.failed" maxmemory="1000m">
<sysproperty key="test.build.data" value="${test.build.data}" />
<sysproperty key="test.src.dir" value="${test.src.dir}" />
<sysproperty key="javax.xml.parsers.DocumentBuilderFactory" value="com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl" />
<classpath refid="test.classpath" />
<formatter type="${test.junit.output.format}" />
<batchtest todir="${test.build.dir}" unless="testcase">
<fileset dir="${test.src.dir}"
includes="**/Test*.java" excludes="**/${test.exclude}.java" />
</batchtest>
<batchtest todir="${test.build.dir}" if="testcase">
<fileset dir="${test.src.dir}" includes="**/${testcase}.java" />
</batchtest>
</junit>
<fail if="tests.failed">Tests failed!</fail>
</target>
<!-- ================================================================== -->
<!-- Ivy targets -->
<!-- ================================================================== -->
<!-- target: resolve ================================================= -->
<target name="resolve-default" depends="clean-lib, init" description="--> resolve and retrieve dependencies with ivy">
<ivy:resolve file="${ivy.file}" conf="default" log="download-only" />
<ivy:retrieve pattern="${build.lib.dir}/[artifact]-[revision].[ext]" symlink="false" log="quiet" />
<antcall target="copy-libs" />
</target>
<target name="resolve-test" depends="clean-lib, init" description="--> resolve and retrieve dependencies with ivy">
<ivy:resolve file="${ivy.file}" conf="test" log="download-only" />
<ivy:retrieve pattern="${build.lib.dir}/[artifact]-[revision].[ext]" symlink="false" log="quiet" />
<antcall target="copy-libs" />
</target>
<target name="copy-libs" description="--> copy the libs in lib, which are not ivy enabled">
<!-- copy the libs in lib, which are not ivy enabled -->
<copy todir="${build.lib.dir}/" failonerror="false">
<fileset dir="${lib.dir}" includes="**/*.jar" />
</copy>
</target>
<!-- target: publish-local =========================================== -->
<target name="publish-local" depends="jar" description="--> publish this project in the local ivy repository">
<ivy:publish artifactspattern="${build.dir}/[artifact]-${version}.[ext]"
resolver="local"
pubrevision="${version}"
pubdate="${now}"
status="integration"
forcedeliver="true" overwrite="true" />
<echo message="project ${ant.project.name} published locally with version ${version}" />
</target>
<!-- target: report ================================================== -->
<target name="report" depends="resolve-test" description="--> generates a report of dependencies">
<ivy:report todir="${build.dir}" />
</target>
<!-- target: ivy-init ================================================ -->
<target name="ivy-init" depends="ivy-probe-antlib, ivy-init-antlib" description="--> initialise Ivy settings">
<ivy:settings file="${ivy.dir}/ivysettings.xml" />
</target>
<!-- target: ivy-probe-antlib ======================================== -->
<target name="ivy-probe-antlib" description="--> probe the antlib library">
<condition property="ivy.found">
<typefound uri="antlib:org.apache.ivy.ant" name="cleancache" />
</condition>
</target>
<!-- target: ivy-download ============================================ -->
<target name="ivy-download" description="--> download ivy">
<available file="${ivy.jar}" property="ivy.jar.found" />
<antcall target="ivy-download-unchecked" />
</target>
<!-- target: ivy-download-unchecked ================================== -->
<target name="ivy-download-unchecked" unless="ivy.jar.found" description="--> fetch any ivy file">
<get src="${ivy.repo.url}" dest="${ivy.jar}" usetimestamp="true" />
</target>
<!-- target: ivy-init-antlib ========================================= -->
<target name="ivy-init-antlib" depends="ivy-download" unless="ivy.found" description="--> attempt to use Ivy with Antlib">
<typedef uri="antlib:org.apache.ivy.ant" onerror="fail"
loaderRef="ivyLoader">
<classpath>
<pathelement location="${ivy.jar}" />
</classpath>
</typedef>
<fail>
<condition>
<not>
<typefound uri="antlib:org.apache.ivy.ant" name="cleancache" />
</not>
</condition>
You need Apache Ivy 2.0 or later from http://ant.apache.org/
It could not be loaded from ${ivy.repo.url}
</fail>
</target>
<!-- ================================================================== -->
<!-- Make bin release zip -->
<!-- ================================================================== -->
<!--
<target name="zip-bin" depends="package-bin" description="generate bin.zip distribution package">
<zip compress="true" casesensitive="yes"
destfile="${bin.dist.version.dir}.zip">
<zipfileset dir="${bin.dist.version.dir}" filemode="664" prefix="${final.name}">
<exclude name="bin/*" />
<include name="**" />
</zipfileset>
<zipfileset dir="${bin.dist.version.dir}" filemode="755" prefix="${final.name}">
<include name="bin/*" />
</zipfileset>
</zip>
</target>
-->
<!-- ================================================================== -->
<!-- Clean. Delete the build files, and their directories -->
<!-- ================================================================== -->
<!-- target: clean =================================================== -->
<target name="clean" depends="clean-build, clean-lib, clean-dist, clean-runtime" description="--> clean the project" />
<!-- target: clean-local ============================================= -->
<target name="clean-local" depends="" description="--> cleans the local repository for the current module">
<delete dir="${ivy.local.default.root}/${ivy.organisation}/${ivy.module}" />
</target>
<!-- target: clean-lib =============================================== -->
<target name="clean-lib" description="--> clean the project libraries directory (dependencies)">
<delete includeemptydirs="true" dir="${build.lib.dir}" />
</target>
<!-- target: clean-build ============================================= -->
<target name="clean-build" description="--> clean the project built files">
<delete includeemptydirs="true" dir="${build.dir}" />
</target>
<!-- target: clean-dist ============================================= -->
<target name="clean-dist" description="--> clean the project dist files">
<delete includeemptydirs="true" dir="${dist.dir}" />
</target>
<!-- target: clean-cache ============================================= -->
<target name="clean-cache" depends="" description="--> delete ivy cache">
<ivy:cleancache />
</target>
<target name="clean-runtime" description="--> clean the project runtime area">
<delete includeemptydirs="true" dir="${runtime.dir}" />
</target>
<target name="git-version" depends="init" description="--> get the git version">
<exec executable="git" failonerror="true" resultproperty="get.exit.code" output="build/classes/.version">
<arg value="log" />
<arg value="--pretty=format:'%H'" />
<arg value="-1" />
</exec>
<echo message="Git Status: ${get.exit.code}" />
<loadfile srcFile=".version" property="core.version" />
<echo message="Core Version: ${core.version}" />
</target>
</project>
<file_sep>package tw.com.ruten.ts.mapreduce;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
public class SortedKey implements WritableComparable<SortedKey> {
Text sortValue = new Text();
Text defaultKey = new Text();
SortedKey() {
}
@Override
public void readFields(DataInput in) throws IOException {
defaultKey.set(Text.readString(in));
sortValue.set(in.readLine());
}
@Override
public void write(DataOutput out) throws IOException {
Text.writeString(out, defaultKey.toString());
out.writeBytes(sortValue.toString());
}
@Override
public int compareTo(SortedKey other) { /// default
return this.defaultKey.compareTo(other.defaultKey);
}
public int sort(SortedKey other) { /// for sort
int r = this.defaultKey.compareTo(other.defaultKey);
if (r == 0) {
return this.sortValue.toString().compareTo(other.sortValue.toString());
}
return r;
}
public int group(SortedKey other) { /// for group
return compareTo(other);
}
@Override
public int hashCode() { /// for partition
return this.defaultKey.toString().hashCode();
}
public static class SortComparator extends WritableComparator {
SortComparator() {
super(SortedKey.class, true);
}
@Override
public int compare(WritableComparable o1, WritableComparable o2) {
if (o1 instanceof SortedKey && o2 instanceof SortedKey) {
SortedKey k1 = (SortedKey) o1;
SortedKey k2 = (SortedKey) o2;
return k1.sort(k2);
}
return o1.compareTo(o2);
}
}
public static class GroupComparator extends WritableComparator {
GroupComparator() {
super(SortedKey.class, true);
}
@Override
public int compare(WritableComparable o1, WritableComparable o2) {
if (o1 instanceof SortedKey && o2 instanceof SortedKey) {
SortedKey k1 = (SortedKey) o1;
SortedKey k2 = (SortedKey) o2;
return k1.group(k2);
}
return o1.compareTo(o2);
}
}
}
<file_sep>package tw.com.ruten.ts.mapreduce;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import tw.com.ruten.ts.mapreduce.ProdClusteringJob.SortedKey.GroupComparator;
import tw.com.ruten.ts.mapreduce.ProdClusteringJob.SortedKey.SortComparator;
import tw.com.ruten.ts.utils.JobUtils;
import tw.com.ruten.ts.utils.TsConf;
/**
* 同一賣家內的商品進行分群
*/
public class ProdClusteringJob extends Configured implements Tool {
//
public static Logger LOG = Logger.getLogger(ProdClusteringJob.class);
private static String CLUSTERING_FORMAT = "clustering.file.format";
private static String STOPWORD_FILE = "stopword.file";
public Configuration conf;
public static class SortedKey implements WritableComparable<SortedKey> {
Text sortValue = new Text();
Text defaultKey = new Text();
SortedKey() {
}
@Override
public void readFields(DataInput in) throws IOException {
defaultKey.set(Text.readString(in));
sortValue.set(in.readLine());
}
@Override
public void write(DataOutput out) throws IOException {
Text.writeString(out, defaultKey.toString());
out.writeBytes(sortValue.toString());
}
@Override
public int compareTo(SortedKey other) { /// default
return this.defaultKey.compareTo(other.defaultKey);
}
public int sort(SortedKey other) { /// for sort
int r = this.defaultKey.compareTo(other.defaultKey);
if (r == 0) {
return this.sortValue.toString().compareTo(other.sortValue.toString());
}
return r;
}
public int group(SortedKey other) { /// for group
return compareTo(other);
}
@Override
public int hashCode() { /// for partition
return this.defaultKey.toString().hashCode();
}
public static class SortComparator extends WritableComparator {
SortComparator() {
super(SortedKey.class, true);
}
@Override
public int compare(WritableComparable o1, WritableComparable o2) {
if (o1 instanceof SortedKey && o2 instanceof SortedKey) {
SortedKey k1 = (SortedKey) o1;
SortedKey k2 = (SortedKey) o2;
return k1.sort(k2);
}
return o1.compareTo(o2);
}
}
public static class GroupComparator extends WritableComparator {
GroupComparator() {
super(SortedKey.class, true);
}
@Override
public int compare(WritableComparable o1, WritableComparable o2) {
if (o1 instanceof SortedKey && o2 instanceof SortedKey) {
SortedKey k1 = (SortedKey) o1;
SortedKey k2 = (SortedKey) o2;
return k1.group(k2);
}
return o1.compareTo(o2);
}
}
}
public static class ProdClusteringJobMapper extends Mapper<Object, MapWritable, SortedKey, MapWritable> {
private Configuration conf;
// private SimHash simHash = new SimHash(Hashing.murmur3_128());
private HashFunction hf = Hashing.sha1();
private HashSet<String> stopwordList = new HashSet<>();
@Override
public void setup(Context context) throws IOException, InterruptedException {
conf = context.getConfiguration();
for (String word : conf.getStrings(STOPWORD_FILE)) {
stopwordList.add(word);
}
}
@Override
public void map(Object key, MapWritable value, Context context) throws IOException, InterruptedException {
// (Key, Value) = (CTRL_ROWID, fingerPrint)
SortedKey outKey = new SortedKey();
outKey.defaultKey.set(value.get(new Text("CTRL_ROWID")).toString());
String fingerprint = value.get(new Text("CTRL_ROWID")).toString() + ","
+ value.get(new Text("G_NAME")).toString();
outKey.sortValue.set(hf.hashString(fingerprint, Charset.defaultCharset()).toString());
context.write(outKey, value);
}
}
public static class ProdClusteringJobReducer extends Reducer<SortedKey, MapWritable, NullWritable, Text> {
public static SimpleDateFormat sdfSolr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
private Configuration conf;
private MultipleOutputs mos;
public static String THRESHOLD_SIMILARITY = "threshold.similarity";
private double threshold;
private Text info = new Text();
private Text result = new Text();
private Text clusterInfo = new Text();
private HashFunction hf = Hashing.sha1();
private List<String> clusterField;
@Override
public void setup(Reducer.Context context) throws IOException, InterruptedException {
conf = context.getConfiguration();
threshold = context.getConfiguration().getDouble(THRESHOLD_SIMILARITY, 0.1d);
clusterField = Arrays.asList(conf.getStrings(CLUSTERING_FORMAT));
mos = new MultipleOutputs(context);
}
public void reduce(SortedKey key, Iterable<MapWritable> values, Context context)
throws IOException, InterruptedException {
int prodCount = 0, clusterCount = 0, clusterNum = 0;
String last = null;
for (MapWritable val : values) {
val.put(new Text("UPDATE"), new Text(sdfSolr.format(new Date())));
String current = key.sortValue.toString();
val.put(new Text("FINGERPRINT"), new Text(current));
if (last != null) { // 第一個商品之後接要與先前的商品比較是否一樣
if (!current.equalsIgnoreCase(last)) {
clusterInfo.set(last + "\t" + clusterNum);// 儲存上一個集群的資訊
mos.write("clusterInfo", NullWritable.get(), clusterInfo, "clusterInfo/part");
clusterNum = 0;
clusterCount++;
}
} else {// 第一個商品,直接計算Fingerprint
clusterCount++;
}
prodCount++;
clusterNum++;
last = current;
String outValue = "";
for (String keyField : clusterField) {
Text tmp = new Text(keyField);
if (!outValue.isEmpty()) {
outValue += "\t";
}
if (val.containsKey(tmp)) {
Writable writable = val.get(tmp);
outValue += writable.toString();
} else {
outValue += "(null)";
}
}
result.set(outValue);
mos.write("result", NullWritable.get(), result, "result/part");
}
clusterInfo.set(last + "\t" + clusterNum); // 儲存最後集群的資訊
mos.write("clusterInfo", NullWritable.get(), clusterInfo, "clusterInfo/part");
info.set(new Text(key.defaultKey + "\t"
+ (clusterCount == 0 && prodCount == 0 ? 0.0 : (clusterCount / (float) prodCount))) + "\t"
+ clusterCount + "\t" + prodCount);
mos.write("info", NullWritable.get(), info, "info/part");
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
mos.close();
}
}
@Override
public int run(String[] args) throws Exception {
conf = getConf();
if (args.length < 2) {
System.err.println("Usage: ProdClusteringJob <in> <out>");
return -1;
}
if (args.length > 2) {
conf.setDouble(ProdClusteringJobReducer.THRESHOLD_SIMILARITY, Double.parseDouble(args[2]));
}
FileSystem fs = FileSystem.get(conf);
Path outputPath = new Path(args[1]);
fs.delete(outputPath, true);
Job job = Job.getInstance(conf, "ProdClusteringJob");
job.setJarByClass(ProdClusteringJob.class);
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapperClass(ProdClusteringJobMapper.class);
/// map reduce change
job.setMapOutputKeyClass(SortedKey.class);
job.setMapOutputValueClass(MapWritable.class);
job.setReducerClass(ProdClusteringJobReducer.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setSortComparatorClass(SortComparator.class);
job.setGroupingComparatorClass(GroupComparator.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, outputPath);
MultipleOutputs.addNamedOutput(job, "info", TextOutputFormat.class, NullWritable.class, Text.class);
MultipleOutputs.addNamedOutput(job, "clusterInfo", TextOutputFormat.class, NullWritable.class, Text.class);
MultipleOutputs.addNamedOutput(job, "result", TextOutputFormat.class, NullWritable.class, Text.class);
return JobUtils.sumbitJob(job, true) ? 0 : -1;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(TsConf.create(), new ProdClusteringJob(), args);
System.exit(res);
}
}
|
fa8d81331d68cde27eec640643ad94d94a0ddab8
|
[
"Java",
"Ant Build System"
] | 7 |
Java
|
applepaoo/MRSimProd
|
456cb2c00f37fdf2ac3302dca922dc37872883a8
|
d6c394e5d635c75c0c9b368adb7146d165d29196
|
refs/heads/master
|
<file_sep>/**
* This example turns the ESP32 into a Bluetooth LE keyboard that you can use num/caps/scroll lock led for some reason ex: turn your room light by scroll lock :)))
*/
#include <BleKeyboard.h>
BleKeyboard bleKeyboard;
//note that this function should run "fast" or esp will crash
void KbdLedCb(KbdLeds *kbls)
{
digitalWrite(2,kbls->bmNumLock);
// digitalWrite(2,kbls->bmCapsLock);
// digitalWrite(2,kbls->bmScrollLock);
// ...
}
void setup() {
pinMode(2,OUTPUT);
Serial.begin(115200);
Serial.println("Starting BLE work!");
bleKeyboard.begin();
delay(1000);//must have delay for the BLE finish inital
bleKeyboard.setLedChangeCallBack(KbdLedCb);
}
void loop() {
bleKeyboard.write(KEY_NUM_LOCK);
delay(10000);
}
|
a91603aca4c976fc426b0724ee8e74a828e6a1ad
|
[
"C++"
] | 1 |
C++
|
SparkyCola/ESP32-BLE-Keyboard-LED
|
447608dfb488af2bbd75aeb8794a0bbd8ffae00d
|
ece1ad3db31cfb7c8eac81eb7034fddea80b4859
|
refs/heads/master
|
<file_sep>$(function(){
$("form#matchMaker").submit(function(event){
event.preventDefault();
var userAge = $("#userAge").val();
userAge = parseInt(userAge);
var userProfession = $("#profession").val();
var userGender = $("#gender").val();
if (userAge < 30 && userProfession === "singer" && userGender === "male"){
$(".JustinB").show();
} else if (userAge < 30 && userProfession === "singer" && userGender === "female"){
$(".Taylor").show();
} else if (userAge < 30 && userProfession === "actor" && userGender === "male"){
$(".JustinT").show();
} else if (userAge < 30 && userProfession === "actor" && userGender === "female") {
$(".Lucy").show();
} else if ((userAge >= 30 && userAge <= 50) && userProfession === "actor" && userGender === "male"){
$(".Brad").show();
} else if ((userAge >= 30 && userAge <= 50) && userProfession === "actor" && userGender === "female"){
$(".Cindy").show();
} else if ((userAge >= 30 && userAge <= 50) && userProfession === "singer" && userGender === "male"){
$(".Jayz").show();
} else if ((userAge >= 30 && userAge <= 50) && userProfession === "singer" && userGender === "female"){
$(".Beyonce").show();
} else if (userAge > 50 && userProfession === "actor" && userGender === "male"){
$(".Donald").show();
} else if (userAge > 50 && userProfession === "actor" && userGender === "female"){
$(".Susan").show();
} else if (userAge > 50 && userProfession === "singer" && userGender === "male"){
$(".Michael").show();
} else if (userAge > 50 && userProfession === "singer" && userGender === "female"){
$(".Madonna").show();
};
});
});
|
20344a554c16b8aabd670e9715df2bc2dada8d6d
|
[
"JavaScript"
] | 1 |
JavaScript
|
eliotcarlsen/DatingGame
|
7760f5e3320a89204d29ca1eed2bce117df835fa
|
9647132cf43ea5e380fc1dcda15c3dc231b3867b
|
refs/heads/master
|
<repo_name>adalby/lamp<file_sep>/1.pkg.sh
# 2017 Jun 01 RAD Start with a fresh, fully updated system
sudo yum update -y
# 2017 Jun 01 RAD Add Extra Package repo, utils that should have been installed by default
sudo yum install epel-release
sudo yum install mailx wget -y
# 2017 Jun 01 RAD Install emacs & git for development, deployment
sudo yum install emacs git -y
# 2017 Jun 01 RAD Second tier of a LAMP stack is the Database Server
sudo yum install mariadb mariadb-server -y
sudo systemctl enable mariadb
sudo systemctl start mariadb
# 2017 Jun 01 RAD Next up is the Web Server
sudo yum install httpd php php-mysql php-gd -y
sudo systemctl enable httpd
sudo systemctl start httpd
# 2018 Oct 29 RSD Download latest copy of WordPress (for Linux, unzip)
wget https://wordpress.org/latest.tar.gz
tar -xvzf latest.tar.gz
# 2017 Aug 30 RAD Get certbot for https
# Enable EPEL Optional Channels per https://certbot.eff.org/all-instructions/#centos-rhel-7-apache
sudo yum -y install yum-utils
sudo yum-config-manager --enable rhui-REGION-rhel-server-extras rhui-REGION-rhel-server-optional
#sudo yum install certbot python-certbot-apache -y
sudo yum install certbot-apache -y
# 2017 Jun 07 RAD Finish up by making sure everything is up to date
sudo yum update -y
<file_sep>/README.md
# lamp
Set up for Shared Tennancy LAMP/WordPress
|
b1cd0f6dbef0cee8476c5a12f86ac941c6d0093c
|
[
"Markdown",
"Shell"
] | 2 |
Shell
|
adalby/lamp
|
8fb8df1c60039e9e40220a1e3493aba3c2c447a4
|
460508a9299709b0f6633d22d86ece889d451ce0
|
refs/heads/main
|
<repo_name>MaxRev-Dev/math-modelling<file_sep>/MathModelling/S4/MM4_MassTransfer.cs
using System;
using System.Linq;
using MM.Abstractions;
namespace MM.S4
{
internal class MM4_MassTransfer : BaseMethod
{
[ReflectedUICoefs]
public double
k_ = 1.65,
D = 0.08,
Cm_ = 10;
[ReflectedUICoefs]
public int
t_ = 5,
n_ = 10,
l_ = 50;
public override double[][] Calculate()
{
return MassTransfer(13.0 / 23, D,
FilteringSpeed(k_, l_, n_, t_),
19.5 * Math.Pow(10, -5), Cm_, l_, n_, t_);
}
private double[][] MassTransfer(double NN, double D, double[][] U,
double y,
double Cm, double l, int n, int t)
{
var h = l * 1.0 / n;
var T = 1;
var inline = new double[n + 1];
var tIrs = new double[t + 1][];
inline[0] = n;
inline[n] = Cm;
for (var k = n - 1; k > 0; k--)
inline[k] = Cm * Math.Exp(-5 * n * h);
tIrs[0] = inline;
for (var i = 1; i < t + 1; i++)
{
double[]
a = new double[n + 1],
b = new double[n + 1],
c = new double[n + 1],
f = new double[n + 1];
inline = new double[n + 1];
for (var j = 0; j < n + 1; j++)
{
var N = D / (1 + h * Math.Abs(U[i][j]) / (2 * D));
var R = (-U[i][j] + Math.Abs(U[i][j])) / 2;
var r = (-U[i][j] - Math.Abs(U[i][j])) / 2;
a[j] = T * (N / Math.Pow(h, 2) - r / h) / NN;
b[j] = T * (N / Math.Pow(h, 2) - R / h) / NN;
c[j] = 1.0 + T * (a[j] + b[j] + y) / NN;
f[j] = T * y * Cm / NN;
}
var L = new double[n];
var B = new double[n];
B[0] = Cm;
for (var m = 1; m < n; m++)
{
L[m] = b[m] / c[m] - a[m] * L[m - 1];
B[m] = (a[m] * B[m - 1] + tIrs[i - 1][m] + f[m]) /
(c[m] - a[m] * L[m - 1]);
}
inline[n] = (-U[0][n] * 10 * h / D + B[n - 1]) /
(1 - U[0][n] * h / D - L[n - 1]);
for (var k = n - 1; k > 0; k--)
inline[k] = L[k] * inline[k + 1] + B[k];
inline[0] = Cm;
tIrs[i] = inline;
}
return tIrs.ToArray();
}
private double[][] FilteringSpeed(double k, int l, int n, int t)
{
var Q = new double[t + 1].Select(x => new double[l + 1]).ToArray();
var h = l / n;
for (var i = 0; i < t + 1; i++)
for (var j = 0; j < l + 1; j++)
Q[i][j] = k * (l - 2 * j * h);
return Q;
}
}
}<file_sep>/MathModelling/S5/S5M4_2DMassHeatTransferUndergr.cs
using System;
using System.Collections.Generic;
using System.Linq;
using MM.Abstractions;
using F = System.Func<double, double>;
namespace MM.S5
{
internal class S5M4_2DMassHeatTransferUndergr : BaseMethod
{
[ReflectedUICoefs]
public static double
N = 5,
k = 1.5,
D = 0.02,
Dt = 0.04,
Lx = 100,
By = 10,
tau = 30,
sigma = 0.4,
hx = 10,
lam = 0.5,
hy = 2,
H1 = 1.5,
H2 = 0.5,
C1 = 350,
C2 = 8 * N,
Cm = 350,
Cp_ = 4.2,
Cn_ = 3,
T1 = 25 + N,
T2 = 8 + N,
T3 = 18;
[ReflectedUICoefs]
public static int
times = 4;
[ReflectedUICoefs(P = 6)]
public double
gamma = 0.065;
public override int Priority => 4;
public override double ChartStepX => hx;
public override double? ChartStepY => hy;
public override double? StepTime => tau;
public override double? MaxX => Lx;
public override bool Is3D => true;
private double GetFilteringSpeed()
{
return (H1 - H2) * k / Lx; // filtering speed
}
public double[][][] CalculateMassTransfer2D()
{
var Nx = (int) (Lx / hx); // interm points x
var Ny = (int) (By / hy); // interm points y
var V = GetFilteringSpeed(); // filtering speed
var Cx = 0.1 * Cm;
var h_2 = Math.Pow(hx, 2);
var r = -V / D;
var M = 1f / (1 + hx * V / (2 * D));
var ax_const = M / h_2 - r / hx;
var bx_const = M / h_2;
var cx_const = ax_const + bx_const + gamma / (2 * D) +
sigma / (D * tau);
var ay_const = 1f / Math.Pow(hy, 2);
var by_const = ay_const;
var cy_const = 2 * ay_const + gamma / (2 * D) + sigma / (D * tau);
var f2_1 = gamma * Cx / D;
var fk = sigma / (D * tau);
var fp = gamma * Cx / (2 * D);
var layers = new List<double[][]>();
var hC2d = CalculateHeatTransfer2D();
void FillOnZero()
{
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
for (var v = 0; v < Ny + 1; v++)
{
layer[v][0] = C1;
for (var i = 1; i < Nx; i++)
layer[v][i] =
v == 0 ? Cm : (C2 - C1) * hx * i / Lx + C1;
layer[v][Nx] = C2;
}
layers.Add(layer);
}
void FillByHalf(int layerTimek)
{
// 0.5k -> OX
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
var prev = layers[layerTimek - 1];
var hC = hC2d[layerTimek - 1];
for (var v = 0; v < Ny + 1; v++)
if (v == 0)
{
layer[v][0] = C1;
for (var i = 1; i < Nx; i++) layer[v][i] = Cm;
layer[v][Nx] = C2;
}
else
{
double[]
alfa = new double[Nx],
beta = new double[Nx];
beta[0] = C1;
for (var i = 1; i < Nx; i++)
{
alfa[i] = bx_const /
(cx_const - alfa[i - 1] * ax_const);
var F1 = Dt *
(hC[v][i - 1] - 2 * hC[v][i] +
hC[v][i + 1]) /
(D * h_2);
var f2 = f2_1 + F1 + fk * prev[v - 1][i];
beta[i] = (ax_const * beta[i - 1] + f2) /
(cx_const - alfa[i - 1] * ax_const);
}
layer[v][0] = C1;
for (var j = Nx - 1; j > 0; j--)
layer[v][j] = alfa[j] * layer[v][j + 1] + beta[j];
layer[v][Nx] = C2;
}
layers.Add(layer);
}
void FillByFull(int layerTimek)
{
// 1k -> fill OY
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
var prev = layers[layerTimek - 1];
var hC = hC2d[layerTimek - 1];
for (var v = 0; v < Nx + 1; v++)
if (v == 0)
{
layer[v][0] = C1;
for (var i = 0; i < Nx; i++) layer[v][i] = Cm;
layer[v][Nx] = C2;
}
else
{
double[]
alfa = new double[Ny],
beta = new double[Ny];
beta[0] = C1;
for (var i = 1; i < Ny; i++)
{
alfa[i] = by_const /
(cy_const - alfa[i - 1] * ay_const);
var F1 = Dt *
(hC[i - 1][v] - 2 * hC[i][v] +
hC[i + 1][v]) /
(D * h_2);
var f2 = f2_1 + F1 + fk * prev[i][v - 1];
beta[i] = (ay_const * beta[i - 1] + f2) /
(cy_const - alfa[i - 1] * ay_const);
layer[i][0] = C1;
}
layer[Ny][0] = C1;
layer[Ny][v] = beta[Ny - 1] / (1 - alfa[Ny - 1]);
for (var j = Ny - 1; j > 0; j--)
layer[j][v] = alfa[j] * layer[j + 1][v] + beta[j];
}
layers.Add(layer);
}
for (var layerTimeK = 0;
layerTimeK < times * 2;
layerTimeK++) // time layers
if (layerTimeK == 0)
{
FillOnZero();
}
else
{
FillByHalf(layerTimeK);
FillByFull(layerTimeK);
}
return layers.ToArray();
}
[ReflectedTarget]
public double[][][] GetMassTransfer2D()
{
var layers = CalculateMassTransfer2D();
var ret = new List<double[][]>();
for (var i = 0; i < layers.Length; i++)
if (i == 0 || i % 2 == 0)
ret.Add(layers[i].Reverse().ToArray());
return ret.ToArray().Reverse().ToArray();
}
[ReflectedTarget]
public double[][][] GetHeatTransfer2D()
{
var layers = CalculateHeatTransfer2D();
var ret = new List<double[][]>();
for (var i = 0; i < layers.Length; i++)
if (i == 0 || i % 2 == 0)
ret.Add(layers[i].Reverse().ToArray());
return ret.ToArray().Reverse().ToArray();
}
public double[][][] CalculateHeatTransfer2D()
{
var Nx = (int) (Lx / hx); // interm points x
var Ny = (int) (By / hy); // interm points y
var V = GetFilteringSpeed(); // filtering speed
var h_2 = Math.Pow(hx, 2);
F T0 = x => (T2 - T1) * hx * x / Lx + T1;
var Cp = Cp_ * Math.Pow(10, 6);
var Cn = Cn_ * Math.Pow(10, 6);
var r = -V * Cp / lam;
var nt = Cn / lam;
var nt_tau = nt / tau;
var M = 1f / (1 + 0.5 * (hx * V * Cp / lam));
var bx_const = M / h_2;
var ax_const = bx_const - r / hx;
var cx_const = 2 * bx_const - r / hx + nt_tau;
var ay_const = 1f / Math.Pow(hy, 2);
var by_const = ay_const;
var cy_const = 2 * ay_const + nt_tau;
var layers = new List<double[][]>();
void FillOnZero()
{
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
for (var v = 0; v < Ny + 1; v++)
{
layer[v][0] = T1;
for (var i = 1; i < Nx; i++)
layer[v][i] = T0(i);
layer[v][Nx] = T2;
}
layers.Add(layer);
}
void FillByHalf()
{
// 0.5k -> OX
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
var prev = layers.Last();
for (var v = 0; v < Ny + 1; v++)
if (v == 0)
{
layer[v][0] = T1;
for (var i = 1; i < Nx; i++) layer[v][i] = T3;
layer[v][Nx] = T2;
}
else
{
double[]
alfa = new double[Nx],
beta = new double[Nx];
beta[0] = T1;
for (var i = 1; i < Nx; i++)
{
alfa[i] = bx_const /
(cx_const - alfa[i - 1] * ax_const);
var f1 = nt_tau * prev[v][i];
beta[i] = (ax_const * beta[i - 1] + f1) /
(cx_const - alfa[i - 1] * ax_const);
}
layer[v][0] = T1;
for (var j = Nx - 1; j > 0; j--)
layer[v][j] = alfa[j] * layer[v][j + 1] + beta[j];
layer[v][Nx] = T2;
}
layers.Add(layer);
}
void FillByFull()
{
// 1k -> fill OY
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
var prev = layers.Last();
for (var v = 0; v < Nx + 1; v++)
if (v == 0)
{
layer[v][0] = T1;
for (var i = 1; i < Nx; i++) layer[v][i] = T3;
layer[v][Nx] = T2;
}
else
{
double[]
alfa = new double[Ny],
beta = new double[Ny];
beta[0] = T1;
for (var i = 1; i < Ny; i++)
{
alfa[i] = by_const /
(cy_const - alfa[i - 1] * ay_const);
var f1 = nt_tau * prev[i][v];
beta[i] = (ay_const * beta[i - 1] + f1) /
(cy_const - alfa[i - 1] * ay_const);
layer[i][0] = T1;
}
layer[Ny][0] = T1;
layer[Ny][v] = beta[Ny - 1] / (1 - alfa[Ny - 1]);
for (var j = Ny - 1; j > 0; j--)
layer[j][v] = alfa[j] * layer[j + 1][v] + beta[j];
}
layers.Add(layer);
}
for (var layerTimeI = 0;
layerTimeI < times * 2;
layerTimeI++) // time layers
if (layerTimeI == 0)
{
FillOnZero();
}
else
{
FillByHalf();
FillByFull();
}
return layers.ToArray();
}
}
}<file_sep>/MathModelling/S6/S6M2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.LinearAlgebra.Double;
using MM.Abstractions;
using F = System.Func<double, double>;
namespace MM.S6
{
internal class S6M2 : BaseMethod
{
#region Props
public override int Priority => 11;
public override int Precision => 6;
public override double ChartStepX => h;
public override string[] YLegend => new[] { "Orig.", "Approx." };
[ReflectedUICoefs]
public static int
n = 10;
[ReflectedUICoefs]
public static double
a = 0,
b = 1;
private static int
nn = n * n;
private static double
h = (b - a) / nn;
private enum T
{
FI,
FIDX,
F
}
F p = x => 1;
F g = x => 1;
F f = x => -x;
#endregion
#region selectors
private static double Fi(double i, double x) => x * Math.Exp(i * x);
private static double Fidx(double i, double x) => Math.Exp(i * x) + i * x * Math.Exp(i * x);
private static double Psi(double i, double x) => x * Math.Exp(Math.Pow(-1, i) * i * x);
private static double Psidx(double i, double x)
{
var mI = Math.Pow(-1, i);
var vI = mI * i * x;
return Math.Exp(vI) + vI * x * Math.Exp(vI);
}
private F SelectorFunc(double i, double j, T type)
{
return type switch
{
T.FIDX => x => p(x) * Fidx(j, x) * Psidx(i, x),
T.FI => x => g(x) * Fi(j, x) * Psi(i, x),
T.F => x => f(x) * Psi(i, x),
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
}
IEnumerable<IEnumerable<double>> MatA(Func<double, double, T, F> wrapSelector)
{
for (int i = 0; i < n; i++)
{
var localI = i;
IEnumerable<double> Row()
{
for (int j = 0; j < n; j++)
{
yield return Tpz(wrapSelector(localI + 1, j + 1, T.FIDX)) + Tpz(wrapSelector(localI + 1, j + 1, T.FI));
}
}
yield return Row();
}
}
IEnumerable<double> VecF(Func<double, double, T, F> wrapSelector)
{
for (int i = 0; i < n; i++)
{
yield return Tpz(wrapSelector(i + 1, 0, T.F));
}
}
private static double Tpz(F func)
{
return h * (0.5 * (func(a) + func(b)) +
Enumerable.Range(1, nn).Select(x => func(a + x * h)).Sum());
}
private static IEnumerable<double> CalculatedU(IEnumerable<int> xi, IEnumerable<double> c)
{
return xi.Select(i => a + i * h)
.Select(x => c.Select((v, i) => v * Fi(i + 1, x)).Sum());
}
private static IEnumerable<double> OriginalU(IEnumerable<int> xi)
{
return xi.Select(i => a + i * h).Select(x =>
Math.Exp(1) * (Math.Exp(x) - Math.Exp(-x)) / (Math.Pow(Math.Exp(1), 2) + 1) - x);
}
#endregion
[ReflectedTarget]
public double[][] Solution()
{
var matA = MatA(SelectorFunc);
var vecF = VecF(SelectorFunc);
var denseA = DenseMatrix.Build.DenseOfRows(matA);
var denseF = DenseVector.Build.DenseOfEnumerable(vecF);
var denseC = denseA.Solve(denseF);
Info.Clear();
var xi = Enumerable.Range(0, nn).ToArray();
return new[] { OriginalU(xi).ToArray(), CalculatedU(xi, denseC).ToArray() };
}
}
}<file_sep>/MathModelling/S5/S5M8_TDS.cs
using System;
using System.Collections.Generic;
using System.Linq;
using MM.Abstractions;
namespace MM.S5
{
internal class S5M8_TDS : BaseMethod
{
public override int Priority => 8;
public override int Precision => 6;
public override double ChartStepX => .1;
public override bool SwapAxis => true;
public override string[] YLegend
=> new[]
{
"Soil",
"Half-point"
};
[ReflectedUICoefs(P = 6)]
public static double
lam1 = 2.16 * Math.Pow(10, 6),
lam2 = 2.95 * Math.Pow(10, 6),
u1 = 9.26 * Math.Pow(10, 5),
u2 = 1.11 * Math.Pow(10, 6);
[ReflectedUICoefs]
public static double
l1 = 0.5,
L = 1,
h = 0.1;
private (double[][] tension, double[][] deform) _effector;
[ReflectedTarget]
public double[][] GetTransfer()
{
var tensions = new List<double[]>();
var deforms = new List<double[]>();
var lamn = 17;//lam1 * g;
var lamw = 10.5;//lam2 - (1 - v1) * pp;
var den1 = lam1 + 2 * u1;
var den2 = lam2 + 2 * u2;
var a1 = lamw / den1;
var a2 = lamn / den2;
var l1p2 = Math.Pow(l1, 2);
var lp2 = Math.Pow(L, 2);
var c3 = (a2 * lp2 / 2f - (a1 + a2) * l1p2 / 2f
+ den2 * a2 * l1p2 / den1) /
((1 - den2 / den1) * l1 - L);
var c1 = den2 * (a2 * l1 + c3) / den1 - a1 * l1;
var c4 = -c3 * L - a2 * lp2 / 2f;
double U1(double a, double x) => a * Math.Pow(x, 2) / 2f + c1 * x;
double U2(double a, double x) => a * Math.Pow(x, 2) / 2f + c3 * x + c4;
double Deform1(double a, double x) => a * x + c1;
double Deform2(double a, double x) => a * x + c3;
double Tension1(double a, double x) => den1 * Deform1(a, x);
double Tension2(double a, double x) => den2 * Deform2(a, x);
var b = (int)(L / h);
double[] soilx = new double[b + 1],
tension = new double[b + 1],
deform = new double[b + 1];
for (int i = 0; i <= b; i++)
{
var x = i * h;
var cx = x < l1;
var a = cx ? a1 : a2;
soilx[i] = cx ? U1(a, x) : U2(a, x);
tension[i] = cx ? Tension1(a, x) : Tension2(a, x);
deform[i] = cx ? Deform1(a, x) : Deform2(a, x);
}
tensions.Add(tension);
deforms.Add(deform);
_effector = (tensions.ToArray(), deforms.ToArray());
return new[] { soilx }.ToArray();
}
[ReflectedTarget]
public double[][] GetTension()
{
GetTransfer();
return _effector.tension;
}
[ReflectedTarget]
public double[][] GetDeform()
{
GetTransfer();
return _effector.deform;
}
}
}<file_sep>/MathModelling/Abstractions/BaseMethod.cs
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms.DataVisualization.Charting;
namespace MM.Abstractions
{
internal abstract class BaseMethod
{
private readonly CultureInfo ci;
protected BaseMethod()
{
ci = CultureInfo.GetCultureInfo("en-US");
}
public virtual int Priority { get; } = 0;
public virtual int Precision { get; } = 4;
public virtual string[] YLegend { get; }
public virtual double ChartStepX { get; } = 1;
public virtual double? ChartStepY { get; } = 1;
public virtual double? StepTime { get; } = 1;
public virtual double? MaxX { get; } = default;
public virtual string SwitchItem { get; set; }
public virtual string[] SwitchData { get; set; }
public virtual bool Is3D => false;
public virtual StringBuilder Info { get; } = new StringBuilder();
public virtual SeriesChartType? SeriesType { get; } = default;
public virtual bool SwapAxis { get; } = false;
public virtual double[][] Calculate()
{
return new double[0][];
}
public virtual double[][][] Calculate3D()
{
return new double[0][][];
}
public string AsString(double[][] result)
{
var s = new StringBuilder();
foreach (var t in result.Reverse())
{
foreach (var v in t) s.Append(v.ToString($"f{Precision}", ci).PadLeft(11));
s.AppendLine();
}
return s.ToString();
}
}
}<file_sep>/MathModelling/Abstractions/ReflectedUICoefsAttribute.cs
using System;
namespace MM.Abstractions
{
internal class ReflectedTargetAttribute : Attribute
{
}
internal class DefaultModAttribute : Attribute
{
}
internal class ReflectedUICoefsAttribute : Attribute
{
/// <summary>
/// Precision
/// </summary>
public int P { get; set; } = 2;
}
}<file_sep>/MathModelling/S6/S6M1.cs
using MM.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.LinearAlgebra.Double;
using F = System.Func<double, double>;
namespace MM.S6
{
internal class S6M1 : BaseMethod
{
#region Props
public override int Priority => 10;
public override int Precision => 6;
public override double ChartStepX => h;
public override string[] YLegend => new[] { "Orig.", "Approx." };
[ReflectedUICoefs]
public static int
n = 10;
[ReflectedUICoefs]
public static double
a = 0,
b = 1;
private static int
nn = n * n;
private static double
h = (b - a) / nn;
private enum T
{
FI,
FIDX,
F
}
F p = x => 1;
F g = x => 1;
F f = x => -x;
#endregion
private static double Fi(double i, double x)
{
if (i % 2 == 0)
return x * Math.Cos(Math.PI * i * x);
return x * Math.Sin(Math.PI * i * x);
}
private static double Fidx(double i, double x)
{
if (i % 2 == 0)
return Math.Cos(Math.PI * i * x) - Math.PI * i * x * Math.Sin(Math.PI * i * x);
return Math.Sin(Math.PI * i * x) + Math.PI * i * x * Math.Cos(Math.PI * i * x);
}
private F SelectorFunc(double i, double j, T type)
{
return type switch
{
T.FIDX => x => p(x) * Fidx(i, x) * Fidx(j, x),
T.FI => x => g(x) * Fi(i, x) * Fi(j, x),
T.F => x => f(x) * Fi(i, x),
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
}
private static IEnumerable<IEnumerable<double>> MatA(Func<double, double, T, F> wrapSelector)
{
for (int i = 0; i < n; i++)
{
var localI = i;
IEnumerable<double> InnerWrap()
{
for (int j = 0; j < n; j++)
{
yield return Tpz(wrapSelector(localI, j, T.FIDX)) + Tpz(wrapSelector(localI, j, T.FI));
}
}
yield return InnerWrap();
}
}
private static IEnumerable<double> VecF(Func<double, double, T, F> wrapSelector)
{
for (int i = 0; i < n; i++)
{
yield return Tpz(wrapSelector(i, 0, T.F));
}
}
private static double Tpz(F func)
{
return h * (0.5 * (func(a) + func(b)) +
Enumerable.Range(1, nn).Select(x => func(a + x * h)).Sum());
}
private static IEnumerable<double> CalculatedU(IEnumerable<int> xi, IEnumerable<double> c)
{
return xi.Select(i => a + i * h)
.Select(x => c.Select((v, i) => v * Fi(i, x)).Sum());
}
private static IEnumerable<double> OriginalU(IEnumerable<int> xi)
{
return xi.Select(i => a + i * h)
.Select(x => Math.Exp(1) * (Math.Exp(x) - Math.Exp(-x)) / (Math.Pow(Math.Exp(1), 2) + 1) - x);
}
[ReflectedTarget]
public double[][] Solution()
{
var matA = MatA(SelectorFunc);
var vecF = VecF(SelectorFunc);
var denseA = DenseMatrix.Build.DenseOfRows(matA);
var denseF = DenseVector.Build.DenseOfEnumerable(vecF);
var denseC = denseA.Solve(denseF);
Info.Clear();
var xi = Enumerable.Range(0, nn).ToArray();
return new[] { OriginalU(xi).ToArray(), CalculatedU(xi, denseC).ToArray() };
}
}
}<file_sep>/MathModelling/S5/S5M1_MassTransferUndergr.cs
using System;
using System.Linq;
using MM.Abstractions;
namespace MM.S5
{
internal class S5M1_MassTransferUndergr : BaseMethod
{
[ReflectedUICoefs]
public static double
N = 7,
k = 1.25,
D = 0.01 * N,
H1 = 1.5 + 0.1 * Math.Sin(N),
H2 = 0.5 + 0.1 * Math.Cos(N),
l = 50,
tau = 30,
sigma = 0.2,
h = 2.5;
[ReflectedUICoefs]
public static int
times = 4;
[ReflectedUICoefs(P = 6)]
public double
gamma = 0.00065;
public override int Priority => 1;
public override double ChartStepX => h;
public override double? ChartStepY => tau;
public override double? MaxX => l;
public override double[][] Calculate()
{
var V = (H1 - H2) * k / l; // filtering speed
Func<double, double> cx0 = x =>
N - 6 + Math.Pow(Math.Sin(N * x * h), 2);
Func<double, double> c0t = t => 0;
Func<double, double> clt = i =>
N - 6 + Math.Pow(Math.Sin(N * l), 2) + 0.2;
var Cx = 0.1 * k;
var h_2 = Math.Pow(h, 2);
var r = -V / D;
var M = 1f / (1 + h * V / (2 * D));
var a_const = M / h_2 - r / h;
var b_const = M / h_2;
var c_const = 2 * M / h_2 - r / h + gamma / D + sigma / (D * tau);
var fk = sigma / (D * tau);
var b = (int) (l / h); // interm points
var fp = gamma * Cx / D;
double[]
alfa = new double[b + 1],
beta = new double[b + 1];
var u = new double[times + 1][].Select(x => new double[b + 1])
.ToArray();
for (var i = 1; i < b; i++) u[0][i] = cx0(i);
for (var tl = 1; tl <= times; tl++) // time layers
{
u[tl][0] = c0t(tl);
u[tl][b] = clt(tl);
beta[0] = c0t(tl);
for (var i = 1; i <= b; i++)
{
alfa[i] = b_const / (c_const - alfa[i - 1] * a_const);
var f = fk + fp;
beta[i] = (a_const * beta[i - 1] + f * u[tl - 1][i]) /
(c_const - alfa[i - 1] * a_const);
}
for (var j = b - 1; j > 0; j--)
u[tl][j] = alfa[j] * u[tl][j + 1] + beta[j];
}
return u.ToArray();
}
}
}<file_sep>/Belman/Program.cs
using System;
using System.Collections.Generic;
using MaxRev.Extensions.Matrix;
namespace Belman
{
internal class Program
{
private static void Main(string[] args)
{
Belman.CreateContext().Solve();
}
}
internal class Belman
{
private static readonly double M = 1000;
private double[,] Minimization(double[,] C)
{
var n = C.GetLength(0);
var Cf = new double[n, n];
for (var i = 0; i < n; i++)
for (var j = 0; j < n; j++)
if (i != j)
{
var mins = M;
for (var k = 0; k < n; k++)
{
var mm = C[i, k] + C[k, j];
if (Math.Abs(mm - 1) < 0.001) break;
if (mm < mins) mins = mm;
Cf[i, j] = mins;
}
}
else
{
Cf[i, j] = 0;
}
return Cf;
}
public void Solve()
{
var m = new[,]
{
{0, M, 2, 1, M, M},
{M, 0, M, 7, 3, M},
{2, M, 0, 3, 4, 1},
{1, 7, 3, 0, 2, M},
{M, 3, 4, 2, 0, M},
{M, M, 1, M, 4, 0}
};
m.Print();
var shortestPath = FindShortestPath(m, 0, 1);
Console.WriteLine(
$@"Shortest path: {string.Join(",", shortestPath)}");
}
private int[] FindShortestPath(double[,] matrix, int from, int to)
{
var current = matrix;
while (true)
{
var m1 = Minimization(current);
var m2 = Minimization(m1);
if (MatrixEquals(m1, m2))
{
current = m1;
break;
}
current = m2;
}
return Path(matrix, current, from, to);
}
private bool MatrixEquals(double[,] m1, double[,] m2)
{
for (var i = 0; i < m1.GetLength(0); i++)
for (var j = 0; j < m1.GetLength(1); j++)
if (Math.Abs(m1[i, j] - m2[i, j]) > 0.001)
return false;
return true;
}
private int[] Path(double[,] matrix, double[,] c, int from, int to)
{
var num = new List<int>();
var result = new List<int>();
for (var i = 0; i < c.GetLength(0); i++) num.Add(i);
num.Remove(from);
result.Add(from + 1);
var k = 1;
for (var i = 0; i < c.GetLength(0); i++)
{
if (from == to) continue;
var mins = M;
foreach (var j in num)
{
var mm = matrix[from, j] + c[j, to];
if (Math.Abs(mm - 1) < 0.0001) // mm==1
{
k = j;
break;
}
if (!(mm < mins))
continue;
k = j;
mins = mm;
}
result.Add(k + 1);
num.Remove(k);
from = k;
}
return result.ToArray();
}
public static Belman CreateContext()
{
return new Belman();
}
}
}<file_sep>/MathModelling/S5/S5M3_2DMassTransferUndergr.cs
using System;
using System.Collections.Generic;
using System.Linq;
using MM.Abstractions;
namespace MM.S5
{
internal class S5M3_2DMassTransferUndergr : BaseMethod
{
[ReflectedUICoefs]
public static double
N = 5,
k = 1.5,
D = 0.02,
Lx = 100,
By = 10,
tau = 30,
sigma = 0.4,
hx = 10,
hy = 2,
H1 = 1.5,
H2 = 0.5,
C1 = 350,
C2 = 8 * N,
Cm = 350;
[ReflectedUICoefs]
public static int
times = 4;
[ReflectedUICoefs(P = 6)]
public double
gamma = 0.0065;
public override int Priority => 3;
public override double ChartStepX => hx;
public override double? ChartStepY => hy;
public override double? StepTime => tau;
public override double? MaxX => Lx;
public override bool Is3D => true;
private double GetFilteringSpeed()
{
return (H1 - H2) * k / Lx; // filtering speed
}
public override double[][][] Calculate3D()
{
var Nx = (int) (Lx / hx); // interm points x
var Ny = (int) (By / hy); // interm points y
var V = GetFilteringSpeed(); // filtering speed
var Cx = 0.1 * Cm;
var h_2 = Math.Pow(hx, 2);
var r = -V / D;
var M = 1f / (1 + hx * V / (2 * D));
var ax_const = M / h_2 - r / hx;
var bx_const = M / h_2;
var cx_const = ax_const + bx_const + gamma / (2 * D) +
sigma / (D * tau);
var ay_const = 1f / Math.Pow(hy, 2);
var by_const = ay_const;
var cy_const = 2 * ay_const + gamma / (2 * D) + sigma / (D * tau);
var fk = sigma / (D * tau);
var fp = gamma * Cx / (2 * D);
var layers = new List<double[][]>();
void FillOnZero()
{
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
for (var v = 0; v < Ny + 1; v++)
{
layer[v][0] = C1;
for (var i = 1; i < Nx; i++)
layer[v][i] =
v == 0 ? Cm : (C2 - C1) * hx * i / Lx + C1;
layer[v][Nx] = C2;
}
layers.Add(layer);
}
void FillByHalf()
{
// 0.5k -> OX
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
var prev = layers.Last();
for (var v = 0; v < Ny + 1; v++)
if (v == 0)
{
layer[v][0] = C1;
for (var i = 0; i < Nx; i++) layer[v][i] = Cm;
layer[v][Nx] = C2;
}
else
{
double[]
alfa = new double[Nx],
beta = new double[Nx];
beta[0] = C1;
for (var i = 1; i < Nx; i++)
{
alfa[i] = bx_const /
(cx_const - alfa[i - 1] * ax_const);
beta[i] =
(ax_const * beta[i - 1] + fk * prev[v][i] +
fp) /
(cx_const - alfa[i - 1] * ax_const);
}
layer[v][0] = C1;
for (var j = Nx - 1; j > 0; j--)
layer[v][j] = alfa[j] * layer[v][j + 1] + beta[j];
layer[v][Nx] = C2;
}
layers.Add(layer);
}
void FillByFull()
{
// 1k -> fill OY
var layer = new double[Ny + 1].Select(x => new double[Nx + 1])
.ToArray();
var prev = layers.Last();
for (var v = 0; v < Nx + 1; v++)
if (v == 0)
{
layer[v][0] = C1;
for (var i = 0; i < Nx; i++) layer[v][i] = Cm;
layer[v][Nx] = C2;
}
else
{
double[]
alfa = new double[Ny],
beta = new double[Ny];
beta[0] = C1;
for (var i = 1; i < Ny; i++)
{
alfa[i] = by_const /
(cy_const - alfa[i - 1] * ay_const);
beta[i] =
(ay_const * beta[i - 1] + fk * prev[i][v] +
fp) /
(cy_const - alfa[i - 1] * ay_const);
layer[i][0] = C1;
}
layer[Ny][0] = C1;
layer[Ny][v] = beta[Ny - 1] / (1 - alfa[Ny - 1]);
for (var j = Ny - 1; j > 0; j--)
layer[j][v] = alfa[j] * layer[j + 1][v] + beta[j];
}
layers.Add(layer);
}
for (var layerTimeI = 0;
layerTimeI < times * 2;
layerTimeI++) // time layers
if (layerTimeI == 0)
{
FillOnZero();
}
else
{
FillByHalf();
FillByFull();
}
var ret = new List<double[][]>();
for (var i = 0; i < layers.Count; i++)
if (i % 2 == 1)
ret.Add(layers[i].Reverse().ToArray());
return ret.ToArray();
}
}
}<file_sep>/MathModelling/S5/S5M9_TDS.cs
using MM.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MM.S5
{
internal class S5M9_TDS : BaseMethod
{
private (double[][] task1, double[][] task2) _effector;
private readonly Random _rand = new Random();
public override int Priority => 9;
public override int Precision => 6;
public override double ChartStepX => h;
public override bool SwapAxis => false;
[ReflectedUICoefs]
public static double
L = 10,
Q = 1,
D = 1,
gm = 1,
x0 = 2.82,
xi = 2.8,
h = 1,
ci_exact = 0.416,
ci_approx = 0.39;
public void CalculateCore()
{
var w = Math.Sqrt(gm / D);
double A0 = Q / (w * D * Math.Sinh(L));
double A1(double x) => Math.Sinh(w * (L - x));
double A2(double x) => Math.Sinh(w * x);
var b = (int)(L / h);
double Cx1(double xc, double x) => A0 * A1(xc) * A2(x);
double Cx2(double xc, double x) => A0 * A2(xc) * A1(x);
double Asinh(double x) => Math.Log(x + Math.Sqrt(x * x + 1));
double[] Concentration(double r)
{
var ret = new List<double>();
for (int i = 0; i <= b; i++)
{
var x = i * h;
var cx = x < r;
ret.Add(cx ? Cx1(r, x) : Cx2(r, x));
}
return ret.ToArray();
}
double GetValue(double cil)
{
double x;
if (xi < L / 2f)
{
x = L - 1 * (Asinh(cil / (A0 * Math.Sinh(w * xi)))) / w;
}
else
{
x = 1 * (Asinh(cil / (A0 * Math.Sinh(w * (L - xi))))) / w;
}
return x;
}
var task1 = Concentration(x0);
var rand = Enumerable.Range(0, b)
.Select(_ => _rand.NextDouble() * 10)
.Concat(new[] { L / 2f }).ToArray();
Info.Clear();
Info.AppendLine($"Exact: { GetValue(ci_exact)}");
Info.AppendLine($"Approx: { GetValue(ci_approx)}");
_effector = (new[] { task1.ToArray() },
rand.Select(Concentration).ToArray()
);
}
[ReflectedTarget]
public double[][] GetTask1()
{
CalculateCore();
return _effector.task1;
}
[ReflectedTarget]
public double[][] GetTask2()
{
CalculateCore();
return _effector.task2;
}
}
}<file_sep>/MathModelling/S4/MM5_HeatTransfer.cs
using System;
using System.Linq;
using MM.Abstractions;
namespace MM.S4
{
internal class MM5_HeatTransfer : BaseMethod
{
[ReflectedUICoefs]
public double
k_ = 1.65,
lam_ = 93,
Ct_ = 720,
Cp_ = 440,
Tz_ = 40,
alfa_ = 0.1;
[ReflectedUICoefs]
public int
t_ = 5,
l_ = 2,
n_ = 10;
public override double[][] Calculate()
{
return HeatTransfer(Ct_, lam_,
FilteringSpeed(k_, l_, n_, t_),
Cp_, Tz_, alfa_, l_, n_, t_);
}
private double[][] HeatTransfer(double Ct, double lam, double[][] U,
double Cp,
double Tz, double alfa, int l, int n, int t)
{
var h = l * 1.0 / n;
var c0 = 5;
var T = 1;
var inline = new double[n + 1];
var tIrs = new double[t + 1][];
inline[0] = c0;
inline[n] = 2;
for (var k = n - 1; k > 0; k--)
inline[k] = 5 * Math.Exp(l - k * h);
tIrs[0] = inline;
for (var i = 1; i < t + 1; i++)
{
double[]
a = new double[n + 1],
b = new double[n + 1],
c = new double[n + 1];
inline = new double[n + 1];
for (var j = 0; j < n + 1; j++)
{
var N = lam /
(1 + h * Math.Abs(1003 * Cp * U[i][j]) / (2 * lam));
var R = (-U[i][j] + Math.Abs(U[i][j])) / 2;
var r = (-U[i][j] - Math.Abs(U[i][j])) / 2;
a[j] = T * (N / Math.Pow(h, 2) - r / h) / Ct;
b[j] = T * (N / Math.Pow(h, 2) - R / h) / Ct;
c[j] = 1.0 + T * (a[j] + b[j]) / Ct;
}
var L = new double[n];
var B = new double[n];
L[0] = lam / (h * alfa + lam);
B[0] = alfa * h * Tz / (h * alfa + lam);
for (var m = 1; m < n; m++)
{
L[m] = b[m] / c[m] - a[m] * L[m - 1];
B[m] = (a[m] * B[m - 1] + tIrs[i - 1][m]) /
(c[m] - a[m] * L[m - 1]);
}
inline[n] = (-alfa * h * L[1] * Tz + lam + B[1]) /
(-(lam + alfa * h) * L[1] + lam);
for (var k = n - 1; k > 0; k--)
inline[k] = L[k] * inline[k + 1] + B[k];
inline[0] = c0;
tIrs[i] = inline;
}
return tIrs.ToArray();
}
private double[][] FilteringSpeed(double k, int l, int n, int t)
{
var Q = new double[t + 1][];
var h = l / n;
var len = (l + 1) * (t + 1);
var q = new double[len];
for (var i = 0; i < t + 1; i++)
{
for (var j = 0; j < len; j++) q[j] = -k * (5 * l - 10 * j * h);
Q[i] = q.ToArray();
}
return Q;
}
}
}<file_sep>/MathModelling/S5/S5M7_TDS.cs
using MM.Abstractions;
using System;
using System.Collections.Generic;
namespace MM.S5
{
internal class S5M7_TDS : BaseMethod
{
public override int Priority => 7;
public override double ChartStepX => 1;
public override string[] YLegend
=> new[]
{
"Dry",
"Dewy",
"Filt"
};
public override double? MaxX => L;
[ReflectedUICoefs(P = 6)]
public static double
E = 2.5 * Math.Pow(10, 6);
[ReflectedUICoefs]
public static int
L = 10;
[ReflectedUICoefs]
public static double
H1 = 1,
H2 = 5,
g = 9.8,
v = 0.35,
ps = 2200,
pp = 1000;
private (double[][] tension, double[][] deform) _effector;
[ReflectedTarget]
public double[][] GetTDS()
{
var lam = (E * v) / ((1 + v) * (1 - 2 * v));
var u = E / (2 * (1 + v));
var den = lam + 2 * u;
double U(double a, double x) => a * x * (x - 1) / 2;
double Up(double a, double x) => a * x - a / 2;
double Sp(double a, double x) => (lam + 2 * u) * Up(a, x);
var a1 = (ps * g) / den;
var a2 = (-pp + ps) * g / den;
var a3 = g * (ps + ((H2 - H1) / L - 1) * pp) / den;
var b = L;
double[] dry = new double[b + 1],
dewy = new double[b + 1],
filt = new double[b + 1];
var tensions = new List<double[]>();
var deforms = new List<double[]>();
foreach (var a in new[] { a1, a2, a3 })
{
double[] tension = new double[b + 1],
deform = new double[b + 1];
for (int i = 0; i <= b; i++)
{
var x = i * .1;
tension[i] = Up(a, x);
deform[i] = Sp(a, x);
}
tensions.Add(tension);
deforms.Add(deform);
}
for (int i = 1; i < b; i++)
{
var x = i * .1;
dry[i] = U(a1, x);
dewy[i] = U(a2, x);
filt[i] = U(a3, x);
}
_effector = (tensions.ToArray(), deforms.ToArray());
return new List<double[]>(new[] { dry, dewy, filt }).ToArray();
}
[ReflectedTarget]
public double[][] GetTension()
{
GetTDS();
return _effector.tension;
}
[ReflectedTarget]
public double[][] GetDeform()
{
GetTDS();
return _effector.deform;
}
}
}<file_sep>/MathModelling/Main.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using MM.Abstractions;
namespace MM
{
public partial class Main : Form
{
private readonly object _lockGate = new object();
private readonly Dictionary<string, BaseMethod> _methodMap;
private readonly Dictionary<string, FlowLayoutPanel> _panelMap;
private FieldInfo _currentField;
private NumericUpDown _currentFieldUI;
private BaseMethod _currentMethod;
private int _currentTimeLayer;
private Form _preview;
private bool _requireRedraw;
private SeriesChartType _seriesType = SeriesChartType.Line;
private Timer liveTimer;
private Timer redrawTimer;
private double[][] result2d;
private double[][][] result3d;
public Main()
{
InitializeComponent();
_panelMap = new Dictionary<string, FlowLayoutPanel>();
var methods = Assembly.GetExecutingAssembly().GetTypes()
.Where(x => x.BaseType == typeof(BaseMethod));
_methodMap = methods.Select(x => new
{ x.Name, Value = (BaseMethod)Activator.CreateInstance(x) })
.OrderByDescending(c => c.Value.Priority)
.ToDictionary(x => x.Name, x => x.Value);
}
private void Main_Load(object sender, EventArgs e)
{
foreach (var method in _methodMap) MapProperties(method);
var sct = new[] { SeriesChartType.Line, SeriesChartType.Spline };
comboBox3.DataSource = sct;
comboBox3.SelectedIndex = 0;
comboBox3.SelectedIndexChanged += ChartTypeChanged;
comboBox1.DataSource = _methodMap.Select(x => x.Key).ToArray();
timeLayerValues.SelectedIndexChanged +=
TimeLayerValues_SelectedIndexChanged;
redrawTimer = new Timer { Interval = 500 };
redrawTimer.Tick += (s, _) =>
{
if (!_requireRedraw) return;
DoRedraw();
_requireRedraw = false;
redrawTimer.Stop();
};
redrawTimer.Start();
liveTimer = new Timer { Interval = 100 };
liveTimer.Tick += (s, _) =>
{
if (liveCheck.Checked)
{
trackBar1.Value += 1;
if (trackBar1.Value == trackBar1.Maximum)
trackBar1.Value = trackBar1.Minimum;
}
};
liveTimer.Start();
}
private void TimeLayerValues_SelectedIndexChanged(object sender,
EventArgs e)
{
if (sender is ComboBox cb)
{
if (cb.SelectedIndex == -1) return;
_currentTimeLayer = cb.SelectedIndex;
VisualizeAs2D(_currentMethod,
result3d[result3d.Length - 1 - _currentTimeLayer]);
}
}
private void ChartTypeChanged(object sender, EventArgs e)
{
if (!(sender is ComboBox s)) return;
if (s.SelectedIndex == -1) return;
_seriesType = (SeriesChartType)s.SelectedItem;
_requireRedraw = true;
redrawTimer.Start();
}
private void MapProperties(KeyValuePair<string, BaseMethod> method)
{
var panel = new FlowLayoutPanel
{
AutoScroll = true,
AutoSize = true,
FlowDirection = FlowDirection.TopDown,
Dock = DockStyle.Fill
};
panel.VerticalScroll.Enabled = true;
Type t = method.Value.GetType();
var fds = t.GetFields().Where(x =>
x.GetCustomAttributes<ReflectedUICoefsAttribute>().Any())
.ToArray();
foreach (FieldInfo field in fds)
{
var ruic =
field.GetCustomAttribute<ReflectedUICoefsAttribute>();
var prec = ruic.P;
var c = new FlowLayoutPanel();
var lb = new Label { Text = field.Name.Trim('_') };
var upDown = new NumericUpDown();
if (field.Name.Contains("tau")) upDown.Name = "upDowntau";
//
// label2
//
lb.AutoSize = true;
lb.Location = new Point(4, 22);
lb.Size = new Size(80, 18);
lb.TextAlign = ContentAlignment.MiddleCenter;
lb.Font = new Font(label1.Font.Name, 15F);
lb.TabIndex = 0;
//
// numericUpDown1
//
if (field.FieldType != typeof(int))
{
upDown.DecimalPlaces = prec;
upDown.Increment = 1m / (decimal)Math.Pow(10, prec);
}
else
{
upDown.Increment = 1;
}
upDown.Location = new Point(46, 14);
upDown.Minimum = decimal.MinValue;
upDown.Maximum = decimal.MaxValue;
upDown.Size = new Size(100, 20);
upDown.Text = field.GetValue(method.Value).ToString();
upDown.Font = new Font(label1.Font.Name, 15F);
c.Location = new Point(3, 3);
c.Size = new Size(200, 35);
c.Controls.Add(lb);
c.Controls.Add(upDown);
panel.Controls.Add(c);
upDown.TextChanged += (s, e) =>
{
try
{
field.SetValue(method.Value,
Convert.ChangeType(upDown.Text, field.FieldType));
if (field.Name.Contains("time"))
ResetTimelayerControl(true);
_requireRedraw = true;
redrawTimer?.Start();
}
catch
{
// ignored
}
};
if (lb.Text.Equals("tau"))
_currentFieldUI = upDown;
}
trackBar1.ValueChanged += OnTrackChange;
_panelMap[method.Key] = panel;
}
private void OnTrackChange(object sender, EventArgs e)
{
if (_currentField == default) return;
FieldInfo field = _currentField;
field.SetValue(_currentMethod,
Convert.ChangeType(trackBar1.Value, field.FieldType));
_currentFieldUI.Value = trackBar1.Value;
_currentFieldUI.Refresh();
_requireRedraw = true;
redrawTimer?.Start();
}
private void SelectForChange(FieldInfo fieldInfo, BaseMethod method)
{
var val = fieldInfo.Name.Trim('_');
trackBarCurLab.Text = val;
trackBar1.Minimum = 1;
trackBar1.Maximum = 500;
trackBar1.Value =
(int)Convert.ChangeType(fieldInfo.GetValue(method),
TypeCode.Int32);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex < 0) return;
DoRedraw();
var sel = (string)comboBox1.SelectedItem;
panel3.Controls.Clear();
panel3.Controls.Add(_panelMap[sel]);
}
private void DoRedraw()
{
if (comboBox1.SelectedIndex < 0) return;
try
{
var sel = (string)comboBox1.SelectedItem;
_currentFieldUI =
_panelMap[sel].Controls.Find("upDowntau", true)
.FirstOrDefault() as NumericUpDown;
lock (_lockGate)
{
MethodAction(_methodMap[sel]);
}
}
catch
{
// ignored
}
}
private void MethodAction(BaseMethod method)
{
comboBox2.SelectedIndexChanged -= comboBox2_SelectedIndexChanged;
is3dcheck.Visible =
timeLayerBox.Visible = method.Is3D;
_currentMethod = method;
Type t = method.GetType();
var fds = t.GetFields().Where(x =>
x.GetCustomAttributes<ReflectedUICoefsAttribute>().Any())
.ToList();
_currentField = fds.FirstOrDefault(x =>
x.GetCustomAttributes<DefaultModAttribute>()
.Any()) ??
fds.FirstOrDefault(x => x.Name.Contains("tau"));
if (_currentField != default)
{
SelectForChange(_currentField, _currentMethod);
}
trackBox.Visible = _currentField != default &&
_currentField.Name.Contains("tau");
var msCalc = method.GetType().GetMethods()
.Where(x =>
x.GetCustomAttributes<ReflectedTargetAttribute>().Any())
.ToArray();
if (method.SwitchData == default && msCalc.Any())
{
var ms = msCalc
.Select(x =>
x.Name.StartsWith("Get") ? x.Name.Substring(3) : x.Name)
.ToArray();
method.SwitchData = ms;
method.SwitchItem = ms[0];
comboBox2.DataSource = method.SwitchData;
}
if (method.SwitchData != default)
{
if (comboBox2.DataSource == default)
{
_currentTimeLayer = 0;
}
comboBox2.DataSource = method.SwitchData;
comboBox2.SelectedItem = method.SwitchItem;
panel5.Visible = true;
}
else
{
panel5.Visible = false;
comboBox2.DataSource = default;
}
result2d = default;
result3d = default;
if (method.Is3D)
BindChart3D(msCalc, method);
else
BindChart2D(msCalc, method);
}
private void BindChart3D(MethodInfo[] msCalc, BaseMethod method)
{
if (msCalc.Any())
result3d = (double[][][])msCalc
.First(x => x.Name.Contains(method.SwitchItem))
.Invoke(method, Array.Empty<object>());
else
result3d = method.Calculate3D();
ResetTimelayerControl();
VisualizeAs2D(method, result3d[_currentTimeLayer]);
}
private void ResetTimelayerControl(bool force = false)
{
if (timeLayerValues.DataSource == default || force)
{
if (!_currentMethod.Is3D) return;
timeLayerValues.SelectedIndexChanged -=
TimeLayerValues_SelectedIndexChanged;
timeLayerValues.DataSource = Enumerable
.Range(1, result3d.Length)
.Select(x => "t" + _currentMethod.StepTime * x)
.ToArray();
timeLayerValues.SelectedIndexChanged +=
TimeLayerValues_SelectedIndexChanged;
}
}
private string GetTextFor3D(BaseMethod method, double[][][] doubles)
{
var sb = new StringBuilder();
var tau = method.ChartStepY ?? 1;
var i = 1;
foreach (var layer in doubles.Reverse())
{
sb.Append("------------");
sb.Append("time layer ");
sb.Append(tau * i++);
sb.AppendLine("------------");
sb.AppendLine(method.AsString(layer.Reverse().ToArray()));
sb.AppendLine();
}
return sb.ToString();
}
private void BindChart2D(MethodInfo[] msCalc, BaseMethod method)
{
if (msCalc.Any())
result2d = (double[][])msCalc
.First(x => x.Name.Contains(method.SwitchItem))
.Invoke(method, Array.Empty<object>());
else
result2d = method.Calculate();
VisualizeAs2D(method, result2d);
}
private void VisualizeAs2D(BaseMethod method, double[][] result)
{
var xv = Enumerable.Range(0, result[0].Length)
.Select(x => x * method.ChartStepX).ToArray();
var n = 0;
chart1.Series.Clear();
chart1.Series.SuspendUpdates();
foreach (var array in result)
{
var s = new Series
{
ChartType = method.SeriesType.HasValue ?
(_seriesType = method.SeriesType.Value)
: _seriesType,
BorderWidth = 3,
BackImageTransparentColor = Color.WhiteSmoke,
MarkerColor = Color.Blue
};
if (method.ChartStepY.HasValue)
if (method.Is3D)
s.Name = "h" + (result.Length - n++);
else
{
if (method.YLegend != default)
{
s.Name = method.YLegend[n++];
}
else
{
s.Name = "t" + method.ChartStepY * n++;
}
}
if (method.MaxX.HasValue)
{
if (method.SwapAxis)
s.Points.DataBindXY(array, xv);
else
s.Points.DataBindXY(xv, array);
}
else
{
if (method.SwapAxis)
s.Points.DataBindXY(array, xv);
else
s.Points.DataBindY(array);
}
chart1.Series.Add(s);
}
ChartArea ca = chart1.ChartAreas[0];
if (method.MaxX.HasValue)
{
ca.AxisX.Minimum = 0;
ca.AxisX.Maximum = method.MaxX.Value;
}
else
{
ca.AxisY.Minimum =
ca.AxisY.Maximum =
ca.AxisX.Minimum =
ca.AxisX.Maximum = double.NaN;
}
chart1.ResetAutoValues();
chart1.Series.ResumeUpdates();
richTextBox1.Text = GetInfo(_currentMethod, method.AsString(result.Reverse().ToArray())).ToString();
comboBox2.SelectedIndexChanged += comboBox2_SelectedIndexChanged;
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.SelectedIndexChanged -= comboBox2_SelectedIndexChanged;
var sel = (string)comboBox1.SelectedItem;
_methodMap[sel].SwitchItem = (string)comboBox2.SelectedItem;
DoRedraw();
comboBox2.SelectedIndexChanged += comboBox2_SelectedIndexChanged;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (sender is CheckBox cb)
chart1.ChartAreas[0].Area3DStyle.Enable3D = cb.Checked;
}
private void richTextBox1_MouseDoubleClick(object sender,
MouseEventArgs e)
{
_preview = new Form { Name = "Preview", Size = Size };
var textTable = result2d != default
? GetTextFor2D(_currentMethod, result2d)
: GetTextFor3D(_currentMethod, result3d);
var info = GetInfo(_currentMethod, textTable);
var p = new RichTextBox
{
Font = new Font(Font.Name, 15F),
Dock = DockStyle.Fill,
Text = info.ToString()
};
_preview.Controls.Add(p);
_preview.Show(this);
}
private StringBuilder GetInfo(BaseMethod currentMethod, string textTable)
{
var info = _currentMethod.Info;
if (info.Length > 0)
{
info.Insert(0, "----- info -----\n");
info.AppendLine("--- !!! info !!! ---");
}
info.AppendLine(textTable);
return info;
}
private string GetTextFor2D(BaseMethod method, double[][] result)
{
return method.AsString(result.Reverse().ToArray());
}
}
}<file_sep>/MathModelling/S5/S5M6_MoistureTransfer.cs
using MM.Abstractions;
using System;
using System.Collections.Generic;
namespace MM.S5
{
internal class S5M6_MoistureTransfer : BaseMethod
{
[ReflectedUICoefs]
public static double
a = 1,
k = 0.1,
H1 = 7,
H2 = 20,
L = 15,
tau = 360,
sigma = 0.5,
h = 1.5,
g = 9.8,
v = 2.8 * Math.Pow(10, -5),
C0 = 0,
C1 = 0,
C2 = 10,
Cx = 10,
p = 1000;
[ReflectedUICoefs(P = 6)]
public static double
gm = 0.0065,
Dm = Math.Pow(10, -6);
[ReflectedUICoefs]
public static int
times = 4;
public override int Priority => 6;
public override double ChartStepX => h;
public override double? ChartStepY => tau;
public override double? MaxX => L;
private (double[][] filt, double[][] mass, double[][] moist) CalculateCore()
{
var b = (int)(L / h); // interm points
var h_2 = Math.Pow(h, 2);
double[] massTransfer(int tl, double[] massPrev, double[] filtK)
{
Func<double, double> cx0 = x => C0;
Func<double, double> c0t = t => C1;
Func<double, double> clt = i => C2;
var mass = new double[b + 1];
if (tl == 0)
{
mass[0] = c0t(0);
mass[b] = clt(0);
for (var i = 1; i < b; i++) mass[i] = cx0(i * h);
return mass;
}
double[]
alfa = new double[b + 1],
beta = new double[b + 1];
mass[0] = c0t(tl * h);
mass[b] = clt(tl * h);
beta[0] = c0t(tl * h);
var fp = Cx * gm;
var fk = sigma / tau;
for (var i = 1; i < b; i++)
{
var rp = (-filtK[i] + Math.Abs(filtK[i])) / 2;
var rm = (-filtK[i] - Math.Abs(filtK[i])) / 2;
var r = rp + rm;
var n = 1f / (1 + h * Math.Abs(r) / 2);
var a_const = n / h_2 - rm / h;
var b_const = n / h_2 + rp / h;
var c_const = a_const + b_const + gm + sigma / tau;
alfa[i] = b_const / (c_const - alfa[i - 1] * a_const);
var f = fp + fk * massPrev[i];
beta[i] = (a_const * beta[i - 1] + f) /
(c_const - alfa[i - 1] * a_const);
}
for (var j = b - 1; j >= 0; j--)
mass[j] = alfa[j] * mass[j + 1] + beta[j];
return mass;
}
double[] moistureTransfer(int tl, double[] moistK, double[] massK)
{
Func<double, double> cx0 = x => (H2 - H1) * x / L + H1;
Func<double, double> c0t = _ => H1;
Func<double, double> clt = _ => H2;
var moist = new double[b + 1];
if (tl == 0)
{
moist[0] = c0t(0);
moist[b] = clt(0);
for (var i = 1; i < b; i++) moist[i] = cx0(i * h);
return moist;
}
double[]
alfa = new double[b + 1],
beta = new double[b + 1];
moist[0] = c0t(tl * h);
moist[b] = clt(tl * h);
beta[0] = c0t(tl * h);
for (var i = 1; i < b; i++)
{
var hk = moistK;
var hp = hk[i - 1];
var hn = hk[i + 1];
var M = a * p * g * (1 - 2 * h / (hn - hp));
var a_const = k / h_2;
var b_const = a_const;
var c_const = M / tau + 2 * k / h_2;
alfa[i] = b_const / (M - alfa[i - 1] * a_const);
var f = M * hk[i] / tau - (massK[i + 1] - 2 * massK[i] + massK[i - 1]) / h_2;
beta[i] = (a_const * beta[i - 1] + f) /
(c_const - alfa[i - 1] * a_const);
}
for (var j = b - 1; j > 0; j--)
moist[j] = alfa[j] * moist[j + 1] + beta[j];
return moist;
}
double[] filtration(double[] moist, double[] mass)
{
var filt = new double[b + 1];
for (var i = 1; i < b; i++)
{
filt[i] = -k * (moist[i + 1] - moist[i - 1]) / (2 * h) +
v * (mass[i + 1] - 2 * mass[i] + mass[i - 1]) / h_2;
}
return filt;
}
var massLocal = massTransfer(0, default, default);
var moisLocal = moistureTransfer(0, default, default);
var f1list = new List<double[]>();
var m1list = new List<double[]>();
var m2list = new List<double[]>();
m1list.Add(massLocal);
m2list.Add(moisLocal);
for (var tl = 1; tl <= times; tl++) // time layers
{
var filtK = filtration(moisLocal, massLocal);
f1list.Add(filtK);
m1list.Add(massLocal = massTransfer(tl, massLocal, filtK));
m2list.Add(moisLocal = moistureTransfer(tl, moisLocal, massLocal));
}
return (f1list.ToArray(), m1list.ToArray(), m2list.ToArray());
}
[ReflectedTarget]
public double[][] GetMoistureTransfer()
{
return CalculateCore().moist;
}
[ReflectedTarget]
public double[][] GetMassTransfer()
{
return CalculateCore().mass;
}
[ReflectedTarget]
public double[][] GetFiltration()
{
return CalculateCore().filt;
}
}
}<file_sep>/MathModelling/S4/MM3_Diff.cs
using System;
using System.Linq;
using MM.Abstractions;
namespace MM.S4
{
internal class MM3_Diff : BaseMethod
{
[ReflectedUICoefs]
public static int
b = 5,
a = 3,
m = a,
i;
[ReflectedUICoefs]
public double
n = 0.68,
teta0 = 0.02,
l = 0.5,
h = 0.1,
sigma = 1.0 / 6;
private double DiffusionCoef(int _m, double teta)
{
return Math.Pow(10, -6) * (1 - Math.Exp(-_m * teta));
}
public override double[][] Calculate()
{
var diff = DiffusionCoef(6, teta0);
var apw = diff; //lamda * 1.0 / (c * ro);
var tau = Math.Pow(h, 2) * sigma / apw;
var u = new double[a + 1]
.Select(x => new double[b + 1].ToArray()).ToArray();
u[0][0] = u[0][b] = n;
for (i = 1; i < (int) (l / h); i++)
u[0][i] = teta0; //(txb - tx0) * gx(h * i) / gx(l) + tx0;
double[]
alfa = new double[b],
beta = new double[b],
_a = new double[b],
_b = new double[b],
_c = new double[b];
for (var j = 0; j < b; j++)
{
_a[j] = _b[j] = apw * tau * 1.0 / Math.Pow(h, 2);
_c[j] = 1 + sigma * 2;
}
for (var it = 1; it <= m; it++)
{
u[it][0] = n;
u[it][b] = n;
beta[0] = n;
for (i = 1; i <= b - 1; i++)
{
alfa[i] = _b[i] * 1.0 / (_c[i] - alfa[i - 1] * _a[i]);
beta[i] = (_a[i - 1] * beta[i - 1] + u[it - 1][i]) * 1.0 /
(_c[i] - alfa[i - 1] * _a[i]);
}
for (var j = b - 1; j > 0; j--)
u[it][j] = alfa[j] * u[it][j + 1] + beta[j];
}
return u.Reverse().ToArray();
}
}
}<file_sep>/MathModelling/S5/S5M5_Consolidation.cs
using System;
using System.Linq;
using MM.Abstractions;
namespace MM.S5
{
internal class S5M5_Consolidation : BaseMethod
{
[ReflectedUICoefs(P = 6)]
public static double
a = 51.2 * Math.Pow(10, -7);
[ReflectedUICoefs]
public static double
N = 5,
k = 0.001,
D = 0.02,
H1 = 59,
H2 = 26,
L = 100,
tau = 30,
sigma = 0.2,
h = 10,
e = 0.6,
v = 2.8 * Math.Pow(10, -3),
C1 = 350,
C2 = 10 + N,
Cx = 0.15;
[ReflectedUICoefs(P = 6)]
public static double
gm = 2 * Math.Pow(10, -4),
gmS = 2 * Math.Pow(10, 4);
[ReflectedUICoefs]
public static int
times = 4;
public override int Priority => 5;
public override double ChartStepX => h;
public override double? ChartStepY => tau;
public override double? MaxX => L;
[ReflectedTarget]
public double[][] GetConsolidation()
{
var MT = GetMassTransfer();
Func<double, double> cx0 = x => (H2 - H1) * x / L + H1;
Func<double, double> c0t = _ => H1;
Func<double, double> clt = _ => H2;
var h_2 = Math.Pow(h, 2);
var a_ = k * (1 + e) / (gmS * a);
var b_ = v * (1 + e) / (gmS * a);
var a_const = a_ / h_2;
var b_const = a_const;
var c_const = 1f / tau - 2 * b_const;
var b = (int) (L / h); // interm points
double[]
alfa = new double[b + 1],
beta = new double[b + 1];
var u = new double[times + 1][].Select(x => new double[b + 1])
.ToArray();
u[0][0] = c0t(0);
u[0][b] = clt(0);
for (var i = 1; i < b; i++) u[0][i] = cx0(i * h);
for (var tl = 1; tl <= times; tl++) // time layers
{
u[tl][0] = c0t(tl);
u[tl][b] = clt(tl);
beta[0] = c0t(tl);
for (var i = 1; i < b; i++)
{
alfa[i] = b_const / (c_const - alfa[i - 1] * a_const);
var F1 = b_ *
(MT[tl][i - 1] - 2 * MT[tl][i] + MT[tl][i + 1]) / h_2;
var f2 = 1f * u[tl - 1][i] / tau + F1;
beta[i] = (a_const * beta[i - 1] + f2) /
(c_const - alfa[i - 1] * a_const);
}
for (var j = b - 1; j > 0; j--)
u[tl][j] = alfa[j] * u[tl][j + 1] + beta[j];
}
return u.ToArray();
}
[ReflectedTarget]
public double[][] GetMassTransfer()
{
var V = (H1 - H2) * k / L; // filtering speed
Func<double, double> cx0 = x =>
C1 * Math.Exp(-x * Math.Log(C1 / C2) / L);
Func<double, double> c0t = t => C1;
Func<double, double> clt = i => C2;
var h_2 = Math.Pow(h, 2);
var r = -V / D;
var M = 1f / (1 + h * V / (2 * D));
var a_const = M / h_2 - r / h;
var b_const = M / h_2;
var c_const = 2 * M / h_2 - r / h + gm / D + sigma / (D * tau);
var b = (int) (L / h); // interm points
var fp = gm * Cx / D;
var fk = sigma / (D * tau);
double[]
alfa = new double[b + 1],
beta = new double[b + 1];
var u = new double[times + 1][].Select(x => new double[b + 1])
.ToArray();
u[0][0] = c0t(0);
u[0][b] = clt(0);
for (var i = 1; i < b; i++) u[0][i] = cx0(i * h);
for (var tl = 1; tl <= times; tl++) // time layers
{
u[tl][0] = c0t(tl * h);
u[tl][b] = clt(tl * h);
beta[0] = c0t(tl * h);
for (var i = 1; i <= b; i++)
{
alfa[i] = b_const / (c_const - alfa[i - 1] * a_const);
var f = fk + fp;
beta[i] = (a_const * beta[i - 1] + f * u[tl - 1][i]) /
(c_const - alfa[i - 1] * a_const);
}
for (var j = b - 1; j > 0; j--)
u[tl][j] = alfa[j] * u[tl][j + 1] + beta[j];
}
return u.ToArray();
}
}
}<file_sep>/MathModelling/S4/MM6_ArmsRace.cs
using MM.Abstractions;
namespace MM.S4
{
internal class MM6_ArmsRace : BaseMethod
{
[ReflectedUICoefs]
public double
L1 = 2.2,
L2 = 0.8,
B1 = 0.35,
B2 = 0.8,
T = 0.5;
[ReflectedUICoefs]
public int
Y1 = 1,
Y2 = 2,
M10 = 160,
M20 = 172,
N = 5;
public override double[][] Calculate()
{
return ArmsRace(L1, L2, B1, B2, Y1, Y2, M10, M20, T, N);
}
private double[][] ArmsRace(
double l1, double l2,
double b1, double b2,
int y1, int y2,
int m10, int m20,
double t, int n)
{
var k = (int) (n / t);
double[] m1 = new double[k],
m2 = new double[k];
m1[0] = m10;
m2[0] = m20;
for (var i = 1; i < k; i++)
{
m1[i] = t * (l1 * m2[i - 1] + y1) + m1[i - 1] / (1 - t * b1);
m2[i] = t * (l2 * m2[i - 1] + y2) + m2[i - 1] / (1 - t * b2);
}
return new[] {m1, m2};
}
}
}<file_sep>/MathModelling/S6/S6M6.cs
using MathNet.Numerics.LinearAlgebra.Double;
using MM.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using Enu = System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<double>>;
using F = System.Func<double, double>;
namespace MM.S6
{
internal class S6M6 : BaseMethod
{
#region Props
public override int Priority => 12;
public override int Precision => 6;
public override double ChartStepX => h;
public override string[] YLegend => new[] { "Orig.", "Approx." };
[ReflectedUICoefs]
public static int
m = 100;
[ReflectedUICoefs]
public static double
a = 0,
b = 1,
e = 10;
private static double
h = (b - a) / m;
F y = Math.Sqrt;
F fi = r => Math.Sqrt(1 + Math.Pow(r * e, 2));
#endregion
#region selectors
Enu MatR(double[] x)
{
for (int i = 0; i < m; i++)
{
var localI = i;
IEnumerable<double> Row()
{
for (int j = 0; j < m; j++)
{
yield return Math.Sqrt(Math.Pow(x[localI] - x[j], 2));
}
}
yield return Row();
}
}
Enu MatA(Enu r)
{
return r.Select(x => x.Select(f => fi(f)));
}
IEnumerable<double> VecF(IEnumerable<double> l, Enu r)
{
var lpEnu = l.ToArray();
var rpEnu = r.Select(x => x.ToArray()).ToArray();
var range = Enumerable.Range(0, m).ToArray();
for (int i = 0; i < m; i++)
{
yield return range
.Select(v => lpEnu[v] * fi(rpEnu[i][v])).Sum();
}
}
#endregion
[ReflectedTarget]
public double[][] Solution()
{
var xs = RangeOf(m, x => a + x * h).ToArray();
var matR = MatR(xs).ToArray();
var ys = RangeOf(m, i => y(xs[i])).ToArray();
var matA = MatA(matR);
var denseA = DenseMatrix.Build.DenseOfRows(matA);
var denseY = DenseVector.Build.DenseOfEnumerable(ys);
var denseC = denseA.Solve(denseY);
var vecF = VecF(denseC, matR).ToArray();
Info.Clear();
return new[] { ys, vecF };
}
private IEnumerable<T> RangeOf<T>(int i, Func<int, T> func)
{
return Enumerable.Range(0, i).Select(func);
}
}
}<file_sep>/MathModelling/S5/S5M2_MassHeatTransferUndergr.cs
using System;
using System.Linq;
using MM.Abstractions;
using F = System.Func<double, double>;
namespace MM.S5
{
internal class S5M2_MassHeatTransferUndergr : BaseMethod
{
[ReflectedUICoefs]
public static int
k = 7,
times = 4;
[ReflectedUICoefs]
public static double
kappa = 1.5,
Cp_ = 4.2,
Cn_ = 3,
lam = 0.5,
D = 0.2,
H1 = 1.5,
H2 = 0.5,
l = 100,
tau = 30,
sigma = 0.2,
h = 20,
T1 = 20 * k,
T2 = 8 + k;
[ReflectedUICoefs(P = 3)]
public double
Dt = 0.04,
gamma = 0.065;
public override int Priority => 2;
private double GetFilteringSpeed()
{
return (H1 - H2) * kappa / l; // filtering speed
}
[ReflectedTarget]
public double[][] GetHeatTransfer()
{
var b = (int) (l / h); // interm points
double[]
alfa = new double[b + 1],
beta = new double[b + 1];
var u = new double[times + 1][].Select(x => new double[b + 1])
.ToArray();
var V = GetFilteringSpeed();
var Cp = Cp_ * Math.Pow(10, 6);
var Cn = Cn_ * Math.Pow(10, 6);
var h_2 = Math.Pow(h, 2);
var r = -V * Cp / lam;
var nt = Cn / lam;
var nt_tau = nt / tau;
F tx0 = x => (T2 - T1) * x * h / l + T1;
F t0t = t_ => T1;
F tlt = t_ => T2;
u[0][0] = t0t(0);
u[0][b] = tlt(0);
for (var i = 1; i < b; i++) u[0][i] = tx0(i);
var M = 1f / (1 + 0.5 * (h * V * Cp / lam));
var a_const = M / h_2 - r / h;
var b_const = M / h_2;
var c_const = a_const + b_const + nt_tau;
for (var tl = 1; tl <= times; tl++) // time layers
{
u[tl][0] = t0t(tl * tau);
u[tl][b] = tlt(tl * tau);
beta[0] = u[tl][0];
for (var i = 1; i <= b; i++)
{
alfa[i] = b_const / (c_const - alfa[i - 1] * a_const);
var f1 = nt_tau * u[tl - 1][i];
beta[i] = (a_const * beta[i - 1] + f1) /
(c_const - alfa[i - 1] * a_const);
}
for (var j = b - 1; j > 0; j--)
u[tl][j] = alfa[j] * u[tl][j + 1] + beta[j];
}
return u.ToArray();
}
[ReflectedTarget]
public double[][] GetMassTransfer()
{
var V = GetFilteringSpeed();
F cx0 = x => 0;
F c0t = t_ => Math.Pow(t_, 2) * Math.Exp(-0.1 * t_ * k);
F clt = t_ => Math.Pow(t_, 2) * Math.Exp(-0.2 * t_ * k);
var h_2 = Math.Pow(h, 2);
var r = -V / D;
var M = 1f / (1 + h * V / (2 * D));
var a_const = M / h_2 - r / h;
var b_const = M / h_2;
var c_const = 2 * M / h_2 - r / h + gamma / D + sigma / (D * tau);
var Cx = 0.1 * kappa;
var f2_1 = gamma * Cx / D;
var fk = sigma / (D * tau);
var b = (int) (l / h); // interm points
double[]
alfa = new double[b + 1],
beta = new double[b + 1];
var u = new double[times + 1][].Select(x => new double[b + 1])
.ToArray();
for (var i = 1; i <= b; i++) u[0][i] = cx0(i);
var hC = GetHeatTransfer();
for (var tl = 1; tl <= times; tl++) // time layers
{
u[tl][0] = c0t(tl * tau);
u[tl][b] = clt(tl * tau);
beta[0] = c0t(tl * tau);
for (var i = 1; i < b; i++)
{
alfa[i] = b_const / (c_const - alfa[i - 1] * a_const);
var F1 = Dt *
(hC[tl][i - 1] - 2 * hC[tl][i] + hC[tl][i + 1]) /
(D * h_2);
var f2 = f2_1 + F1 + fk * u[tl - 1][i];
beta[i] = (a_const * beta[i - 1] + f2) /
(c_const - alfa[i - 1] * a_const);
}
for (var j = b - 1; j > 0; j--)
u[tl][j] = alfa[j] * u[tl][j + 1] + beta[j];
}
return u.ToArray();
}
#region Helpers
public override double? ChartStepY => tau;
public override double ChartStepX => h;
public override double? MaxX => l;
#endregion
}
}
|
7f92a2389b7620ff68a3279e8064718e2de78aa9
|
[
"C#"
] | 20 |
C#
|
MaxRev-Dev/math-modelling
|
3e0c50a5196c64fd80db7e95455d28f8e36c9984
|
daa8091c917723b9be14604593e26c2bf87acf6b
|
refs/heads/master
|
<file_sep>include Java
Camping.goes :Campdepict
module Campdepict::Controllers
class Index < R '/'
def get
if input.smiles then
@smiles = input.smiles
else
@smiles = ''
end
@escapedSmiles = CGI::escape(@smiles)
render :smiles_picture
end
end
class Image_for < R '/image_for'
def get
render_smiles(input.smiles)
end
end
end
module Campdepict::Views
def layout
html do
head do
title { "SMILES Depictor" }
end
body { self << yield }
end
end
def smiles_picture
h1 "Depict a SMILES String"
img :src=> "/image_for/?smiles=#{@escapedSmiles}"
br
form :action => R(Index), :method => 'get' do
label 'Smiles', :for => 'smiles'
input :name => 'smiles', :value => @smiles, :size => "50", :type => 'text'
end
br
end
end
module Campdepict::Helpers
EDGE_SIZE = 200 # image size
MIME_TYPES = {'.css' => 'text/css', '.js' => 'text/javascript',
'.jpg' => 'image/jpeg', '.png' => 'image/png'}
PATH = Dir.pwd
def render_smiles(smiles)
if ! smiles || (smiles.eql? '') then
return static_get('blank.png')
end
# cdk-20060714 dependent code
begin
smiles_parser = org.openscience.cdk.smiles.SmilesParser.new
sdg = org.openscience.cdk.layout.StructureDiagramGenerator.new
sdg.setMolecule( smiles_parser.parseSmiles( smiles ) )
sdg.generateCoordinates
image = Java::net.sf.structure.cdk.util.ImageKit.createRenderedImage(sdg.getMolecule(), EDGE_SIZE, EDGE_SIZE )
rescue
return static_get('invalid.png')
end
out = java.io.ByteArrayOutputStream.new
javax.imageio.ImageIO.write image, "png", out
String.from_java_bytes out.toByteArray
end
# static_get is straight outa the Camping wiki
def static_get(path)
@headers['Content-Type'] = MIME_TYPES[path[/\.\w+$/, 0]] || "text/plain"
unless path.include? ".." # prevent directory traversal attacks
@headers['X-Sendfile'] = "#{PATH}/static/#{path}"
else
@status = "403"
"403 - Invalid path"
end
end
end
<file_sep>#! /bin/sh -v
export CAMPING_HOME=`pwd`
export CLASSPATH=$CAMPING_HOME/lib/cdk-20060714.jar:$CAMPING_HOME/lib/structure-cdk-0.1.2.jar:$CLASSPATH
jruby $JRUBY_HOME/bin/camping campdepict.rb
# jruby -J-server -J-Djruby.thread.pooling=true $JRUBY_HOME/bin/camping campdepict.rb
<file_sep>#! /bin/bash -v
jruby -J-server $JRUBY_HOME/bin/camping nuts.rb
<file_sep>#
Camping.goes :Nuts
module Nuts::Controllers
class Index < R '/'
def get
@t = Time.now.to_s
render :sundial
end
end
end
module Nuts::Views
def layout
html do
head do
title { "Nuts And GORP" }
end
body { self << yield }
end
end
def sundial
p "The current time is: #{@t}"
end
end
|
00c725b9656b5a8e58072ce1bdfb9cdf2aaa4432
|
[
"Ruby",
"Shell"
] | 4 |
Ruby
|
jj4395722/camping
|
ac61588b78b4eae79353506d0dd31cc727f5bafb
|
1f7709e92fd1c8e49e8059a17806515cb611694a
|
refs/heads/master
|
<repo_name>madetech/frontend<file_sep>/src/components/Pagination/index.test.js
import React from 'react'
import Pagination from '.'
import { mount } from 'enzyme'
it('renders single page link if only one page', () => {
const pagination = mount(
<Pagination currentPage={1} hrefPrefix='/blog' totalPages={1} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(3)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('1')
})
it('renders disables prev and next if only one page', () => {
const pagination = mount(
<Pagination currentPage={1} hrefPrefix='/blog' totalPages={1} />
)
const items = pagination.find('PaginationItem')
expect(items.first().prop('disabled')).toBe(true)
expect(items.last().prop('disabled')).toBe(true)
})
it('renders 1-5 if many pages and on page 1', () => {
const pagination = mount(
<Pagination currentPage={1} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('1')
expect(links.at(2).text()).toMatch('2')
expect(links.at(3).text()).toMatch('3')
expect(links.at(4).text()).toMatch('4')
expect(links.at(5).text()).toMatch('5')
})
it('renders 1-5 if many pages and on page 2', () => {
const pagination = mount(
<Pagination currentPage={2} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('1')
expect(links.at(2).text()).toMatch('2')
expect(links.at(3).text()).toMatch('3')
expect(links.at(4).text()).toMatch('4')
expect(links.at(5).text()).toMatch('5')
})
it('renders 1-5 if many pages and on page 3', () => {
const pagination = mount(
<Pagination currentPage={3} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('1')
expect(links.at(2).text()).toMatch('2')
expect(links.at(3).text()).toMatch('3')
expect(links.at(4).text()).toMatch('4')
expect(links.at(5).text()).toMatch('5')
})
it('renders 2-6 if many pages and on page 4', () => {
const pagination = mount(
<Pagination currentPage={4} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('2')
expect(links.at(2).text()).toMatch('3')
expect(links.at(3).text()).toMatch('4')
expect(links.at(4).text()).toMatch('5')
expect(links.at(5).text()).toMatch('6')
})
it('renders 3-7 if many pages and on page 5', () => {
const pagination = mount(
<Pagination currentPage={5} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('3')
expect(links.at(2).text()).toMatch('4')
expect(links.at(3).text()).toMatch('5')
expect(links.at(4).text()).toMatch('6')
expect(links.at(5).text()).toMatch('7')
})
it('renders 16-20 if 20 pages and on page 17', () => {
const pagination = mount(
<Pagination currentPage={17} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('15')
expect(links.at(2).text()).toMatch('16')
expect(links.at(3).text()).toMatch('17')
expect(links.at(4).text()).toMatch('18')
expect(links.at(5).text()).toMatch('19')
})
it('renders 16-20 if 20 pages and on page 18', () => {
const pagination = mount(
<Pagination currentPage={18} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('16')
expect(links.at(2).text()).toMatch('17')
expect(links.at(3).text()).toMatch('18')
expect(links.at(4).text()).toMatch('19')
expect(links.at(5).text()).toMatch('20')
})
it('renders 16-20 if 20 pages and on page 19', () => {
const pagination = mount(
<Pagination currentPage={19} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('16')
expect(links.at(2).text()).toMatch('17')
expect(links.at(3).text()).toMatch('18')
expect(links.at(4).text()).toMatch('19')
expect(links.at(5).text()).toMatch('20')
})
it('renders 16-20 if 20 pages and on page 20', () => {
const pagination = mount(
<Pagination currentPage={20} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.length).toEqual(7)
expect(links.first().text()).toMatch('Prev')
expect(links.last().text()).toMatch('Next')
expect(links.at(1).text()).toMatch('16')
expect(links.at(2).text()).toMatch('17')
expect(links.at(3).text()).toMatch('18')
expect(links.at(4).text()).toMatch('19')
expect(links.at(5).text()).toMatch('20')
})
it('creates correct page urls with /blog prefix', () => {
const pagination = mount(
<Pagination currentPage={1} hrefPrefix='/blog' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.first().prop('href')).toEqual('/blog')
expect(links.last().prop('href')).toEqual('/blog/2')
expect(links.at(1).prop('href')).toEqual('/blog')
expect(links.at(2).prop('href')).toEqual('/blog/2')
expect(links.at(3).prop('href')).toEqual('/blog/3')
expect(links.at(4).prop('href')).toEqual('/blog/4')
expect(links.at(5).prop('href')).toEqual('/blog/5')
})
it('creates correct page urls with / prefix', () => {
const pagination = mount(
<Pagination currentPage={1} hrefPrefix='/' totalPages={20} />
)
const links = pagination.find('.page-link')
expect(links.first().prop('href')).toEqual('/')
expect(links.last().prop('href')).toEqual('/2')
expect(links.at(1).prop('href')).toEqual('/')
expect(links.at(2).prop('href')).toEqual('/2')
expect(links.at(3).prop('href')).toEqual('/3')
expect(links.at(4).prop('href')).toEqual('/4')
expect(links.at(5).prop('href')).toEqual('/5')
})
<file_sep>/docs/getting-started.md
---
layout: docs
---
# Getting Started
<p class="lead">
Made Tech Frontend is a collection of components and resources for creating Made Tech branded sites and applications.
</p>
We created this library to make it easier for teams to create their own sites, whether that be for careers, events or learning materials. It has been created to handle a number of use cases including GitHub Pages powered sites and React powered web apps.
## Quick start
The quickest way to get going with Made Tech Frontend is with the compiled assets including CSS, fonts, images and JavaScript. All you need to do is download the [latest release](https://github.com/madetech/frontend/releases) and then start using the assets.
Presuming you are starting from scratch:
1. Download latest `madetech-frontend.zip` from [Made Tech Frontend releases](https://github.com/madetech/frontend/releases)
2. Create a new directory for your project
3. Create an `index.html` file in that directory and copy the contents of [this example](https://github.com/madetech/frontend/blob/master/examples/static/index.html) into it
4. Now create an `assets/` directory and put the contents of `dist/` in it
Now view the `index.html` in your browser. Cool huh?
## Using with GitHub Pages
If you are creating a documentation site using GitHub Pages, we again recommend using a similar route to the above.
We recommend the following steps are take with a themeless install of Jekyll:
1. Download latest copy of [Made Tech Frontend](https://github.com/madetech/frontend/releases)
2. Create or replace `_layouts/default.html` with [this example](https://github.com/madetech/frontend/blob/master/docs/_layouts/default.html)
3. Now create an `assets/` directory and put the contents of `dist/` in it
If you have installed `github-pages` gem locally you can now run `bundle exec jekyll s` and you will see a Made Tech theme.
Made Tech Frontend's documentation site is built with GitHub Pages so take a look at the [`docs/`](https://github.com/madetech/frontend/tree/master/docs) directory for another example.
## Using as component library
If you are building a React based application or site then you can take advantage of the React components provided by this kit.
In order to use as a component library you first need to add `@madetech/frontend` NPM module to your application:
```
npm i @madetech/frontend
```
Once it's installed you can get to work:
```jsx
import { Header } from '@madetech/frontend'
export default function Layout ({ children }) {
return (
<div>
<Header
logoHref='/'
logoText='Learn Tech'
>
<a href='/' className='nav-link'>
Getting Started
</a>
<a href='/help' className='nav-link'>
Ask for Help
</a>
</Header>
{children}
</div>
)
}
```
To find out what components are available, take a look at the [style guide](styleguide/). You can use the style guide to play with components and find out how to use them.
**Importing styles**
- Import `@madetech/frontend/all.scss` if your build process supports compiling Sass
- Import `@madetech/frontend/dist/madetech-frontend.css` if your build process supports CSS
- Link to the static asset with <link> by copying `@madetech/frontend/dist/madetech-frontend.css` into your `public/` dir
## Using with Create React App
If you are building an app with [`create-react-app`](https://facebook.github.io/create-react-app/), it's easy to get started.
In order to use as a component library you first need to add `@madetech/frontend` NPM module to your application:
```
npm i @madetech/frontend
```
Now you can use components in your `App.js` for example:
```jsx
import React from 'react'
import { Header } from '@madetech/frontend'
import '@madetech/frontend/all.scss'
export default function App () {
return (
<Header />
)
}
```
**Importing styles**
You have a number of options for importing styles with Create React App:
- Import `@madetech/frontend/all.scss` (as seen above) as Create React App supports compiling Sass
- Import `@madetech/frontend/dist/madetech-frontend.css` as Create React App supports compiling CSS
- Link to the static asset with <link> by copying `@madetech/frontend/dist/madetech-frontend.css` into your `public/` dir
If you need a further example for using `create-react-app`, [check this out](https://github.com/madetech/frontend/tree/master/examples/create-react-app).
## Next steps
We recommend you read about [how this library works](how-does-it-work) under the hood.
<file_sep>/src/components/FooterDynamic/index.js
import React from 'react'
export default function FooterDynamic() {
const currentYear = new Date().getFullYear();
return (
<footer className='footer'>
<div className='container'>
<div className='row'>
<div className='col-12 text-center col-sm-6 text-sm-left d-sm-block footer__copyright_notice'>
© <span itemProp='copyrightHolder' itemScope itemType='http://schema.org/Organization'><span itemProp='name'>Made Tech</span></span> <span itemProp='copyrightYear' data-test='copyrightYear'>{currentYear}</span>
<span> | </span>
<a href="https://www.madetech.com/privacy">Privacy Policy</a>
</div>
<nav className='col-12 text-center col-sm-6 text-sm-right footer__social_wrapper'>
{children}
</nav>
</div>
</div>
</footer>
)
}
<file_sep>/src/components/Header/LogoType.js
import React from 'react'
import Logo from './Logo'
function LogoTypeImitation ({ textWithoutSpaces }) {
return (
<div className='header_logo_type'>
<div className='position-relative mr-3' style={{ top: '-3px' }}>
<Logo width='162px' />
</div>
<span className='header_logo_type__text'>{textWithoutSpaces}</span>
</div>
)
}
function LogoTypeBy ({ textWithoutSpaces }) {
return (
<div className='header_logo_type--by'>
<span className='header_logo_type__text'>{textWithoutSpaces}</span>
<span className='px-3'>by</span>
<span className='position-relative' style={{ top: '-2px' }}>
<Logo width='120px' />
</span>
</div>
)
}
export default function LogoType ({ by, text }) {
const textWithoutSpaces = text.replace(' ', '\u200A')
if (by === false) {
return <LogoTypeImitation textWithoutSpaces={textWithoutSpaces} />
} else {
return <LogoTypeBy textWithoutSpaces={textWithoutSpaces} />
}
}
<file_sep>/README.md
# Made Tech Frontend
A collection of components and resources for creating Made Tech branded sites and applications.
## Quick start
You can get started by:
- [Downloading madetech-frontend.zip](https://github.com/madetech/frontend/releases) from our latest release
- Installing via NPM: `npm i --save @madetech/frontend`
Read our [Getting Started](https://madetech.github.com/frontend/getting-started) guide.
## Status
[](https://www.npmjs.com/package/@madetech/frontend)
## What's included?
- A Sass library that extends the Bootstrap front-end framework, start with [`src/all.scss`](https://github.com/madetech/frontend/blob/master/src/all.scss)
- A React component library that builds on Reactstrap, take a look at [`src/components/`](https://github.com/madetech/frontend/tree/master/src/components) and [the style guide](https://madetech.github.io/frontend/styleguide/)
- Made Tech branding kit (images and fonts) from [`@madetech/marketing-assets`](https://github.com/madetech/marketing-assets)
- Compiled and minified assets for static sites, download from [madetech-frontend.zip](https://github.com/madetech/frontend/releases)
**Compiled and minified assets**
We provide the following assets for ease of use. If you're using GitHub Pages, the easiest way to get started is copying the compiled assets into your project. If you'd prefer a "cleaner" way, investigate using the component library instead.
The CSS and JavaScript includes Bootstrap so there is no need to pull that in separately, though you will need to include jQuery.
```
madetech-frontend.zip
└── dist/
├── css/
│ ├── madetech-frontend.css
│ ├── madetech-frontend.css.map
│ ├── madetech-frontend.min.css
│ └── madetech-frontend.min.css.map
├── fonts/
│ ├── montserrat-bold.{eot,ttf,woff}
│ ├── montserrat-reg.{eot,ttf,woff}
│ └── poppins.{eot,ttf,woff}
├── images/
│ ├── favicon.ico
│ ├── made-tech-logo-blk.png
│ ├── made-tech-logo-colour.png
│ └── made-tech-logo-wht.png
└── js/
├── madetech-frontend.js
├── madetech-frontend.js.map
├── madetech-frontend.min.js
└── madetech-frontend.min.js.map
```
You can download [madetech-frontend.zip](https://github.com/madetech/frontend/releases) from our latest release.
## Documentation
- [Get started](https://madetech.github.com/frontend/getting-started)
- [View available components in our Styleguide](https://madetech.github.com/frontend/styleguide/)
## Updating npm
Upon making changes to this repository, a new version will need to be published to npm.
Initially you will need to run `npm login` with credentials that have access to the @madetech packages.
Following this, you will need to use a Github API Key to run the following command: `env GITHUB_TOKEN=xxxx npm run release -- minor`
(Follow these instructions if you need to generate a token from Github: [Generating a personal access token](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line))
## License
Copyright © Made Tech 2020.
<file_sep>/src/components/Prose/Prose.md
```jsx
<Prose>
<h1>heading 1</h1>
<h2>heading 1</h2>
<h3>heading 1</h3>
<h4>heading 1</h4>
<p>
Some text with <a href='#'>a link</a>.
</p>
<blockquote>
<p>A quote from someone</p>
</blockquote>
</Prose>
```
<file_sep>/src/components/TopBar/TopBar.md
Example:
```jsx
<TopBar />
```
Example with custom links:
```jsx
<TopBar>
<a href='/blog'>Blog</a>
<a href='/learn'>Learn</a>
<a href='/careers'>Careers</a>
</TopBar>
```
<file_sep>/docs/README.md
<div class="row mt-lg-3">
<div class="col-md-6 text-center text-lg-left">
<h1 class="mt-2">
A frontend kit for Made Tech.
</h1>
<p class="lead">A collection of assets and components for building Made Tech branded applications and sites.</p>
<p class="lead mt-4">
<a href="/getting-started" class="btn btn-success">Get Started</a>
<a href="https://github.com/madetech/frontend/releases" class="btn btn-outline-success ml-3">Download</a>
</p>
</div>
<div class="col-md-6">
<img src="https://www.dropbox.com/s/0a0lt8tp3izwvu7/Screenshot%202018-11-17%2018.41.19.png?raw=1" class="img-fluid" />
</div>
</div>
<div class="row mt-5">
<div class="col-md-8 offset-md-2">
<div class="text-center">
<h2 class="h1">Consistency everywhere.</h2>
<p class="lead">Okay, let's be honest we've got a little more work to do. <br />Perhaps it's more "eventual consistency"?</p>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-5 offset-md-1">
<img src="https://www.dropbox.com/s/jfuvtwdljgofd22/Screenshot%202018-11-17%2018.45.00.png?raw=1" class="img-fluid" />
</div>
<div class="col-md-5">
<img src="https://www.dropbox.com/s/2h7zw9o1t2nfc1d/Screenshot%202018-11-17%2018.45.15.png?raw=1" class="img-fluid" />
</div>
</div>
<file_sep>/src/components/Header/index.js
import React from 'react'
import { Navbar } from 'reactstrap'
import Logo from './Logo'
import LogoType from './LogoType'
import Nav from './Nav'
function HeaderLogo ({ logoBy, logoHref, logoText }) {
const logo = logoText ? <LogoType by={logoBy} text={logoText} /> : <Logo />
if (logoHref) {
return (
<div className='header__logo'>
<a href={logoHref} className='header__logo_link'>{logo}</a>
</div>
)
} else {
return (
<div className='header__logo'>
{logo}
</div>
)
}
}
export default function Header ({ constrainLinkWidth, children, logoBy, logoHref, logoText, scrollable }) {
return (
<header className='header'>
<div className='header__inner'>
<Navbar expand className='p-0 flex-row flex-sm-column flex-lg-row'>
<div className='mr-lg-auto'>
<HeaderLogo
logoBy={logoBy}
logoHref={logoHref}
logoText={logoText}
/>
</div>
<Nav constrainLinkWidth={constrainLinkWidth} scrollable={scrollable}>
{children}
</Nav>
</Navbar>
</div>
</header>
)
}
<file_sep>/src/components/index.js
import Footer from './Footer'
import FooterDynamic from './FooterDynamic'
import Header from './Header'
import Jumbotron from './Jumbotron'
import Logo from './Header/Logo'
import Pagination from './Pagination'
import Prose from './Prose'
import Hero from './Hero'
import SiteMap from './SiteMap'
import TopBar from './TopBar'
export { Footer, Header, Jumbotron, Logo, Pagination, Prose, Hero, SiteMap, TopBar, FooterDynamic }
<file_sep>/src/components/Jumbotron/Jumbotron.md
```jsx
<Jumbotron>
<div className='container'>
<div className='row'>
<div className='col-lg-10 offset-lg-1'>
<h1>Made Tech Blog</h1>
<p>Writings on building software delivery capabilities, delivering digital & technology, and running live services for ambitious organisations.</p>
</div>
</div>
</div>
</Jumbotron>
```
You can add extra class names to the Jumbotron like so:
```jsx
<Jumbotron extraClassName='py-5 text-center'>
<div className='container'>
<div className='row'>
<div className='col-lg-8 offset-lg-2'>
<h3>Made Tech Blog</h3>
<p>Writings on building software delivery capabilities, delivering digital & technology, and running live services for ambitious organisations.</p>
<p>
<button className='btn btn-outline-light'>
Find out more
</button>
</p>
</div>
</div>
</div>
</Jumbotron>
```
With background image:
```jsx
<Jumbotron backgroundUrl='https://www.madetech.com/assets/sectors/government/master_header_westminster-456ab9fe224157f2e946461ffd8af43e.jpg'>
<div className='container'>
<div className='row'>
<div className='col-lg-10 offset-lg-1 px-4 py-5'>
<h3>Made Tech Blog</h3>
<p>Writings on building software delivery capabilities, delivering digital & technology, and running live services for ambitious organisations.</p>
</div>
</div>
</div>
</Jumbotron>
<Jumbotron backgroundUrl='https://www.madetech.com/assets/sectors/government/quote_background-b324bf74b5381fe447654e9e8c457eaa.jpg'>
<div className='container'>
<div className='row'>
<div className='col-lg-8 offset-lg-2 py-5'>
<blockquote><p>Made Tech's commitment to partnering with and strengthening their clients is exactly what many organisations need.</p></blockquote>
<p><NAME>, Deputy CTO, UK Central Government</p>
</div>
</div>
</div>
</Jumbotron>
```
<file_sep>/src/components/SiteMap/index.js
import React from 'react'
import logoSrc from '@madetech/marketing-assets/logos/made-tech-logo-colour-white.png'
import crownSrc from '@madetech/marketing-assets/logos/certifications/logo-crown-commercial-service.png'
import cyberSrc from '@madetech/marketing-assets/logos/certifications/logo-cyber-essentials-plus-white.png'
import iso9001Src from '@madetech/marketing-assets/logos/certifications/iso-badge-9001.png'
import iso27001Src from '@madetech/marketing-assets/logos/certifications/iso-badge-27001.png'
export default function SiteMap({ children }) {
return (
<div className='site_map'>
<div className='container'>
<div className='row map_header'>
<div className="col-lg-2 col-sm-2 col-12">
<img src={logoSrc} height='19' alt='Made Tech' />
</div>
<div className="col-lg-7 offset-lg-3 col-sm-6 offset-sm-4 col-12 tagline">
Made Tech provide Digital, Data and Technology services to the UK public sector
</div>
</div>
<div className='row nav_links'>
{children}
</div>
<div className='row'>
<div className="col-12 text-center text-sm-left logos">
<img src={crownSrc} height='100' alt='Crown Commercial Service' />
<img src={cyberSrc} height='100' alt='Cyber Essentials Plus' />
<img src={iso9001Src} height='100' alt='ISO 9001' />
<img src={iso27001Src} height='100' alt='ISO 27001' />
</div>
</div>
</div>
</div>
)
}
<file_sep>/src/components/Pagination/Pagination.md
Example:
```jsx
<Pagination
currentPage={1}
hrefPrefix='/blog'
totalPages={1}
/>
<Pagination
currentPage={1}
hrefPrefix='/blog'
totalPages={2}
/>
<Pagination
currentPage={3}
hrefPrefix='/blog'
totalPages={10}
/>
<Pagination
currentPage={10}
hrefPrefix='/blog'
totalPages={10}
/>
```
<file_sep>/src/index.test.js
import { Footer, Header, Jumbotron, Pagination, Prose, TopBar } from './index'
it('exports components', () => {
expect(Footer).toBeTruthy()
expect(Header).toBeTruthy()
expect(Jumbotron).toBeTruthy()
expect(Pagination).toBeTruthy()
expect(Prose).toBeTruthy()
expect(TopBar).toBeTruthy()
})
<file_sep>/src/components/Header/Header.md
Example with Made Tech logo and constrainWidth:
```jsx
<Header logoHref='/' constrainLinkWidth>
<a href='/agile-transformation' className='nav-link'>
Agile Team Transformation
</a>
<a href='/software-development' className='nav-link'>
Software Development
</a>
<a href='/continuous-delivery' className='nav-link'>
Continuous Delivery
</a>
<a href='/devops' className='nav-link'>
DevOps & <br className='d-none d-lg-block' />Live Services
</a>
</Header>
```
Example with Made Tech logo, constrainWidth and scrollable:
```jsx
<Header logoHref='/' constrainLinkWidth scrollable>
<a href='/agile-transformation' className='nav-link'>
Agile Team Transformation
</a>
<a href='/software-development' className='nav-link'>
Software Development
</a>
<a href='/continuous-delivery' className='nav-link'>
Continuous Delivery
</a>
<a href='/devops' className='nav-link'>
DevOps
</a>
<a href='/live-services' className='nav-link'>
Reliability Engineering
</a>
</Header>
```
Example with custom logo:
```jsx
<Header logoHref='/' logoText='Learn Tech'>
<a href='/' className='nav-link'>
Getting Started
</a>
<a href='/help' className='nav-link'>
Ask for Help
</a>
</Header>
<Header logoBy={false} logoHref='/' logoText='Blog'>
<a href='/' className='nav-link'>
Getting Started
</a>
<a href='/help' className='nav-link'>
Ask for Help
</a>
</Header>
```
<file_sep>/examples/create-react-app/src/App.js
import React from 'react'
import { Footer, Header, Jumbotron, SiteMap, TopBar } from '@madetech/frontend'
import '@madetech/frontend/all.scss'
export default function App () {
return (
<>
<TopBar />
<Header>
<a href="/agile-transformation" className="nav-link">
Agile Team<br />Transformation
</a>
<a href="/software-development" className="nav-link">
Software<br />Development
</a>
<a href="/continuous-delivery" className="nav-link">
Continuous<br />Delivery
</a>
<a href="/devops" className="nav-link">
DevOps
</a>
<a href="/support-and-maintainance" className="nav-link">
Reliability<br />Engineering
</a>
</Header>
<Jumbotron>
<div className="container">
<div className="row">
<div className="col-lg-10 offset-lg-1 text-center my-5">
<h1>Hello world!</h1>
</div>
</div>
</div>
</Jumbotron>
<SiteMap />
<Footer />
</>
)
}
<file_sep>/Makefile
all: clean dist dist/madetech-frontend.zip lib
clean:
rm -rf lib/
rm -rf dist/
dist:
mkdir -p dist/{css,fonts,js,images}
mkdir -p dist/images/icons
cp node_modules/@madetech/marketing-assets/fonts/*.{eot,ttf,woff} dist/fonts
cp node_modules/@madetech/marketing-assets/logos/*.png dist/images
cp node_modules/@madetech/marketing-assets/logos/certifications/*.png dist/images
cp node_modules/@madetech/marketing-assets/icons/* dist/images/icons
npm run sass:build
touch dist/js/madetech-frontend.js
cat node_modules/bootstrap/js/dist/util.js >> dist/js/madetech-frontend.js
cat node_modules/bootstrap/js/dist/collapse.js >> dist/js/madetech-frontend.js
cp -r src/images/ dist/images/
dist/madetech-frontend.zip:
zip -r dist/madetech-frontend.zip dist/
lib:
npm run lib:build
clean-docs:
rm -rf docs/assets
rm -rf docs/styleguide
docs: docs/assets docs/styleguide
docs/assets:
cp -r dist/ docs/assets/
cp src/styleguide/highlighting.css docs/assets/css/
docs/styleguide:
GH_PAGES=true npm run docs:styleguide
<file_sep>/src/components/Footer/footer.test.js
import React from 'react';
import { shallow } from 'enzyme';
import Footer from './index';
describe('<Footer>', () => {
it('displays the correct copyright year', () => {
const wrapper = shallow(<Footer />);
const currentYear = new Date().getFullYear();
expect(wrapper.find({"data-test": "copyrightYear"}).length).toEqual(1);
expect(wrapper.find({"data-test": "copyrightYear"}).text()).toEqual(currentYear.toString());
})
})
<file_sep>/src/components/Header/Logo.js
import React from 'react'
import logoSrc from '@madetech/marketing-assets/logos/made-tech-logo-colour.png'
export default function Logo ({ width }) {
return (
<img
alt='Made Tech'
itemProp='logo'
src={logoSrc}
width={width || '200px'}
/>
)
}
<file_sep>/src/components/Pagination/index.js
import React from 'react'
import * as Reactstrap from 'reactstrap'
function buildHref(hrefPrefix, page) {
if (page === 0 || page === 1) return hrefPrefix
if (hrefPrefix[hrefPrefix.length - 1] !== '/') {
hrefPrefix += '/'
}
return `${hrefPrefix}${page}`
}
function PreviousPage ({ currentPage, hrefPrefix }) {
return (
<Reactstrap.PaginationItem disabled={currentPage <= 1}>
<Reactstrap.PaginationLink previous href={buildHref(hrefPrefix, currentPage - 1)}>
« Prev
</Reactstrap.PaginationLink>
</Reactstrap.PaginationItem>
)
}
function NextPage ({ currentPage, hrefPrefix, totalPages }) {
return (
<Reactstrap.PaginationItem disabled={currentPage >= totalPages}>
<Reactstrap.PaginationLink next href={buildHref(hrefPrefix, currentPage + 1)}>
Next »
</Reactstrap.PaginationLink>
</Reactstrap.PaginationItem>
)
}
function PageNumbers ({ currentPage, hrefPrefix, totalPages }) {
let pages
switch (currentPage) {
case 1:
case 2:
pages = [1, 2, 3, 4, 5].slice(0, totalPages)
break;
case totalPages:
pages = [currentPage - 4, currentPage -3, currentPage -2, currentPage - 1, currentPage]
break;
case totalPages - 1:
pages = [currentPage -3, currentPage -2, currentPage - 1, currentPage, currentPage + 1]
break;
default:
pages = [currentPage -2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2]
}
return pages.filter(page => page > 0 && page <= totalPages).map((page, i) => {
return (
<Reactstrap.PaginationItem active={currentPage === page} key={i}>
<Reactstrap.PaginationLink href={buildHref(hrefPrefix, page)}>
{page}
</Reactstrap.PaginationLink>
</Reactstrap.PaginationItem>
)
})
}
export default function Pagination ({ currentPage, hrefPrefix, totalPages }) {
return (
<Reactstrap.Pagination size='md' listClassName='justify-content-center'>
<PreviousPage currentPage={currentPage} hrefPrefix={hrefPrefix} />
<PageNumbers currentPage={currentPage} hrefPrefix={hrefPrefix} totalPages={totalPages} />
<NextPage currentPage={currentPage} hrefPrefix={hrefPrefix} totalPages={totalPages} />
</Reactstrap.Pagination>
)
}
<file_sep>/docs/how-does-it-work.md
---
layout: docs
---
# How does it work?
<file_sep>/src/components/Jumbotron/index.js
import React from 'react'
export default function Jumbotron ({ backgroundUrl, extraClassName, children }) {
const props = {
className: 'jumbotron jumbotron-fluid'
}
if (extraClassName) props.className += ` ${extraClassName}`
if (backgroundUrl) props.style = { backgroundImage: `url(${backgroundUrl})` }
return (
<div {...props}>
{children}
</div>
)
}
<file_sep>/src/components/TopBar/index.js
import React from 'react'
function DefaultLinks () {
return (
<>
<span className='top_bar__item'>
<a href='/blog'>Blog</a>
</span>
<span className='top_bar__item'>
<a href='/careers'>Careers</a>
</span>
<span className='top_bar__item'>
<a href='/contact'>Contact Us</a>
</span>
</>
)
}
function wrapItem (link) {
return (
<span className='top_bar__item'>
{link}
</span>
)
}
export default function TopBar ({ children }) {
return (
<div className='top_bar'>
<div className='top_bar__inner'>
<div className='container'>
<div className='row d-md-flex justify-content-center justify-content-md-between'>
<div className='d-none d-md-block'>
Improving software delivery in public sector organisations
</div>
<nav>
{children ? React.Children.map(children, wrapItem) : <DefaultLinks />}
</nav>
</div>
</div>
</div>
</div>
)
}
<file_sep>/src/components/SiteMap/SiteMap.md
```jsx
<SiteMap />
```
<file_sep>/src/styleguide/StyleGuideRenderer.js
import React from 'react'
import Footer from '../components/Footer'
import Header from '../components/Header'
import TopBar from '../components/TopBar'
import Ribbon from 'rsg-components/Ribbon';
export function StyleGuideRenderer({
title,
homepageUrl,
children,
toc
}) {
return (
<div>
<TopBar>
<a href='https://www.madetech.com'>Who are Made Tech?</a>
<a href='https://www.madetech.com/blog'>Blog</a>
<a href='https://learn.madetech.com'>Learn</a>
<a href='https://www.madetech.com/careers'>Careers</a>
</TopBar>
<Header logoHref='..' logoText='Frontend'>
<a href='..' className='nav-link mx-1'>
Home
</a>
<a href='../getting-started' className='nav-link mx-1'>
Documentation
</a>
<a href='.' className='nav-link mx-1'>
Styleguide
</a>
<a href='https://github.com/madetech/frontend' className='nav-link mx-1'>
GitHub
</a>
</Header>
<main className="container">
<div className="row">
<div className="col-lg-2 border-right">
{toc}
</div>
<div className="col-md-10">
{children}
</div>
</div>
</main>
<Footer />
<Ribbon />
</div>
);
}
export default StyleGuideRenderer;
|
55cea62b554d6a3e100b9a1b0ae347e81d40897f
|
[
"JavaScript",
"Makefile",
"Markdown"
] | 25 |
JavaScript
|
madetech/frontend
|
602ee4c66a9040b0f282b4b9a0ede9e5e7624e56
|
1e2cec8e205a775f9ef26ebf56b437a97fcbfa4c
|
refs/heads/master
|
<repo_name>sinivuori/redux-music-search-prototype<file_sep>/src/actions/action_fetch_music.js
import axios from 'axios';
const BASE_URL = 'https://itunes.apple.com/search?media=music&limit=25';
export const FETCH_MUSIC = 'FETCH_MUSIC';
export function fetchMusic(term) {
const musicSearchUrl = `${BASE_URL}&term=${term}`;
const searchResult = axios.get(musicSearchUrl);
return {
type: FETCH_MUSIC,
payload: searchResult
};
}
<file_sep>/src/containers/music_item.js
import React, {Component} from 'react';
import {selectMusic} from '../actions/action_select_music';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
class MusicItem extends Component {
render() {
return (
<div className="row music-item">
<div className="col-md-2 col-xs-2 music-info-text">
<img src={this.props.music.artworkUrl100} alt={this.props.music.trackName} className="music-thumbnail rounded" onClick={() => this.props.selectMusic(this.props.music)} />
<div className="play-icon-positioner">
<div className="play-icon-container" onClick={() => this.props.selectMusic(this.props.music)}>
<i className="fas fa-play fa-3x"></i>
</div>
</div>
</div>
<div className="col-md-10 col-xs-10">
<div className="row">
<div className="col-md-12">
<div className="music-info-text">
<strong>{this.props.music.trackName}</strong>
</div>
</div>
</div>
<div className="row">
<div className="col-md-4">
<div className="music-info-text">
<p><strong>By:</strong> {this.props.music.artistName}</p>
</div>
</div>
</div>
</div>
</div>
);
}
};
function mapDispatchToProps(dispatch) {
return bindActionCreators({selectMusic: selectMusic}, dispatch);
}
export default connect(null, mapDispatchToProps)(MusicItem);
<file_sep>/src/containers/music_list.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import MusicItem from './music_item';
class MusicList extends Component {
render() {
var musicList = [];
if (this.props.musicSearchResults && this.props.musicSearchResults.results) {
musicList = this.props.musicSearchResults.results.map((musicItem) => {
return (
<MusicItem
key={musicItem.trackId}
music={musicItem} />
);
});
}
return (
<div className="music-items-container">
{musicList}
</div>
);
}
};
function mapStateToProps(state) {
return {
musicSearchResults: state.musicSearchResults
};
}
export default connect(mapStateToProps)(MusicList);
<file_sep>/src/actions/action_select_music.js
export const SELECT_MUSIC = 'SELECT_MUSIC';
export function selectMusic(music) {
return {
type: SELECT_MUSIC,
payload: music
};
}
<file_sep>/src/components/app.js
import React, {Component} from 'react';
import SearchBar from '../containers/search_bar';
import MusicList from '../containers/music_list';
import MusicDetail from '../containers/music_detail';
import 'bootstrap/dist/css/bootstrap.min.css';
export default class App extends Component {
render() {
return (
<div className="container-fluid" id="page-container">
<SearchBar />
<MusicDetail />
<MusicList />
</div>
);
}
}
<file_sep>/src/reducers/index.js
import { combineReducers } from 'redux';
import MusicSearchResults from './reducer_fetch_music';
import ActiveMusic from './reducer_select_music';
const rootReducer = combineReducers({
musicSearchResults: MusicSearchResults,
activeMusic: ActiveMusic
});
export default rootReducer;
<file_sep>/src/containers/music_detail.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
class MusicDetail extends Component {
render() {
if (!this.props.music) {
return (
<div className="row"></div>
);
}
return (
<div className="music-detail">
<div className="row">
<audio src={this.props.music.previewUrl} autoPlay controls className="col-md-12">
</audio>
</div>
<div className="alert alert-info courtesy-of-iTunes">
<div className="row">
<div className="col-md-12">
<strong>Music preview is provided courtesy of iTunes</strong>
</div>
</div>
<br/>
<div className="row">
<div className="col-md-12">
<strong>Now playing: </strong>{this.props.music.trackName}
</div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<strong>By: </strong>
<a href={this.props.music.artistViewUrl}>
{this.props.music.artistName}
</a>
</div>
</div>
<br/>
<div className="row">
<div className="col-md-12">
<strong>From collection: </strong>{this.props.music.collectionName}
</div>
</div>
<br/>
<div className="row">
<div className="col-md-12">
<strong><a href={this.props.music.trackViewUrl}>View on iTunes Store</a></strong>
</div>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
music: state.activeMusic
};
}
export default connect(mapStateToProps)(MusicDetail);
<file_sep>/__test__/reducer_fetch_music.spec.js
import FetchMusicReducer from '../src/reducers/reducer_fetch_music';
describe('Fetch music reducer', () => {
it('Should have initial state of two songs', () => {
expect(FetchMusicReducer(undefined, {}).results.length).toEqual(2);
});
});
<file_sep>/src/reducers/reducer_fetch_music.js
import {FETCH_MUSIC} from '../actions/action_fetch_music';
var initialMusic = {
results: [
{
collectionName: "Divine Land of China",
artistName: "<NAME>",
trackName: "Hope",
previewUrl: "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/Music/83/ae/92/mzm.wmyobrlk.aac.p.m4a",
artworkUrl100: "http://is4.mzstatic.com/image/thumb/Music/v4/60/e3/89/60e389cc-9dd2-3ff6-d924-a10688fd8c57/source/100x100bb.jpg",
trackViewUrl: "https://itunes.apple.com/us/album/hope/411543012?i=411543081&uo=4",
trackId: 411543081,
artistViewUrl: "https://itunes.apple.com/us/artist/tony-chen/377092325?uo=4"
},
{
collectionName: "Music for My Little Friends",
artistName: "<NAME> & <NAME>",
trackName: "Lament for the Wild Geese",
previewUrl: "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/Music/f8/6f/67/mzm.ceohsdlt.aac.p.m4a",
artworkUrl100: "http://is2.mzstatic.com/image/thumb/Music/v4/fd/4e/17/fd4e175f-3f28-cb48-75b7-792cb0bc74f7/source/100x100bb.jpg",
trackViewUrl: "https://itunes.apple.com/us/album/lament-for-the-wild-geese/358292520?i=358293431&uo=4",
trackId: 358293431,
artistViewUrl: "https://itunes.apple.com/us/artist/james-galway/219103?uo=4"
}
]
}
export default function(state = initialMusic, action) {
var newState = [];
switch (action.type) {
case FETCH_MUSIC:
newState = action.payload.data;
break;
default:
newState = state;
break;
}
return newState;
}
<file_sep>/README.md
[](https://travis-ci.org/sinivuori/redux-music-search-prototype)
# Description
A simple web app to search music using iTunes API. For learning and portfolio building.
# Techs & tools
Redux, iTunes API, Jest, Travis CI, Bootstrap 4, Fontawesome 5, and so on.
# Demo
https://sinivuori.github.io/redux-music-search-prototype/
|
c56113fcd3c872d7404007bdc6672d078cdfaf04
|
[
"JavaScript",
"Markdown"
] | 10 |
JavaScript
|
sinivuori/redux-music-search-prototype
|
e1bc6f118efc866b3ece2905acfcfd00db4f3dca
|
673c6385ed4e141ca0d81080cca571fd570f9549
|
refs/heads/master
|
<repo_name>alejandrayllon/KaggleGalaxy<file_sep>/Class4Image.R
#install packages for assignment
install.packages("ripa")
library(ripa)
install.packages("jpeg")
library(jpeg)
source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
library(EBImage)
#create a matrix with the files and source names
image_names <- list.files(path = "images_training_rev1")
#declare variables
x = 0
v = 0
q10 = 0
q25 = 0
q75 = 0
q90 = 0
for(n in 1:61578)
{
image = readJPEG(paste0("images_training_rev1/", image_names[n]))
#convert images to grayscale
image1 <- as.matrix(rgb2grey(image))
#resize images to 50x50
resize(image1, 50, 50)
#compute mean, variance, 10th, 25th, 75th, 90th quantiles images
x[n] = mean(image1)
v[n] = var(image1)
q10[n] = quantile(image1, probs = .1)
q25[n] = quantile(image1, probs = .25)
q75[n] = quantile(image1, probs = .75)
q90[n] = quantile(image1, probs = .9)
}
#store features into dataframe
images <- data.frame(x, v, q10, q25, q75, q90)
#save features so that they are not lost and don't need to rerun this code
write.csv(images, "GalaxyImages.csv", row.names = FALSE)
#pull up features and include the names of images
images <- read.csv("GalaxyImages.csv")
images["GalaxyID"] <- image_names
images$GalaxyID <- sub(".jpg", "", images$GalaxyID)
#bring in the training probabilities
images_prob <- read.csv("galaxy_train.csv")
#merge the features with the probabilities, separate training and testing images
images_all <- merge(x = images, y = images_prob, by = "GalaxyID", all = TRUE)
images_train <- na.omit(images_all)
images_test <- subset(images_all, is.na(images_all$Prob_Smooth))
#bring in caret package
library(caret)
#Use data splitting
DataSplit1 <- createDataPartition(y=images_train$Prob_Smooth, p=0.75, list=FALSE)
train1 <- images_train[DataSplit1,]
test1 <- images_train[-DataSplit1]
Galaxy1 <- train(Prob_Smooth~x+v+q10+q25+q75+q90, data = images_train, method = "glm")
summary(Galaxy1)
#Coefficients:
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 0.363455 0.007821 46.471 < 2e-16 ***
# x -4.213173 0.578963 -7.277 3.49e-13 ***
# v -2.181923 0.345315 -6.319 2.67e-10 ***
# q10 -11.915672 1.198295 -9.944 < 2e-16 ***
# q25 13.506510 1.217020 11.098 < 2e-16 ***
# q75 -1.715120 0.279108 -6.145 8.09e-10 ***
# q90 2.901330 0.157485 18.423 < 2e-16 ***
#We can see here that all the features are significant for estimating Prob_Smooth
#Predict for the test data
Galaxy_Predictions1 <- predict(Galaxy1, newdata = images_test)
#Put predictions in correct format
Galaxy_Info1 <- data.frame("GalaxyID" = images_test$GalaxyID, "Prob_Smooth" = Galaxy_Predictions1)
#Output predictions
write.csv(Galaxy_Info1, "Galaxy_Predict1.csv", row.names = FALSE)
#Score: 0.27655
#
#
#
#
#
#
#
#
#
#
#install necessary packages
install.packages("kernlab")
library(kernlab)
#Use data splitting
DataSplit2 <- createDataPartition(y=images_train$Prob_Smooth, p=0.75, list=FALSE)
train2 <- images_train[DataSplit2,]
test2 <- images_train[-DataSplit2]
Galaxy2 <- train(Prob_Smooth~x+v+q10+q25+q75+q90, data = images_train, method = "gaussprLinear")
summary(Galaxy2)
Galaxy_Predictions2 <- predict(Galaxy2, newdata = images_test)
Galaxy_Info2 <- data.frame("GalaxyID" = images_test$GalaxyID, "Prob_Smooth" = Galaxy_Predictions2)
write.csv(Galaxy_Info2, "Galaxy_Predict2.csv", row.names = FALSE)
#Did not work, error when tried to train data with guassprLinear method
#
#
#
#
#
#
#
#
#
#
#declare variable for variance of transpose, since that is the only feeature that
#will change when taking the transpose
vt = 0
for(n in 1:61578)
{
image = readJPEG(paste0("images_training_rev1/", image_names[n]))
#convert images to grayscale
image1 <- as.matrix(rgb2grey(image))
#resize images to 50x50
resize(image1, 50, 50)
#take the transpose
image2 <- t(image1)
#compute variance
vt[n] = var(image2)
}
#copy images_all into images_all_t and update variance
images_all_t <- images_all
images_all_t$v <- vt
#store all the results
write.csv(images_all_t, "GalaxyImagesT.csv", row.names = FALSE)
#bring in the data and split it between training and testing
images_all_t <- read.csv("GalaxyImagesT.csv")
images_train_t <- na.omit(images_all_t)
images_test_t <- subset(images_all_t, is.na(images_all_t$Prob_Smooth))
#install necessary packages
install.packages("caret")
install.packages("quantreg")
library(caret)
#use a gbm model
set.seed(123)
Galaxy_control_t <- trainControl(method = "repeatedcv", number = 2, repeats = 1, verbose = TRUE)
gbmGrid_t <- expand.grid(interaction.depth = c(1, 2), n.trees = seq(200,10000, by=200), shrinkage = c(0.1,.05), n.minobsinnode=1)
gbm_fit_t <- train(Prob_Smooth~x+v+q10+q25+q75+q90, data = images_train_t, method = "gbm", trControl = Galaxy_control_t, verbose = FALSE, tuneGrid = gbmGrid_t)
#use the model to predict the test data
Galaxy_Predictions_t <- predict(gbm_fit_t, newdata = images_test_t)
#output the predictions in the correct formal
Galaxy_Info_t <- data.frame("GalaxyID" = images_test$GalaxyID, "Prob_Smooth" = Galaxy_Predictions_t)
write.csv(Galaxy_Info_t, "Galaxy_Predict_t.csv", row.names = FALSE)
#Score: 0.25561
#
#
#
#
#
#
#
#
#
#
#install necessary package for cropping
install.packages("fields")
library(fields)
#Set the size for cropping
galaxy_crop = matrix(c(10, 40, 10, 40), nrow = 2, ncol = 2)
for(n in 1:61578)
{
image = readJPEG(paste0("images_training_rev1/", image_names[n]))
#convert images to grayscale
image1 <- as.matrix(rgb2grey(image))
#resize images to 50x50
resize(image1, 50, 50)
#crop image
image2 <- crop.image(image1, loc=galaxy_crop)
#compute mean, variance, 10th, 25th, 75th, 90th quantiles images
x[n] = mean(image2)
v[n] = var(image2)
q10[n] = quantile(image2, probs = .1)
q25[n] = quantile(image2, probs = .25)
q75[n] = quantile(image2, probs = .75)
q90[n] = quantile(image2, probs = .9)
}
#Did not work, could not figure out how to crop image right, this was best guess
#in attempting this feature
#
#
#
#
#
#
#
#
#
#
#install necessary packages
install.packages("caret")
install.packages("quantreg")
library(caret)
#fit a gbm model on original features
set.seed(123)
Galaxy_control <- trainControl(method = "repeatedcv", number = 2, repeats = 1, verbose = TRUE)
gbmGrid <- expand.grid(interaction.depth = c(1, 2), n.trees = seq(200,10000, by=200), shrinkage = c(0.1,.05), n.minobsinnode=1)
gbm_fit <- train(Prob_Smooth~x+v+q10+q25+q75+q90, data = images_train, method = "gbm", trControl = Galaxy_control, verbose = FALSE, tuneGrid = gbmGrid)
#use model to predict test data
Galaxy_Predictions4 <- predict(gbm_fit, newdata = images_test)
#output predictions in correct format
Galaxy_Info4 <- data.frame("GalaxyID" = images_test$GalaxyID, "Prob_Smooth" = Galaxy_Predictions4)
write.csv(Galaxy_Info4, "Galaxy_Predict4.csv", row.names = FALSE)
#Score: 0.25603
#
#
#
#
#
#
#
#
#
#
#try scaling images, declare variables
xe = 0
ve = 0
q10e = 0
q25e = 0
q75e = 0
q90e = 0
for(n in 1:61578)
{
image = readJPEG(paste0("images_training_rev1/", image_names[n]))
#convert images to grayscale
image1 <- as.matrix(rgb2grey(image))
#resize images to 50x50
resize(image1, 50, 50)
#centered matrix
image2 <- scale(image1, center = TRUE, scale = TRUE)
image2
#compute mean, variance, 10th, 25th, 75th, 90th quantiles images
xe[n] = mean(image2)
ve[n] = var(image2)
q10e[n] = quantile(image2, probs = .1)
q25e[n] = quantile(image2, probs = .25)
q75e[n] = quantile(image2, probs = .75)
q90e[n] = quantile(image2, probs = .9)
}
#there was an error when n was in the 17,000s with the scaling formula
#
#
#
#
#
#
#
#
#
#
#try a glm model with gaussian family
Galaxy_fit5 <- glm(Prob_Smooth~x+v+q10+q25+q75+q90, data = images_train, family = "gaussian")
#predict test values using the model
Galaxy_Predictions_5 <- predict(Galaxy_fit5, images_test, type = "response")
#output predictions in proper format
Galaxy_Info_5 <- data.frame("GalaxyID" = images_test$GalaxyID, "Prob_Smooth" = Galaxy_Predictions_5)
write.csv(Galaxy_Info_5, "Galaxy_Predict_5.csv", row.names = FALSE)
#Score: 0.27655
#
#
#
#
#
#
#
#
#
#
#try glm gaussian model with the transpose
Galaxy_fit6 <- glm(Prob_Smooth~x+v+q10+q25+q75+q90, data = images_train_t, family = "gaussian")
#make predictions
Galaxy_Predictions_6 <- predict(Galaxy_fit6, images_test_t, type = "response")
#output predictions
Galaxy_Info_6 <- data.frame("GalaxyID" = images_test_t$GalaxyID, "Prob_Smooth" = Galaxy_Predictions_6)
write.csv(Galaxy_Info_6, "Galaxy_Predict_6.csv", row.names = FALSE)
#Score: 0.27648
#
#
#
#
#
#
#
#
#
#
#download necessary packages
install.packages("caret")
install.packages("quantreg")
library(caret)
#Use a gbm train model with a higher number of repeated CV and with the transpose
set.seed(123)
Galaxy_control_t3 <- trainControl(method = "repeatedcv", number = 10, repeats = 1, verbose = TRUE)
gbmGrid_t3 <- expand.grid(interaction.depth = c(1, 2), n.trees = seq(200,10000, by=200), shrinkage = c(0.1,.05), n.minobsinnode=1)
gbm_fit_t3 <- train(Prob_Smooth~x+v+q10+q25+q75+q90, data = images_train_t, method = "gbm", trControl = Galaxy_control_t3, verbose = FALSE, tuneGrid = gbmGrid_t3)
#make predictions
Galaxy_Predictions_t3 <- predict(gbm_fit_t3, newdata = images_test_t)
#output predictions
Galaxy_Info_t3 <- data.frame("GalaxyID" = images_test_t$GalaxyID, "Prob_Smooth" = Galaxy_Predictions_t3)
write.csv(Galaxy_Info_t3, "Galaxy_Predict_t3.csv", row.names = FALSE)
#Score: 0.25541
|
81f078700dcdb08f189818ce69d078da25814a9f
|
[
"R"
] | 1 |
R
|
alejandrayllon/KaggleGalaxy
|
1562a1e876e5e8cc8bad75f563bc4fd94bea41e8
|
1e1e5d4b5aef3e6358a8f48860c947de6faa95f3
|
refs/heads/master
|
<file_sep>var cssthief = { // Namespace
el: null,
style: {
outline: null,
"-webkit-box-shadow": null,
zIndex: null
},
click: function(e){
var el = e.target;
// TODO: Fetch HTML and CSS
// TODO: Strip comments and other useless tags
// TODO: Strip attributes, such as classnames, ids, etc..
// TODO: Generate proper selectors for CSS?
// TODO: Grab files / images referenced in CSS as well and alter paths?
// TODO: Optionally, tidy it all up
// TODO: Make sure to somehow grab pseudo styles: hover, etc..
// TODO: Save to the clipboard
// TODO: Publish to jsfiddle or something similar?
cssthief.disable();
// Copy HTML to clipboard
// FIXME: This isn't working, despite permissions
var html = document.createElement("textarea");
html.style.visibility = "hidden";
document.body.appendChild(html);
html.value = el.outerHTML;
html.focus();
document.execCommand("SelectAll");
document.execCommand("Copy", false, null);
document.body.removeChild(html);
e.preventDefault();
},
enabled: false,
enable: function(){
cssthief.enabled = true;
window.addEventListener("click", cssthief.click);
},
disable: function(){
cssthief.enabled = false;
cssthief.restoreStyles();
window.removeEventListener("click", cssthief.click);
},
restoreStyles: function(){
if(cssthief.el){
for(prop in cssthief.style)
cssthief.el.style[prop] = cssthief.style[prop];
}
}
};
window.addEventListener("mousemove", function(e){
var el = document.elementFromPoint(e.clientX, e.clientY);
if(cssthief.el != el && cssthief.enabled){
// Restore old styles
cssthief.restoreStyles();
// Save styles from new element
for(prop in cssthief.style)
cssthief.style[prop] = el.style[prop];
// Apply styles to new element
el.style.outline = "5px solid rgba(255, 0, 0, 0.5)";
el.style["webkit-box-shadow"] = "0px 0px 5px rgba(255, 0, 0, 0.5)";
el.style.zIndex = 9999;
// Save reference to new element
cssthief.el = el;
}
}, true);<file_sep>cssthief
========
cssthief is a Chrome extension which copies the HTML and CSS for a selected element in any page into the clipboard in a ready-to-use form.
Work in progress!<file_sep>chrome.extension.onMessage.addListener(function(details){
console.log(details);
});
var el;
document.body.addEventListener("contextmenu", function(event){
el = event.target;
}, true);<file_sep>chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.executeScript(tab.id, {code: "cssthief.enable();"});
});
|
010453e8d42c8f939508c98f4ef248babb220137
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
collectivecognition/cssthief
|
c1947e46ebec6a7b7dac8b90fd428ce7430f0492
|
a91bf36d6eee619c98d6046a6a8ea66377db040e
|
refs/heads/master
|
<repo_name>nesho84/necom.at<file_sep>/library/dbconnect.php
<?php
// database connection config
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '<PASSWORD>';
$dbname = 'd0198000';
global $con;
/*
connecting to mysql database
*/
$con = mysqli_connect($dbhost,$dbuser,$dbpass);
if(!$con)
{
die("Connection to database failed".mysql_error());
}
/* selecting the database "dbname" */
$dataselect = mysqli_select_db($con,$dbname);
if(!$dataselect)
{
die("Database namelist not selected".mysql_error());
}
?><file_sep>/inc/menu_header.inc.php
<div id="container"><!--#Container START-->
<div id="container_inside"><!--#Container_inside START-->
<div id="header-wrapper">
<div id="header">
<div id="logo">
<h1><a href="http://necom.at"><img src="<?php echo SITE_URL; ?>images/new logo by nebo-header.png"></a></h1>
<!--<p> Information Technology Management</p>-->
</div>
<div id="menu">
<!-- Getting Pages from Database -->
<!-- <?php $qry = mysqli_query($con, "SELECT * FROM pages");
if (!$qry) { die("Query Failed: " . mysqli_error($con)); }
?>
<ul>
<li><a href="http://necom.at" accesskey="1" title="">Home</a></li>
<?php
while ($row = mysqli_fetch_array($qry))
{
?>
<li><a href="<?php echo (stripslashes($row['link'])); ?>" accesskey="1" title=""><?php echo (stripslashes($row['title'])); ?></a></li>
<?php
}
?>
</ul> -->
<!-- deleted sql File so I will put the links Manually -->
<ul>
<li><a href="/" data-rel="close" class="ui-btn">HOME</a></li></li>
<li><a href="uns.php" class="ui-btn">ÜBER UNS</a></li></li>
<li><a href="services.php" class="ui-btn">SERVICES</a></li></li>
<li><a href="referenzen.php" class="ui-btn">REFERENZEN</a></li></li>
<li><a href="kontakt.php" class="ui-btn">KONTAKT</a></li></li>
</ul>
</div>
</div>
</div>
<!--START main_content-->
<div id="page-wrapper">
<div id="page-wrapper-inside"><file_sep>/adm/admin.php
<?php
require ('adm_header.php');
?>
<!---------------Main Content START---------------------------------->
<h1 style="color: #686868;">Administration</h1>
<p style="left: 83%; margin-top: -20px; position: absolute;">Welcome <a href="#" style=" text-decoration: none;"><b><?php echo $_SESSION['username']; ?></b></a></p>
<hr />
<ul class="ex_menu">
<?php
$qry = mysql_query("SELECT * FROM pages", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
$count = mysql_num_rows($qry);
$qry2 = mysql_query("SELECT * FROM referenzen", $con);
if (!$qry2) {
die("Query Failed: " . mysql_error());
}
$count2 = mysql_num_rows($qry2);
$qry3 = mysql_query("SELECT * FROM users", $con);
if (!$qry3) {
die("Query Failed: " . mysql_error());
}
$count3 = mysql_num_rows($qry3);
$qry5 = mysql_query("SELECT * FROM news", $con);
if (!$qry5) {
die("Query Failed: " . mysql_error());
}
$count5 = mysql_num_rows($qry5);
?>
<li><a href="<?php ADM_URL ?>pages/pages.php">Pages</a><?php echo ' <span><b>(' . $count . ')</b></span>' ?><br />
Display.Edit and Delete top_menu Pages</li>
<li><a href="referenzen/">Referenzen</a><?php echo ' <span><b>(' . $count2 . ')</b></span>' ?><br />
Display, Edit and Delete References</li>
<li><a href="<?php ADM_URL ?>users/users.php">Users</a><?php echo ' <span><b>(' . $count3 . ')</b></span>' ?><br />
Website Administrators & Users with full Access</li>
<li><a href="<?php ADM_URL ?>news/">News</a><br />
News: <?php echo ' <span><b>(' . $count5 . ')</b></span>' ?> >>This Option is Coming Soon...<<</li>
<li class="active"><a href="<?php echo ADM_URL ?>logout.php">Logout</a><br />
Destroy Sessions and Back to Home Page</li>
</ul>
<!---------------Main Content END---------------------------------->
<?php
require ('adm_footer.php');
?> <file_sep>/library/config.php
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
//connect to database
require_once 'dbconnect.php';
// Variables to include and upload files
$siteRoot = $_SERVER['DOCUMENT_ROOT']. '/';
$admRoot = $_SERVER['DOCUMENT_ROOT']. '/adm/';
$upload_path = $_SERVER['DOCUMENT_ROOT']. 'upl/';
define('SITE_URL', 'http://'.$_SERVER['HTTP_HOST'].'/necom.at/'); //Apsolute site path
define('ADM_URL', SITE_URL .'adm/');
define('UPLOAD_DIR', SITE_URL .'upl/');
define('IMAGE_DIR', SITE_URL . 'images/');
define('STYLE_DIR', SITE_URL . 'library/');
//SECURE $_GET $_POST VARIABLES
// if(!get_magic_quotes_gpc())
// {
// $_GET = array_map('mysql_real_escape_string', $_GET);
// $_POST = array_map('mysql_real_escape_string', $_POST);
// $_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);
// }
// else
// {
// $_GET = array_map('stripslashes', $_GET);
// $_POST = array_map('stripslashes', $_POST);
// $_COOKIE = array_map('stripslashes', $_COOKIE);
// $_GET = array_map('mysql_real_escape_string', $_GET);
// $_POST = array_map('mysql_real_escape_string', $_POST);
// $_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);
// }
<file_sep>/adm/news/add_edit_category.php
<?php
require ('../library/config.php');
require ('../template/tpl_functions.php');
logged_in();
do_header('Add Category');
top_left_menu('Admin');
?>
<style type="text/css">
<!--
.ed{ border-style:solid; border-width:thin; border-color:#00CCFF; padding:5px; margin-bottom: 4px; width: 355px; }
.ed-select{ border-style:solid; border-width:thin; border-color:#00CCFF; padding:5px; margin-bottom: 4px; width: 366px; }
#caption{ margin-top: 5px; }
-->
</style>
<!------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------// Add //--------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------->
<?php
if (isset($_GET['add']) == 'category') {
?>
<h2>Create Category
<hr style="border:1px solid #bbb; margin-right:25px;">
</h2>
<p style="color:#5f5f5f; margin-bottom:-7px; margin-top:-15px;">
<a href="admin_categories.php"><img src="../images/back.png" style="vertical-align:top; margin-top:3px;" /> Back to Categories
</a>
</p>
<hr style="border:1px solid #bbb; margin-bottom:-5px; margin-right:25px;"><br /><br />
<form name="addroom" action="" method="post" enctype="multipart/form-data">
Select Category Logo: <br />
<input type="file" name="logo" class="ed"><br />
Category Name:<br />
<input name="cat_name" type="text" class="ed" />
<br />
<input type="submit" name="add" value="Upload" id="button1" />
</form>
<br /><hr style="border:1px solid #bbb; margin-right:25px;">
<?php
}
if (isset($_POST['add'])) {
if (empty($_FILES['logo']['tmp_name'])) {
die('<p align="center" style="padding-top: 100px;"><img src="../images/ok2.jpg" width="40" height="25" /><br />Logo Image not Selected...<br /><a href="javascript:history.go(-1)">Try again...</a></p>');
}
$file1 = $_FILES['logo']['tmp_name'];
;
$logo = addslashes(file_get_contents($_FILES['logo']['tmp_name']));
$image_name1 = addslashes($_FILES['logo']['name']);
move_uploaded_file($_FILES["logo"]["tmp_name"], "uploads/categories/" . $_FILES["logo"]["name"]);
$path = 'uploads/categories/';
$cat_img = $_FILES["logo"]["name"];
$cat_name = $_POST['cat_name'];
//Don't allow duplicate category
$qry_check = mysql_query("SELECT cat_name FROM categories where cat_name='$cat_name' ", $con);
if (!$qry_check) {
die("Query Failed: " . mysql_error());
}
$row = mysql_fetch_array($qry_check);
if (mysql_num_rows($qry_check)) {
echo "<br /><br />";
echo '<p align="center" style="color:red";><b>Category</b> exists!<br /><a href="javascript:history.go(-1)">Try again...</a></p>';
exit;
}
$save = mysql_query("INSERT INTO categories (cat_img, cat_name) VALUES ('$cat_img','$cat_name')");
if (!$save) {
die("Query Failed: " . mysql_error());
}
?>
<p align="center" style="padding-top: 10px;"><img src="../images/ok1.gif" width="40" height="25" /><br />Category <?php echo "<b>" . $cat_name . "</b>"; ?> added Successfully.</p>
<?php
}
?>
<!------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------// EDIT //--------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------->
<?php
if (isset($_GET['cat_id'])) {
$cat_id = $_GET['cat_id'];
$qry1 = mysql_query("SELECT * FROM categories WHERE cat_id='$cat_id'", $con);
if (!$qry1) {
die("Query Failed: " . mysql_error());
}
while ($row = mysql_fetch_array($qry1)) {
?>
<h2>Edit Category
<hr style="border:1px solid #bbb; margin-right:25px;">
</h2>
<p style="color:#5f5f5f; margin-bottom:-7px; margin-top:-15px;">
<a href="admin_categories.php"><img src="../images/back.png" style="vertical-align:top; margin-top:3px;" /> Back to Categories
</a>
</p>
<hr style="border:1px solid #bbb; margin-bottom:-5px; margin-right:25px;"><br />
<div style="border:1px solid #bbb; margin-right:25px; padding-left:4px; background:#f5f5f5; color:#d45031; font-weight:bold;">
<span>Category can be edited only if none of Products are related to this Category!</span>
</div><br />
<form name="addroom" action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="cat_id" id="id" value="<?php echo $row['cat_id']; ?>" />
Change Category Name:<br />
<input name="cat_name" value="<?php echo $row['cat_name']; ?>" type="text" class="ed" />
<br />
<input type="submit" name="edit" value="OK" id="button1" />
</form>
<br /><hr style="border:1px solid #bbb; margin-right:25px;">
<?php
}
}
if (isset($_POST['edit'])) {
$cat_id = $_POST['cat_id'];
$cat_name = $_POST['cat_name'];
$save = mysql_query("UPDATE categories SET cat_name='$cat_name' WHERE cat_id='$cat_id'", $con);
if (!$save) {
die("Query Failed: " . mysql_error());
}
?>
<p align="center" style="padding-top: 10px;"><img src="../images/ok1.gif" width="40" height="25" /><br />Category <?php echo "<b>" . $cat_name . "</b>"; ?> edited Successfully</p>
<?php
}
footer2();
?><file_sep>/adm/pages/add_edit_pages.php
<?php
require ('../adm_header.php');
require (($_SERVER['DOCUMENT_ROOT']) . 'fancybox/my-fancybox-js-css.php');
?>
<style type="text/css">
<!--
.ed{ border-style:solid; border-width:thin; border-color:#00CCFF; padding:5px; margin-bottom: 4px; width: 355px; }
.ed-select{ border-style:solid; border-width:thin; border-color:#00CCFF; padding:5px; margin-bottom: 4px; width: 366px; }
#caption{ margin-top: 5px; }
-->
</style>
<!-- TinyMCE -->
<script type="text/javascript" src="../tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
theme : "advanced",
plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,visualblocks",
// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft,visualblocks",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
// Example content CSS (should be your site CSS)
content_css : "css/content.css",
// Drop lists for link/image/media/template dialogs
template_external_list_url : "lists/template_list.js",
external_link_list_url : "lists/link_list.js",
external_image_list_url : "lists/image_list.js",
media_external_list_url : "lists/media_list.js",
// Style formats
style_formats : [
{title : 'Bold text', inline : 'b'},
{title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},
{title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},
{title : 'Example 1', inline : 'span', classes : 'example1'},
{title : 'Example 2', inline : 'span', classes : 'example2'},
{title : 'Table styles'},
{title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
],
// Replace values for the template plugin
template_replace_values : {
username : "Some User",
staffid : "991234"
}
});
</script>
<!-- /TinyMCE -->
<!------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------// Add //--------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------->
<?php
if (isset($_GET['add']) == 'page') {
$c_date = date("Y-m-d H:i:s");
?>
<!--< Go Back button START-->
<div class="title">
<div style="float: left;">
<a href="pages.php"><img style="width:48px; height:48px" src="<?php echo IMAGE_DIR; ?>adm_back.png" /></a>
</div>
<h1>Add Page</h1>
</div>
<div id="clear"> </div>
<!--< Go Back button END-->
<form name="addroom" action="" method="post" enctype="multipart/form-data" style="font-weight: bold;">
Select Page Image: <br />
<input type="file" name="img" class="ed"><br />
Page Name:<br />
<input name="title" type="text" class="ed" />
<br />
Date:<br />
<input name="date" type="text" class="ed" value="<?php echo $c_date; ?>" disabled />
<br />
Link:<br />
<input name="link" type="text" class="ed" value="http://necom.at/" />
<br />
Text:<br />
<div>
<textarea id="elm1" name="text" rows="15" cols="80" style="width: 80%">
Example:
<h1>This text was from background code!</h1>
Please fill the Content!
</textarea>
</div>
<!-- Some integration calls -->
<a href="javascript:;" onclick="tinyMCE.get('elm1').show();return false;">[Show]</a>
<a href="javascript:;" onclick="tinyMCE.get('elm1').hide();return false;">[Hide]</a>
<a href="javascript:;" onclick="tinyMCE.get('elm1').execCommand('Bold');return false;">[Bold]</a>
<a href="javascript:;" onclick="alert(tinyMCE.get('elm1').getContent());return false;">[Get contents]</a>
<a href="javascript:;" onclick="alert(tinyMCE.get('elm1').selection.getContent());return false;">[Get selected HTML]</a>
<a href="javascript:;" onclick="alert(tinyMCE.get('elm1').selection.getContent({format : 'text'}));return false;">[Get selected text]</a>
<a href="javascript:;" onclick="alert(tinyMCE.get('elm1').selection.getNode().nodeName);return false;">[Get selected element]</a>
<a href="javascript:;" onclick="tinyMCE.execCommand('mceInsertContent',false,'<b>Hello world!!</b>');return false;">[Insert HTML]</a>
<a href="javascript:;" onclick="tinyMCE.execCommand('mceReplaceContent',false,'<b>{$selection}</b>');return false;">[Replace selection]</a>
<br /><br />
<input type="submit" name="add" value="Submit" class="adm_button" style="font-weight: bold;" />
</form>
<hr />
<?php
}
if (isset($_POST['add'])) {
if (empty($_FILES['img']['tmp_name'])) {
die('<p align="center"><img src="../../images/ok2.jpg" width="35" height="25" /><br />Image not Selected...<br /><a href="javascript:history.go(-1)">Try again...</a></p>');
}
$file1 = $_FILES['img']['tmp_name'];
;
$img = addslashes(file_get_contents($_FILES['img']['tmp_name']));
$image_name1 = addslashes($_FILES['img']['name']);
move_uploaded_file($_FILES["img"]["tmp_name"], "../../upl/" . $_FILES["img"]["name"]);
$path = '../../upl/';
$img = $_FILES["img"]["name"];
$title = $_POST['title'];
$link = $_POST['link'];
$text = $_POST['text'];
//Don't allow duplicate page
$qry_check = mysql_query("SELECT title FROM pages where title='$title' ", $con);
if (!$qry_check) {
die("Query Failed: " . mysql_error());
}
$row = mysql_fetch_array($qry_check);
if (mysql_num_rows($qry_check)) {
echo "<br /><br />";
echo '<p align="center" style="color:red";><img src="../../images/ok2.jpg" width="40" height="25" /><br /><b>Page</b> exists!<br /><a href="javascript:history.go(-1)">Try again...</a></p>';
exit;
}
$save = mysql_query("INSERT INTO pages (img, title, date, link, text) VALUES ('$img','$title',NOW(),'$link','$text')");
if (!$save) {
die("Query Failed: " . mysql_error());
}
?>
<p align="center" style="padding-top: 10px;"><img src="../../images/ok1.gif" width="35" height="25" /><br />Page <?php echo "<b>" . $title . "</b>"; ?> added Successfully.</p>
<?php
}
?>
<!------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------// EDIT //--------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------->
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$qry1 = mysql_query("SELECT * FROM pages WHERE id='$id'", $con);
if (!$qry1) {
die("Query Failed: " . mysql_error());
}
while ($row = mysql_fetch_array($qry1)) {
$c_date = date("Y-m-d H:i:s");
?>
<!--< Go Back button START-->
<div class="title">
<div style="float:left;">
<a href="pages.php"><img style="width:48px; height:48px" src="<?php echo IMAGE_DIR; ?>adm_back.png" /></a>
</div>
<h1>Edit Page</h1>
</div>
<div id="clear"> </div>
<!--< Go Back button END-->
<form name="addroom" action="" method="post" enctype="multipart/form-data" style="font-weight: bold;">
<input type="hidden" name="id" id="id" value="<?php echo $row['id']; ?>" />
<!--|||||||||||||||FancyBOX pages Image Zoom|||||||||||||||-->
<p><a id="adm_pages" href="<?php echo UPLOAD_DIR . $row['img']; ?>" title="<?php echo $row['title']; ?>">
<img style="width: 100px; height: 100px; border: 1px solid #ccc;" src="<?php echo UPLOAD_DIR . $row['img']; ?>" alt="" />
</a></p>
<!--|||||||||||||||FancyBOX Pages Image Zoom END|||||||||||||||-->
Page Name:<br />
<input name="title" type="text" class="ed" value="<?php echo $row['title']; ?>" />
<br />
Date:<br />
<input name="date" type="text" class="ed" value="<?php echo $row['date']; ?>" disabled />
<br />
Link: <span style="font-size: x-small;">(Ex. http://necom.at/kontakt)</span><br />
<input name="link" type="text" class="ed" value="<?php echo $row['link']; ?>" />
<br />
Text:<br />
<div>
<textarea id="elm1" name="text" rows="15" cols="80" style="width: 80%">
<?php echo $row['text']; ?>
</textarea>
</div><br />
<input type="submit" name="edit" value="Update" id="button1" style="font-weight: bold;" />
</form>
<br /><hr />
<?php
}
}
if (isset($_POST['edit'])) {
$id = $_POST['id'];
$title = $_POST['title'];
$link = $_POST['link'];
$text = $_POST['text'];
$c_date = date("Y-m-d H:i:s");
$save = mysql_query("UPDATE pages SET title='$title', date='$c_date', link='$link', text='$text' WHERE id='$id'", $con);
if (!$save) {
die("Query Failed: " . mysql_error());
}
?>
<p align="center" style="padding-top: 10px;"><img src="../../images/ok1.gif" width="40" height="25" /><br />Page <?php echo "<b>" . $title . "</b>"; ?> edited Successfully</p>
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = "add_edit_pages.php?id=$id";
?>
<meta http-equiv="Refresh" content="1; url=<?php echo 'http://'. $host . $uri . '/' . $extra; ?>">
<?php
}
require ('../adm_footer.php');
?> <file_sep>/adm/adm_header.php
<?php
require (($_SERVER['DOCUMENT_ROOT']) . 'library/config.php');
require (($_SERVER['DOCUMENT_ROOT']) . 'library/functions.php');
logged_in();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>NECOM - Administration</title>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900" rel="stylesheet" />
<link href="<?php $_SERVER['DOCUMENT_ROOT']; ?>/library/default.css" rel="stylesheet" type="text/css" media="all" />
<link href="<?php $_SERVER['DOCUMENT_ROOT']; ?>/library/adm.css" rel="stylesheet" type="text/css" media="all" /><!--main admin css-->
<link href="<?php $_SERVER['DOCUMENT_ROOT']; ?>/fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="<?php $_SERVER['DOCUMENT_ROOT']; ?>/images/necom.ico">
<!--[if IE 6]><link href="library/default_ie6.css" rel="stylesheet" type="text/css" /><![endif]-->
<!-- Add my_js_funstions -->
<script type="text/javascript" src="<?php $_SERVER['DOCUMENT_ROOT']; ?>/library/js_functions.js"></script>
</head>
<body>
<div class="adm_main">
<table id="adm_content">
<tr>
<td><file_sep>/adm/users/add_edit_users.php
<?php
require ('../adm_header.php');
?>
<style type="text/css">
<!--
.ed{ border-style:solid; border-width:thin; border-color:#00CCFF; padding:5px; margin-bottom: 4px; width: 355px; }
.ed-select{ border-style:solid; border-width:thin; border-color:#00CCFF; padding:5px; margin-bottom: 4px; width: 366px; }
#caption{ margin-top: 5px; }
-->
</style>
<!------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------// Add //--------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------->
<?php
if (isset($_GET['add']) == 'user') {
?>
<!--< Go Back button START-->
<div class="title">
<div style="float:left;">
<a href="users.php"><img style="width:48px; height:48px" src="<?php echo IMAGE_DIR; ?>adm_back.png" /></a>
</div>
<h1>Add User</h1>
</div>
<div id="clear"> </div>
<!--< Go Back button END-->
<form name="addroom" action="" method="post" enctype="multipart/form-data" style="font-weight: bold;">
Username: <br />
<input type="text" name="user_name" class="ed"><br />
Password:<br />
<input type="text" value="Password will be generated Automatically..." class="ed" disabled />
<br />
<input type="submit" name="add" value="Add" class="adm_button" />
</form>
<br /><hr />
<?php
}
if (isset($_POST['add'])) {
$user_name = $_POST['user_name'];
//Don't allow duplicate Users
$qry_check = mysql_query("SELECT username FROM users where username='$user_name' ", $con);
if (!$qry_check) {
die("Query Failed: " . mysql_error());
}
$row = mysql_fetch_array($qry_check);
;
if (mysql_num_rows($qry_check)) {
echo "<br />";
echo '<p align="center" style="color:red";><img src="../../images/ok2.jpg" width="40" height="25" /><br /><b>User</b> exists!</p>';
exit;
}
$str = rand(10000, 100000); //random userid
$length = 10;
$randompass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); //random user pass
$save = mysql_query("INSERT INTO users (id, username, password) VALUES ('$str','<PASSWORD>','<PASSWORD>')");
if (!$save) {
die("Query Failed: " . mysql_error());
}
?>
<p align="center" style="padding-top: 10px;"><img src="../../images/ok1.gif" width="40" height="25" /><br />User <?php echo "<b>" . $user_name . "</b>"; ?> added Successfully.</p>
<?php
}
?>
<!------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------// EDIT //--------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------->
<?php
if (isset($_GET['user_id'])) {
$user_id = $_GET['user_id'];
$qry1 = mysql_query("SELECT * FROM users WHERE id='$user_id'", $con);
if (!$qry1) {
die("Query Failed: " . mysql_error());
}
while ($row = mysql_fetch_array($qry1)) {
?>
<!--< Go Back button START-->
<div class="title">
<div style="float:left;">
<a href="users.php"><img style="width:48px; height:48px" src="<?php echo IMAGE_DIR; ?>adm_back.png" /></a>
</div>
<h1>Edit User</h1>
</div>
<div id="clear"> </div>
<!--< Go Back button END-->
<form name="addroom" action="" method="post" enctype="multipart/form-data" style="font-weight: bold;">
<input type="hidden" name="id" id="id" value="<?php echo $row['id']; ?>" />
Change Username:<br />
<input name="user_name" value="<?php echo $row['username']; ?>" type="text" class="ed" />
<br />
Password:<br />
<input value="<?php echo $row['password']; ?>" type="text" class="ed" disabled />
<br />
New Password:<br />
<input name="pass" value="" type="text" class="ed" />
<br />
Comfirm New Password:<br />
<input name="pass2" value="" type="text" class="ed" />
<br />
<input type="submit" name="edit" value="Update" class="adm_button" />
</form>
<br /><hr />
<?php
}
}
if (isset($_POST['edit'])) {
$user_name = $_POST['user_name'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
if ($pass != $pass2) { die ('<p style="color: red; font-weight: bold; text-align: center;">Password do not match!<br /> Please try again...</p>'); }
$save = mysql_query("UPDATE users SET username='$user_name', password='$pass' WHERE id='$user_id'", $con);
if (!$save) { die("Query Failed: " . mysql_error()); }
?>
<p align="center" style="padding-top: 10px;"><img src="../../images/ok1.gif" width="40" height="25" /><br />User <?php echo "<b>" . $user_name . "</b>"; ?> edited Successfully.</p>
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = "add_edit_users.php?user_id=$user_id";
?>
<meta http-equiv="Refresh" content="2; url=<?php echo 'http://'. $host . $uri . '/' . $extra; ?>">
<?php
}
require ('../adm_footer.php');
?> <file_sep>/mobile.necom.at/kontakt.php
<!DOCTYPE html>
<?php require ('../library/config.php'); ?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
<!--MyIncludes STart-->
<link href="mycss.css" rel="stylesheet" type="text/css" media="all" />
<link href="fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="http://necom.at/images/icon-1.9.2014.ico">
<!--MyIncludes END-->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
</head>
<body>
<!--*********************************************************************************/
/* uns */
/*********************************************************************************/-->
<div data-role="page" id="kontakt">
<!--Panel-->
<?php require_once ('inc/panel.inc.php'); ?>
<div data-role="header">
<div id="header-bg">
<!--Logo-->
<div class="logo">
<a href="http://mobile.necom.at"><img src="http://necom.at/images/new logo by nebo-header.png" style="width:100%;"></a>
</div>
<!--Top MENU-->
<?php require_once ('inc/navbar.inc.php'); ?>
</div>
</div>
<div data-role="main" class="ui-content" style="min-height:400px; background-color:#71a6ee;">
<ul style="list-style:none;">
<li>
<h1> Kontakt </h1>
<img src="http://necom.at/images/kont.png">
<h1 style="text-align: left; padding-bottom: 10px;"><span style="font-family: trebuchet ms,geneva;"><span style="color: #888888;"><span style="font-size: x-large;">NECOM-IT GmbH</span></span></span><span style="font-family: trebuchet ms,geneva;"><span style="color: #888888;"> </span></span></h1>
<p><span style="font-family: trebuchet ms,geneva; color: #fff;"><strong>Adresse</strong>: Penzingerstrasse 53/8</span></p>
<p style="text-align: left;"><span style="font-family: trebuchet ms,geneva; color: #fff;">1140 Wien, Österreich</span></p>
<p style="text-align: left;"><span style="font-family: trebuchet ms,geneva; color: #fff;"><strong>UID</strong>: ATU68480048</span></p>
<p style="text-align: left;"><span style="font-family: trebuchet ms,geneva; color: #fff;"><strong>FN.</strong>: 411038 v</span></p>
<p style="text-align: left;"><span style="font-family: trebuchet ms,geneva; color: #fff;"><strong>Tel.</strong>: +43(1)8920697</span></p>
<p style="text-align: left;"><span style="font-family: trebuchet ms,geneva; color: #fff;"><strong>Fax.</strong>: +43(1)8920697-99</span></p>
<p style="text-align: left;"><span style="font-family: trebuchet ms,geneva; color: #fff;"><strong>E-mail</strong>: <a href="mailto:<EMAIL>"><span style="color: #fff;"><EMAIL></span></a></span></p>
<!--<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script><div style="overflow:hidden;height:500px;width:250px;">
<div id="gmap_canvas" style="height:500px;width:250px;"></div>
<a class="google-map-code" href="http://www.map-embed.com" id="get-map-data">www.map-embed.com</a>
<style>#gmap_canvas img{max-width:none!important;background:none!important}</style>
</div>
<script type="text/javascript"> function init_map(){var myOptions = {zoom:14,center:new google.maps.LatLng(48.1896309,16.306144399999994),mapTypeId: google.maps.MapTypeId.ROADMAP};map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);marker = new google.maps.Marker({map: map,position: new google.maps.LatLng(48.1896309, 16.306144399999994)});infowindow = new google.maps.InfoWindow({content:"<b>NECOM-IT GmbH</b><br/><NAME>traße 53<br/>1140 Wien" });google.maps.event.addListener(marker, "click", function(){infowindow.open(map,marker);});infowindow.open(map,marker);}google.maps.event.addDomListener(window, 'load', init_map);</script>
-->
</li>
</ul>
</div>
<div data-role="footer" style="background-color:#4083e3; margin:0; padding:0; border:0;">
<div id="footer-bg">
<ul class="contact">
<li>
<a class="icon icon-facebook" href="http://www.facebook.com/sharer.php?u=http://necom.at&t=The World is Small" target="_blank" title="Share This on Facebook"></a>
</li>
<li><a href="http://twitter.com/share?url=http://campaignmonitor.com/blog&text=I love the Campaign Monitor blog!&via=campaignmonitor&related=yarrcat" target="_blank"" class="icon icon-twitter"><span>Twitter</span></a></li>
<li><a href="https://plus.google.com/share?url=http://necom.at" class="icon icon-google-plus"><span>Google+</span></a></li>
<li><a href="#" class="icon icon-dribbble"><span>Pinterest</span></a></li>
<li><a href="#" class="icon icon-youtube"><span>Youtube</span></a></li>
</ul>
<p>Copyright (c) 2014 necom.at All rights reserved. | <a href="http://www.necom.at/" rel="nofollow">necom.at</a></p>
</div>
</div>
</div>
</body>
</html><file_sep>/login.php
<?php session_start();
if (isset($_SESSION['username'])) {
header("Location: adm/admin.php");
}
else {
?>
<html>
<head>
<title>NECOM - Administration</title>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900" rel="stylesheet" />
<link href="fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="images/necom.ico">
<style>
body {
margin: 0px;
padding: 0px;
background: #FFF url(../images/bg_app.png) repeat;
}
/* form */
ol { list-style:none; margin-left: -25px; }
ol li { display:block; clear:both;}
ol li label { display:block; margin:0; padding:16px 0 0 0;}
ol li .text { width:320px; height:26px; border:1px solid #c0c0c0; margin:2px 5px 0px 0px; background:#fff;}
ol li .send { margin:16px 0 0 0; width: 100px; height: 26px;}
.ontop { z-index: 999; width: 100%; height: 100%; top: 0; left: -5%; color: #aaaaaa; filter: alpha(opacity = 90); }
#popup_login { width: 350px; height: 180px; position: absolute; box-shadow: 0px 0px 20px 3px #000; color: #000000; font-size:12px; background: #fff; top: 50%; left: 50%; border-radius:10px; margin: -200px 0 0 -200px; padding: 10px; }
h1 { text-align:center; width: 345px; }
hr { border-top: 1px solid #ccc; width: 320px; }
</style>
</head>
<body>
<!--**************Login FORM********************-->
<div class="ontop">
<table id="popup_login">
<tr style="margin-top:-10px;">
<td>
<!---------------Main Content START------------------------------------------->
<h1 style="color:#ccc; font-size:46px; margin:0;">Members Login</h1>
<hr />
<form id="form1" name="form1" method="post" action="adm/check_login.php">
<ol>
<li>
<label for="name">Username:</label>
<input type="text" name="username" id="username" class="text" />
</li>
<li>
<label for="email">Password:</label>
<input type="<PASSWORD>" name="password" id="password" class="text" />
</li>
<li>
<input type="submit" name="imageField" value="Login" id="imageField" class="send" alt="Login" />
</li>
<li> </li>
</ol>
</form>
<!---------------Main Content END---------------------------------->
</td>
</tr>
</table>
</div>
</body>
</html>
<?php
}
?><file_sep>/README.md
# necom.at
Startup Company necom.at
<file_sep>/library/functions.php
<?php
session_start();
function logged_in() {
if(isset($_SESSION['username']))
{
if (!$_SESSION['username'])
{
require (SITE_URL. 'login.php');
echo '<p style=font-size:small align=center><img src='.IMAGE_DIR.'ok2.jpg width=100 height=100/><br />You are not authorised to access this page unless you are administrator of this website...<br /><br /><a href="'.SITE_URL.'login.php">Please Login...</a></p>';
}
}
else
{
echo '<p style=font-size:small align=center><img src='.IMAGE_DIR.'stop.png width=100 height=100/><br />You are not authorised to access this page unless you are administrator of this website...<br /><br /><a href="'.SITE_URL.'login.php">Please Login...</a></p>';
exit;
}
}
?>
<file_sep>/mobile.necom.at/suchen.php
<!DOCTYPE html>
<?php require ('../library/config.php'); ?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
<!--MyIncludes STart-->
<link href="mycss.css" rel="stylesheet" type="text/css" media="all" />
<link href="fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="http://necom.at/images/icon-1.9.2014.ico">
<!--MyIncludes END-->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
</head>
<body>
<!--*********************************************************************************/
/* uns */
/*********************************************************************************/-->
<div data-role="page" id="uns">
<!--Panel-->
<?php require_once ('inc/panel.inc.php'); ?>
<div data-role="header">
<div id="header-bg">
<!--Logo-->
<div class="logo">
<a href="http://mobile.necom.at"><img src="http://necom.at/images/new logo by nebo-header.png" style="width:100%;"></a>
</div>
<!--Top MENU-->
<?php require_once ('inc/navbar.inc.php'); ?>
</div>
</div>
<div data-role="main" class="ui-content" style="min-height:400px; background-color:#71a6ee;">
<form method="post" action=""http://mobile.necom.at/suchen.php">
<div class="ui-field-contain">
<label for="search">Suchen:</label>
<input type="search" name="search" id="search" placeholder="Suchen nach Inhalt...">
</div>
<input type="submit" data-inline="true" value="Suchen">
</form>
</div>
<div data-role="footer" style="background-color:#4083e3; margin:0; padding:0; border:0;">
<div id="footer-bg">
<ul class="contact">
<li>
<a class="icon icon-facebook" href="http://www.facebook.com/sharer.php?u=http://necom.at&t=The World is Small" target="_blank" title="Share This on Facebook"></a>
</li>
<li><a href="http://twitter.com/share?url=http://campaignmonitor.com/blog&text=I love the Campaign Monitor blog!&via=campaignmonitor&related=yarrcat" target="_blank"" class="icon icon-twitter"><span>Twitter</span></a></li>
<li><a href="https://plus.google.com/share?url=http://necom.at" class="icon icon-google-plus"><span>Google+</span></a></li>
<li><a href="#" class="icon icon-dribbble"><span>Pinterest</span></a></li>
<li><a href="#" class="icon icon-youtube"><span>Youtube</span></a></li>
</ul>
<p>Copyright (c) 2014 necom.at All rights reserved. | <a href="http://www.necom.at/" rel="nofollow">necom.at</a></p>
</div>
</div>
</div>
</body>
</html><file_sep>/kontakt.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php require_once __DIR__ . '/library/config.php'; ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>NECOM - Kontakt</title>
<meta name="keywords" content="Netzwerke, Webdesign, Mobile App, WebApplication, Datenbanken, etc." />
<meta name="description" content="NECOM IT GmbH - Information Technology Management" />
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900" rel="stylesheet" />
<link href="library/default.css" rel="stylesheet" type="text/css" media="all" />
<link href="fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="images/icon-1.9.2014.ico">
<!--[if IE 6]><link href="library/default_ie6.css" rel="stylesheet" type="text/css" /><![endif]-->
</head>
<body>
<?php require('./inc/menu_header.inc.php'); ?>
<div class="page_title">
<h1> Kontakt </h1>
<img src="images/kont.png">
</div>
<div class="page_content1">
<?php
$qry1 = mysqli_query($con, "SELECT * FROM pages WHERE link='http://necom.at/kontakt'");
if (!$qry1) {
die("Query Failed: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($qry1)) {
echo $row['text'];
}
?>
</div>
</div>
<div class="page_content2">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div style="overflow:hidden;height:500px;width:555px;">
<div id="gmap_canvas" style="height:500px;width:555px;"></div><a class="google-map-code" href="http://www.map-embed.com" id="get-map-data">www.map-embed.com</a>
<style>
#gmap_canvas img {
max-width: none !important;
background: none !important
}
</style>
</div>
<script type="text/javascript">
function init_map() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(48.1896309, 16.306144399999994),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(48.1896309, 16.306144399999994)
});
infowindow = new google.maps.InfoWindow({
content: "<b>NECOM-IT GmbH</b><br/><NAME>ße 53<br/>1140 Wien"
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
</div>
<?php require('./inc/footer.inc.php'); ?>
</body>
</html><file_sep>/adm/logout.php
<?php
ob_start();
session_start();
$_SESSION = array();
setcookie(session_name(), "", time() - 3600);
session_destroy();
?>
<html>
<head>
<title>NECOM - Logout</title>
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900" rel="stylesheet" />
<link href="../fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="../images/necom.ico">
<style>
body {
margin: 0px;
padding: 0px;
background: #FFF url(../images/bg_app.png) repeat;
}
.ontop { z-index: 999; width: 100%; height: 100%; top: 0; left: -5%; color: #aaaaaa; filter: alpha(opacity = 90); }
#popup_login { width: 350px; height: 180px; position: absolute; box-shadow: 0px 0px 20px 3px #000; color: #000000; font-size:12px; background: #fff; top: 50%; left: 50%; border-radius:10px; margin: -200px 0 0 -200px; padding: 10px; }
h1 { text-align:center; width: 320px; }
hr { border-top: 1px solid #ccc; width: 320px; }
</style>
</head>
<body>
<!--**************Login FORM********************-->
<div class="ontop">
<table id="popup_login">
<tr style=" margin-top:-10px;">
<td>
<!---------------Main Content START---------------------------------->
<h1 style="color:#ccc; font-size:46px; margin:0;">Logout</h1>
<hr />
<?php
echo '<h4 align="center">';
echo '<img src="../images/ok1.gif" width="40" height="25" /><br /><br />';
echo 'You are successfully logged out.<br /><br />';
echo '<a href="../login.php">Login again...</a>';
echo '</h4>';
?>
<!---------------Main Content END---------------------------------->
</td>
</tr>
</table>
</div>
</body>
</html><file_sep>/adm/news/admin_categories.php
<?php
require ('../library/config.php');
require ('../template/tpl_functions.php');
logged_in();
do_header('Administration');
top_left_menu('Admin');
/* -----------------------------------------------------------------------------------------
--------------------------------- DELETE -------------------------------------------------
----------------------------------------------------------------------------------------- */
if (isset($_GET['del_category'])) {
$cat_id = $_GET['del_category'];
$cat_name = $_GET['cat_name'];
$qry = mysql_query("SELECT cat_img, cat_name FROM categories WHERE cat_id='$cat_id'", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
while ($row = mysql_fetch_array($qry)) {
$path = 'uploads/categories/';
$cat_img = $row['cat_img'];
if ($row['cat_img']) {
@unlink("$path/$cat_img");
}
}
$qry = mysql_query("DELETE FROM categories WHERE cat_id='$cat_id'", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
echo '<p class="executed"><img src="../images/ok1.gif" width="40" height="25" />Category: <b>' . $cat_name . '</b> deleted Successfully</p>';
}
/* -----------------------------------------------------------------------------------------
--------------------------------- END DELETING --------------------------------------------
----------------------------------------------------------------------------------------- */
/* * *****************Pagination TOP START ********************** */
$records_per_page = 5;
if (isset($_GET['pg'])) {
$current_pg = $_GET['pg'];
} else {
$current_pg = 1;
}
if ($current_pg <= 1) {
$start = 0;
} else {
$start = ($current_pg * $records_per_page) - $records_per_page;
}
$total_records = mysql_num_rows(mysql_query("SELECT * FROM categories", $con));
if (!$total_records) {
die("Query Failed: " . mysql_error());
}
//echo $total_records;
$total_pages = ceil($total_records / $records_per_page);
//echo $total_pages;
$qry = mysql_query("SELECT * FROM categories order by categories.cat_id DESC LIMIT $start,$records_per_page", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
$num_rows = mysql_num_rows($qry);
/* * *****************Pagination TOP END********************** */
?>
<!--Main Content START!-->
<h2>Product Categories <span style="float:right; margin:-10px 25px 0px 0px;">
<a href="add_edit_category.php?add=category"><input type="button" name="submit" value="+ Add New" id="button1" /></a></span>
<hr style="border:1px solid #bbb; margin-right:25px;">
</h2>
<p style="color:#5f5f5f; margin-bottom:-7px; margin-top:-15px;">
<a href="admin.php"><img src="../images/back.png" style="vertical-align:top; margin-top:3px;" /> Back to Main Menu
</a>
</p>
<hr style="border:1px solid #bbb; margin-bottom:-5px; margin-right:25px;"><br />
<!--Warning to User!-->
<div style="border:1px solid #bbb; margin-right:25px; padding-left:4px; background:#f5f5f5; color:#d45031; font-weight:bold;">
<span>Category can be edited or deleted only if none of Products are related to that Category!</span>
</div><br />
<?php
echo '<table cellspacing="1" cellpadding="5" width="97%" style="border:1px solid #cfcfcf; font-size:17px;">';
echo '<tr bgcolor="#e8e8e8">';
echo '<th>Logo</th><th>Category Name</th><th>Action</th>';
echo '</tr>';
while ($row = mysql_fetch_array($qry, MYSQL_ASSOC)) {
echo '<tr bgcolor="#f8f8f8">';
echo '<td width="75px">';
?>
<!--|||||||||||||||FancyBOX Category Image Zoom|||||||||||||||-->
<p><a id="single_1" href="<?php echo $cat_upload_path . $row['cat_img']; ?>" title="<?php echo $row['cat_name']; ?>">
<img style="width: 100px; height: 100px;" src="<?php echo $cat_upload_path . $row['cat_img']; ?>" alt="" />
</a></p>
<!--|||||||||||||||FancyBOX Category Image Zoom END|||||||||||||||-->
<?php
echo '</td>';
echo '<td>' . $row['cat_name'] . '</td>';
echo '<td style="text-align:center; width:190px;"><a href="add_edit_category.php?cat_id=' . $row['cat_id'] . '">edit</a> | <a href="admin_categories.php?del_category=' . $row['cat_id'] . '&cat_name=' . $row['cat_name'] . '">delete</a></td>';
echo '</tr>';
}
echo '</table><br />';
echo '<div class="clr"></div><hr style="backgound-color:#f5f5f5; border:2px solid #f5f5f5; margin-right:25px;">';
//--Main Content END!-->
/* * *****************Page Pagination DOWN START 'end of main content'********************** */
echo '<p align=center>';
$previous = $current_pg - 1;
$next = $current_pg + 1;
$pg_number = 1;
for ($pg_number; $pg_number <= $total_pages; $pg_number++) {
if ($current_pg == $pg_number) {
echo ' <span style="background-color:#f5f5f5; padding:5px; font-weight:bold;">' . $pg_number . '</span> ';
} else {
echo " <a href=\"admin_categories.php?pg=" . $pg_number . "\">" . $pg_number . "</a>";
}
}
echo " ";
if ($current_pg >= 2) {
echo "<a href=\"admin_categories.php?pg=" . $previous . "\">Previous</a>";
}
if ($current_pg < $total_pages) {
echo "<a href=\"admin_categories.php?pg=" . $next . "\">Next</a>";
}
if ($current_pg > 1) {
echo " ";
echo "<a href=\"admin_categories.php?pg=1\">First</a>";
}
if ($current_pg < $total_pages) {
echo " ";
echo "<a href=\"admin_categories.php?pg=" . $total_pages . "\">Last</a>";
}
echo '<p align="center" style="color: #9c9ca7; margin-top:-14px;">Page<b> ' . $current_pg . '/' . $total_pages . '</b></p>';
/* * *****************Page Pagination DOWN END********************** */
footer2();
?><file_sep>/mobile.necom.at/services.php
<!DOCTYPE html>
<?php require ('../library/config.php'); ?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
<!--MyIncludes STart-->
<link href="mycss.css" rel="stylesheet" type="text/css" media="all" />
<link href="fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="http://necom.at/images/icon-1.9.2014.ico">
<!--MyIncludes END-->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
</head>
<body>
<!--*********************************************************************************/
/* uns */
/*********************************************************************************/-->
<div data-role="page" id="services">
<!--Panel-->
<?php require_once ('inc/panel.inc.php'); ?>
<div data-role="header">
<div id="header-bg">
<!--Logo-->
<div class="logo">
<a href="http://mobile.necom.at"><img src="http://necom.at/images/new logo by nebo-header.png" style="width:100%;"></a>
</div>
<!--Top MENU-->
<?php require_once ('inc/navbar.inc.php'); ?>
</div>
</div>
<div data-role="main" class="ui-content" style="min-height:400px; background-color:#71a6ee;">
<ul style="list-style:none; color:#fff;">
<li>
<h1 style="color:#222;"> Services </h1>
<img src="http://necom.at/images/service.png">
</li>
<li>
<h5><span style="font-family: trebuchet ms,geneva; color: #fff;">Hier eine Übersicht über unser Serviceangebot:</span></h5>
</li>
<li>
<img src="http://necom.at/images/icons/sup.png" alt="" width="58" height="58" />
<span style="font-size: large;"><strong><br>ONLINE SUPPORT</strong></span>
</li>
<br />
<li>
<img src="http://necom.at/images/icons/hard.png" alt="" width="60" height="60" />
<span style="font-size: large;"><strong><br>HARDWARE</strong></span>
</li>
<br />
<li>
<img src="http://necom.at/images/icons/design.png" alt="" width="64" height="54" />
<span style="font-size: large;"><strong><br>HOMEPAGES DESIGN</strong></span>
</li>
<br />
<li>
<img src="http://necom.at/images/icons/soft.png" alt="" width="59" height="59" />
<span style="font-size: large;"><strong><br>SOFTWARE</strong></span>
</li>
<br />
<li>
<img src="http://necom.at/images/icons/reparatur.png" alt="" width="59" height="59" />
<span style="font-size: large;"><strong><br>REPARATUR</strong></span>
</li>
<br />
<li>
<img src="http://necom.at/images/icons/net.png" alt="" width="63" height="63" />
<span style="font-size: large;"><strong><br>NETZWERK & INTERNET</strong></span>
</li>
<br />
<li>
<img src="http://necom.at/images/icons/inst.png" alt="" width="63" height="63" />
<span style="font-size: large;"><strong><br>INSTALLIEREN</strong></span>
</li>
<br />
<li>
<img src="http://necom.at/images/icons/sec.png" alt="" width="64" height="68" />
<span style="font-size: large;"><strong><br>COMPUTERSICHERHEIT</strong></span>
</li>
<br />
<li>
<img src="http://necom.at/images/icons/learn.png" alt="" width="74" height="74" />
<span style="font-size: large;"><strong><br>IT PRIVATKURS</strong></span></li>
</ul>
</div>
<div data-role="footer" style="background-color:#4083e3; margin:0; padding:0; border:0;">
<div id="footer-bg">
<ul class="contact">
<li>
<a class="icon icon-facebook" href="http://www.facebook.com/sharer.php?u=http://necom.at&t=The World is Small" target="_blank" title="Share This on Facebook"></a>
</li>
<li><a href="http://twitter.com/share?url=http://campaignmonitor.com/blog&text=I love the Campaign Monitor blog!&via=campaignmonitor&related=yarrcat" target="_blank"" class="icon icon-twitter"><span>Twitter</span></a></li>
<li><a href="https://plus.google.com/share?url=http://necom.at" class="icon icon-google-plus"><span>Google+</span></a></li>
<li><a href="#" class="icon icon-dribbble"><span>Pinterest</span></a></li>
<li><a href="#" class="icon icon-youtube"><span>Youtube</span></a></li>
</ul>
<p>Copyright (c) 2014 necom.at All rights reserved. | <a href="http://www.necom.at/" rel="nofollow">necom.at</a></p>
</div>
</div>
</div>
</body>
</html><file_sep>/adm/users/users.php
<?php
require ('../adm_header.php');
?>
<!---------------***************Main Content START******************---------------------------------->
<!--< Go Back button and +Add New button START-->
<div class="title">
<div style="float:left;">
<a href="../admin.php"><img style="width:48px; height:48px" src="<?php echo IMAGE_DIR; ?>adm_back.png" /></a>
</div>
<h1>Users</h1>
<div style="float:right;">
<a href="add_edit_users.php?add=user"><img style="width:48px; height:48px" src="<?php echo IMAGE_DIR; ?>add.png" /></a>
</div>
</div>
<div id="clear"> </div>
<!--< Go Back button and +Add New button END-->
<?php
$qry = mysql_query("SELECT * FROM users order by users.id DESC", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
$num_rows = mysql_num_rows($qry);
echo '<table cellspacing="2" cellpadding="1" width="100%" style="border:1px solid #cfcfcf; font-size:14px; color:#222; text-align:center;">';
echo '<tr bgcolor="#e8e8e8">';
echo '<th>UserID</th><th>Username</th><th>Password</th><th colspan="2">Action</th>';
echo '</tr>';
while ($row = mysql_fetch_array($qry, MYSQL_ASSOC)) {
echo '<tr bgcolor="#f8f8f8">';
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['password'] . '</td>';
?>
<td style="width:60px;"><a href="add_edit_users.php?user_id=<?php echo $row['id']; ?>" class="action"><img style="width:32px; height:32px" src="<?php echo IMAGE_DIR; ?>edit.png" /></a></td><td style="width:60px;"><a href="users.php?del_user=<?php echo $row['id']; ?>&user_name=<?php echo $row['username']; ?>" class="action" onclick="return confirm('Are you sure?');"><img style="width:32px; height:32px" src="<?php echo IMAGE_DIR; ?>delete.png" /></a></td>
<?php
echo '</tr>';
}
echo '</table>';
?>
<?php
/* -----------------------------------------------------------------------------------------
--------------------------------- Query DELETE --------------------------------------------------
----------------------------------------------------------------------------------------- */
if (isset($_GET['del_user'])) {
$user_id = $_GET['del_user'];
$user_name = $_GET['user_name'];
$qry = mysql_query("DELETE FROM users WHERE id='$user_id'", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
echo '<br /><hr />';
echo '<p align="center" style="padding-top: 10px;"><img src="../../images/ok1.gif" width="40" height="25" /><br />User <b>' . $user_name . '</b> deleted Successfully.</p>';
//Refresh page
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = "users.php";
?>
<meta http-equiv="Refresh" content="2; url=<?php echo 'http://'. $host . $uri . '/' . $extra; ?>">
<?php
}
/* -----------------------------------------------------------------------------------------
--------------------------------- END Query DELETE -----------------------------------------------
----------------------------------------------------------------------------------------- */
?>
<!---------------******************Main Content END******************---------------------------------->
<?php
require ('../adm_footer.php');
?><file_sep>/adm/pages/pages.php
<?php
require ('adm_header.php');
require (($_SERVER['DOCUMENT_ROOT']) . 'fancybox/my-fancybox-js-css.php');
/* * *****************Pagination TOP START ********************** */
$records_per_page = 3;
if (isset($_GET['pg'])) {
$current_pg = $_GET['pg'];
} else {
$current_pg = 1;
}
if ($current_pg <= 1) {
$start = 0;
} else {
$start = ($current_pg * $records_per_page) - $records_per_page;
}
$total_records = mysql_num_rows(mysql_query("SELECT * FROM pages", $con));
if (!$total_records) {
die("Query Failed: " . mysql_error());
}
//echo $total_records;
$total_pages = ceil($total_records / $records_per_page);
//echo $total_pages;
$qry = mysql_query("SELECT * FROM pages order by pages.id DESC LIMIT $start,$records_per_page", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
$num_rows = mysql_num_rows($qry);
/* * *****************Pagination TOP END********************** */
?>
<!---------------***************Main Content START******************---------------------------------->
<!--< Go Back button and +Add New button START-->
<div class="title">
<div style="float:left;">
<a href="../admin.php"><img style="width:48px; height:48px" src="<?php echo IMAGE_DIR; ?>adm_back.png" /></a>
</div>
<h1>Main Pages</h1>
<div style="float:right;">
<a href="add_edit_pages.php?add=page"><img style="width:48px; height:48px" src="<?php echo IMAGE_DIR; ?>add.png" /></a>
</div>
</div>
<div id="clear"> </div>
<!--< Go Back button and +Add New button END-->
<?php
echo '<table cellspacing="1" cellpadding="1" width="100%" style="text-align:center; border:1px solid #cfcfcf; font-size:14px;">';
echo '<tr bgcolor="#e8e8e8">';
echo '<th>Image</th><th>Creation</th><th>Menu Title</th><th>link</th><th colspan="2">Action</th>';
echo '</tr>';
while ($row = mysql_fetch_array($qry, MYSQL_ASSOC)) {
echo '<tr bgcolor="#f8f8f8">';
echo '<td width="75px">';
?>
<!--|||||||||||||||FancyBOX pages Image Zoom|||||||||||||||-->
<p style="margin: 0; padding: 0;"><a id="adm_pages" href="<?php echo UPLOAD_DIR . $row['img']; ?>" title="<?php echo $row['title']; ?>">
<img style="width: 64px; height: 64px;" src="<?php echo UPLOAD_DIR . $row['img']; ?>" alt="" />
</a></p>
<!--|||||||||||||||FancyBOX Pages Image Zoom END|||||||||||||||-->
<?php
echo '</td>';
echo '<td>' . $row['date'] . '</td>';
echo '<td>' . $row['title'] . '</td>';
echo '<td>' . $row['link'] . '</td>';
?>
<td style="width:60px;"><a href="add_edit_pages.php?id=<?php echo $row['id']; ?>" class="action"><img style="width:32px; height:32px" src="<?php echo IMAGE_DIR; ?>edit.png" /></a></td><td style="width:60px;"><a href="pages.php?del_pages=<?php echo $row['id']; ?>&title=<?php echo $row['title']; ?>" class="action" onclick="return confirm('Are you sure?');"><img style="width:32px; height:32px" src="<?php echo IMAGE_DIR; ?>delete.png" /></a></td>
<?php
echo '</tr>';
}
echo '</table><br />';
echo '<div class="clr"></div><hr style="backgound-color:#f5f5f5; border:2px solid #f5f5f5; margin-bottom: 10px;">';
//<!---------------******************Main Content END******************---------------------------------->
/* * *****************Page Pagination DOWN START********************** */
echo '<p align=center>';
$previous = $current_pg - 1;
$next = $current_pg + 1;
$pg_number = 1;
for ($pg_number; $pg_number <= $total_pages; $pg_number++) {
if ($current_pg == $pg_number) {
echo ' <span style="background-color:#f5f5f5; border:1px solid #ccc; padding:7px; font-weight:bold;">' . $pg_number . '</span> '; } else {
echo " <a href=\"pages.php?pg=" . $pg_number . "\">" . $pg_number . "</a>";
}
}
echo " ";
if ($current_pg >= 2) {
echo "<a href=\"pages.php?pg=" . $previous . "\">Previous</a>";
}
if ($current_pg < $total_pages) {
echo "<a href=\"pages.php?pg=" . $next . "\">Next</a>";
}
if ($current_pg > 1) {
echo " ";
echo "<a href=\"pages.php?pg=1\">First</a>";
}
if ($current_pg < $total_pages) {
echo " ";
echo "<a href=\"pages.php?pg=" . $total_pages . "\">Last</a>";
}
echo '<p align="center" style="color: #9c9ca7; margin-top:-14px;">Page<b> ' . $current_pg . '/' . $total_pages . '</b></p>';
/* * *****************Page Pagination DOWN END********************** */
/* -----------------------------------------------------------------------------------------
--------------------------------- DELETE -------------------------------------------------
----------------------------------------------------------------------------------------- */
if (isset($_GET['del_pages'])) {
$id = $_GET['del_pages'];
$title = $_GET['title'];
$qry = mysql_query("SELECT img, title FROM pages WHERE id='$id'", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
while ($row = mysql_fetch_array($qry)) {
$path = '../../upl';
$img = $row['img'];
if ($row['img']) {
@unlink("$path/$img");
}
}
$qry = mysql_query("DELETE FROM pages WHERE id='$id'", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
//Refresh page
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = "pages.php";
?>
<meta http-equiv="Refresh" content="1; url=<?php echo 'http://'. $host . $uri . '/' . $extra; ?>">
<?php
}
/* -----------------------------------------------------------------------------------------
--------------------------------- END DELETING --------------------------------------------
----------------------------------------------------------------------------------------- */
require ('../adm_footer.php');
?><file_sep>/referenzen.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php require_once __DIR__ . '/library/config.php'; ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>NECOM - Referenzen</title>
<meta name="keywords" content="Netzwerke, Webdesign, Mobile App, WebApplication, Datenbanken, etc." />
<meta name="description" content="NECOM IT GmbH - Information Technology Management" />
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900" rel="stylesheet" />
<link href="library/default.css" rel="stylesheet" type="text/css" media="all" />
<link href="fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="images/icon-1.9.2014.ico">
<!--[if IE 6]><link href="library/default_ie6.css" rel="stylesheet" type="text/css" /><![endif]-->
</head>
<body>
<?php require('./inc/menu_header.inc.php'); ?>
<div class="page_content_all">
<?php
$qry1 = mysqli_query($con, "SELECT * FROM pages WHERE link='http://necom.at/referenzen'");
if (!$qry1) {
die("Query Failed: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($qry1)) {
echo $row['text'];
}
?>
</div>
</div>
<?php require('./inc/footer.inc.php'); ?>
</body>
</html><file_sep>/mobile.necom.at/referenzen.php
<!DOCTYPE html>
<?php require ('../library/config.php'); ?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
<!--MyIncludes STart-->
<link href="mycss.css" rel="stylesheet" type="text/css" media="all" />
<link href="fonts/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link rel="shortcut icon" href="http://necom.at/images/icon-1.9.2014.ico">
<!--MyIncludes END-->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
</head>
<body>
<!--*********************************************************************************/
/* uns */
/*********************************************************************************/-->
<div data-role="page" id="referenzen">
<!--Panel-->
<?php require_once ('inc/panel.inc.php'); ?>
<div data-role="header">
<div id="header-bg">
<!--Logo-->
<div class="logo">
<a href="http://necom.at"><img src="http://necom.at/images/new logo by nebo-header.png" style="width:100%;"></a>
</div>
<!--Top MENU-->
<?php require_once ('inc/navbar.inc.php'); ?>
</div>
</div>
<div data-role="main" class="ui-content" style="min-height:400px; background-color:#71a6ee; text-align:center;">
<ul style="list-style:none;">
<li>
<h1 style="text-align:left; margin-left:0px;">Referenzen </h1>
</li>
</ul>
<!--ref UM start-->
<a href="#myPopup4" data-rel="popup" data-position-to="window">
<img src="http://necom.at/images/necom_reference.png" alt="Universal Management" style="width:100%; margin:0;"><br />
</a>
<a href="#myPopup4" data-rel="popup" data-position-to="window" class="ui-btn ui-icon-action ui-btn-icon-left ui-shadow" style="margin:0;">Universal Management</a>
<div data-role="popup" id="myPopup4" style="text-align:center; margin-bottom:10px;">
<p>Das ist Universal Management Bildschirmabdruck...</p>
<a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a><img src="http://necom.at/images/necom_reference.png" style="width:800px; height:300px;" alt="Universal Management">
<a href="http://www.necom.at/UM" target="_blank" class="ui-btn ui-icon-arrow-r ui-btn-icon-right ui-shadow" style="margin:0;">Details</a>
</div>
<!--ref UM end-->
<br />
<!--ref umr start-->
<a href="#myPopup" data-rel="popup" data-position-to="window">
<img src="http://necom.at/images/umr-screen.png" alt="UMR GmbH" style="width:100%; margin:0;"><br />
</a>
<a href="#myPopup" data-rel="popup" data-position-to="window" class="ui-btn ui-icon-action ui-btn-icon-left ui-shadow" style="margin:0;">UMR GmbH</a>
<div data-role="popup" id="myPopup" style="text-align:center; margin-bottom:10px;">
<p>Das ist UMR GmbH Bildschirmabdruck...</p>
<a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a><img src="http://necom.at/images/umr-screen.png" style="width:800px; height:300px;" alt="UMR GmbH">
<a href="http://www.umr.at" target="_blank" class="ui-btn ui-icon-arrow-r ui-btn-icon-right ui-shadow" style="margin:0;">Zur Website</a>
</div>
<!--ref umr end-->
<br />
<!--ref albimco start-->
<a href="#myPopup2" data-rel="popup" data-position-to="window">
<img src="http://necom.at/images/albimco-screen.png" alt="Albimco" style="width:100%; margin:0;"><br />
</a>
<a href="#myPopup2" data-rel="popup" data-position-to="window" class="ui-btn ui-icon-action ui-btn-icon-left ui-shadow" style="margin:0;">Albimco Immobilien</a>
<div data-role="popup" id="myPopup2" style="text-align:center; margin-bottom:10px;">
<p>Das ist Albimco.com Immobilien Bildschirmabdruck...</p>
<a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a><img src="http://necom.at/images/albimco-screen.png" style="width:800px;height:300px;" alt="Albimco">
<a href="http://www.albimco.com" target="_blank" class="ui-btn ui-icon-arrow-r ui-btn-icon-right ui-shadow" style="margin:0;">Zur Website</a>
</div>
<!--ref albimco end-->
<br />
<!--ref promdress start-->
<a href="#myPopup3" data-rel="popup" data-position-to="window">
<img src="http://necom.at/images/promdress.png" alt="PromDress" style="width:100%; margin:0;"><br />
</a>
<a href="#myPopup3" data-rel="popup" data-position-to="window" class="ui-btn ui-icon-action ui-btn-icon-left ui-shadow" style="margin:0;">PromDress.at - Online Shopping</a>
<div data-role="popup" id="myPopup3" style="text-align:center; margin-bottom:10px;">
<p>HomePage in Arbeit......</p>
<a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a><img src="http://necom.at/images/promdress.png" style="width:800px;height:300px;" alt="Albimco">
<a href="http://www.PromDress.at" target="_blank" class="ui-btn ui-icon-arrow-r ui-btn-icon-right ui-shadow" style="margin:0;">Zur Website</a>
</div>
<!--ref promdress end-->
</div>
<div data-role="footer" style="background-color:#4083e3; margin:0; padding:0; border:0;">
<div id="footer-bg">
<ul class="contact">
<li>
<a class="icon icon-facebook" href="http://www.facebook.com/sharer.php?u=http://necom.at&t=The World is Small" target="_blank" title="Share This on Facebook"></a>
</li>
<li><a href="http://twitter.com/share?url=http://campaignmonitor.com/blog&text=I love the Campaign Monitor blog!&via=campaignmonitor&related=yarrcat" target="_blank"" class="icon icon-twitter"><span>Twitter</span></a></li>
<li><a href="https://plus.google.com/share?url=http://necom.at" class="icon icon-google-plus"><span>Google+</span></a></li>
<li><a href="#" class="icon icon-dribbble"><span>Pinterest</span></a></li>
<li><a href="#" class="icon icon-youtube"><span>Youtube</span></a></li>
</ul>
<p>Copyright (c) 2014 necom.at All rights reserved. | <a href="http://www.necom.at/" rel="nofollow">necom.at</a></p>
</div>
</div>
</div>
</body>
</html><file_sep>/fancybox/my-fancybox-js-css.php
<!--FancyBOX START-->
<!-- Add jQuery library -->
<script type="text/javascript" src="<?php echo SITE_URL; ?>fancybox/lib/jquery-1.10.1.min.js"></script>
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="<?php echo SITE_URL; ?>fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox main JS and CSS files -->
<script type="text/javascript" src="<?php echo SITE_URL; ?>fancybox/source/jquery.fancybox.js?v=2.1.5"></script>
<link rel="stylesheet" type="text/css" href="<?php echo SITE_URL; ?>fancybox/source/jquery.fancybox.css?v=2.1.5" media="screen" />
<!-- Add Button helper (this is optional) -->
<link rel="stylesheet" type="text/css" href="<?php echo SITE_URL; ?>fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" />
<script type="text/javascript" src="<?php echo SITE_URL; ?>fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<!-- Add Thumbnail helper (this is optional) -->
<link rel="stylesheet" type="text/css" href="<?php echo SITE_URL; ?>fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" />
<script type="text/javascript" src="<?php echo SITE_URL; ?>fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<!-- Add Media helper (this is optional) -->
<script type="text/javascript" src="<?php echo SITE_URL; ?>fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script>
<!--email_form.php-->
<script type="text/javascript">
$(document).ready(function() {
$(".email_form").fancybox({
maxWidth: 415,
maxHeight: 463,
fitToView: false,
autoSize: true,
closeClick: false,
openEffect: 'fade',
closeEffect: 'fade',
padding: 0,
});
});
</script>
<!--referenzen_popup.php-->
<script type="text/javascript">
$(document).ready(function() {
$("#referenzen").fancybox({
maxWidth: 1200,
height: 640,
fitToView: false,
autoSize: false,
closeClick: false,
openEffect: 'none',
closeEffect: 'none',
closeBtn: true
});
});
</script>
<!--adm--pages.php-->
<script type="text/javascript">
$(document).ready(function() {
$("#adm_pages").fancybox({
maxWidth: 1200,
maxHeight: 920,
fitToView: false,
autoSize: false,
closeClick: false,
openEffect: 'none',
closeEffect: 'none',
closeBtn: true
});
});
</script><file_sep>/adm/check_login.php
<?php
require ('../library/config.php');
if (isset($_POST['username']) && !empty($_POST['username'])) {
$username = (mysql_real_escape_string($_POST['username']));
$password = (mysql_real_escape_string($_POST['password']));
$qry = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$<PASSWORD>'", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
}
$row = mysql_fetch_array($qry);
if ($username == (mysql_real_escape_string($row['username'])) && $password == (mysql_real_escape_string($row['password']))) {
session_start();
$_SESSION['username'] = stripslashes($username);
header("Location: admin.php");
} else {
?>
<!-- First else -->
<style>
body {
margin: 0px;
padding: 0px;
background: #FFF url(../images/bg_app.png) repeat;
}
.ontop { z-index: 999; width: 100%; height: 100%; top: 0; left: -5%; color: #aaaaaa; filter: alpha(opacity = 90); }
#popup_login { width: 350px; height: 180px; position: absolute; box-shadow: 0px 0px 20px 3px #000; color: #000000; font-size:12px; background: #fff; top: 50%; left: 50%; border-radius:10px; margin: -200px 0 0 -200px; padding: 10px; }
h1 { text-align:center; width: 320px; }
hr { border-top: 1px solid #ccc; width: 320px; }
</style>
<div class="ontop">
<table id="popup_login">
<tr style=" margin-top:-10px;">
<td>
<!---------------Main Content 1 START---------------------------------->
<?php
echo '<p align=center><img src=../images/stop.png /><br />Username or Password you entered is incorrect!<br /><br /><a href=javascript:history.go(-1)>[Try Again...]</a></p>';
?>
<!---------------Main Content 1 END---------------------------------->
</td>
</tr>
</table>
</div>
<?php
}
}
else {
?>
<!-- Second else -->
<style>
body {
margin: 0px;
padding: 0px;
background: #FFF url(../images/bg_app.png) repeat;
}
.ontop { z-index: 999; width: 100%; height: 100%; top: 0; left: -5%; color: #aaaaaa; filter: alpha(opacity = 90); }
#popup_login { width: 350px; height: 180px; position: absolute; box-shadow: 0px 0px 20px 3px #000; color: #000000; font-size:12px; background: #fff; top: 50%; left: 50%; border-radius:10px; margin: -200px 0 0 -200px; padding: 10px; }
h1 { text-align:center; width: 320px; }
hr { border-top: 1px solid #ccc; width: 320px; }
</style>
<div class="ontop">
<table id="popup_login">
<tr style=" margin-top:-10px;">
<td>
<!---------------Main Content 2 START---------------------------------->
<?php
echo '<p align=center><img src=../images/stop.png /><br />Please enter username or password!<br /><br /><a href=javascript:history.go(-1)>[Try Again...]</a></p>';
?>
<!---------------Main Content 2 END---------------------------------->
</td>
</tr>
</table>
</div>
<?php
}
?>
|
0dc1f18a6fccdf497e359947da05d107af2c35c2
|
[
"Markdown",
"PHP"
] | 23 |
PHP
|
nesho84/necom.at
|
d5d050a5e2edcab337498a51bc53a6bf22a29dcf
|
cccccc5f2e006c8ac26d952cd710254c32f5a037
|
refs/heads/master
|
<file_sep>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { JhipsterCityModule } from './city/city.module';
import { JhipsterActivityModule } from './activity/activity.module';
/* jhipster-needle-add-entity-module-import - JHipster will add entity modules imports here */
@NgModule({
imports: [
JhipsterCityModule,
JhipsterActivityModule,
/* jhipster-needle-add-entity-module - JHipster will add entity modules here */
],
declarations: [],
entryComponents: [],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class JhipsterEntityModule {}
<file_sep>package com.mycompany.myapp.repository;
import com.mycompany.myapp.domain.City;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* Spring Data JPA repository for the City entity.
*/
@SuppressWarnings("unused")
@Repository
public interface CityRepository extends JpaRepository<City, Long> {
@Query("select distinct city from City city left join fetch city.users")
List<City> findAllWithEagerRelationships();
@Query("select city from City city left join fetch city.users where city.id =:id")
City findOneWithEagerRelationships(@Param("id") Long id);
}
|
109cc0334d4ac647b4c1ba9fab0c44f404665e17
|
[
"Java",
"TypeScript"
] | 2 |
TypeScript
|
chakibc18/jhipster
|
4809a972ffb1c3587dca1639077c934cc746aa74
|
97766a32ba1b4bf566869be2cedcc9a40936904f
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for EditMembership.xaml
/// </summary>
public partial class EditMembership : Window
{
private SQLiteHelper helper;
private int membershipId;
public EditMembership(int mid)
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
membershipId = mid;
helper = new SQLiteHelper();
DataTable oldvals = helper.GetDataTable("SELECT name, deposit, discount FROM memberships WHERE membershipId=" + membershipId);
if ((double)oldvals.Rows[0].ItemArray[2] == 0) //If no discount
noDiscount.IsChecked = true;
else discountButton.IsChecked = true;
name.Text = oldvals.Rows[0].ItemArray[0].ToString();
deposit.Text = oldvals.Rows[0].ItemArray[1].ToString();
discountPercent.Text = oldvals.Rows[0].ItemArray[2].ToString();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
if (deposit.Text.Contains("^[0-9]") || discountPercent.Text.Contains("^[0-9]"))
MessageBox.Show("Deposit and Discount must be numbers.");
else
helper.ExecuteNonQuery("UPDATE memberships " +
"SET " +
"name=\"" + name.Text + "\", " +
"deposit=\"" + deposit.Text + "\", " +
"discount=\"" + ((bool)(discountButton.IsChecked) ? discountPercent.Text : "0") + "\" " +//Discount or not
"WHERE membershipId="+membershipId);
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for EnterCustomerCode.xaml
/// </summary>
public partial class EnterCustomerCodeRent : Window
{
public EnterCustomerCodeRent()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
ClickHelper("customers.code");
}
private void Name_Click(object sender, RoutedEventArgs e)
{
ClickHelper("customers.name");
}
public void ClickHelper(string condition)
{
SQLiteHelper helper = new SQLiteHelper();
DataTable table = helper.GetDataTable( //TODO: Implement volume sets
"SELECT customers.customerId, customers.code AS Code, customers.name AS Name " +
"FROM customers " +
"WHERE "+condition+" LIKE '%" + code.Text + "%'");
int count = table.Rows.Count;
CustomerRent win;
int id;
switch (count)
{
case 0: MessageBox.Show("Customer not found."); break;
case 1:
id = Convert.ToInt32(table.Rows[0].ItemArray[0].ToString());
win = new CustomerRent(id);
win.ShowDialog();
break;
default:
SearchResults search = new SearchResults(table);
search.ShowDialog();
id = search.getId;
if (id != -1)
{
win = new CustomerRent(id);
win.ShowDialog();
}
break;
}
if(count != 0)
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for EditCustomer.xaml
/// </summary>
public partial class EditCustomer : Window
{
private SQLiteHelper helper;
private DataTable table;
private int customerId;
public EditCustomer(int cid)
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
customerId = cid;
table = helper.GetDataTable( //TODO: Implement volume sets
"SELECT memberships.membershipId, memberships.name " +
"FROM memberships");
membership.DataContext = table;
DataTable oldVals = helper.GetDataTable("SELECT name, code, email, id, phone, note, membershipId FROM customers WHERE customerId=" + customerId);
object[] items = oldVals.Rows[0].ItemArray;
name.Text = items[0].ToString();
code.Text = items[1].ToString();
email.Text = items[2].ToString();
id.Text = items[3].ToString();
phone.Text = items[4].ToString();
note.Text = items[5].ToString();
membership.SelectedIndex = Convert.ToInt32(items[6]);
}
private void OK_Click(object sender, RoutedEventArgs e)
{
string sql =
"UPDATE customers " +
"SET "+
"name=\"" + name.Text + "\", " +
"code=\"" + code.Text + "\", " +
"membershipId=\"" + membership.SelectedValue + "\", " +
"id=\"" + id.Text + "\", " +
"email=\"" + email.Text + "\", " +
"phone=\"" + phone.Text + "\", " +
"note=\"" + note.Text + "\" " +
"WHERE customerId=" + customerId;
helper.ExecuteNonQuery(sql);
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for NewType.xaml
/// </summary>
public partial class NewType : Window
{
private SQLiteHelper helper;
public NewType()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
string sql1 =
"INSERT INTO types (name," +
"rentMultiplier,rentValue,rentQuantity,rentDays," +
"hotMultiplier,hotValue,hotQuantity,hotDays,hotLength," +
"houseMultiplier,houseValue," +
"depositMultiplier,depositValue," +
"membershipMultiplier,membershipValue," +
"overdueMultiplier,overdueValue,overdueDays ) " +
"VALUES (\"" +
name.Text + "\", \"";
string sql2 =
(((bool)rentMultiplier.IsChecked) ? 1 : 0) + "\", \"" +
(((bool)rentMultiplier.IsChecked) ? rentMulti.Text : rentFlat.Text) + "\", \"" +
rentQuantity.Text + "\", \"" +
rentDays.Text + "\", \"" +
(((bool)hotMultiplier.IsChecked) ? 1 : 0) + "\", \"" +
(((bool)hotMultiplier.IsChecked) ? hotMulti.Text : hotFlat.Text) + "\", \"" +
hotQuantity.Text + "\", \"" +
hotDays.Text + "\", \"" +
hotLength.Text + "\", \"" +
(((bool)houseMultiplier.IsChecked) ? 1 : 0) + "\", \"" +
(((bool)houseMultiplier.IsChecked) ? houseMulti.Text : houseFlat.Text) + "\", \"" +
(((bool)depositMultiplier.IsChecked) ? 1 : 0) + "\", \"" +
(((bool)depositMultiplier.IsChecked) ? depositMulti.Text : depositFlat.Text) + "\", \"" +
(((bool)membershipMultiplier.IsChecked) ? 1 : 0) + "\", \"" +
(((bool)membershipMultiplier.IsChecked) ? membershipMulti.Text : membershipFlat.Text) + "\", \"" +
(((bool)overdueMultiplier.IsChecked) ? 1 : 0) + "\", \"" +
(((bool)overdueMultiplier.IsChecked) ? overdueMulti.Text : overdueFlat.Text) + "\", \"" +
overdueDays.Text + "\")";
string temp2 = sql2.Replace("True","").Replace("False","").Replace("\")",""); //Removes all booleans
char[] delim = "\", \"".ToCharArray();
string[] temp = temp2.Split(delim);
bool success = true;
foreach(string s in temp) //Check if each input is valid
{
if(s != "")
{
try
{
Convert.ToDouble(s);
}
catch (Exception oops)
{
MessageBox.Show("Rates may only contain numbers and decimals.");
success = false;
break;
}
}
}
if(success)
{
helper.ExecuteNonQuery(sql1 + sql2);
Close();
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace Rental
{
/// <summary>
/// Interaction logic for Inventory.xaml
/// </summary>
public partial class Inventory : Window
{
private SQLiteHelper helper;
private DataTable table;
public Inventory()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate //Clock
{
this.clock.Text = DateTime.Now.ToString();
}, this.Dispatcher);
helper = new SQLiteHelper();
table = helper.GetDataTable( //TODO: Implement volume sets
"SELECT series.*, types.name AS type " +
"FROM series, types " +
"WHERE types.typeId=series.typeId");
gridInv.DataContext = table.DefaultView;
}
private void search_KeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Return)
table = helper.GetDataTable(
"SELECT series.*, types.name AS type " +
"FROM series, types " +
"WHERE types.typeId=series.typeId AND (customers.code=" + search.Text + " OR customers.name=" + search.Text + ")");
}
private void Edit_Click(object sender, RoutedEventArgs e)
{
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
}
private void Search_Click(object sender, RoutedEventArgs e)
{
}
private void Details_Click(object sender, RoutedEventArgs e)
{
}
private void Serials_Click(object sender, RoutedEventArgs e)
{
}
private void Exit_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for EditType.xaml
/// </summary>
public partial class EditType : Window
{
private SQLiteHelper helper;
private int typeId;
public EditType(int tid)
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
typeId = tid;
DataTable oldVals = helper.GetDataTable("SELECT * FROM types WHERE typeId="+typeId);
object[] items = oldVals.Rows[0].ItemArray;
name.Text = items[1].ToString();
if ((bool)items[2])
{
rentMulti.Text = items[3].ToString();
rentMultiplier.IsChecked = true;
}
else
{
rentFlat.Text = items[3].ToString();
rentFlatiplier.IsChecked = true;
}
rentQuantity.Text = items[4].ToString();
rentDays.Text = items[5].ToString();
if ((bool)items[6])
{
hotMulti.Text = items[7].ToString();
hotMultiplier.IsChecked = true;
}
else
{
hotFlat.Text = items[7].ToString();
hotFlatiplier.IsChecked = true;
}
hotQuantity.Text = items[8].ToString();
hotDays.Text = items[9].ToString();
hotLength.Text = items[10].ToString();
if ((bool)items[11])
{
houseMulti.Text = items[12].ToString();
houseMultiplier.IsChecked = true;
}
else
{
houseFlat.Text = items[12].ToString();
houseFlatiplier.IsChecked = true;
}
if ((bool)items[13])
{
depositMulti.Text = items[14].ToString();
depositMultiplier.IsChecked = true;
}
else
{
depositFlat.Text = items[14].ToString();
depositFlatiplier.IsChecked = true;
}
if ((bool)items[15])
{
membershipMulti.Text = items[16].ToString();
membershipMultiplier.IsChecked = true;
}
else
{
membershipFlat.Text = items[16].ToString();
membershipFlatiplier.IsChecked = true;
}
if ((bool)items[17])
{
overdueMulti.Text = items[18].ToString();
overdueMultiplier.IsChecked = true;
}
else
{
overdueFlat.Text = items[18].ToString();
overdueFlatiplier.IsChecked = true;
}
overdueDays.Text = items[19].ToString();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
string checking =
(((bool)rentMultiplier.IsChecked) ? rentMulti.Text : rentFlat.Text) + ", " +
rentQuantity.Text + "," +
rentDays.Text + "," +
(((bool)hotMultiplier.IsChecked) ? hotMulti.Text : hotFlat.Text) + "," +
hotQuantity.Text + "," +
hotDays.Text + "," +
hotLength.Text + "," +
(((bool)houseMultiplier.IsChecked) ? houseMulti.Text : houseFlat.Text) + "," +
(((bool)depositMultiplier.IsChecked) ? depositMulti.Text : depositFlat.Text) + "," +
(((bool)overdueMultiplier.IsChecked) ? overdueMulti.Text : overdueFlat.Text) + "," +
overdueDays.Text;
string[] checklist = checking.Split(",".ToCharArray());
bool success = true;
foreach(string s in checklist)
{
if (s != "")
{
try
{
Convert.ToDouble(s);
}
catch (Exception oops)
{
MessageBox.Show("Rates may only contain numbers and decimals.");
success = false;
break;
}
}
}
if (success)
{
string sql =
"UPDATE types " +
"SET " +
"name=\"" + name.Text + "\", " +
"rentMultiplier=\"" + (((bool)rentMultiplier.IsChecked) ? 1 : 0) + "\", " +
"rentValue=\"" + (((bool)rentMultiplier.IsChecked) ? rentMulti.Text : rentFlat.Text) + "\", " +
"rentQuantity=\"" + rentQuantity.Text + "\", " +
"rentDays=\"" + rentDays.Text + "\", " +
"hotMultiplier=\"" + (((bool)hotMultiplier.IsChecked) ? 1 : 0) + "\", " +
"hotValue=\"" + (((bool)hotMultiplier.IsChecked) ? hotMulti.Text : hotFlat.Text) + "\", " +
"hotQuantity=\"" + hotQuantity.Text + "\", " +
"hotDays=\"" + hotDays.Text + "\", " +
"hotLength=\"" + hotLength.Text + "\", " +
"houseMultiplier=\"" + (((bool)houseMultiplier.IsChecked) ? 1 : 0) + "\", " +
"houseValue=\"" + (((bool)houseMultiplier.IsChecked) ? houseMulti.Text : houseFlat.Text) + "\", " +
"depositMultiplier=\"" + (((bool)depositMultiplier.IsChecked) ? 1 : 0) + "\", " +
"depositValue=\"" + (((bool)depositMultiplier.IsChecked) ? depositMulti.Text : depositFlat.Text) + "\", " +
"membershipMultiplier=\"" + (((bool)membershipMultiplier.IsChecked) ? 1 : 0) + "\", " +
"membershipValue=\"" + (((bool)membershipMultiplier.IsChecked) ? membershipMulti.Text : membershipFlat.Text) + "\", " +
"overdueMultiplier=\"" + (((bool)overdueMultiplier.IsChecked) ? 1 : 0) + "\", " +
"overdueValue=\"" + (((bool)overdueMultiplier.IsChecked) ? overdueMulti.Text : overdueFlat.Text) + "\", " +
"overdueDays=\"" + overdueDays.Text + "\" " +
"WHERE typeId=" + typeId;
helper.ExecuteNonQuery(sql);
Close();
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace Rental
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private SQLiteHelper helper;
public MainWindow()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate //Clock
{
this.clock.Text = DateTime.Now.ToString();
}, this.Dispatcher);
helper = new SQLiteHelper();
companyname.DataContext = helper.ExecuteScalar("SELECT name FROM companyinfo");
}
//Searchbar
private void Search_Enter(object sender, KeyEventArgs e)
{
if (e.Key != Key.Return)
return;
DataTable table = helper.GetDataTable( //TODO: Implement volume sets
"SELECT customers.customerId, customers.code AS Code, customers.name AS Name " +
"FROM customers " +
"WHERE customers.code LIKE '%" + searchBox.Text + "%'");
int count = table.Rows.Count;
CustomerRent win;
int id;
switch (count)
{
case 0: MessageBox.Show("Customer not found."); break;
case 1:
id = Convert.ToInt32(table.Rows[0].ItemArray[0].ToString());
win = new CustomerRent(id);
win.ShowDialog();
break;
default:
SearchResults search = new SearchResults(table);
search.ShowDialog();
id = search.getId;
if (id != -1)
{
win = new CustomerRent(id);
win.ShowDialog();
}
break;
}
}
//Business
private void Rent_Click(object sender, RoutedEventArgs e)
{
EnterCustomerCodeRent win = new EnterCustomerCodeRent();
win.ShowDialog();
}
private void Return_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
private void Buy_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
private void InStore_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
private void SwitchShifts_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
private void Exit_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
//Data
private void NewCustomer_Click(object sender, RoutedEventArgs e)
{
NewCustomer win = new NewCustomer();
win.ShowDialog();
}
private void ManageCustomers_Click(object sender, RoutedEventArgs e)
{
ManageCustomers win = new ManageCustomers();
win.ShowDialog();
}
private void NewSeries_Click(object sender, RoutedEventArgs e)
{
NewSeries win = new NewSeries();
win.ShowDialog();
}
private void ManageInventory_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
private void RentedOutLog_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
//Setup
private void MembershipTypeSetup_Click(object sender, RoutedEventArgs e)
{
MembershipSetup win = new MembershipSetup();
win.ShowDialog();
}
private void CreditPrepaySetup_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
private void InventoryTypeSetup_Click(object sender, RoutedEventArgs e)
{
TypeSetup win = new TypeSetup();
win.ShowDialog();
}
private void EmployeeSetup_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
private void VendorSetup_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
private void CustomerIDSetup_Click(object sender, RoutedEventArgs e)
{
Inventory win = new Inventory();
win.ShowDialog();
}
//Management
private void CashRegisterTotal_Click(object sender, RoutedEventArgs e)
{
CompanyInfoSetup win = new CompanyInfoSetup();
win.ShowDialog();
companyname.DataContext = helper.ExecuteScalar("SELECT name FROM companyinfo");
}
private void TransactionLog_Click(object sender, RoutedEventArgs e)
{
CompanyInfoSetup win = new CompanyInfoSetup();
win.ShowDialog();
companyname.DataContext = helper.ExecuteScalar("SELECT name FROM companyinfo");
}
private void CompanyInfo_Click(object sender, RoutedEventArgs e)
{
CompanyInfoSetup win = new CompanyInfoSetup();
win.ShowDialog();
companyname.DataContext = helper.ExecuteScalar("SELECT name FROM companyinfo");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for Type_Setup.xaml
/// </summary>
public partial class TypeSetup : Window
{
private DataTable table;
private SQLiteHelper helper;
public TypeSetup()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
table = helper.GetDataTable(
"SELECT typeId, name " +
"FROM types");
gridTypes.DataContext = table.DefaultView;
}
private void New_Click(object sender, RoutedEventArgs e)
{
NewType win = new NewType();
win.ShowDialog();
table = helper.GetDataTable(
"SELECT typeId, name " +
"FROM types");
gridTypes.DataContext = table.DefaultView;
}
private void Edit_Click(object sender, RoutedEventArgs e)
{
try
{
EditType win = new EditType(Convert.ToInt32(gridTypes.SelectedValue));
win.ShowDialog();
table = helper.GetDataTable(
"SELECT typeId, name " +
"FROM types");
gridTypes.DataContext = table.DefaultView;
}
catch (IndexOutOfRangeException oops) { } //Click w/o any selection
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
try
{
DataTable rented = helper.GetDataTable( //Check if anything with this type is rented out
"SELECT rented.* " +
"FROM rented " +
"JOIN serials USING (serialId) " +
"JOIN series USING (seriesId) " +
"WHERE series.typeId=" + Convert.ToInt32(gridTypes.SelectedValue));
if (rented.Rows.Count != 0)
MessageBox.Show("Error: There exist items of this type with active rentals.");
else
{
if (MessageBox.Show(
"Are you sure you want to delete type \"" + ((DataRowView)gridTypes.SelectedItems[0])["name"] + "\"?\nAll items of this type will be deleted!",
"Confirm Delete", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
helper.ExecuteNonQuery("DELETE FROM types WHERE typeId=" + gridTypes.SelectedValue);
table = helper.GetDataTable(
"SELECT typeId, name " +
"FROM types");
gridTypes.DataContext = table.DefaultView;
}
}
}
catch (IndexOutOfRangeException oops) { } //Click w/o any selection
}
private void Close_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void Select_Type(object sender, RoutedEventArgs e)
{
try
{
if (gridTypes.SelectedValue == null) //Closing a dialogue selects a row before the table can update
throw new IndexOutOfRangeException();
DataTable vals = helper.GetDataTable(
"SELECT rentMultiplier,rentValue,hotMultiplier,hotValue,houseMultiplier,houseValue,depositMultiplier,depositValue,membershipMultiplier,membershipValue,overdueMultiplier,overdueValue " +
"FROM types WHERE typeId=" + gridTypes.SelectedValue);
object[] items = vals.Rows[0].ItemArray;
rentRate.DataContext = "Regular Rate: " + (((bool)items[0]) ? "x" : "+") + items[1].ToString();
hotRate.DataContext = "Hot Rate: " + (((bool)items[2]) ? "x" : "+") + items[3].ToString();
houseRate.DataContext = "In-Store Rate: " + (((bool)items[4]) ? "x" : "+") + items[5].ToString();
depositRate.DataContext = "Deposit Rate: " + (((bool)items[6]) ? "x" : "+") + items[7].ToString();
membershipRate.DataContext = "Membership Rate: " + (((bool)items[8]) ? "x" : "+") + items[9].ToString();
overdueRate.DataContext = "Overdue Rate: " + (((bool)items[10]) ? "x" : "+") + items[11].ToString();
}
catch (IndexOutOfRangeException oops) { } //New Type selects new row before table can update, causing this exception
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
public partial class NewMembership : Window
{
private SQLiteHelper helper;
public NewMembership()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
if (deposit.Text.Contains("^[0-9]") || discountPercent.Text.Contains("^[0-9]"))
MessageBox.Show("Deposit and Discount must be numbers.");
else
helper.ExecuteNonQuery("INSERT INTO memberships (name,deposit,discount) " +
"VALUES (\"" + name.Text + "\"," + deposit.Text + "," +
((bool)(discountButton.IsChecked) ? discountPercent.Text : "0") + ")");
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for SearchResults.xaml
/// </summary>
public partial class SearchResults : Window
{
private SQLiteHelper helper;
private DataTable table;
private int id;
public SearchResults(DataTable dt)
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
table = dt;
gridSearch.DataContext = table.DefaultView;
}
public int getId { get { return id; } }
private void OK_Click(object sender, RoutedEventArgs e)
{
int ind = gridSearch.SelectedIndex;
id = Convert.ToInt32(table.Rows[ind].ItemArray[0].ToString());
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
id = -1;
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for ManageCustomers.xaml
/// </summary>
public partial class ManageCustomers : Window
{
private DataTable table;
private SQLiteHelper helper;
public ManageCustomers()
{
InitializeComponent();
helper = new SQLiteHelper();
table = helper.GetDataTable(
"SELECT customers.*, memberships.name AS memName " +
"FROM customers, memberships " +
"WHERE memberships.membershipId=customers.membershipId");
gridCustomers.DataContext = table.DefaultView;
}
private void search_Enter(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
table = helper.GetDataTable( //TODO: select from datatable instead of database?
"SELECT customers.*, memberships.name AS memName " +
"FROM customers, memberships " +
"WHERE memberships.membershipId=customers.membershipId AND (customers.code LIKE \"%" + search.Text + "%\" OR customers.name LIKE \"%" + search.Text + "%\")");
gridCustomers.DataContext = table.DefaultView;
}
}
//Data
private void NewCustomer_Click(object sender, RoutedEventArgs e)
{
NewCustomer win = new NewCustomer();
win.ShowDialog();
table = helper.GetDataTable(
"SELECT customers.*, memberships.name AS memName " +
"FROM customers, memberships " +
"WHERE memberships.membershipId=customers.membershipId AND (customers.code LIKE \"%" + search.Text + "%\" OR customers.name LIKE \"%" + search.Text + "%\")");
gridCustomers.DataContext = table.DefaultView;
}
private void EditCustomer_Click(object sender, RoutedEventArgs e)
{
try
{
EditCustomer win = new EditCustomer(Convert.ToInt32(gridCustomers.SelectedValue));
win.ShowDialog();
table = helper.GetDataTable(
"SELECT customers.*, memberships.name AS memName " +
"FROM customers, memberships " +
"WHERE memberships.membershipId=customers.membershipId AND (customers.code LIKE \"%" + search.Text + "%\" OR customers.name LIKE \"%" + search.Text + "%\")");
gridCustomers.DataContext = table.DefaultView;
}
catch (IndexOutOfRangeException oops) { } //Click w/o any selection
}
private void DeleteCustomer_Click(object sender, RoutedEventArgs e)
{
try
{
DataTable rented = helper.GetDataTable("SELECT rented.* FROM rented, customers WHERE rented.customerId=" + Convert.ToInt32(gridCustomers.SelectedValue));
if (rented.Rows.Count != 0)
MessageBox.Show("Error: Customer has active rentals.");
else
{
if (MessageBox.Show(
"Are you sure you want to delete customer \"" + ((DataRowView)gridCustomers.SelectedItems[0])["name"] + "\"?",
"Confirm Delete", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
helper.ExecuteNonQuery("DELETE FROM customers WHERE customerId=" + gridCustomers.SelectedValue);
table = helper.GetDataTable(
"SELECT customers.*, memberships.name AS memName " +
"FROM customers, memberships " +
"WHERE memberships.membershipId=customers.membershipId");
gridCustomers.DataContext = table.DefaultView;
}
}
}
catch (IndexOutOfRangeException oops) { } //Click w/o any selection
}
private void Print_Click(object sender, RoutedEventArgs e)
{
}
private void Finish_Click(object sender, RoutedEventArgs e)
{
Close();
}
//Logs
private void Credit_Click(object sender, RoutedEventArgs e)
{
}
private void Debit_Click(object sender, RoutedEventArgs e)
{
}
private void DepositCash_Click(object sender, RoutedEventArgs e)
{
}
private void DepositOther_Click(object sender, RoutedEventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for NewItem.xaml
/// </summary>
public partial class NewSeries : Window
{
private SQLiteHelper helper;
private DataTable table;
public NewSeries()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
table = helper.GetDataTable( //TODO: Implement volume sets
"SELECT typeId, name " +
"FROM types");
type.DataContext = table;
}
private void OK_Click(object sender, RoutedEventArgs e)
{
string sql =
"INSERT INTO series (title,typeId,artist,publisher,reference,defaultPrice,finished) " +
"VALUES (\"" +
title.Text + "\", \"" +
type.SelectedValue + "\", \"" +
author.Text + "\", \"" +
publisher.Text + "\", \"" +
reference.Text + "\", \"" +
defaultPrice.Text + "\", \"" +
( ((bool)finished.IsChecked) ? "TRUE" : "FALSE" ) + "\")";
helper.ExecuteNonQuery(sql);
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rental
{
class SQLiteHelper
{
private string dbfile;
private SQLiteConnection con;
public SQLiteHelper() {
dbfile = @"Data Source=C:\Users\Panda\Source\Repos\sql-rental-system\Rental\Rental.sqlite";
}
public DataTable GetDataTable(string sql)
{
DataTable dt = new DataTable();
//try
//{
con = new SQLiteConnection(dbfile);
con.Open();
SQLiteCommand command = new SQLiteCommand(con);
command.CommandText = sql;
SQLiteDataReader reader = command.ExecuteReader();
dt.Load(reader);
reader.Close();
// con.Close();
//}
//catch (Exception e)
//{
// throw new Exception("Failed to get table.");
//}
return dt;
}
public string ExecuteScalar(string sql)
{
con = new SQLiteConnection(dbfile);
con.Open();
SQLiteCommand command = new SQLiteCommand(con);
command.CommandText = sql;
object value = command.ExecuteScalar();
con.Close();
if (value != null)
return value.ToString();
return "";
}
public int ExecuteNonQuery(string sql)
{
con = new SQLiteConnection(dbfile);
con.Open();
SQLiteCommand command = new SQLiteCommand(con);
command.CommandText = sql;
int rowsUpdated = command.ExecuteNonQuery();
con.Close();
return rowsUpdated;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for CompanyInfoSetup.xaml
/// </summary>
public partial class CompanyInfoSetup : Window
{
public CompanyInfoSetup()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
}
private void OK_Click(object sender, RoutedEventArgs e)
{
SQLiteHelper helper = new SQLiteHelper();
string sql = "UPDATE companyinfo " +
"SET name=\"" + name.Text + "\", rentDays=";
if ((bool)days1.IsChecked)
sql += "0";
else sql += rentDays.Text;
sql += ", rentQuantity=";
if ((bool)quantity1.IsChecked)
sql += "0";
else sql += rentQuantity.Text;
sql += " WHERE rowid=1;";
helper.ExecuteNonQuery(sql);
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for Serials.xaml
/// </summary>
public partial class Serials : Window
{
private int seriesId;
public Serials(int i)
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
seriesId = i;
SQLiteHelper helper = new SQLiteHelper();
DataTable table = helper.GetDataTable(
"SELECT serials.setIndex AS Set, serials.volume AS Volume, serials.serial AS Serial, serials.price AS Price, serials.hotPrice AS Hot Price, serials.hot AS Hot " +
"FROM serials, series " +
"WHERE " + seriesId + "=serials.seriesId");
gridSerial.DataContext = table.DefaultView;
}
private void Add_Click(object sender, RoutedEventArgs e)
{
}
private void Edit_Click(object sender, RoutedEventArgs e)
{
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
}
private void Copy_Click(object sender, RoutedEventArgs e)
{
}
private void Finish_Click(object sender, RoutedEventArgs e)
{
}
}
}
<file_sep>Lionfish Rentals
=================
Rental/retail system, written using C# and SQLite.
###Packages:###
* NuGet System.Data.SQLite (x86/x64)
* Project -> Add Reference, System.Data.SQLite (Remember to check "Copy Local")
###Features:###
* Robust database system
* Keep track of Customer:
* Transactions
* Credit Balance
* Active Rentals
* Deposits
* Create Customer Memberships for discounts and benefits
* Organize items by Series Title, Media Type
* UPC Barcode support
* Preset default pricings and values for each membership or media type
* Supplier information/transactions
* Employee shifts
* Detailed inventory logs
*Developed by <NAME>*
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for MembershipSetup.xaml
/// </summary>
public partial class MembershipSetup : Window
{
private SQLiteHelper helper;
private DataTable table;
public MembershipSetup()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
table = helper.GetDataTable("SELECT * FROM memberships");
gridMemberships.DataContext = table.DefaultView;
deposit.DataContext = "Deposit: ";
discount.DataContext = "Discount: ";
}
private void New_Click(object sender, RoutedEventArgs e)
{
NewMembership win = new NewMembership();
win.ShowDialog();
table = helper.GetDataTable("SELECT * FROM memberships");
gridMemberships.DataContext = table.DefaultView;
}
private void Edit_Click(object sender, RoutedEventArgs e)
{
try
{
EditMembership win = new EditMembership(Convert.ToInt32(gridMemberships.SelectedValue));
win.ShowDialog();
table = helper.GetDataTable("SELECT * FROM memberships");
gridMemberships.DataContext = table.DefaultView;
}
catch (IndexOutOfRangeException oops) { } //Click w/o any selection
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
try
{
DataTable children = helper.GetDataTable("SELECT * FROM customers WHERE membershipId=" + Convert.ToInt32(gridMemberships.SelectedValue));
if (children.Rows.Count != 0)
MessageBox.Show("Error: There exist customers with this membership.");
else
{
if (MessageBox.Show(
"Are you sure you want to delete membership type \"" + gridMemberships.SelectedItems[0] + "\" ?",
"Confirm Delete", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
helper.ExecuteNonQuery("DELETE FROM memberships WHERE membershipId=" + gridMemberships.SelectedValue);
table = helper.GetDataTable("SELECT * FROM memberships");
gridMemberships.DataContext = table.DefaultView;
}
}
}
catch (IndexOutOfRangeException oops) { } //Click w/o any selection
}
private void Finish_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void Select_Type(object sender, RoutedEventArgs e)
{
try
{
deposit.DataContext = "Deposit: " + table.Rows[gridMemberships.SelectedIndex].ItemArray[2];
discount.DataContext = "Discount: " + table.Rows[gridMemberships.SelectedIndex].ItemArray[3];
}
catch (IndexOutOfRangeException oops) { Console.WriteLine(oops.Message); } //New Membership selects new row before table can update, causing this exception
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for CustomerRent.xaml
/// </summary>
public partial class CustomerRent : Window
{
public CustomerRent(int id)
{
InitializeComponent();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Rental
{
/// <summary>
/// Interaction logic for NewCustomer.xaml
/// </summary>
public partial class NewCustomer : Window
{
private SQLiteHelper helper;
private DataTable table;
public NewCustomer()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
helper = new SQLiteHelper();
table = helper.GetDataTable( //TODO: Implement volume sets
"SELECT memberships.membershipId, memberships.name " +
"FROM memberships");
membership.DataContext = table;
}
private void OK_Click(object sender, RoutedEventArgs e)
{
string sql =
"INSERT INTO customers (name,code,membershipId,id,email,phone,note) " +
"VALUES (\"" +
name.Text + "\", \"" +
code.Text + "\", \"" +
membership.SelectedValue + "\", \"" +
id.Text + "\", \"" +
email.Text + "\", \"" +
phone.Text + "\", \"" +
note.Text + "\")";
helper.ExecuteNonQuery(sql);
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
|
49d6f93c0c8717d1024a1d6f4667ef9cef4267bc
|
[
"Markdown",
"C#"
] | 19 |
C#
|
wilsonmyeh/sql-rental-system
|
471d9159d6ffe623cac944076d82e709c04a78f0
|
8a5ccb7ecaf0a03b8608a088ae3cb232959520cd
|
refs/heads/main
|
<repo_name>JoshuaFMarais/CustomGUIBehavior<file_sep>/Custom GUI Assets/Custom GUI Tutorial/TestCanvasMono.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestCanvasMono : MonoBehaviour
{
public void PrintSomething() {
Debug.Log("From something else");
}
public void PrintSomethingElse()
{
Debug.Log("From something else ");
}
}
<file_sep>/Custom GUI Assets/Custom GUI Tutorial/CustomGUIBehavior.cs
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public abstract class CustomGUIBehavior : MonoBehaviour,
IPointerUpHandler, IPointerClickHandler, IPointerEnterHandler,
IPointerExitHandler, IPointerDownHandler
{
protected abstract void ClickAction();
protected abstract void Init();
public Color normalColor = Color.white;
public Color ClickColor = Color.black;
public Color HoverColor = Color.white;
Image TargetGraphic;
[Header("Sprites")]
public Sprite HoverSprite;
[HideInInspector]
public Sprite DefaultSprite;
private void Awake()
{
TargetGraphic = GetComponent<Image>();
DefaultSprite = TargetGraphic.sprite;
if (HoverSprite == null) HoverSprite = DefaultSprite;
NormalState();
Init();
}
//interfaces implementations
//you can easily add all sorts of extra functionality in these methods
public void OnPointerClick(PointerEventData eventData)
{
ClickAction();
}
public void OnPointerEnter(PointerEventData eventData)
{
HoverState();
}
public void OnPointerExit(PointerEventData eventData)
{
NormalState();
}
public void OnPointerDown(PointerEventData eventData)
{
ClickState();
}
public void OnPointerUp(PointerEventData eventData)
{
HoverState();
}
//States
//they are made virtual so you can override them if needed
//otherwise you should make them private
//private void HoverState()
protected virtual void HoverState()
{
transform.localScale = Vector3.one * 1.1f;
TargetGraphic.color = HoverColor;
TargetGraphic.sprite = DefaultSprite;
}
protected virtual void ClickState()
{
transform.localScale = Vector3.one;
TargetGraphic.color = ClickColor;
TargetGraphic.sprite = HoverSprite;
}
protected virtual void NormalState()
{
transform.localScale = Vector3.one;
TargetGraphic.color = normalColor;
TargetGraphic.sprite = DefaultSprite;
}
}
<file_sep>/Custom GUI Assets/Custom GUI Tutorial/Editor/CustomGUIBehaviorEditor.cs
using UnityEngine;
using UnityEditor;
using System;
using System.Reflection;
[CustomEditor(typeof(CustomButton))]
public class CustomGUIBehaviorEditor : Editor
{
CustomButton mono;
private void OnEnable()
{
mono = (CustomButton)target;
}
public override void OnInspectorGUI()
{
GUILayout.BeginHorizontal();
mono.TargetSceneGameobject = GUIEditorHelpers.GetTargetSceneObject(mono.TargetSceneGameobject);
if (mono.TargetSceneGameobject != null)
{
mono.SelectedMono = GUIEditorHelpers.GetTargetMono(mono.TargetSceneGameobject, mono.SelectedMono);
GUILayout.EndHorizontal();
string cMethodeName = mono.m_method?.Name;
mono.m_method = GUIEditorHelpers.GUIMethodeSelect(mono.SelectedMono, cMethodeName);
}
else
{
GUILayout.EndHorizontal();
}
base.OnInspectorGUI();
}
}
public static class GUIEditorHelpers
{
//Gets the target Gameobject in the scene
public static GameObject GetTargetSceneObject(GameObject currentObj)
{
currentObj = (GameObject)EditorGUILayout.ObjectField(currentObj, typeof(GameObject), allowSceneObjects: true);
return currentObj;
}
//selects a Monobehavior on the targeted GameObject
public static MonoBehaviour GetTargetMono(GameObject TargetObj, MonoBehaviour currentMono)
{
MonoBehaviour[] ms = TargetObj.GetComponents<MonoBehaviour>();
if (ms.Length == 0)
{
return null;
}
//set to 0
int currentIndex = 0;
if (currentMono != null)
{
Type currentT = currentMono.GetType();
for (int i = 0; i < ms.Length; i++)
{
if (currentT == ms[i].GetType())
{
currentIndex = i;
break;
}
}
}
string[] names = GetObjectNames(ms);
currentIndex = EditorGUILayout.Popup(currentIndex, names);
return ms[currentIndex];
}
//selects a method from the selected mono
public static MethodInfo GUIMethodeSelect(MonoBehaviour targetMono, string currentFunction)
{
MethodInfo[] mis = targetMono.GetType().GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
string[] s = new string[mis.Length];
int cIndex = 0;
//get the Method infos as a string array
for (int i = 0; i < s.Length; i++) s[i] = mis[i].Name;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == currentFunction)
{
cIndex = i;
break;
}
}
return mis[EditorGUILayout.Popup(cIndex, s)];
}
public static string[] GetObjectNames(object[] obs)
{
string[] names = new string[obs.Length];
for (int i = 0; i < obs.Length; i++)
{
names[i] = obs[i].GetType().ToString();
}
return names;
}
}
<file_sep>/Custom GUI Assets/Custom GUI Tutorial/CustomButton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
public class CustomButton : CustomGUIBehavior
{
[HideInInspector]
public GameObject TargetSceneGameobject;
[HideInInspector]
public MonoBehaviour SelectedMono;
[HideInInspector]
public MethodInfo m_method;
[Header("Sound")]
public AudioClip ClickSound;
AudioSource source;
protected override void Init()
{
if (ClickSound == null) ClickSound = Resources.Load<AudioClip>("click_sound");
source = GetComponent<AudioSource>();
}
protected override void ClickAction()
{
source.PlayOneShot(ClickSound);
m_method?.Invoke(SelectedMono, null);
}
}
<file_sep>/Custom GUI Assets/Custom GUI Tutorial/SimpleButton.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
public class SimpleButton : CustomGUIBehavior
{
public int m_num;
public string m_text;
public delegate void CustomEvent();
public CustomEvent m_event;
protected override void ClickAction()
{
Debug.Log(m_text + ": " + m_num);
m_event?.Invoke();
}
protected override void Init()
{
}
}
|
ccf4fd13b60d278a95a5a9be63692adc5c7c0014
|
[
"C#"
] | 5 |
C#
|
JoshuaFMarais/CustomGUIBehavior
|
3d4401f5124f3dc6a0c0c2c7b7c1429797ee0fc7
|
4a8175b40d71163887f7ac89e6c4bd7a941635b9
|
refs/heads/master
|
<repo_name>swkyyme/cms-demo<file_sep>/src/controllers/student.js
const Student = require('../models/student');
const Course = require('../models/course');
async function addStudent(req, res) {
const { firstName, lastName, email } = req.body;
const student = new Student({
firstName,
lastName,
email
});
// try {
// await student.save();
// } catch (e) {
// return res.json(e);
// }
await student.save(); //async
return res.status(201).json(student);
}
async function getStudent(req, res) {
const { id } = req.params;
const student = await Student.findOne({ id }).populate(
'courses',
'code name'
).exec();
if (!student) {
return res.status(404).json('student not found');
}
return res.json(student);
}
async function getAllStudents(req, res) {
// const { pageSize, page }
// let query = Student.find();
// if(pageSize && page) {
// query = query.skip().limit();
// }
// const students = await query.exec();
const students = await Student.find().exec();
return res.json(students);
}
async function updateStudent(req, res) {
const { id } = req.params;
const { firstName, lastName, email } = req.body;
//joi.validate({}, template) for findbyidandupdate
const newStudent = await Student.findByIdAndUpdate(
id,
{ firstName, lastName, email },
{ new:true }
).exec();
//Student.findById();
//student.save(); use save() !!!! when you can! not skip validate
if (!newStudent) {
return res.status(404).json('student not found');
}
return res.json(newStudent);
}
async function deleteStudent(req, res) {
const { id } = req.params;
const deletedStudent = await Student.findByIdAndDelete(id).exec();
if (!deletedStudent) {
return res.sendStatus(404).json('student not found');
}
await Course.updateMany(
{ _id: { $in: student.courses } },
{ $pull: { studens: student._id } }
).exec();
return res.status(200).json(deletedStudent);
}
async function addCourse(req, res) {
const { id, code } = req.params;
const student = await Student.findById(id).exec();
const course = await Course.findById(code).exec();
if (!student) {
return res.status(404).json('student not found');
} else if (!course) {
return res.status(404).json('course not found');
}
const oldCount = student.courses.length;
student.courses.addToSet(course._id);
course.students.addToSet(student._id);
if (student.courses.length === oldCount) {
return res.json('enrollment already exist');
}
await course.save();
await student.save();
return res.json(student);
}
async function deleteCourse(req, res) {
const { id, code } = req.params;
const student = await Student.findById(id).exec();
const course = await Course.findById(code).exec();
if (!student) {
return res.status(404).json('student not found');
} else if (!course) {
return res.status(404).json('course not found');
}
const oldCount = student.courses.length;
student.courses.remove(course._id);
if (student.courses.length === oldCount) {
return res.status(404).json('enrollment does not exist');
}
course.students.pull(student._id);
await course.save();
await student.save();
return res.json(student);
}
module.exports = {
addStudent,
getAllStudents,
getStudent,
updateStudent,
deleteStudent,
addCourse,
deleteCourse
};
|
bb6243ced546f2d4b8095089a1e686a9ba8cbe35
|
[
"JavaScript"
] | 1 |
JavaScript
|
swkyyme/cms-demo
|
90cf12052e62635858f6ab428d92e8fa12385fb9
|
d7bf6c0136dded3265bb130a52a42e5eaee08d7b
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.